diff --git a/.gitignore b/.gitignore index 850758cf1e..75da3674af 100644 --- a/.gitignore +++ b/.gitignore @@ -60,3 +60,6 @@ debug.log # Ignore OS X Desktop Services Store files .DS_Store + +# Orig diff files +*.orig diff --git a/README.md b/README.md index 352e44ac26..f3b988b81a 100644 --- a/README.md +++ b/README.md @@ -22,6 +22,8 @@ Documentation Supported Microcontrollers and Boards ------------------------------------- +View all on the [mbed Platforms](https://mbed.org/platforms/) page. + NXP: * [mbed LPC1768](http://mbed.org/platforms/mbed-LPC1768/) (Cortex-M3) * [u-blox C027 LPC1768](http://mbed.org/platforms/u-blox-C027/) (Cortex-M3) @@ -36,19 +38,24 @@ NXP: * [LPC1114](http://mbed.org/platforms/LPC1114FN28/) (Cortex-M0) * LPC11C24 (Cortex-M0) * [LPC1549](https://mbed.org/platforms/LPCXpresso1549/) (Cortex-M3) +* [LPC800-MAX](https://mbed.org/platforms/NXP-LPC800-MAX/) (Cortex-M0+) +* [DipCortex-M0](https://mbed.org/platforms/DipCortex-M0/) (Cortex-M0) +* [DipCortex-M3](https://mbed.org/platforms/DipCortex-M3/) (Cortex-M3) +* [BlueBoard-LPC11U24](https://mbed.org/platforms/BlueBoard-LPC11U24/) (Cortex-M0) Freescale: * FRDM-K20D50M (Cortex-M4) * [FRDM-KL05Z](https://mbed.org/platforms/FRDM-KL05Z/) (Cortex-M0+) * [FRDM-KL25Z](http://mbed.org/platforms/KL25Z/) (Cortex-M0+) * [FRDM-KL46Z](https://mbed.org/platforms/FRDM-KL46Z/) (Cortex-M0+) -* FRDM-K64F (Cortex-M4) +* [FRDM-K64F](https://mbed.org/platforms/FRDM-K64F/) (Cortex-M4) STMicroelectronics: * [Nucleo-F103RB](https://mbed.org/platforms/ST-Nucleo-F103RB/) (Cortex-M3) * [Nucleo-L152RE](https://mbed.org/platforms/ST-Nucleo-L152RE/) (Cortex-M3) * [Nucleo-F030R8](https://mbed.org/platforms/ST-Nucleo-F030R8/) (Cortex-M0) * [Nucleo-F401RE](https://mbed.org/platforms/ST-Nucleo-F401RE/) (Cortex-M4) +* [Nucleo-F302R8](https://mbed.org/platforms/ST-Nucleo-F302R8/) (Cortex-M4) * STM32F4XX (Cortex-M4F) * STM32F3XX (Cortex-M4F) * STM32F0-Discovery (Cortex-M0) diff --git a/libraries/USBDevice/USBAudio/USBAudio.h b/libraries/USBDevice/USBAudio/USBAudio.h index a1057ebfa2..6b6b4bcc45 100644 --- a/libraries/USBDevice/USBAudio/USBAudio.h +++ b/libraries/USBDevice/USBAudio/USBAudio.h @@ -50,7 +50,7 @@ * * int main() { * int16_t buf[AUDIO_LENGTH_PACKET/2]; -* +* * while (1) { * // read an audio packet * audio.read((uint8_t *)buf); @@ -88,7 +88,7 @@ public: * @returns volume */ float getVolume(); - + /** * Read an audio packet. During a frame, only a single reading (you can't write and read an audio packet during the same frame)can be done using this method. Warning: Blocking * @@ -97,7 +97,7 @@ public: * @returns true if successfull */ bool read(uint8_t * buf); - + /** * Try to read an audio packet. During a frame, only a single reading (you can't write and read an audio packet during the same frame)can be done using this method. Warning: Non Blocking * @@ -106,7 +106,7 @@ public: * @returns true if successfull */ bool readNB(uint8_t * buf); - + /** * Write an audio packet. During a frame, only a single writing (you can't write and read an audio packet during the same frame)can be done using this method. * @@ -114,7 +114,7 @@ public: * @returns true if successful */ bool write(uint8_t * buf); - + /** * Write and read an audio packet at the same time (on the same frame) * @@ -123,7 +123,7 @@ public: * @returns true if successful */ bool readWrite(uint8_t * buf_read, uint8_t * buf_write); - + /** attach a handler to update the volume * @@ -212,12 +212,12 @@ protected: * Callback called on each Start of Frame event */ virtual void SOF(int frameNumber); - + /* * Callback called when a packet is received */ virtual bool EP3_OUT_callback(); - + /* * Callback called when a packet has been sent */ @@ -227,13 +227,13 @@ private: // stream available ? volatile bool available; - + // interrupt OUT has been received volatile bool interruptOUT; - + // interrupt IN has been received volatile bool interruptIN; - + // audio packet has been written volatile bool writeIN; @@ -248,7 +248,7 @@ private: // mono, stereo,... uint8_t channel_nb_in; uint8_t channel_nb_out; - + // channel config: master, left, right uint8_t channel_config_in; uint8_t channel_config_out; @@ -270,16 +270,16 @@ private: // Buffer containing one audio packet (to be read) volatile uint8_t * buf_stream_in; - + // Buffer containing one audio packet (to be written) volatile uint8_t * buf_stream_out; - + // callback to update volume FunctionPointer updateVol; - + // boolean showing that the SOF handler has been called. Useful for readNB. volatile bool SOF_handler; - + volatile float volume; }; diff --git a/libraries/USBDevice/USBDevice/USBDescriptor.h b/libraries/USBDevice/USBDevice/USBDescriptor.h index 0793e9cac9..9d4ce849f0 100644 --- a/libraries/USBDevice/USBDevice/USBDescriptor.h +++ b/libraries/USBDevice/USBDevice/USBDescriptor.h @@ -32,7 +32,7 @@ /*string offset*/ -#define STRING_OFFSET_LANGID (0) +#define STRING_OFFSET_LANGID (0) #define STRING_OFFSET_IMANUFACTURER (1) #define STRING_OFFSET_IPRODUCT (2) #define STRING_OFFSET_ISERIAL (3) diff --git a/libraries/USBDevice/USBDevice/USBDevice.cpp b/libraries/USBDevice/USBDevice/USBDevice.cpp index ffe0b448b1..53659164a7 100644 --- a/libraries/USBDevice/USBDevice/USBDevice.cpp +++ b/libraries/USBDevice/USBDevice/USBDevice.cpp @@ -106,7 +106,7 @@ bool USBDevice::requestGetDescriptor(void) transfer.ptr = stringImanufacturerDesc(); transfer.direction = DEVICE_TO_HOST; success = true; - break; + break; case STRING_OFFSET_IPRODUCT: #ifdef DEBUG printf("3\r\n"); @@ -115,7 +115,7 @@ bool USBDevice::requestGetDescriptor(void) transfer.ptr = stringIproductDesc(); transfer.direction = DEVICE_TO_HOST; success = true; - break; + break; case STRING_OFFSET_ISERIAL: #ifdef DEBUG printf("4\r\n"); @@ -124,7 +124,7 @@ bool USBDevice::requestGetDescriptor(void) transfer.ptr = stringIserialDesc(); transfer.direction = DEVICE_TO_HOST; success = true; - break; + break; case STRING_OFFSET_ICONFIGURATION: #ifdef DEBUG printf("5\r\n"); @@ -133,7 +133,7 @@ bool USBDevice::requestGetDescriptor(void) transfer.ptr = stringIConfigurationDesc(); transfer.direction = DEVICE_TO_HOST; success = true; - break; + break; case STRING_OFFSET_IINTERFACE: #ifdef DEBUG printf("6\r\n"); @@ -142,7 +142,7 @@ bool USBDevice::requestGetDescriptor(void) transfer.ptr = stringIinterfaceDesc(); transfer.direction = DEVICE_TO_HOST; success = true; - break; + break; } break; case INTERFACE_DESCRIPTOR: @@ -357,7 +357,7 @@ bool USBDevice::requestSetInterface(void) { success = true; currentInterface = transfer.setup.wIndex; - currentAlternate = transfer.setup.wValue; + currentAlternate = transfer.setup.wValue; } return success; } @@ -473,12 +473,12 @@ bool USBDevice::requestGetStatus(void) if (success) { - /* Send the status */ + /* Send the status */ transfer.ptr = (uint8_t *)&status; /* Assumes little endian */ transfer.remaining = sizeof(status); transfer.direction = DEVICE_TO_HOST; } - + return success; } @@ -546,7 +546,7 @@ bool USBDevice::controlSetup(void) transfer.direction = 0; transfer.zlp = false; transfer.notify = false; - + #ifdef DEBUG printf("dataTransferDirection: %d\r\nType: %d\r\nRecipient: %d\r\nbRequest: %d\r\nwValue: %d\r\nwIndex: %d\r\nwLength: %d\r\n",transfer.setup.bmRequestType.dataTransferDirection, transfer.setup.bmRequestType.Type, @@ -593,7 +593,7 @@ bool USBDevice::controlSetup(void) } else { - + /* OUT data stage is required */ if (transfer.direction != HOST_TO_DEVICE) { @@ -707,7 +707,7 @@ void USBDevice::connect(bool blocking) { /* Connect device */ USBHAL::connect(); - + if (blocking) { /* Block if not configured */ while (!configured()); @@ -793,8 +793,8 @@ void USBDevice::suspendStateChanged(unsigned int suspended) USBDevice::USBDevice(uint16_t vendor_id, uint16_t product_id, uint16_t product_release){ - VENDOR_ID = vendor_id; - PRODUCT_ID = product_id; + VENDOR_ID = vendor_id; + PRODUCT_ID = product_id; PRODUCT_RELEASE = product_release; /* Set initial device state */ @@ -818,12 +818,12 @@ bool USBDevice::write(uint8_t endpoint, uint8_t * buffer, uint32_t size, uint32_ { return false; } - - + + if(!configured()) { return false; } - + /* Send report */ result = endpointWrite(endpoint, buffer, size); @@ -849,7 +849,7 @@ bool USBDevice::writeNB(uint8_t endpoint, uint8_t * buffer, uint32_t size, uint3 { return false; } - + if(!configured()) { return false; } @@ -872,7 +872,7 @@ bool USBDevice::writeNB(uint8_t endpoint, uint8_t * buffer, uint32_t size, uint3 bool USBDevice::readEP(uint8_t endpoint, uint8_t * buffer, uint32_t * size, uint32_t maxSize) { EP_STATUS result; - + if(!configured()) { return false; } @@ -889,13 +889,13 @@ bool USBDevice::readEP(uint8_t endpoint, uint8_t * buffer, uint32_t * size, uint bool USBDevice::readEP_NB(uint8_t endpoint, uint8_t * buffer, uint32_t * size, uint32_t maxSize) { EP_STATUS result; - + if(!configured()) { return false; } result = endpointReadResult(endpoint, buffer, size); - + return (result == EP_COMPLETED); } diff --git a/libraries/USBDevice/USBDevice/USBDevice.h b/libraries/USBDevice/USBDevice/USBDevice.h index 2035aaec38..a25ca1adfe 100644 --- a/libraries/USBDevice/USBDevice/USBDevice.h +++ b/libraries/USBDevice/USBDevice/USBDevice.h @@ -27,26 +27,26 @@ class USBDevice: public USBHAL { public: USBDevice(uint16_t vendor_id, uint16_t product_id, uint16_t product_release); - + /* * Check if the device is configured * * @returns true if configured, false otherwise */ bool configured(void); - + /* * Connect a device - * + * * @param blocking: block if not configured */ void connect(bool blocking = true); - + /* * Disconnect a device */ void disconnect(void); - + /* * Add an endpoint * @@ -65,7 +65,7 @@ public: * @return true if successful */ bool readStart(uint8_t endpoint, uint32_t maxSize); - + /* * Read a certain endpoint. Before calling this function, USBUSBDevice_readStart * must be called. @@ -79,20 +79,20 @@ public: * @returns true if successful */ bool readEP(uint8_t endpoint, uint8_t * buffer, uint32_t * size, uint32_t maxSize); - + /* * Read a certain endpoint. * * Warning: non blocking * * @param endpoint endpoint which will be read - * @param buffer buffer will be filled with the data received (if data are available) + * @param buffer buffer will be filled with the data received (if data are available) * @param size the number of bytes read will be stored in *size * @param maxSize the maximum length that can be read * @returns true if successful */ bool readEP_NB(uint8_t endpoint, uint8_t * buffer, uint32_t * size, uint32_t maxSize); - + /* * Write a certain endpoint. * @@ -104,8 +104,8 @@ public: * @param maxSize the maximum length that can be written on this endpoint */ bool write(uint8_t endpoint, uint8_t * buffer, uint32_t size, uint32_t maxSize); - - + + /* * Write a certain endpoint. * @@ -118,14 +118,14 @@ public: */ bool writeNB(uint8_t endpoint, uint8_t * buffer, uint32_t size, uint32_t maxSize); - + /* * Called by USBDevice layer on bus reset. Warning: Called in ISR context * * May be used to reset state */ virtual void USBCallback_busReset(void) {}; - + /* * Called by USBDevice on Endpoint0 request. Warning: Called in ISR context * This is used to handle extensions to standard requests @@ -133,8 +133,8 @@ public: * * @returns true if class handles this request */ - virtual bool USBCallback_request() { return false; }; - + virtual bool USBCallback_request() { return false; }; + /* * Called by USBDevice on Endpoint0 request completion * if the 'notify' flag has been set to true. Warning: Called in ISR context @@ -146,7 +146,7 @@ public: * @param length length of this buffer */ virtual void USBCallback_requestCompleted(uint8_t * buf, uint32_t length) {}; - + /* * Called by USBDevice layer. Set configuration of the device. * For instance, you can add all endpoints that you need on this function. @@ -154,7 +154,7 @@ public: * @param configuration Number of the configuration */ virtual bool USBCallback_setConfiguration(uint8_t configuration) { return false; }; - + /* * Called by USBDevice layer. Set interface/alternate of the device. * @@ -170,63 +170,63 @@ public: * @returns pointer to the device descriptor */ virtual uint8_t * deviceDesc(); - + /* * Get configuration descriptor * * @returns pointer to the configuration descriptor */ virtual uint8_t * configurationDesc(){return NULL;}; - + /* * Get string lang id descriptor * * @return pointer to the string lang id descriptor */ virtual uint8_t * stringLangidDesc(); - + /* * Get string manufacturer descriptor * * @returns pointer to the string manufacturer descriptor */ virtual uint8_t * stringImanufacturerDesc(); - + /* * Get string product descriptor * * @returns pointer to the string product descriptor */ virtual uint8_t * stringIproductDesc(); - + /* * Get string serial descriptor * * @returns pointer to the string serial descriptor */ virtual uint8_t * stringIserialDesc(); - + /* * Get string configuration descriptor * * @returns pointer to the string configuration descriptor */ virtual uint8_t * stringIConfigurationDesc(); - + /* * Get string interface descriptor * * @returns pointer to the string interface descriptor */ virtual uint8_t * stringIinterfaceDesc(); - + /* * Get the length of the report descriptor * * @returns length of the report descriptor */ virtual uint16_t reportDescLength() { return 0; }; - + protected: @@ -238,7 +238,7 @@ protected: virtual void suspendStateChanged(unsigned int suspended); uint8_t * findDescriptor(uint8_t descriptorType); CONTROL_TRANSFER * getTransferPtr(void); - + uint16_t VENDOR_ID; uint16_t PRODUCT_ID; uint16_t PRODUCT_RELEASE; @@ -262,7 +262,7 @@ private: CONTROL_TRANSFER transfer; USB_DEVICE device; - + uint16_t currentInterface; uint8_t currentAlternate; }; diff --git a/libraries/USBDevice/USBDevice/USBEndpoints.h b/libraries/USBDevice/USBDevice/USBEndpoints.h index cdba1322cf..fb9af13d70 100644 --- a/libraries/USBDevice/USBDevice/USBEndpoints.h +++ b/libraries/USBDevice/USBDevice/USBEndpoints.h @@ -39,7 +39,7 @@ typedef enum { /* Include configuration for specific target */ #if defined(TARGET_LPC1768) || defined(TARGET_LPC2368) || defined(TARGET_LPC4088) #include "USBEndpoints_LPC17_LPC23.h" -#elif defined(TARGET_LPC11UXX) || defined(TARGET_LPC1347) +#elif defined(TARGET_LPC11UXX) || defined(TARGET_LPC1347) || defined (TARGET_LPC11U6X) #include "USBEndpoints_LPC11U.h" #elif defined(TARGET_KL25Z) | defined(TARGET_KL46Z) | defined(TARGET_K20D5M) | defined(TARGET_K64F) #include "USBEndpoints_KL25Z.h" diff --git a/libraries/USBDevice/USBDevice/USBEndpoints_KL25Z.h b/libraries/USBDevice/USBDevice/USBEndpoints_KL25Z.h index 957e02d834..5cb3f7b395 100644 --- a/libraries/USBDevice/USBDevice/USBEndpoints_KL25Z.h +++ b/libraries/USBDevice/USBDevice/USBEndpoints_KL25Z.h @@ -23,38 +23,38 @@ /* Endpoint No. */ /* ---------------- */ -#define EP0OUT (0) -#define EP0IN (1) -#define EP1OUT (2) -#define EP1IN (3) -#define EP2OUT (4) -#define EP2IN (5) -#define EP3OUT (6) -#define EP3IN (7) -#define EP4OUT (8) -#define EP4IN (9) -#define EP5OUT (10) -#define EP5IN (11) -#define EP6OUT (12) -#define EP6IN (13) -#define EP7OUT (14) -#define EP7IN (15) -#define EP8OUT (16) -#define EP8IN (17) -#define EP9OUT (18) -#define EP9IN (19) -#define EP10OUT (20) -#define EP10IN (21) -#define EP11OUT (22) -#define EP11IN (23) -#define EP12OUT (24) -#define EP12IN (25) -#define EP13OUT (26) -#define EP13IN (27) -#define EP14OUT (28) -#define EP14IN (29) -#define EP15OUT (30) -#define EP15IN (31) +#define EP0OUT (0) +#define EP0IN (1) +#define EP1OUT (2) +#define EP1IN (3) +#define EP2OUT (4) +#define EP2IN (5) +#define EP3OUT (6) +#define EP3IN (7) +#define EP4OUT (8) +#define EP4IN (9) +#define EP5OUT (10) +#define EP5IN (11) +#define EP6OUT (12) +#define EP6IN (13) +#define EP7OUT (14) +#define EP7IN (15) +#define EP8OUT (16) +#define EP8IN (17) +#define EP9OUT (18) +#define EP9IN (19) +#define EP10OUT (20) +#define EP10IN (21) +#define EP11OUT (22) +#define EP11IN (23) +#define EP12OUT (24) +#define EP12IN (25) +#define EP13OUT (26) +#define EP13IN (27) +#define EP14OUT (28) +#define EP14IN (29) +#define EP15OUT (30) +#define EP15IN (31) /* Maximum Packet sizes */ diff --git a/libraries/USBDevice/USBDevice/USBHAL.h b/libraries/USBDevice/USBDevice/USBHAL.h index 29516e6e40..eafa008409 100644 --- a/libraries/USBDevice/USBDevice/USBHAL.h +++ b/libraries/USBDevice/USBDevice/USBHAL.h @@ -58,7 +58,7 @@ public: bool realiseEndpoint(uint8_t endpoint, uint32_t maxPacket, uint32_t options); bool getEndpointStallState(unsigned char endpoint); uint32_t endpointReadcore(uint8_t endpoint, uint8_t *buffer); - + protected: virtual void busReset(void){}; virtual void EP0setupCallback(void){}; @@ -67,7 +67,7 @@ protected: virtual void connectStateChanged(unsigned int connected){}; virtual void suspendStateChanged(unsigned int suspended){}; virtual void SOF(int frameNumber){}; - + virtual bool EP1_OUT_callback(){return false;}; virtual bool EP1_IN_callback(){return false;}; virtual bool EP2_OUT_callback(){return false;}; @@ -102,7 +102,7 @@ protected: virtual bool EP15_IN_callback(){return false;}; #endif #endif - + private: void usbisr(void); static void _usbisr(void); @@ -116,6 +116,6 @@ private: bool (USBHAL::*epCallback[32 - 2])(void); #endif - + }; #endif diff --git a/libraries/USBDevice/USBDevice/USBHAL_LPC11U.cpp b/libraries/USBDevice/USBDevice/USBHAL_LPC11U.cpp index 07be6e3cc4..a35c09ccaf 100644 --- a/libraries/USBDevice/USBDevice/USBHAL_LPC11U.cpp +++ b/libraries/USBDevice/USBDevice/USBHAL_LPC11U.cpp @@ -16,11 +16,11 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -#if defined(TARGET_LPC11U24) || defined(TARGET_LPC11U35_401) || defined(TARGET_LPC1347) +#if defined(TARGET_LPC11U24) || defined(TARGET_LPC11U35_401) || defined(TARGET_LPC1347) || defined(TARGET_LPC11U35_501) || defined(TARGET_LPC11U68) #if defined(TARGET_LPC1347) #define USB_IRQ USB_IRQ_IRQn -#elif defined(TARGET_LPC11U24) || defined(TARGET_LPC11U35_401) +#elif defined(TARGET_LPC11U24) || defined(TARGET_LPC11U35_401) || defined(TARGET_LPC11U35_501) || defined(TARGET_LPC11U68) #define USB_IRQ USB_IRQn #endif @@ -134,7 +134,7 @@ void USBMemCopy(uint8_t *dst, uint8_t *src, uint32_t size) { USBHAL::USBHAL(void) { NVIC_DisableIRQ(USB_IRQ); - + // fill in callback array epCallback[0] = &USBHAL::EP1_OUT_callback; epCallback[1] = &USBHAL::EP1_IN_callback; @@ -145,11 +145,11 @@ USBHAL::USBHAL(void) { epCallback[6] = &USBHAL::EP4_OUT_callback; epCallback[7] = &USBHAL::EP4_IN_callback; - #if defined(TARGET_LPC11U35_401) + #if defined(TARGET_LPC11U35_401) || defined(TARGET_LPC11U35_501) // USB_VBUS input with pull-down LPC_IOCON->PIO0_3 = 0x00000009; #endif - + // nUSB_CONNECT output LPC_IOCON->PIO0_6 = 0x00000001; @@ -287,13 +287,13 @@ EP_STATUS USBHAL::endpointRead(uint8_t endpoint, uint32_t maximumSize) { bf = 0; } } - + // if isochronous endpoint, T = 1 if(endpointState[endpoint].options & ISOCHRONOUS) { flags |= CMDSTS_T; } - + //Active the endpoint for reading ep[PHY_TO_LOG(endpoint)].out[bf] = CMDSTS_A | CMDSTS_NBYTES(maximumSize) \ | CMDSTS_ADDRESS_OFFSET((uint32_t)ct->out) | flags; @@ -408,7 +408,7 @@ EP_STATUS USBHAL::endpointWrite(uint8_t endpoint, uint8_t *data, uint32_t size) EP_STATUS USBHAL::endpointWriteResult(uint8_t endpoint) { uint32_t bf; - + // Validate parameters if (endpoint > LAST_PHYSICAL_ENDPOINT) { return EP_INVALID; @@ -680,7 +680,7 @@ void USBHAL::usbisr(void) { // EP0IN ACK event (IN data sent) EP0in(); } - + for (uint8_t num = 2; num < 5*2; num++) { if (LPC_USB->INTSTAT & EP(num)) { LPC_USB->INTSTAT = EP(num); diff --git a/libraries/USBDevice/USBDevice/USBHAL_LPC17.cpp b/libraries/USBDevice/USBDevice/USBHAL_LPC17.cpp index 2786fccafe..8bffe10ace 100644 --- a/libraries/USBDevice/USBDevice/USBHAL_LPC17.cpp +++ b/libraries/USBDevice/USBDevice/USBHAL_LPC17.cpp @@ -279,7 +279,7 @@ uint32_t USBHAL::endpointReadcore(uint8_t endpoint, uint8_t *buffer) { SIEselectEndpoint(endpoint); SIEclearBuffer(); } - + return size; } @@ -327,7 +327,7 @@ static void endpointWritecore(uint8_t endpoint, uint8_t *buffer, uint32_t size) USBHAL::USBHAL(void) { // Disable IRQ NVIC_DisableIRQ(USB_IRQn); - + // fill in callback array epCallback[0] = &USBHAL::EP1_OUT_callback; epCallback[1] = &USBHAL::EP1_IN_callback; @@ -466,7 +466,7 @@ EP_STATUS USBHAL::endpointReadResult(uint8_t endpoint, uint8_t * buffer, uint32_ if (!(epComplete & EP(endpoint))) return EP_PENDING; } - + *bytesRead = endpointReadcore(endpoint, buffer); epComplete &= ~EP(endpoint); return EP_COMPLETED; @@ -606,7 +606,7 @@ void USBHAL::usbisr(void) { LPC_USB->USBDevIntClr = EP_SLOW; EP0in(); } - + for (uint8_t num = 2; num < 16*2; num++) { if (LPC_USB->USBEpIntSt & EP(num)) { selectEndpointClearInterrupt(num); diff --git a/libraries/USBDevice/USBDevice/USBHAL_LPC40.cpp b/libraries/USBDevice/USBDevice/USBHAL_LPC40.cpp index f2643afa37..108f402e9c 100644 --- a/libraries/USBDevice/USBDevice/USBHAL_LPC40.cpp +++ b/libraries/USBDevice/USBDevice/USBHAL_LPC40.cpp @@ -280,7 +280,7 @@ uint32_t USBHAL::endpointReadcore(uint8_t endpoint, uint8_t *buffer) { SIEselectEndpoint(endpoint); SIEclearBuffer(); } - + return size; } @@ -328,7 +328,7 @@ static void endpointWritecore(uint8_t endpoint, uint8_t *buffer, uint32_t size) USBHAL::USBHAL(void) { // Disable IRQ NVIC_DisableIRQ(USB_IRQn); - + // fill in callback array epCallback[0] = &USBHAL::EP1_OUT_callback; epCallback[1] = &USBHAL::EP1_IN_callback; @@ -367,7 +367,7 @@ USBHAL::USBHAL(void) { // Enable USB clocks LPC_USB->USBClkCtrl |= DEV_CLK_EN | AHB_CLK_EN | PORT_CLK_EN; while ((LPC_USB->USBClkSt & (DEV_CLK_EN | AHB_CLK_EN | PORT_CLK_EN)) != (DEV_CLK_ON | AHB_CLK_ON | PORT_CLK_EN)); - + // Select port USB2 LPC_USB->StCtrl |= 3; @@ -375,13 +375,13 @@ USBHAL::USBHAL(void) { // Configure pin P0.31 to be USB2 LPC_IOCON->P0_31 &= ~0x07; LPC_IOCON->P0_31 |= 0x01; - + // Disconnect USB device SIEdisconnect(); // Configure pin P0.14 to be Connect LPC_IOCON->P0_14 &= ~0x07; - LPC_IOCON->P0_14 |= 0x03; + LPC_IOCON->P0_14 |= 0x03; // Connect must be low for at least 2.5uS wait(0.3); @@ -471,7 +471,7 @@ EP_STATUS USBHAL::endpointReadResult(uint8_t endpoint, uint8_t * buffer, uint32_ if (!(epComplete & EP(endpoint))) return EP_PENDING; } - + *bytesRead = endpointReadcore(endpoint, buffer); epComplete &= ~EP(endpoint); return EP_COMPLETED; @@ -611,7 +611,7 @@ void USBHAL::usbisr(void) { LPC_USB->DevIntClr = EP_SLOW; EP0in(); } - + for (uint8_t num = 2; num < 16*2; num++) { if (LPC_USB->EpIntSt & EP(num)) { selectEndpointClearInterrupt(num); diff --git a/libraries/USBDevice/USBDevice/USBHAL_STM32F4.cpp b/libraries/USBDevice/USBDevice/USBHAL_STM32F4.cpp index af1c3c3107..5826b39f24 100644 --- a/libraries/USBDevice/USBDevice/USBHAL_STM32F4.cpp +++ b/libraries/USBDevice/USBDevice/USBHAL_STM32F4.cpp @@ -36,7 +36,7 @@ uint32_t USBHAL::endpointReadcore(uint8_t endpoint, uint8_t *buffer) { return 0; } -USBHAL::USBHAL(void) { +USBHAL::USBHAL(void) { NVIC_DisableIRQ(OTG_FS_IRQn); epCallback[0] = &USBHAL::EP1_OUT_callback; epCallback[1] = &USBHAL::EP1_IN_callback; @@ -63,7 +63,7 @@ USBHAL::USBHAL(void) { pin_mode(PA_9, OpenDrain); RCC->AHB2ENR |= RCC_AHB2ENR_OTGFSEN; - + // Enable interrupts OTG_FS->GREGS.GAHBCFG |= (1 << 0); @@ -116,21 +116,21 @@ bool USBHAL::realiseEndpoint(uint8_t endpoint, uint32_t maxPacket, uint32_t type; switch (endpoint) { - case EP0IN: + case EP0IN: case EP0OUT: type = 0; - break; + break; case EPISO_IN: case EPISO_OUT: - type = 1; + type = 1; case EPBULK_IN: case EPBULK_OUT: - type = 2; - break; + type = 2; + break; case EPINT_IN: case EPINT_OUT: - type = 3; - break; + type = 3; + break; } // Generic in or out EP controls @@ -154,7 +154,7 @@ bool USBHAL::realiseEndpoint(uint8_t endpoint, uint32_t maxPacket, if (endpoint != EP0IN) { control |= (1 << 28); // SD0PID } - + control |= (epIndex << 22) | // TxFIFO index (1 << 27); // SNAK OTG_FS->INEP_REGS[epIndex].DIEPCTL = control; @@ -166,7 +166,7 @@ bool USBHAL::realiseEndpoint(uint8_t endpoint, uint32_t maxPacket, // Set the out EP specific control settings control |= (1 << 26); // CNAK OTG_FS->OUTEP_REGS[epIndex].DOEPCTL = control; - + // Unmask the interrupt OTG_FS->DREGS.DAINTMSK |= (1 << (epIndex + 16)); } @@ -190,7 +190,7 @@ uint32_t USBHAL::EP0getReadResult(uint8_t *buffer) { for (uint32_t i = 0; i < length; i += 4) { buffer32[i >> 2] = OTG_FS->FIFO[0][0]; } - + rxFifoCount = 0; return length; } @@ -266,7 +266,7 @@ EP_STATUS USBHAL::endpointWriteResult(uint8_t endpoint) { return EP_COMPLETED; } - return EP_PENDING; + return EP_PENDING; } void USBHAL::stallEndpoint(uint8_t endpoint) { @@ -282,7 +282,7 @@ void USBHAL::stallEndpoint(uint8_t endpoint) { } void USBHAL::unstallEndpoint(uint8_t endpoint) { - + } bool USBHAL::getEndpointStallState(uint8_t endpoint) { diff --git a/libraries/USBDevice/USBDevice/USBRegs_STM32.h b/libraries/USBDevice/USBDevice/USBRegs_STM32.h index 303338cc92..3e11a49c15 100644 --- a/libraries/USBDevice/USBDevice/USBRegs_STM32.h +++ b/libraries/USBDevice/USBDevice/USBRegs_STM32.h @@ -16,8 +16,8 @@ * * http://www.st.com/software_license_agreement_liberty_v2 * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. @@ -70,7 +70,7 @@ typedef struct // 800h } USB_OTG_DREGS; -typedef struct +typedef struct { __IO uint32_t DIEPCTL; /* dev IN Endpoint Control Reg 900h + (ep_num * 20h) + 00h*/ uint32_t Reserved04; /* Reserved 900h + (ep_num * 20h) + 04h*/ @@ -83,7 +83,7 @@ typedef struct } USB_OTG_INEPREGS; -typedef struct +typedef struct { __IO uint32_t DOEPCTL; /* dev OUT Endpoint Control Reg B00h + (ep_num * 20h) + 00h*/ uint32_t Reserved04; /* Reserved B00h + (ep_num * 20h) + 04h*/ @@ -117,7 +117,7 @@ typedef struct } USB_OTG_HC_REGS; -typedef struct +typedef struct { USB_OTG_GREGS GREGS; uint32_t RESERVED0[188]; diff --git a/libraries/USBDevice/USBHID/USBHID.cpp b/libraries/USBDevice/USBHID/USBHID.cpp index 0014a5db7c..571421d823 100644 --- a/libraries/USBDevice/USBHID/USBHID.cpp +++ b/libraries/USBDevice/USBHID/USBHID.cpp @@ -121,7 +121,7 @@ bool USBHID::USBCallback_request() { success = true; } break; - + default: break; } diff --git a/libraries/USBDevice/USBHID/USBHID.h b/libraries/USBDevice/USBHID/USBHID.h index 16e20073b4..faa75cb94a 100644 --- a/libraries/USBDevice/USBHID/USBHID.h +++ b/libraries/USBDevice/USBHID/USBHID.h @@ -70,8 +70,8 @@ public: * @returns true if successful */ bool send(HID_REPORT *report); - - + + /** * Send a Report. warning: non blocking * @@ -79,7 +79,7 @@ public: * @returns true if successful */ bool sendNB(HID_REPORT *report); - + /** * Read a report: blocking * @@ -87,7 +87,7 @@ public: * @returns true if successful */ bool read(HID_REPORT * report); - + /** * Read a report: non blocking * @@ -98,7 +98,7 @@ public: protected: uint16_t reportLength; - + /* * Get the Report descriptor * @@ -119,14 +119,14 @@ protected: * @returns pointer to the string product descriptor */ virtual uint8_t * stringIproductDesc(); - + /* * Get string interface descriptor * * @returns pointer to the string interface descriptor */ virtual uint8_t * stringIinterfaceDesc(); - + /* * Get configuration descriptor * diff --git a/libraries/USBDevice/USBHID/USBKeyboard.cpp b/libraries/USBDevice/USBHID/USBKeyboard.cpp index b82b69b43e..81857095bc 100644 --- a/libraries/USBDevice/USBHID/USBKeyboard.cpp +++ b/libraries/USBDevice/USBHID/USBKeyboard.cpp @@ -183,7 +183,7 @@ const KEYMAP keymap[KEYMAP_SIZE] = { {0x4a, 0}, /* HOME */ {0x4b, 0}, /* PAGE_UP */ {0x4e, 0}, /* PAGE_DOWN */ - + {0x4f, 0}, /* RIGHT_ARROW */ {0x50, 0}, /* LEFT_ARROW */ {0x51, 0}, /* DOWN_ARROW */ @@ -344,7 +344,7 @@ const KEYMAP keymap[KEYMAP_SIZE] = { {0x4a, 0}, /* HOME */ {0x4b, 0}, /* PAGE_UP */ {0x4e, 0}, /* PAGE_DOWN */ - + {0x4f, 0}, /* RIGHT_ARROW */ {0x50, 0}, /* LEFT_ARROW */ {0x51, 0}, /* DOWN_ARROW */ @@ -424,10 +424,10 @@ bool USBKeyboard::EP1_OUT_callback() { uint32_t bytesRead = 0; uint8_t led[65]; USBDevice::readEP(EPINT_OUT, led, &bytesRead, MAX_HID_REPORT_SIZE); - + // we take led[1] because led[0] is the report ID lock_status = led[1] & 0x07; - + // We activate the endpoint to be able to recceive data if (!readStart(EPINT_OUT, MAX_HID_REPORT_SIZE)) return false; diff --git a/libraries/USBDevice/USBHID/USBKeyboard.h b/libraries/USBDevice/USBHID/USBKeyboard.h index 92bcbe3c57..c9e08b16bc 100644 --- a/libraries/USBDevice/USBHID/USBKeyboard.h +++ b/libraries/USBDevice/USBHID/USBKeyboard.h @@ -53,7 +53,7 @@ enum FUNCTION_KEY { KEY_F10, /* F10 key */ KEY_F11, /* F11 key */ KEY_F12, /* F12 key */ - + KEY_PRINT_SCREEN, /* Print Screen key */ KEY_SCROLL_LOCK, /* Scroll lock */ KEY_CAPS_LOCK, /* caps lock */ @@ -62,7 +62,7 @@ enum FUNCTION_KEY { KEY_HOME, /* Home key */ KEY_PAGE_UP, /* Page Up key */ KEY_PAGE_DOWN, /* Page Down key */ - + RIGHT_ARROW, /* Right arrow */ LEFT_ARROW, /* Left arrow */ DOWN_ARROW, /* Down arrow */ diff --git a/libraries/USBDevice/USBHID/USBMouse.h b/libraries/USBDevice/USBHID/USBMouse.h index 4b0b735af3..7aa4263343 100644 --- a/libraries/USBDevice/USBHID/USBMouse.h +++ b/libraries/USBDevice/USBHID/USBMouse.h @@ -35,7 +35,7 @@ enum MOUSE_BUTTON /* X and Y limits */ /* These values do not directly map to screen pixels */ /* Zero may be interpreted as meaning 'no movement' */ -#define X_MIN_ABS (1) /*!< Minimum value on x-axis */ +#define X_MIN_ABS (1) /*!< Minimum value on x-axis */ #define Y_MIN_ABS (1) /*!< Minimum value on y-axis */ #define X_MAX_ABS (0x7fff) /*!< Maximum value on x-axis */ #define Y_MAX_ABS (0x7fff) /*!< Maximum value on y-axis */ @@ -85,7 +85,7 @@ enum MOUSE_TYPE * uint16_t y_center = (Y_MAX_ABS - Y_MIN_ABS)/2; * uint16_t x_screen = 0; * uint16_t y_screen = 0; - * + * * uint32_t x_origin = x_center; * uint32_t y_origin = y_center; * uint32_t radius = 5000; @@ -95,7 +95,7 @@ enum MOUSE_TYPE * { * x_screen = x_origin + cos((double)angle*3.14/180.0)*radius; * y_screen = y_origin + sin((double)angle*3.14/180.0)*radius; - * + * * mouse.move(x_screen, y_screen); * angle += 3; * wait(0.01); @@ -107,7 +107,7 @@ enum MOUSE_TYPE class USBMouse: public USBHID { public: - + /** * Constructor * @@ -117,14 +117,14 @@ class USBMouse: public USBHID * @param product_release Your preoduct_release (default: 0x0001) * */ - USBMouse(MOUSE_TYPE mouse_type = REL_MOUSE, uint16_t vendor_id = 0x1234, uint16_t product_id = 0x0001, uint16_t product_release = 0x0001): + USBMouse(MOUSE_TYPE mouse_type = REL_MOUSE, uint16_t vendor_id = 0x1234, uint16_t product_id = 0x0001, uint16_t product_release = 0x0001): USBHID(0, 0, vendor_id, product_id, product_release, false) - { + { button = 0; this->mouse_type = mouse_type; connect(); }; - + /** * Write a state of the mouse * @@ -135,8 +135,8 @@ class USBMouse: public USBHID * @returns true if there is no error, false otherwise */ bool update(int16_t x, int16_t y, uint8_t buttons, int8_t z); - - + + /** * Move the cursor to (x, y) * @@ -145,7 +145,7 @@ class USBMouse: public USBHID * @returns true if there is no error, false otherwise */ bool move(int16_t x, int16_t y); - + /** * Press one or several buttons * @@ -153,7 +153,7 @@ class USBMouse: public USBHID * @returns true if there is no error, false otherwise */ bool press(uint8_t button); - + /** * Release one or several buttons * @@ -161,22 +161,22 @@ class USBMouse: public USBHID * @returns true if there is no error, false otherwise */ bool release(uint8_t button); - + /** * Double click (MOUSE_LEFT) * * @returns true if there is no error, false otherwise */ bool doubleClick(); - + /** * Click * * @param button state of the buttons ( ex: clic(MOUSE_LEFT)) * @returns true if there is no error, false otherwise */ - bool click(uint8_t button); - + bool click(uint8_t button); + /** * Scrolling * @@ -184,7 +184,7 @@ class USBMouse: public USBHID * @returns true if there is no error, false otherwise */ bool scroll(int8_t z); - + /* * To define the report descriptor. Warning: this method has to store the length of the report descriptor in reportLength. * @@ -199,7 +199,7 @@ class USBMouse: public USBHID * @returns pointer to the configuration descriptor */ virtual uint8_t * configurationDesc(); - + private: MOUSE_TYPE mouse_type; uint8_t button; diff --git a/libraries/USBDevice/USBHID/USBMouseKeyboard.cpp b/libraries/USBDevice/USBHID/USBMouseKeyboard.cpp index b6cb28769c..848d81a686 100644 --- a/libraries/USBDevice/USBHID/USBMouseKeyboard.cpp +++ b/libraries/USBDevice/USBHID/USBMouseKeyboard.cpp @@ -178,7 +178,7 @@ const KEYMAP keymap[KEYMAP_SIZE] = { {0x4a, 0}, /* HOME */ {0x4b, 0}, /* PAGE_UP */ {0x4e, 0}, /* PAGE_DOWN */ - + {0x4f, 0}, /* RIGHT_ARROW */ {0x50, 0}, /* LEFT_ARROW */ {0x51, 0}, /* DOWN_ARROW */ @@ -339,7 +339,7 @@ const KEYMAP keymap[KEYMAP_SIZE] = { {0x4a, 0}, /* HOME */ {0x4b, 0}, /* PAGE_UP */ {0x4e, 0}, /* PAGE_DOWN */ - + {0x4f, 0}, /* RIGHT_ARROW */ {0x50, 0}, /* LEFT_ARROW */ {0x51, 0}, /* DOWN_ARROW */ @@ -552,10 +552,10 @@ bool USBMouseKeyboard::EP1_OUT_callback() { uint32_t bytesRead = 0; uint8_t led[65]; USBDevice::readEP(EPINT_OUT, led, &bytesRead, MAX_HID_REPORT_SIZE); - + // we take led[1] because led[0] is the report ID lock_status = led[1] & 0x07; - + // We activate the endpoint to be able to recceive data if (!readStart(EPINT_OUT, MAX_HID_REPORT_SIZE)) return false; @@ -696,7 +696,7 @@ bool USBMouseKeyboard::mediaControl(MEDIA_KEY key) { report.length = 2; send(&report); - + report.data[0] = REPORT_ID_VOLUME; report.data[1] = 0; diff --git a/libraries/USBDevice/USBHID/USBMouseKeyboard.h b/libraries/USBDevice/USBHID/USBMouseKeyboard.h index ae729d9abf..7eaa355e37 100644 --- a/libraries/USBDevice/USBHID/USBMouseKeyboard.h +++ b/libraries/USBDevice/USBHID/USBMouseKeyboard.h @@ -28,7 +28,7 @@ #include "Stream.h" #include "USBHID.h" -/** +/** * USBMouseKeyboard example * @code * @@ -70,7 +70,7 @@ class USBMouseKeyboard: public USBHID, public Stream { public: - + /** * Constructor * @@ -81,7 +81,7 @@ class USBMouseKeyboard: public USBHID, public Stream * @param product_release Your preoduct_release (default: 0x0001) * */ - USBMouseKeyboard(MOUSE_TYPE mouse_type = REL_MOUSE, uint16_t vendor_id = 0x0021, uint16_t product_id = 0x0011, uint16_t product_release = 0x0001): + USBMouseKeyboard(MOUSE_TYPE mouse_type = REL_MOUSE, uint16_t vendor_id = 0x0021, uint16_t product_id = 0x0011, uint16_t product_release = 0x0001): USBHID(0, 0, vendor_id, product_id, product_release, false) { lock_status = 0; @@ -89,7 +89,7 @@ class USBMouseKeyboard: public USBHID, public Stream this->mouse_type = mouse_type; connect(); }; - + /** * Write a state of the mouse * @@ -100,8 +100,8 @@ class USBMouseKeyboard: public USBHID, public Stream * @returns true if there is no error, false otherwise */ bool update(int16_t x, int16_t y, uint8_t buttons, int8_t z); - - + + /** * Move the cursor to (x, y) * @@ -110,7 +110,7 @@ class USBMouseKeyboard: public USBHID, public Stream * @returns true if there is no error, false otherwise */ bool move(int16_t x, int16_t y); - + /** * Press one or several buttons * @@ -118,7 +118,7 @@ class USBMouseKeyboard: public USBHID, public Stream * @returns true if there is no error, false otherwise */ bool press(uint8_t button); - + /** * Release one or several buttons * @@ -126,22 +126,22 @@ class USBMouseKeyboard: public USBHID, public Stream * @returns true if there is no error, false otherwise */ bool release(uint8_t button); - + /** * Double click (MOUSE_LEFT) * * @returns true if there is no error, false otherwise */ bool doubleClick(); - + /** * Click * * @param button state of the buttons ( ex: clic(MOUSE_LEFT)) * @returns true if there is no error, false otherwise */ - bool click(uint8_t button); - + bool click(uint8_t button); + /** * Scrolling * @@ -151,7 +151,7 @@ class USBMouseKeyboard: public USBHID, public Stream bool scroll(int8_t z); /** - * To send a character defined by a modifier(CTRL, SHIFT, ALT) and the key + * To send a character defined by a modifier(CTRL, SHIFT, ALT) and the key * * @code * //To send CTRL + s (save) @@ -163,7 +163,7 @@ class USBMouseKeyboard: public USBHID, public Stream * @returns true if there is no error, false otherwise */ bool keyCode(uint8_t key, uint8_t modifier = 0); - + /** * Send a character * @@ -171,7 +171,7 @@ class USBMouseKeyboard: public USBHID, public Stream * @returns true if there is no error, false otherwise */ virtual int _putc(int c); - + /** * Control media keys * @@ -179,7 +179,7 @@ class USBMouseKeyboard: public USBHID, public Stream * @returns true if there is no error, false otherwise */ bool mediaControl(MEDIA_KEY key); - + /** * Read status of lock keys. Useful to switch-on/off leds according to key pressed. Only the first three bits of the result is important: * - First bit: NUM_LOCK @@ -189,30 +189,30 @@ class USBMouseKeyboard: public USBHID, public Stream * @returns status of lock keys */ uint8_t lockStatus(); - + /* * To define the report descriptor. Warning: this method has to store the length of the report descriptor in reportLength. * * @returns pointer to the report descriptor */ virtual uint8_t * reportDesc(); - + /* * Called when a data is received on the OUT endpoint. Useful to switch on LED of LOCK keys * * @returns if handle by subclass, return true */ virtual bool EP1_OUT_callback(); - - + + private: bool mouseWrite(int8_t x, int8_t y, uint8_t buttons, int8_t z); MOUSE_TYPE mouse_type; uint8_t button; bool mouseSend(int8_t x, int8_t y, uint8_t buttons, int8_t z); - + uint8_t lock_status; - + //dummy otherwise it doesn't compile (we must define all methods of an abstract class) virtual int _getc() { return -1;} }; diff --git a/libraries/USBDevice/USBMIDI/MIDIMessage.h b/libraries/USBDevice/USBMIDI/MIDIMessage.h index cef7669457..90f695039a 100644 --- a/libraries/USBDevice/USBMIDI/MIDIMessage.h +++ b/libraries/USBDevice/USBMIDI/MIDIMessage.h @@ -22,7 +22,7 @@ #include "mbed.h" // MIDI Message Format -// +// // [ msg(4) | channel(4) ] [ 0 | n(7) ] [ 0 | m(7) ] // // MIDI Data Messages (Channel Specific) @@ -43,15 +43,15 @@ class MIDIMessage { public: MIDIMessage() {} - + MIDIMessage(uint8_t *buf) { for (int i = 0; i < 4; i++) data[i] = buf[i]; } - + // create messages - - /** Create a NoteOff message + + /** Create a NoteOff message * @param key Key ID * @param velocity Key velocity (0-127, default = 127) * @param channel Key channel (0-15, default 0) @@ -62,11 +62,11 @@ public: msg.data[0] = CABLE_NUM | 0x08; msg.data[1] = 0x80 | (channel & 0x0F); msg.data[2] = key & 0x7F; - msg.data[3] = velocity & 0x7F; + msg.data[3] = velocity & 0x7F; return msg; } - - /** Create a NoteOn message + + /** Create a NoteOn message * @param key Key ID * @param velocity Key velocity (0-127, default = 127) * @param channel Key channel (0-15, default 0) @@ -77,26 +77,26 @@ public: msg.data[0] = CABLE_NUM | 0x09; msg.data[1] = 0x90 | (channel & 0x0F); msg.data[2] = key & 0x7F; - msg.data[3] = velocity & 0x7F; + msg.data[3] = velocity & 0x7F; return msg; } - - /** Create a PolyPhonic Aftertouch message + + /** Create a PolyPhonic Aftertouch message * @param key Key ID * @param pressure Aftertouch pressure (0-127) * @param channel Key channel (0-15, default 0) * @returns A MIDIMessage - */ + */ static MIDIMessage PolyphonicAftertouch(int key, int pressure, int channel = 0) { MIDIMessage msg; msg.data[0] = CABLE_NUM | 0x0A; msg.data[1] = 0xA0 | (channel & 0x0F); msg.data[2] = key & 0x7F; - msg.data[3] = pressure & 0x7F; + msg.data[3] = pressure & 0x7F; return msg; } - - /** Create a Control Change message + + /** Create a Control Change message * @param control Controller ID * @param value Controller value (0-127) * @param channel Controller channel (0-15, default 0) @@ -107,63 +107,63 @@ public: msg.data[0] = CABLE_NUM | 0x0B; msg.data[1] = 0xB0 | (channel & 0x0F); msg.data[2] = control & 0x7F; - msg.data[3] = value & 0x7F; + msg.data[3] = value & 0x7F; return msg; } - - /** Create a Program Change message + + /** Create a Program Change message * @param program Program ID * @param channel Channel (0-15, default 0) * @returns A MIDIMessage - */ + */ static MIDIMessage ProgramChange(int program, int channel = 0) { MIDIMessage msg; msg.data[0] = CABLE_NUM | 0x0C; msg.data[1] = 0xC0 | (channel & 0x0F); msg.data[2] = program & 0x7F; - msg.data[3] = 0x00; + msg.data[3] = 0x00; return msg; } - - /** Create a Channel Aftertouch message - * @param pressure Pressure + + /** Create a Channel Aftertouch message + * @param pressure Pressure * @param channel Key channel (0-15, default 0) * @returns A MIDIMessage - */ + */ static MIDIMessage ChannelAftertouch(int pressure, int channel = 0) { MIDIMessage msg; msg.data[0] = CABLE_NUM | 0x0D; msg.data[1] = 0xD0 | (channel & 0x0F); msg.data[2] = pressure & 0x7F; - msg.data[3] = 0x00; + msg.data[3] = 0x00; return msg; } - - /** Create a Pitch Wheel message + + /** Create a Pitch Wheel message * @param pitch Pitch (-8192 - 8191, default = 0) * @param channel Channel (0-15, default 0) * @returns A MIDIMessage - */ + */ static MIDIMessage PitchWheel(int pitch = 0, int channel = 0) { MIDIMessage msg; int p = pitch + 8192; // 0 - 16383, 8192 is center msg.data[0] = CABLE_NUM | 0x0E; msg.data[1] = 0xE0 | (channel & 0x0F); msg.data[2] = p & 0x7F; - msg.data[3] = (p >> 7) & 0x7F; + msg.data[3] = (p >> 7) & 0x7F; return msg; } - - /** Create an All Notes Off message + + /** Create an All Notes Off message * @param channel Channel (0-15, default 0) * @returns A MIDIMessage - */ + */ static MIDIMessage AllNotesOff(int channel = 0) { return ControlChange(123, 0, channel); } - + // decode messages - + /** MIDI Message Types */ enum MIDIMessageType { ErrorType, @@ -176,16 +176,16 @@ public: PitchWheelType, AllNotesOffType }; - + /** Read the message type * @returns MIDIMessageType - */ + */ MIDIMessageType type() { switch((data[1] >> 4) & 0xF) { case 0x8: return NoteOffType; case 0x9: return NoteOnType; case 0xA: return PolyphonicAftertouchType; - case 0xB: + case 0xB: if(controller() < 120) { // standard controllers return ControlChangeType; } else if(controller() == 123) { @@ -200,51 +200,51 @@ public: } } - /** Read the channel number */ + /** Read the channel number */ int channel() { return (data[1] & 0x0F); } - - /** Read the key ID */ + + /** Read the key ID */ int key() { - return (data[2] & 0x7F); - } - - /** Read the velocity */ - int velocity() { - return (data[3] & 0x7F); + return (data[2] & 0x7F); } - /** Read the controller value */ - int value() { - return (data[3] & 0x7F); + /** Read the velocity */ + int velocity() { + return (data[3] & 0x7F); } - - /** Read the aftertouch pressure */ + + /** Read the controller value */ + int value() { + return (data[3] & 0x7F); + } + + /** Read the aftertouch pressure */ int pressure() { if(type() == PolyphonicAftertouchType) { - return (data[3] & 0x7F); + return (data[3] & 0x7F); } else { - return (data[2] & 0x7F); + return (data[2] & 0x7F); } } - /** Read the controller number */ + /** Read the controller number */ int controller() { - return (data[2] & 0x7F); + return (data[2] & 0x7F); } - /** Read the program number */ + /** Read the program number */ int program() { - return (data[2] & 0x7F); + return (data[2] & 0x7F); } - - /** Read the pitch value */ + + /** Read the pitch value */ int pitch() { int p = ((data[3] & 0x7F) << 7) | (data[2] & 0x7F); return p - 8192; // 0 - 16383, 8192 is center } - + uint8_t data[4]; }; diff --git a/libraries/USBDevice/USBMIDI/USBMIDI.h b/libraries/USBDevice/USBMIDI/USBMIDI.h index 89f35abab0..fdf5d6d6bb 100644 --- a/libraries/USBDevice/USBMIDI/USBMIDI.h +++ b/libraries/USBDevice/USBMIDI/USBMIDI.h @@ -29,7 +29,7 @@ #define DEFAULT_CONFIGURATION (1) -/** +/** * USBMIDI example * * @code @@ -38,8 +38,8 @@ * * USBMIDI midi; * -* int main() { -* while (1) { +* int main() { +* while (1) { * for(int i=48; i<83; i++) { // send some messages! * midi.write(MIDIMessage::NoteOn(i)); * wait(0.25); @@ -61,12 +61,12 @@ public: * @param product_release Your preoduct_release */ USBMIDI(uint16_t vendor_id = 0x0700, uint16_t product_id = 0x0101, uint16_t product_release = 0x0001); - + /** * Send a MIDIMessage * * @param m The MIDIMessage to send - */ + */ void write(MIDIMessage m); /** @@ -75,8 +75,8 @@ public: * @param fptr function pointer */ void attach(void (*fptr)(MIDIMessage)); - - + + protected: virtual bool EP2_OUT_callback(); virtual bool USBCallback_setConfiguration(uint8_t configuration); @@ -86,14 +86,14 @@ protected: * @returns pointer to the string product descriptor */ virtual uint8_t * stringIproductDesc(); - + /* * Get string interface descriptor * * @returns pointer to the string interface descriptor */ virtual uint8_t * stringIinterfaceDesc(); - + /* * Get configuration descriptor * diff --git a/libraries/USBDevice/USBMSD/USBMSD.h b/libraries/USBDevice/USBMSD/USBMSD.h index 359ca7052f..b362f5618b 100644 --- a/libraries/USBDevice/USBMSD/USBMSD.h +++ b/libraries/USBDevice/USBMSD/USBMSD.h @@ -79,7 +79,7 @@ public: * Disconnect the USB MSD device. */ void disconnect(); - + /** * Destructor */ diff --git a/libraries/USBDevice/USBSerial/USBCDC.cpp b/libraries/USBDevice/USBSerial/USBCDC.cpp index 2b9027eb7e..12f84751fb 100644 --- a/libraries/USBDevice/USBSerial/USBCDC.cpp +++ b/libraries/USBDevice/USBSerial/USBCDC.cpp @@ -73,15 +73,15 @@ void USBCDC::USBCallback_requestCompleted(uint8_t *buf, uint32_t length) { if (length != 7) { return; } - + CONTROL_TRANSFER * transfer = getTransferPtr(); - + /* Process class-specific requests */ if (transfer->setup.bmRequestType.Type == CLASS_TYPE) { if (transfer->setup.bRequest == CDC_SET_LINE_CODING) { if (memcmp(cdc_line_coding, buf, 7)) { - memcpy(cdc_line_coding, buf, 7); - + memcpy(cdc_line_coding, buf, 7); + int baud = buf[0] + (buf[1] << 8) + (buf[2] << 16) + (buf[3] << 24); int stop = buf[4]; @@ -186,7 +186,7 @@ uint8_t * USBCDC::configurationDesc() { 0, // iConfiguration 0x80, // bmAttributes 50, // bMaxPower - + // IAD to associate the two CDC interfaces 0x08, // bLength 0x0b, // bDescriptorType diff --git a/libraries/USBDevice/USBSerial/USBCDC.h b/libraries/USBDevice/USBSerial/USBCDC.h index 7185ae611f..33c6b0a024 100644 --- a/libraries/USBDevice/USBSerial/USBCDC.h +++ b/libraries/USBDevice/USBSerial/USBCDC.h @@ -40,35 +40,35 @@ public: USBCDC(uint16_t vendor_id, uint16_t product_id, uint16_t product_release, bool connect_blocking); protected: - + /* * Get device descriptor. Warning: this method has to store the length of the report descriptor in reportLength. * * @returns pointer to the device descriptor */ virtual uint8_t * deviceDesc(); - + /* * Get string product descriptor * * @returns pointer to the string product descriptor */ virtual uint8_t * stringIproductDesc(); - + /* * Get string interface descriptor * * @returns pointer to the string interface descriptor */ virtual uint8_t * stringIinterfaceDesc(); - + /* * Get configuration descriptor * * @returns pointer to the configuration descriptor */ virtual uint8_t * configurationDesc(); - + /* * Send a buffer * @@ -78,7 +78,7 @@ protected: * @returns true if successful */ bool send(uint8_t * buffer, uint32_t size); - + /* * Read a buffer from a certain endpoint. Warning: blocking * @@ -89,7 +89,7 @@ protected: * @returns true if successful */ bool readEP(uint8_t * buffer, uint32_t * size); - + /* * Read a buffer from a certain endpoint. Warning: non blocking * @@ -111,7 +111,7 @@ protected: * @param stop The number of stop bits (1 or 2) */ virtual void lineCodingChanged(int baud, int bits, int parity, int stop) {}; - + protected: virtual bool USBCallback_request(); virtual void USBCallback_requestCompleted(uint8_t *buf, uint32_t length); diff --git a/libraries/USBDevice/USBSerial/USBSerial.h b/libraries/USBDevice/USBSerial/USBSerial.h index 887e75c7bd..d5e2ec71d1 100644 --- a/libraries/USBDevice/USBSerial/USBSerial.h +++ b/libraries/USBDevice/USBSerial/USBSerial.h @@ -68,20 +68,20 @@ public: * @returns true if there is no error, false otherwise */ virtual int _putc(int c); - + /** * Read a character: blocking * * @returns character read */ virtual int _getc(); - + /** * Check the number of bytes available. * * @returns the number of bytes available */ - uint8_t available(); + uint8_t available(); /** Determine if there is a character available to read * @@ -90,7 +90,7 @@ public: * 0 otherwise */ int readable() { return available() ? 1 : 0; } - + /** Determine if there is space available to write a character * * @returns @@ -98,9 +98,9 @@ public: * 0 otherwise */ int writeable() { return 1; } // always return 1, for write operation is blocking - + /** - * Write a block of data. + * Write a block of data. * * For more efficiency, a block of size 64 (maximum size of a bulk endpoint) has to be written. * @@ -112,7 +112,7 @@ public: bool writeBlock(uint8_t * buf, uint16_t size); /** - * Attach a member function to call when a packet is received. + * Attach a member function to call when a packet is received. * * @param tptr pointer to the object to call the member function on * @param mptr pointer to the member function to be called diff --git a/libraries/USBHost/USBHost/USBDeviceConnected.cpp b/libraries/USBHost/USBHost/USBDeviceConnected.cpp index dc08c84f4c..8314b3ef40 100644 --- a/libraries/USBHost/USBHost/USBDeviceConnected.cpp +++ b/libraries/USBHost/USBHost/USBDeviceConnected.cpp @@ -50,10 +50,10 @@ void USBDeviceConnected::init() { INTERFACE * USBDeviceConnected::getInterface(uint8_t index) { if (index >= MAX_INTF) return NULL; - + if (intf[index].in_use) return &intf[index]; - + return NULL; } diff --git a/libraries/USBHost/USBHost/USBDeviceConnected.h b/libraries/USBHost/USBHost/USBDeviceConnected.h index 6bc707ca7c..22a4c1d3e9 100644 --- a/libraries/USBHost/USBHost/USBDeviceConnected.h +++ b/libraries/USBHost/USBHost/USBDeviceConnected.h @@ -33,7 +33,7 @@ typedef struct { USBEndpoint * ep[MAX_ENDPOINT_PER_INTERFACE]; FunctionPointer detach; char name[10]; -} INTERFACE; +} INTERFACE; /** * USBDeviceConnected class @@ -157,7 +157,7 @@ public: inline USBHostHub * getHubParent() { return hub_parent; }; inline uint8_t getNbIntf() { return nb_interf; }; inline const char * getName(uint8_t intf_nb) { return intf[intf_nb].name; }; - + // in case this device is a hub USBHostHub * hub; diff --git a/libraries/USBHost/USBHost/USBEndpoint.cpp b/libraries/USBHost/USBHost/USBEndpoint.cpp index 888e1802f0..fc372232f3 100644 --- a/libraries/USBHost/USBHost/USBEndpoint.cpp +++ b/libraries/USBHost/USBHost/USBEndpoint.cpp @@ -29,7 +29,7 @@ void USBEndpoint::init(HCED * hced_, ENDPOINT_TYPE type_, ENDPOINT_DIRECTION dir memcpy((HCTD**)td_list, td_list_, sizeof(HCTD*)*2); //TODO: Maybe should add a param for td_list size... at least a define memset(td_list_[0], 0, sizeof(HCTD)); memset(td_list_[1], 0, sizeof(HCTD)); - + td_list[0]->ep = this; td_list[1]->ep = this; @@ -52,7 +52,7 @@ void USBEndpoint::init(HCED * hced_, ENDPOINT_TYPE type_, ENDPOINT_DIRECTION dir td_current = td_list[0]; td_next = td_list[1]; - + intf_nb = 0; state = USB_TYPE_IDLE; diff --git a/libraries/USBHost/USBHost/USBEndpoint.h b/libraries/USBHost/USBHost/USBEndpoint.h index 44a455678c..2ec90d729f 100644 --- a/libraries/USBHost/USBHost/USBEndpoint.h +++ b/libraries/USBHost/USBHost/USBEndpoint.h @@ -136,9 +136,9 @@ public: inline bool isSetup() { return setup; } inline USBEndpoint * nextEndpoint() { return (USBEndpoint*)nextEp; }; inline uint8_t getIntfNb() { return intf_nb; }; - + USBDeviceConnected * dev; - + Queue ep_queue; private: @@ -163,7 +163,7 @@ private: volatile HCTD * td_list[2]; volatile HCTD * td_current; volatile HCTD * td_next; - + uint8_t intf_nb; }; diff --git a/libraries/USBHost/USBHost/USBHALHost.cpp b/libraries/USBHost/USBHost/USBHALHost.cpp index a943218662..2d67798d04 100644 --- a/libraries/USBHost/USBHost/USBHALHost.cpp +++ b/libraries/USBHost/USBHost/USBHALHost.cpp @@ -57,7 +57,7 @@ USBHALHost::USBHALHost() { void USBHALHost::init() { NVIC_DisableIRQ(USB_IRQn); - + //Cut power LPC_SC->PCONP &= ~(1UL<<31); wait_ms(100); @@ -98,7 +98,7 @@ void USBHALHost::init() { // software reset LPC_USB->HcCommandStatus = OR_CMD_STATUS_HCR; - + // Write Fm Interval and Largest Data Packet Counter LPC_USB->HcFmInterval = DEFAULT_FMINTERVAL; LPC_USB->HcPeriodicStart = FI * 90 / 100; @@ -109,7 +109,7 @@ void USBHALHost::init() { LPC_USB->HcRhStatus = OR_RH_STATUS_LPSC; LPC_USB->HcHCCA = (uint32_t)(usb_hcca); - + // Clear Interrrupt Status LPC_USB->HcInterruptStatus |= LPC_USB->HcInterruptStatus; @@ -249,9 +249,9 @@ void USBHALHost::freeTD(volatile uint8_t * td) { void USBHALHost::resetRootHub() { // Initiate port reset LPC_USB->HcRhPortStatus1 = OR_RH_PORT_PRS; - + while (LPC_USB->HcRhPortStatus1 & OR_RH_PORT_PRS); - + // ...and clear port reset signal LPC_USB->HcRhPortStatus1 = OR_RH_PORT_PRSC; } @@ -266,11 +266,11 @@ void USBHALHost::_usbisr(void) { void USBHALHost::UsbIrqhandler() { if( LPC_USB->HcInterruptStatus & LPC_USB->HcInterruptEnable ) //Is there something to actually process? { - + uint32_t int_status = LPC_USB->HcInterruptStatus & LPC_USB->HcInterruptEnable; // Root hub status change interrupt - if (int_status & OR_INTR_STATUS_RHSC) { + if (int_status & OR_INTR_STATUS_RHSC) { if (LPC_USB->HcRhPortStatus1 & OR_RH_PORT_CSC) { if (LPC_USB->HcRhStatus & OR_RH_STATUS_DRWE) { // When DRWE is on, Connect Status Change @@ -278,27 +278,27 @@ void USBHALHost::UsbIrqhandler() { } else { //Root device connected - if (LPC_USB->HcRhPortStatus1 & OR_RH_PORT_CCS) { - + if (LPC_USB->HcRhPortStatus1 & OR_RH_PORT_CCS) { + // wait 150ms to avoid bounce wait_ms(150); - + //Hub 0 (root hub), Port 1 (count starts at 1), Low or High speed - deviceConnected(0, 1, LPC_USB->HcRhPortStatus1 & OR_RH_PORT_LSDA); - } - + deviceConnected(0, 1, LPC_USB->HcRhPortStatus1 & OR_RH_PORT_LSDA); + } + //Root device disconnected - else { - + else { + if (!(int_status & OR_INTR_STATUS_WDH)) { usb_hcca->DoneHead = 0; } - + // wait 200ms to avoid bounce wait_ms(200); - + deviceDisconnected(0, 1, NULL, usb_hcca->DoneHead & 0xFFFFFFFE); - + if (int_status & OR_INTR_STATUS_WDH) { usb_hcca->DoneHead = 0; LPC_USB->HcInterruptStatus = OR_INTR_STATUS_WDH; diff --git a/libraries/USBHost/USBHost/USBHALHost.h b/libraries/USBHost/USBHost/USBHALHost.h index 0095a8a869..e32969de36 100644 --- a/libraries/USBHost/USBHost/USBHALHost.h +++ b/libraries/USBHost/USBHost/USBHALHost.h @@ -33,61 +33,61 @@ protected: * init variables and memory where will be stored HCCA, ED and TD */ USBHALHost(); - + /** - * Initialize host controller. Enable USB interrupts. This part is not in the constructor because, + * Initialize host controller. Enable USB interrupts. This part is not in the constructor because, * this function calls a virtual method if a device is already connected */ void init(); - + /** * reset the root hub */ void resetRootHub(); - + /** * return the value contained in the control HEAD ED register * * @returns address of the control Head ED */ uint32_t controlHeadED(); - + /** * return the value contained in the bulk HEAD ED register * * @returns address of the bulk head ED */ uint32_t bulkHeadED(); - + /** * return the value of the head interrupt ED contained in the HCCA * * @returns address of the head interrupt ED contained in the HCCA */ uint32_t interruptHeadED(); - + /** * Update the head ED for control transfers */ void updateControlHeadED(uint32_t addr); - + /** * Update the head ED for bulk transfers */ void updateBulkHeadED(uint32_t addr); - + /** * Update the head ED for interrupt transfers */ void updateInterruptHeadED(uint32_t addr); - + /** * Enable List for the specified endpoint type * * @param type enable the list of ENDPOINT_TYPE type */ void enableList(ENDPOINT_TYPE type); - + /** * Disable List for the specified endpoint type * @@ -104,7 +104,7 @@ protected: * @param hub_parent reference to the hub where the device is connected (NULL if the hub parent is the root hub) */ virtual void deviceConnected(int hub, int port, bool lowSpeed, USBHostHub * hub_parent = NULL) = 0; - + /** * Virtual method called when a device has been disconnected * @@ -114,35 +114,35 @@ protected: * @param addr list of the TDs which have been completed to dequeue freed TDs */ virtual void deviceDisconnected(int hub, int port, USBHostHub * hub_parent, volatile uint32_t addr) = 0; - + /** * Virtual method called when a transfer has been completed * * @param addr list of the TDs which have been completed */ virtual void transferCompleted(volatile uint32_t addr) = 0; - + /** * Find a memory section for a new ED * * @returns the address of the new ED */ volatile uint8_t * getED(); - + /** * Find a memory section for a new TD * * @returns the address of the new TD */ volatile uint8_t * getTD(); - + /** * Release a previous memory section reserved for an ED * * @param ed address of the ED */ void freeED(volatile uint8_t * ed); - + /** * Release a previous memory section reserved for an TD * @@ -161,7 +161,7 @@ private: uint8_t volatile * usb_tdBuf; //4 bytes aligned static USBHALHost * instHost; - + bool volatile edBufAlloc[MAX_ENDPOINT]; bool volatile tdBufAlloc[MAX_TD]; }; diff --git a/libraries/USBHost/USBHost/USBHost.cpp b/libraries/USBHost/USBHost/USBHost.cpp index 9da1e8edfa..d05486db91 100644 --- a/libraries/USBHost/USBHost/USBHost.cpp +++ b/libraries/USBHost/USBHost/USBHost.cpp @@ -47,7 +47,7 @@ USBHost * USBHost::instHost = NULL; * - call the callback attached to the endpoint where the td is attached */ void USBHost::usb_process() { - + bool controlListState; bool bulkListState; bool interruptListState; @@ -60,29 +60,29 @@ void USBHost::usb_process() { #if DEBUG_TRANSFER uint8_t * buf_transfer; #endif - + #if MAX_HUB_NB uint8_t k; #endif - + while(1) { osEvent evt = mail_usb_event.get(); - + if (evt.status == osEventMail) { - + message_t * usb_msg = (message_t*)evt.value.p; - + switch (usb_msg->event_id) { - + // a new device has been connected case DEVICE_CONNECTED_EVENT: too_many_hub = false; buf[4] = 0; - + do { Lock lock(this); - + for (i = 0; i < MAX_DEVICE_CONNECTED; i++) { if (!deviceInUse[i]) { USB_DBG_EVENT("new device connected: %p\r\n", &devices[i]); @@ -92,68 +92,68 @@ void USBHost::usb_process() { break; } } - + if (i == MAX_DEVICE_CONNECTED) { USB_ERR("Too many device connected!!\r\n"); continue; } - + if (!controlEndpointAllocated) { control = newEndpoint(CONTROL_ENDPOINT, OUT, 0x08, 0x00); addEndpoint(NULL, 0, (USBEndpoint*)control); controlEndpointAllocated = true; } - + #if MAX_HUB_NB if (usb_msg->hub_parent) devices[i].setHubParent((USBHostHub *)(usb_msg->hub_parent)); #endif - + for (j = 0; j < timeout_set_addr; j++) { - + resetDevice(&devices[i]); - + // set size of control endpoint devices[i].setSizeControlEndpoint(8); - + devices[i].activeAddress(false); - + // get first 8 bit of device descriptor // and check if we deal with a hub USB_DBG("usb_thread read device descriptor on dev: %p\r\n", &devices[i]); res = getDeviceDescriptor(&devices[i], buf, 8); - + if (res != USB_TYPE_OK) { USB_ERR("usb_thread could not read dev descr"); continue; } - + // set size of control endpoint devices[i].setSizeControlEndpoint(buf[7]); - + // second step: set an address to the device res = setAddress(&devices[i], devices[i].getAddress()); - + if (res != USB_TYPE_OK) { USB_ERR("SET ADDR FAILED"); continue; } devices[i].activeAddress(true); USB_DBG("Address of %p: %d", &devices[i], devices[i].getAddress()); - + // try to read again the device descriptor to check if the device // answers to its new address res = getDeviceDescriptor(&devices[i], buf, 8); - + if (res == USB_TYPE_OK) { break; } - + Thread::wait(100); } - + USB_INFO("New device connected: %p [hub: %d - port: %d]", &devices[i], usb_msg->hub, usb_msg->port); - + #if MAX_HUB_NB if (buf[4] == HUB_CLASS) { for (k = 0; k < MAX_HUB_NB; k++) { @@ -169,49 +169,49 @@ void USBHost::usb_process() { break; } } - + if (k == MAX_HUB_NB) { USB_ERR("Too many hubs connected!!\r\n"); too_many_hub = true; } } - + if (usb_msg->hub_parent) ((USBHostHub *)(usb_msg->hub_parent))->deviceConnected(&devices[i]); #endif - + if ((i < MAX_DEVICE_CONNECTED) && !too_many_hub) { deviceInUse[i] = true; } - + } while(0); - + break; - + // a device has been disconnected case DEVICE_DISCONNECTED_EVENT: - + do { Lock lock(this); - + controlListState = disableList(CONTROL_ENDPOINT); bulkListState = disableList(BULK_ENDPOINT); interruptListState = disableList(INTERRUPT_ENDPOINT); - + idx = findDevice(usb_msg->hub, usb_msg->port, (USBHostHub *)(usb_msg->hub_parent)); if (idx != -1) { freeDevice((USBDeviceConnected*)&devices[idx]); } - + if (controlListState) enableList(CONTROL_ENDPOINT); if (bulkListState) enableList(BULK_ENDPOINT); if (interruptListState) enableList(INTERRUPT_ENDPOINT); - + } while(0); - + break; - + // a td has been processed // call callback on the ed associated to the td // we are not in ISR -> users can use printf in their callback method @@ -241,7 +241,7 @@ void USBHost::usb_process() { } break; } - + mail_usb_event.free(usb_msg); } } @@ -272,7 +272,7 @@ USBHost::USBHost() : usbThread(USBHost::usb_process_static, (void *)this, osPrio for (uint8_t j = 0; j < MAX_INTF; j++) deviceAttachedDriver[i][j] = false; } - + #if MAX_HUB_NB for (uint8_t i = 0; i < MAX_HUB_NB; i++) { hubs[i].setHost(this); @@ -313,7 +313,7 @@ void USBHost::transferCompleted(volatile uint32_t addr) tdList = (volatile HCTD*)td->nextTD; //Dequeue element now as it could be modified below if (td->ep != NULL) { USBEndpoint * ep = (USBEndpoint *)(td->ep); - + if (((HCTD *)td)->control >> 28) { state = ((HCTD *)td)->control >> 28; } else { @@ -321,9 +321,9 @@ void USBHost::transferCompleted(volatile uint32_t addr) ep->setLengthTransferred((uint32_t)td->currBufPtr - (uint32_t)ep->getBufStart()); state = 16 /*USB_TYPE_IDLE*/; } - + ep->unqueueTransfer(td); - + if (ep->getType() != CONTROL_ENDPOINT) { // callback on the processed td will be called from the usb_thread (not in ISR) message_t * usb_msg = mail_usb_event.alloc(); @@ -360,7 +360,7 @@ USBHost * USBHost::getHostInst() if (deviceInited[idx]) return; } - + message_t * usb_msg = mail_usb_event.alloc(); usb_msg->event_id = DEVICE_CONNECTED_EVENT; usb_msg->hub = hub; @@ -384,7 +384,7 @@ USBHost * USBHost::getHostInst() } else { return; } - + message_t * usb_msg = mail_usb_event.alloc(); usb_msg->event_id = DEVICE_DISCONNECTED_EVENT; usb_msg->hub = hub; @@ -397,7 +397,7 @@ void USBHost::freeDevice(USBDeviceConnected * dev) { USBEndpoint * ep = NULL; HCED * ed = NULL; - + #if MAX_HUB_NB if (dev->getClass() == HUB_CLASS) { if (dev->hub == NULL) { @@ -412,13 +412,13 @@ void USBHost::freeDevice(USBDeviceConnected * dev) } } } - + // notify hub parent that this device has been disconnected if (dev->getHubParent()) dev->getHubParent()->deviceDisconnected(dev); - + #endif - + int idx = findDevice(dev); if (idx != -1) { deviceInUse[idx] = false; @@ -481,7 +481,7 @@ void USBHost::unqueueEndpoint(USBEndpoint * ep) updateInterruptHeadED(0); headInterruptEndpoint = current->nextEndpoint(); } - + // modify tail switch (current->getType()) { case BULK_ENDPOINT: @@ -553,7 +553,7 @@ USB_TYPE USBHost::resetDevice(USBDeviceConnected * dev) deviceReset[index] = true; return USB_TYPE_OK; } - + return USB_TYPE_ERROR; } @@ -577,7 +577,7 @@ bool USBHost::addEndpoint(USBDeviceConnected * dev, uint8_t intf_nb, USBEndpoint if ((dev != NULL) && dev->getSpeed()) { ep->setSpeed(dev->getSpeed()); } - + ep->setIntfNb(intf_nb); // queue the new USBEndpoint on the ED list @@ -626,7 +626,7 @@ bool USBHost::addEndpoint(USBDeviceConnected * dev, uint8_t intf_nb, USBEndpoint default: return false; } - + ep->dev = dev; dev->addEndpoint(intf_nb, ep); @@ -733,7 +733,7 @@ USB_TYPE USBHost::addTransfer(USBEndpoint * ed, uint8_t * buf, uint32_t len) ed->queueTransfer(); printList(type); enableList(type); - + td_mutex.unlock(); return USB_TYPE_PROCESSING; @@ -750,7 +750,7 @@ USB_TYPE USBHost::getDeviceDescriptor(USBDeviceConnected * dev, uint8_t * buf, u 0, buf, MIN(DEVICE_DESCRIPTOR_LENGTH, max_len_buf)); if (len_dev_descr) *len_dev_descr = MIN(DEVICE_DESCRIPTOR_LENGTH, max_len_buf); - + return t; } @@ -772,10 +772,10 @@ USB_TYPE USBHost::getConfigurationDescriptor(USBDeviceConnected * dev, uint8_t * } total_conf_descr_length = buf[2] | (buf[3] << 8); total_conf_descr_length = MIN(max_len_buf, total_conf_descr_length); - + if (len_conf_descr) *len_conf_descr = total_conf_descr_length; - + USB_DBG("TOTAL_LENGTH: %d \t NUM_INTERF: %d", total_conf_descr_length, buf[4]); return controlRead( dev, @@ -792,7 +792,7 @@ USB_TYPE USBHost::setAddress(USBDeviceConnected * dev, uint8_t address) { SET_ADDRESS, address, 0, NULL, 0); - + } USB_TYPE USBHost::setConfiguration(USBDeviceConnected * dev, uint8_t conf) @@ -821,18 +821,18 @@ USB_TYPE USBHost::enumerate(USBDeviceConnected * dev, IUSBEnumerator* pEnumerato { uint16_t total_conf_descr_length = 0; USB_TYPE res; - + do { Lock lock(this); - + // don't enumerate a device which all interfaces are registered to a specific driver int index = findDevice(dev); - + if (index == -1) { return USB_TYPE_ERROR; } - + uint8_t nb_intf_attached = numberDriverAttached(dev); USB_DBG("dev: %p nb_intf: %d", dev, dev->getNbIntf()); USB_DBG("dev: %p nb_intf_attached: %d", dev, nb_intf_attached); @@ -840,9 +840,9 @@ USB_TYPE USBHost::enumerate(USBDeviceConnected * dev, IUSBEnumerator* pEnumerato USB_DBG("Don't enumerate dev: %p because all intf are registered with a driver", dev); return USB_TYPE_OK; } - + USB_DBG("Enumerate dev: %p", dev); - + // third step: get the whole device descriptor to see vid, pid res = getDeviceDescriptor(dev, data, DEVICE_DESCRIPTOR_LENGTH); @@ -850,7 +850,7 @@ USB_TYPE USBHost::enumerate(USBDeviceConnected * dev, IUSBEnumerator* pEnumerato USB_DBG("GET DEV DESCR FAILED"); return res; } - + dev->setClass(data[4]); dev->setSubClass(data[5]); dev->setProtocol(data[6]); @@ -877,7 +877,7 @@ USB_TYPE USBHost::enumerate(USBDeviceConnected * dev, IUSBEnumerator* pEnumerato // only set configuration if not enumerated before if (!dev->isEnumerated()) { - + USB_DBG("Set configuration 1 on dev: %p", dev); // sixth step: set configuration (only 1 supported) res = setConfiguration(dev, 1); @@ -887,12 +887,12 @@ USB_TYPE USBHost::enumerate(USBDeviceConnected * dev, IUSBEnumerator* pEnumerato return res; } } - + dev->setEnumerated(); // Now the device is enumerated! USB_DBG("dev %p is enumerated\r\n", dev); - + } while(0); // Some devices may require this delay @@ -991,17 +991,17 @@ USB_TYPE USBHost::interruptRead(USBDeviceConnected * dev, USBEndpoint * ep, uint } USB_TYPE USBHost::generalTransfer(USBDeviceConnected * dev, USBEndpoint * ep, uint8_t * buf, uint32_t len, bool blocking, ENDPOINT_TYPE type, bool write) { - + #if DEBUG_TRANSFER const char * type_str = (type == BULK_ENDPOINT) ? "BULK" : ((type == INTERRUPT_ENDPOINT) ? "INTERRUPT" : "ISOCHRONOUS"); USB_DBG_TRANSFER("----- %s %s [dev: %p - %s - hub: %d - port: %d - addr: %d - ep: %02X]------", type_str, (write) ? "WRITE" : "READ", dev, dev->getName(ep->getIntfNb()), dev->getHub(), dev->getPort(), dev->getAddress(), ep->getAddress()); #endif - + Lock lock(this); - + USB_TYPE res; ENDPOINT_DIRECTION dir = (write) ? OUT : IN; - + if (dev == NULL) { USB_ERR("dev NULL"); return USB_TYPE_ERROR; @@ -1026,7 +1026,7 @@ USB_TYPE USBHost::generalTransfer(USBDeviceConnected * dev, USBEndpoint * ep, ui USB_ERR("[ep: %p - dev: %p] USBEndpoint addr and device addr don't match", ep, ep->dev); return USB_TYPE_ERROR; } - + #if DEBUG_TRANSFER if (write) { USB_DBG_TRANSFER("%s WRITE buffer", type_str); @@ -1038,19 +1038,19 @@ USB_TYPE USBHost::generalTransfer(USBDeviceConnected * dev, USBEndpoint * ep, ui addTransfer(ep, buf, len); if (blocking) { - + ep->ep_queue.get(); res = ep->getState(); - + USB_DBG_TRANSFER("%s TRANSFER res: %s on ep: %p\r\n", type_str, ep->getStateString(), ep); - + if (res != USB_TYPE_IDLE) { return res; } - + return USB_TYPE_OK; } - + return USB_TYPE_PROCESSING; } diff --git a/libraries/USBHost/USBHost/USBHost.h b/libraries/USBHost/USBHost/USBHost.h index c8da421f23..802ae99313 100644 --- a/libraries/USBHost/USBHost/USBHost.h +++ b/libraries/USBHost/USBHost/USBHost.h @@ -35,7 +35,7 @@ public: * Static method to create or retrieve the single USBHost instance */ static USBHost * getHostInst(); - + /** * Control read: setup stage, data stage and status stage * @@ -186,19 +186,19 @@ public: dev->onDisconnect(intf, fn); } } - + /** * Instantiate to protect USB thread from accessing shared objects (USBConnectedDevices and Interfaces) */ class Lock { public: - Lock(USBHost* pHost); - ~Lock(); + Lock(USBHost* pHost); + ~Lock(); private: USBHost* m_pHost; }; - + friend class USBHostHub; protected: @@ -257,7 +257,7 @@ private: bool deviceAttachedDriver[MAX_DEVICE_CONNECTED][MAX_INTF]; bool deviceReset[MAX_DEVICE_CONNECTED]; bool deviceInited[MAX_DEVICE_CONNECTED]; - + #if MAX_HUB_NB USBHostHub hubs[MAX_HUB_NB]; bool hub_in_use[MAX_HUB_NB]; @@ -265,7 +265,7 @@ private: // to store a setup packet uint8_t setupPacket[8]; - + typedef struct { uint8_t event_id; void * td_addr; @@ -275,17 +275,17 @@ private: uint8_t td_state; void * hub_parent; } message_t; - + Thread usbThread; void usb_process(); static void usb_process_static(void const * arg); Mail mail_usb_event; Mutex usb_mutex; Mutex td_mutex; - + // buffer for conf descriptor uint8_t data[415]; - + /** * Add a transfer on the TD linked list associated to an ED * @@ -296,7 +296,7 @@ private: * @return status of the transfer */ USB_TYPE addTransfer(USBEndpoint * ed, uint8_t * buf, uint32_t len) ; - + /** * Link the USBEndpoint to the linked list and attach an USBEndpoint this USBEndpoint to a device * @@ -318,7 +318,7 @@ private: * @returns pointer on the USBEndpoint created */ USBEndpoint * newEndpoint(ENDPOINT_TYPE type, ENDPOINT_DIRECTION dir, uint32_t size, uint8_t addr) ; - + /** * Request the device descriptor * @@ -338,7 +338,7 @@ private: * @param len_conf_descr pointer to store the length of the packet transferred */ USB_TYPE getConfigurationDescriptor(USBDeviceConnected * dev, uint8_t * buf, uint16_t max_len_buf, uint16_t * len_conf_descr = NULL); - + /** * Set the address of a specific device * @@ -354,7 +354,7 @@ private: * @param conf configuration number to activate (usually 1) */ USB_TYPE setConfiguration(USBDeviceConnected * dev, uint8_t conf); - + /** * Free a specific device * @@ -378,7 +378,7 @@ private: bool blocking, ENDPOINT_TYPE type, bool write) ; - + void fillControlBuf(uint8_t requestType, uint8_t request, uint16_t value, uint16_t index, int len) ; void parseConfDescr(USBDeviceConnected * dev, uint8_t * conf_descr, uint32_t len, IUSBEnumerator* pEnumerator) ; int findDevice(USBDeviceConnected * dev) ; diff --git a/libraries/USBHost/USBHost/USBHostConf.h b/libraries/USBHost/USBHost/USBHostConf.h index d5515edc3b..9b97752f0c 100644 --- a/libraries/USBHost/USBHost/USBHostConf.h +++ b/libraries/USBHost/USBHost/USBHostConf.h @@ -56,7 +56,7 @@ /* * Enable USB3Gmodule */ -#define USBHOST_3GMODULE 1 +#define USBHOST_3GMODULE 1 /* * Maximum number of interfaces of a usb device diff --git a/libraries/USBHost/USBHost/USBHostTypes.h b/libraries/USBHost/USBHost/USBHostTypes.h index e03c6e4239..c4462aa052 100644 --- a/libraries/USBHost/USBHost/USBHostTypes.h +++ b/libraries/USBHost/USBHost/USBHostTypes.h @@ -67,28 +67,28 @@ enum ENDPOINT_TYPE { #define HUB_CLASS 0x09 #define SERIAL_CLASS 0x0A -// ------------------ HcControl Register --------------------- +// ------------------ HcControl Register --------------------- #define OR_CONTROL_PLE 0x00000004 #define OR_CONTROL_CLE 0x00000010 #define OR_CONTROL_BLE 0x00000020 #define OR_CONTROL_HCFS 0x000000C0 #define OR_CONTROL_HC_OPER 0x00000080 -// ----------------- HcCommandStatus Register ----------------- +// ----------------- HcCommandStatus Register ----------------- #define OR_CMD_STATUS_HCR 0x00000001 #define OR_CMD_STATUS_CLF 0x00000002 #define OR_CMD_STATUS_BLF 0x00000004 -// --------------- HcInterruptStatus Register ----------------- +// --------------- HcInterruptStatus Register ----------------- #define OR_INTR_STATUS_WDH 0x00000002 #define OR_INTR_STATUS_RHSC 0x00000040 #define OR_INTR_STATUS_UE 0x00000010 -// --------------- HcInterruptEnable Register ----------------- +// --------------- HcInterruptEnable Register ----------------- #define OR_INTR_ENABLE_WDH 0x00000002 #define OR_INTR_ENABLE_RHSC 0x00000040 #define OR_INTR_ENABLE_MIE 0x80000000 -// ---------------- HcRhDescriptorA Register ------------------ +// ---------------- HcRhDescriptorA Register ------------------ #define OR_RH_STATUS_LPSC 0x00010000 #define OR_RH_STATUS_DRWE 0x00008000 -// -------------- HcRhPortStatus[1:NDP] Register -------------- +// -------------- HcRhPortStatus[1:NDP] Register -------------- #define OR_RH_PORT_CCS 0x00000001 #define OR_RH_PORT_PRS 0x00000010 #define OR_RH_PORT_CSC 0x00010000 @@ -100,14 +100,14 @@ enum ENDPOINT_TYPE { #define ED_SKIP (uint32_t) (0x00001000) // Skip this ep in queue -#define TD_ROUNDING (uint32_t) (0x00040000) // Buffer Rounding -#define TD_SETUP (uint32_t)(0) // Direction of Setup Packet -#define TD_IN (uint32_t)(0x00100000) // Direction In -#define TD_OUT (uint32_t)(0x00080000) // Direction Out -#define TD_DELAY_INT(x) (uint32_t)((x) << 21) // Delay Interrupt -#define TD_TOGGLE_0 (uint32_t)(0x02000000) // Toggle 0 -#define TD_TOGGLE_1 (uint32_t)(0x03000000) // Toggle 1 -#define TD_CC (uint32_t)(0xF0000000) // Completion Code +#define TD_ROUNDING (uint32_t) (0x00040000) // Buffer Rounding +#define TD_SETUP (uint32_t)(0) // Direction of Setup Packet +#define TD_IN (uint32_t)(0x00100000) // Direction In +#define TD_OUT (uint32_t)(0x00080000) // Direction Out +#define TD_DELAY_INT(x) (uint32_t)((x) << 21) // Delay Interrupt +#define TD_TOGGLE_0 (uint32_t)(0x02000000) // Toggle 0 +#define TD_TOGGLE_1 (uint32_t)(0x03000000) // Toggle 1 +#define TD_CC (uint32_t)(0xF0000000) // Completion Code #define DEVICE_DESCRIPTOR (1) #define CONFIGURATION_DESCRIPTOR (2) @@ -115,7 +115,7 @@ enum ENDPOINT_TYPE { #define ENDPOINT_DESCRIPTOR (5) #define HID_DESCRIPTOR (33) -// ----------- Control RequestType Fields ----------- +// ----------- Control RequestType Fields ----------- #define USB_DEVICE_TO_HOST 0x80 #define USB_HOST_TO_DEVICE 0x00 #define USB_REQUEST_TYPE_CLASS 0x20 @@ -124,14 +124,14 @@ enum ENDPOINT_TYPE { #define USB_RECIPIENT_INTERFACE 0x01 #define USB_RECIPIENT_ENDPOINT 0x02 -// -------------- USB Standard Requests -------------- +// -------------- USB Standard Requests -------------- #define SET_ADDRESS 0x05 #define GET_DESCRIPTOR 0x06 #define SET_CONFIGURATION 0x09 #define SET_INTERFACE 0x0b #define CLEAR_FEATURE 0x01 -// -------------- USB Descriptor Length -------------- +// -------------- USB Descriptor Length -------------- #define DEVICE_DESCRIPTOR_LENGTH 0x12 #define CONFIGURATION_DESCRIPTOR_LENGTH 0x09 @@ -145,7 +145,7 @@ typedef struct HCTD { uint32_t dummy[3]; // padding } PACKED HCTD; -// ----------- HostController EndPoint Descriptor ------------- +// ----------- HostController EndPoint Descriptor ------------- typedef struct hcEd { __IO uint32_t control; // Endpoint descriptor control __IO HCTD * tailTD; // Physical address of tail in Transfer descriptor list @@ -154,73 +154,73 @@ typedef struct hcEd { } PACKED HCED; -// ----------- Host Controller Communication Area ------------ +// ----------- Host Controller Communication Area ------------ typedef struct hcca { __IO uint32_t IntTable[32]; // Interrupt Table __IO uint32_t FrameNumber; // Frame Number __IO uint32_t DoneHead; // Done Head - volatile uint8_t Reserved[116]; // Reserved for future use - volatile uint8_t Unknown[4]; // Unused + volatile uint8_t Reserved[116]; // Reserved for future use + volatile uint8_t Unknown[4]; // Unused } PACKED HCCA; typedef struct { - uint8_t bLength; - uint8_t bDescriptorType; - uint16_t bcdUSB; - uint8_t bDeviceClass; - uint8_t bDeviceSubClass; - uint8_t bDeviceProtocol; - uint8_t bMaxPacketSize; - uint16_t idVendor; - uint16_t idProduct; - uint16_t bcdDevice; - uint8_t iManufacturer; - uint8_t iProduct; - uint8_t iSerialNumber; - uint8_t bNumConfigurations; + uint8_t bLength; + uint8_t bDescriptorType; + uint16_t bcdUSB; + uint8_t bDeviceClass; + uint8_t bDeviceSubClass; + uint8_t bDeviceProtocol; + uint8_t bMaxPacketSize; + uint16_t idVendor; + uint16_t idProduct; + uint16_t bcdDevice; + uint8_t iManufacturer; + uint8_t iProduct; + uint8_t iSerialNumber; + uint8_t bNumConfigurations; } PACKED DeviceDescriptor; typedef struct { - uint8_t bLength; - uint8_t bDescriptorType; - uint16_t wTotalLength; - uint8_t bNumInterfaces; - uint8_t bConfigurationValue; - uint8_t iConfiguration; - uint8_t bmAttributes; - uint8_t bMaxPower; -} PACKED ConfigurationDescriptor; + uint8_t bLength; + uint8_t bDescriptorType; + uint16_t wTotalLength; + uint8_t bNumInterfaces; + uint8_t bConfigurationValue; + uint8_t iConfiguration; + uint8_t bmAttributes; + uint8_t bMaxPower; +} PACKED ConfigurationDescriptor; typedef struct { - uint8_t bLength; - uint8_t bDescriptorType; - uint8_t bInterfaceNumber; - uint8_t bAlternateSetting; - uint8_t bNumEndpoints; - uint8_t bInterfaceClass; + uint8_t bLength; + uint8_t bDescriptorType; + uint8_t bInterfaceNumber; + uint8_t bAlternateSetting; + uint8_t bNumEndpoints; + uint8_t bInterfaceClass; uint8_t bInterfaceSubClass; uint8_t bInterfaceProtocol; - uint8_t iInterface; -} InterfaceDescriptor; + uint8_t iInterface; +} InterfaceDescriptor; typedef struct { - uint8_t bLength; - uint8_t bDescriptorType; - uint8_t bEndpointAddress; - uint8_t bmAttributes; - uint16_t wMaxPacketSize; - uint8_t bInterval; + uint8_t bLength; + uint8_t bDescriptorType; + uint8_t bEndpointAddress; + uint8_t bmAttributes; + uint16_t wMaxPacketSize; + uint8_t bInterval; } EndpointDescriptor; typedef struct { - uint8_t bDescLength; - uint8_t bDescriptorType; - uint8_t bNbrPorts; + uint8_t bDescLength; + uint8_t bDescriptorType; + uint8_t bNbrPorts; uint16_t wHubCharacteristics; - uint8_t bPwrOn2PwrGood; - uint8_t bHubContrCurrent; - uint8_t DeviceRemovable; - uint8_t PortPweCtrlMak; -} HubDescriptor; + uint8_t bPwrOn2PwrGood; + uint8_t bHubContrCurrent; + uint8_t DeviceRemovable; + uint8_t PortPweCtrlMak; +} HubDescriptor; #endif diff --git a/libraries/USBHost/USBHost3GModule/WANDongle.cpp b/libraries/USBHost/USBHost3GModule/WANDongle.cpp index c7896f6e62..49cafb7cc3 100644 --- a/libraries/USBHost/USBHost3GModule/WANDongle.cpp +++ b/libraries/USBHost/USBHost3GModule/WANDongle.cpp @@ -45,12 +45,12 @@ bool WANDongle::tryConnect() USB_DBG("Trying to connect device"); if (dev_connected) { - USB_DBG("Device is already connected!"); + USB_DBG("Device is already connected!"); return true; } - + m_pInitializer = NULL; - + //Protect from concurrent access from USB thread USBHost::Lock lock(host); @@ -59,16 +59,16 @@ bool WANDongle::tryConnect() if ((dev = host->getDevice(i)) != NULL) { m_pInitializer = NULL; //Will be set in setVidPid callback - + USB_DBG("Enumerate"); int ret = host->enumerate(dev, this); if(ret) { return false; } - + USB_DBG("Device has VID:%04x PID:%04x", dev->getVid(), dev->getPid()); - + if(m_pInitializer) //If an initializer has been found { USB_DBG("m_pInitializer=%p", m_pInitializer); @@ -90,18 +90,18 @@ bool WANDongle::tryConnect() USB_DBG("Ep %p", m_pInitializer->getEp(dev, j, true)); m_serial[j].connect( dev, m_pInitializer->getEp(dev, j, false), m_pInitializer->getEp(dev, j, true) ); } - + USB_DBG("Device connected"); - + dev_connected = true; - - + + return true; } else if ((dev->getVid() == m_pInitializer->getMSDVid()) && (dev->getPid() == m_pInitializer->getMSDPid())) { USB_DBG("Vodafone K3370 dongle detected in MSD mode"); - //Try to switch + //Try to switch if( m_pInitializer->switchMode(dev) ) { USB_DBG("Switched OK"); diff --git a/libraries/USBHost/USBHost3GModule/WANDongle.h b/libraries/USBHost/USBHost3GModule/WANDongle.h index ab12bdc6e4..960b8bcfbe 100644 --- a/libraries/USBHost/USBHost3GModule/WANDongle.h +++ b/libraries/USBHost/USBHost3GModule/WANDongle.h @@ -58,47 +58,47 @@ public: * @return true if a serial device is connected */ bool connected(); - + /* * Try to connect device * * * @return true if connection was successful */ bool tryConnect(); - + /* * Disconnect device * * * @return true if disconnection was successful */ bool disconnect(); - + int getDongleType(); - + IUSBHostSerial& getSerial(int index); int getSerialCount(); bool addInitializer(WANDongleInitializer* pInitializer); //From IUSBEnumerator - + virtual void setVidPid(uint16_t vid, uint16_t pid); - + virtual bool parseInterface(uint8_t intf_nb, uint8_t intf_class, uint8_t intf_subclass, uint8_t intf_protocol); //Must return true if the interface should be parsed - + virtual bool useEndpoint(uint8_t intf_nb, ENDPOINT_TYPE type, ENDPOINT_DIRECTION dir); //Must return true if the endpoint will be used - + protected: USBHost * host; USBDeviceConnected * dev; bool dev_connected; - + WANDongleInitializer* m_pInitializer; void init(); - + WANDongleSerialPort m_serial[WANDONGLE_MAX_SERIAL_PORTS]; int m_serialCount; - + int m_totalInitializers; WANDongleInitializer* m_Initializers[WANDONGLE_MAX_INITIALIZERS]; }; diff --git a/libraries/USBHost/USBHost3GModule/WANDongleInitializer.h b/libraries/USBHost/USBHost3GModule/WANDongleInitializer.h index a78d69bdbd..2f0a4a37c7 100644 --- a/libraries/USBHost/USBHost3GModule/WANDongleInitializer.h +++ b/libraries/USBHost/USBHost3GModule/WANDongleInitializer.h @@ -40,29 +40,29 @@ protected: WANDongleInitializer(USBHost* pHost) { m_pHost = pHost; } USBHost* m_pHost; uint8_t m_serialIntfMap[WANDONGLE_MAX_SERIAL_PORTS]; - + public: virtual ~WANDongleInitializer() {} virtual uint16_t getMSDVid() = 0; virtual uint16_t getMSDPid() = 0; - + virtual uint16_t getSerialVid() = 0; virtual uint16_t getSerialPid() = 0; - + virtual bool switchMode(USBDeviceConnected* pDev) = 0; - + virtual USBEndpoint* getEp(USBDeviceConnected* pDev, int serialPortNumber, bool tx) { return pDev->getEndpoint(m_serialIntfMap[serialPortNumber], BULK_ENDPOINT, tx ? OUT : IN, 0); } - + virtual int getSerialPortCount() = 0; - + virtual void setVidPid(uint16_t vid, uint16_t pid) = 0; - + virtual bool parseInterface(uint8_t intf_nb, uint8_t intf_class, uint8_t intf_subclass, uint8_t intf_protocol) = 0; //Must return true if the interface should be parsed - + virtual bool useEndpoint(uint8_t intf_nb, ENDPOINT_TYPE type, ENDPOINT_DIRECTION dir) = 0; //Must return true if the endpoint will be used - + virtual int getType() = 0; virtual uint8_t getSerialIntf(int index) { return m_serialIntfMap[index]; } diff --git a/libraries/USBHost/USBHost3GModule/WANDongleSerialPort.cpp b/libraries/USBHost/USBHost3GModule/WANDongleSerialPort.cpp index 4cb43379e4..96343f15cc 100644 --- a/libraries/USBHost/USBHost3GModule/WANDongleSerialPort.cpp +++ b/libraries/USBHost/USBHost3GModule/WANDongleSerialPort.cpp @@ -58,7 +58,7 @@ void WANDongleSerialPort::reset() buf_in_read_pos = 0; lock_rx = false; cb_rx_pending = false; - + tx_mtx.unlock(); rx_mtx.unlock(); } @@ -73,7 +73,7 @@ int WANDongleSerialPort::readPacket() rx_mtx.unlock(); return -1; } - + if( bulk_in == NULL ) { USB_WARN("Port is disconnected"); @@ -105,7 +105,7 @@ int WANDongleSerialPort::writePacket() tx_mtx.unlock(); return -1; } - + if( bulk_out == NULL ) { USB_WARN("Port is disconnected"); diff --git a/libraries/USBHost/USBHost3GModule/WANDongleSerialPort.h b/libraries/USBHost/USBHost3GModule/WANDongleSerialPort.h index 9da1717078..7c79d17341 100644 --- a/libraries/USBHost/USBHost3GModule/WANDongleSerialPort.h +++ b/libraries/USBHost/USBHost3GModule/WANDongleSerialPort.h @@ -42,11 +42,11 @@ public: * */ WANDongleSerialPort(); - + void init( USBHost* pHost ); - + void connect( USBDeviceConnected* pDev, USBEndpoint* pInEp, USBEndpoint* pOutEp ); - + void disconnect( ); /* @@ -89,13 +89,13 @@ public: * @param pListener instance of the listener deriving from the IUSBHostSerialListener */ virtual void attach(IUSBHostSerialListener* pListener); - + /** * Enable or disable readable/writeable callbacks */ virtual void setupIrq(bool en, IrqType irq = RxIrq); - + protected: USBEndpoint * bulk_in; USBEndpoint * bulk_out; @@ -117,11 +117,11 @@ protected: volatile bool cb_rx_en; volatile bool cb_rx_pending; Mutex rx_mtx; - + IUSBHostSerialListener* listener; - + void reset(); - + void rxHandler(); void txHandler(); diff --git a/libraries/USBHost/USBHostHID/USBHostKeyboard.cpp b/libraries/USBHost/USBHostHID/USBHostKeyboard.cpp index 4c7fef0a8e..dbb2cda53e 100644 --- a/libraries/USBHost/USBHostHID/USBHostKeyboard.cpp +++ b/libraries/USBHost/USBHostHID/USBHostKeyboard.cpp @@ -18,7 +18,7 @@ #if USBHOST_KEYBOARD -static uint8_t keymap[4][0x39] = { +static uint8_t keymap[4][0x39] = { { 0, 0, 0, 0, 'a', 'b' /*0x05*/, 'c', 'd', 'e', 'f', 'g' /*0x0a*/, 'h', 'i', 'j', 'k', 'l'/*0x0f*/, @@ -100,30 +100,30 @@ bool USBHostKeyboard::connected() { bool USBHostKeyboard::connect() { - + if (dev_connected) { return true; } - + for (uint8_t i = 0; i < MAX_DEVICE_CONNECTED; i++) { if ((dev = host->getDevice(i)) != NULL) { if (host->enumerate(dev, this)) break; - + if (keyboard_device_found) { int_in = dev->getEndpoint(keyboard_intf, INTERRUPT_ENDPOINT, IN); - + if (!int_in) break; - + USB_INFO("New Keyboard device: VID:%04x PID:%04x [dev: %p - intf: %d]", dev->getVid(), dev->getPid(), dev, keyboard_intf); dev->setName("Keyboard", keyboard_intf); host->registerDriver(dev, keyboard_intf, this, &USBHostKeyboard::init); - + int_in->attach(this, &USBHostKeyboard::rxHandler); host->interruptRead(dev, int_in, report, int_in->getSize(), false); - + dev_connected = true; return true; } diff --git a/libraries/USBHost/USBHostHID/USBHostKeyboard.h b/libraries/USBHost/USBHostHID/USBHostKeyboard.h index 64af41efaa..93730061c5 100644 --- a/libraries/USBHost/USBHostHID/USBHostKeyboard.h +++ b/libraries/USBHost/USBHostHID/USBHostKeyboard.h @@ -23,12 +23,12 @@ #include "USBHost.h" -/** +/** * A class to communicate a USB keyboard */ class USBHostKeyboard : public IUSBEnumerator { public: - + /** * Constructor */ @@ -83,7 +83,7 @@ private: uint8_t report[9]; int keyboard_intf; bool keyboard_device_found; - + bool dev_connected; void rxHandler(); @@ -92,7 +92,7 @@ private: void (*onKeyCode)(uint8_t key, uint8_t modifier); int report_id; - + void init(); }; diff --git a/libraries/USBHost/USBHostHID/USBHostMouse.cpp b/libraries/USBHost/USBHostHID/USBHostMouse.cpp index 6c596d08b0..493f12dc6c 100644 --- a/libraries/USBHost/USBHostHID/USBHostMouse.cpp +++ b/libraries/USBHost/USBHostHID/USBHostMouse.cpp @@ -35,7 +35,7 @@ void USBHostMouse::init() { dev_connected = false; mouse_device_found = false; mouse_intf = -1; - + buttons = 0; x = 0; y = 0; @@ -51,26 +51,26 @@ bool USBHostMouse::connect() { if (dev_connected) { return true; } - + for (uint8_t i = 0; i < MAX_DEVICE_CONNECTED; i++) { if ((dev = host->getDevice(i)) != NULL) { if(host->enumerate(dev, this)) break; - + if (mouse_device_found) { - + int_in = dev->getEndpoint(mouse_intf, INTERRUPT_ENDPOINT, IN); if (!int_in) break; - + USB_INFO("New Mouse device: VID:%04x PID:%04x [dev: %p - intf: %d]", dev->getVid(), dev->getPid(), dev, mouse_intf); dev->setName("Mouse", mouse_intf); host->registerDriver(dev, mouse_intf, this, &USBHostMouse::init); - + int_in->attach(this, &USBHostMouse::rxHandler); host->interruptRead(dev, int_in, report, int_in->getSize(), false); - + dev_connected = true; return true; } @@ -82,33 +82,33 @@ bool USBHostMouse::connect() { void USBHostMouse::rxHandler() { int len_listen = int_in->getSize(); - + if (onUpdate) { (*onUpdate)(report[0] & 0x07, report[1], report[2], report[3]); } - + if (onButtonUpdate && (buttons != (report[0] & 0x07))) { (*onButtonUpdate)(report[0] & 0x07); } - + if (onXUpdate && (x != report[1])) { (*onXUpdate)(report[1]); } - + if (onYUpdate && (y != report[2])) { (*onYUpdate)(report[2]); } - + if (onZUpdate && (z != report[3])) { (*onZUpdate)(report[3]); } - + // update mouse state buttons = report[0] & 0x07; x = report[1]; y = report[2]; z = report[3]; - + if (dev) host->interruptRead(dev, int_in, report, len_listen, false); } diff --git a/libraries/USBHost/USBHostHID/USBHostMouse.h b/libraries/USBHost/USBHostHID/USBHostMouse.h index 1e97c8e492..03e0994482 100644 --- a/libraries/USBHost/USBHostHID/USBHostMouse.h +++ b/libraries/USBHost/USBHostHID/USBHostMouse.h @@ -23,7 +23,7 @@ #include "USBHost.h" -/** +/** * A class to communicate a USB mouse */ class USBHostMouse : public IUSBEnumerator { @@ -58,7 +58,7 @@ public: onUpdate = ptr; } } - + /** * Attach a callback called when the button state changes * @@ -69,7 +69,7 @@ public: onButtonUpdate = ptr; } } - + /** * Attach a callback called when the X axis value changes * @@ -80,7 +80,7 @@ public: onXUpdate = ptr; } } - + /** * Attach a callback called when the Y axis value changes * @@ -91,7 +91,7 @@ public: onYUpdate = ptr; } } - + /** * Attach a callback called when the Z axis value changes (scrolling) * @@ -114,7 +114,7 @@ private: USBDeviceConnected * dev; USBEndpoint * int_in; uint8_t report[4]; - + bool dev_connected; bool mouse_device_found; int mouse_intf; diff --git a/libraries/USBHost/USBHostHub/USBHostHub.cpp b/libraries/USBHost/USBHostHub/USBHostHub.cpp index e008c9a496..7a9660bdb1 100644 --- a/libraries/USBHost/USBHostHub/USBHostHub.cpp +++ b/libraries/USBHost/USBHostHub/USBHostHub.cpp @@ -64,7 +64,7 @@ void USBHostHub::init() { hub_device_found = false; nb_port = 0; hub_characteristics = 0; - + for (int i = 0; i < MAX_HUB_PORT; i++) { device_children[i] = NULL; } @@ -80,52 +80,52 @@ bool USBHostHub::connected() } bool USBHostHub::connect(USBDeviceConnected * dev) -{ +{ if (dev_connected) { return true; } - + if(host->enumerate(dev, this)) { init(); return false; } - + if (hub_device_found) { this->dev = dev; - + int_in = dev->getEndpoint(hub_intf, INTERRUPT_ENDPOINT, IN); - + if (!int_in) { init(); return false; } - + USB_INFO("New HUB: VID:%04x PID:%04x [dev: %p - intf: %d]", dev->getVid(), dev->getPid(), dev, hub_intf); dev->setName("Hub", hub_intf); host->registerDriver(dev, hub_intf, this, &USBHostHub::disconnect); - + int_in->attach(this, &USBHostHub::rxHandler); - + // get HUB descriptor - host->controlRead( dev, + host->controlRead( dev, USB_DEVICE_TO_HOST | USB_REQUEST_TYPE_CLASS, GET_DESCRIPTOR, 0x29 << 8, 0, buf, sizeof(HubDescriptor)); nb_port = buf[2]; hub_characteristics = buf[3]; - + USB_DBG("Hub has %d port", nb_port); - + for (uint8_t j = 1; j <= nb_port; j++) { setPortFeature(PORT_POWER_FEATURE, j); } wait_ms(buf[5]*2); - + host->interruptRead(dev, int_in, buf, 1, false); dev_connected = true; return true; } - + return false; } @@ -184,7 +184,7 @@ void USBHostHub::rxHandler() { for (int port = 1; port <= nb_port; port++) { status = getPortStatus(port); USB_DBG("[hub handler hub: %d] status port %d [hub: %p]: 0x%X", dev->getHub(), port, dev, status); - + // if connection status has changed if (status & C_PORT_CONNECTION) { if (status & PORT_CONNECTION) { @@ -194,18 +194,18 @@ void USBHostHub::rxHandler() { USB_DBG("[hub handler hub: %d - port: %d] device disconnected", dev->getHub(), port); host->deviceDisconnected(dev->getHub() + 1, port, this, 0); } - + clearPortFeature(C_PORT_CONNECTION_FEATURE, port); } - + if (status & C_PORT_RESET) { clearPortFeature(C_PORT_RESET_FEATURE, port); } - + if (status & C_PORT_ENABLE) { clearPortFeature(C_PORT_ENABLE_FEATURE, port); } - + if ((status & PORT_OVER_CURRENT)) { USB_ERR("OVER CURRENT DETECTED\r\n"); clearPortFeature(PORT_OVER_CURRENT, port); diff --git a/libraries/USBHost/USBHostHub/USBHostHub.h b/libraries/USBHost/USBHostHub/USBHostHub.h index 17fb4ce3bf..e199c369e7 100644 --- a/libraries/USBHost/USBHostHub/USBHostHub.h +++ b/libraries/USBHost/USBHostHub/USBHostHub.h @@ -28,7 +28,7 @@ class USBHost; class USBDeviceConnected; class USBEndpoint; -/** +/** * A class to use a USB Hub */ class USBHostHub : public IUSBEnumerator { @@ -52,7 +52,7 @@ public: * @return true if connection was successful */ bool connect(USBDeviceConnected * dev); - + /** * Automatically called by USBHost when a device * has been enumerated by usb_thread @@ -60,7 +60,7 @@ public: * @param dev device connected */ void deviceConnected(USBDeviceConnected * dev); - + /** * Automatically called by USBHost when a device * has been disconnected from this hub @@ -68,21 +68,21 @@ public: * @param dev device disconnected */ void deviceDisconnected(USBDeviceConnected * dev); - + /** * Rest a specific port * * @param port port number */ void portReset(uint8_t port); - + /* * Called by USBHost to set the instance of USBHost * * @param host host instance */ void setHost(USBHost * host); - + /** * Called by USBhost when a hub has been disconnected */ @@ -114,7 +114,7 @@ private: uint32_t getPortStatus(uint8_t port); USBDeviceConnected * device_children[MAX_HUB_PORT]; - + void init(); void disconnect(); diff --git a/libraries/USBHost/USBHostMSD/USBHostMSD.cpp b/libraries/USBHost/USBHostMSD/USBHostMSD.cpp index a91f5fc982..c8406494c6 100644 --- a/libraries/USBHost/USBHostMSD/USBHostMSD.cpp +++ b/libraries/USBHost/USBHostMSD/USBHostMSD.cpp @@ -65,19 +65,19 @@ bool USBHostMSD::connect() for (uint8_t i = 0; i < MAX_DEVICE_CONNECTED; i++) { if ((dev = host->getDevice(i)) != NULL) { - + USB_DBG("Trying to connect MSD device\r\n"); - + if(host->enumerate(dev, this)) break; if (msd_device_found) { bulk_in = dev->getEndpoint(msd_intf, BULK_ENDPOINT, IN); bulk_out = dev->getEndpoint(msd_intf, BULK_ENDPOINT, OUT); - + if (!bulk_in || !bulk_out) continue; - + USB_INFO("New MSD device: VID:%04x PID:%04x [dev: %p - intf: %d]", dev->getVid(), dev->getPid(), dev, msd_intf); dev->setName("MSD", msd_intf); host->registerDriver(dev, msd_intf, this, &USBHostMSD::init); @@ -219,7 +219,7 @@ int USBHostMSD::SCSITransfer(uint8_t * cmd, uint8_t cmd_len, int flags, uint8_t if (data) { USB_DBG("data stage"); if (flags == HOST_TO_DEVICE) { - + res = host->bulkWrite(dev, bulk_out, data, transfer_len); if (checkResult(res, bulk_out)) return -1; @@ -242,7 +242,7 @@ int USBHostMSD::SCSITransfer(uint8_t * cmd, uint8_t cmd_len, int flags, uint8_t if (csw.Signature != CSW_SIGNATURE) { return -1; } - + USB_DBG("recv csw: status: %d", csw.Status); // ModeSense? @@ -250,27 +250,27 @@ int USBHostMSD::SCSITransfer(uint8_t * cmd, uint8_t cmd_len, int flags, uint8_t USB_DBG("request mode sense"); return SCSIRequestSense(); } - + // perform reset recovery if ((csw.Status == 2) && (cmd[0] != 0x03)) { - + // send Bulk-Only Mass Storage Reset request res = host->controlWrite( dev, USB_RECIPIENT_INTERFACE | USB_HOST_TO_DEVICE | USB_REQUEST_TYPE_CLASS, BO_MASS_STORAGE_RESET, 0, msd_intf, NULL, 0); - + // unstall both endpoints res = host->controlWrite( dev, USB_RECIPIENT_ENDPOINT | USB_HOST_TO_DEVICE | USB_REQUEST_TYPE_STANDARD, CLEAR_FEATURE, 0, bulk_in->getAddress(), NULL, 0); - + res = host->controlWrite( dev, USB_RECIPIENT_ENDPOINT | USB_HOST_TO_DEVICE | USB_REQUEST_TYPE_STANDARD, CLEAR_FEATURE, 0, bulk_out->getAddress(), NULL, 0); - + } return csw.Status; @@ -304,20 +304,20 @@ int USBHostMSD::getMaxLun() { int USBHostMSD::disk_initialize() { USB_DBG("FILESYSTEM: init"); U16 i, timeout = 10; - + getMaxLun(); - + for (i = 0; i < timeout; i++) { Thread::wait(100); if (!testUnitReady()) break; } - + if (i == timeout) { disk_init = false; return -1; } - + inquiry(0, 0); disk_init = 1; return readCapacity(); diff --git a/libraries/USBHost/USBHostMSD/USBHostMSD.h b/libraries/USBHost/USBHostMSD/USBHostMSD.h index 118873996d..b90cd2fe19 100644 --- a/libraries/USBHost/USBHostMSD/USBHostMSD.h +++ b/libraries/USBHost/USBHostMSD/USBHostMSD.h @@ -24,7 +24,7 @@ #include "USBHost.h" #include "FATFileSystem.h" -/** +/** * A class to communicate a USB flash disk */ class USBHostMSD : public IUSBEnumerator, public FATFileSystem { @@ -109,7 +109,7 @@ private: int msd_intf; bool msd_device_found; bool disk_init; - + void init(); }; diff --git a/libraries/USBHost/USBHostSerial/MtxCircBuffer.h b/libraries/USBHost/USBHostSerial/MtxCircBuffer.h index 89b0a224f0..ff79affad6 100644 --- a/libraries/USBHost/USBHostSerial/MtxCircBuffer.h +++ b/libraries/USBHost/USBHostSerial/MtxCircBuffer.h @@ -24,7 +24,7 @@ template class MtxCircBuffer { public: - + MtxCircBuffer() { write = 0; read = 0; @@ -43,7 +43,7 @@ public: mtx.unlock(); return r; } - + void flush() { write = 0; read = 0; diff --git a/libraries/USBHost/USBHostSerial/USBHostSerial.cpp b/libraries/USBHost/USBHostSerial/USBHostSerial.cpp index 2124c3aa60..2d3b1736db 100644 --- a/libraries/USBHost/USBHostSerial/USBHostSerial.cpp +++ b/libraries/USBHost/USBHostSerial/USBHostSerial.cpp @@ -26,7 +26,7 @@ #if (USBHOST_SERIAL <= 1) -USBHostSerial::USBHostSerial() +USBHostSerial::USBHostSerial() { host = USBHost::getHostInst(); ports_found = 0; @@ -46,9 +46,9 @@ void USBHostSerial::disconnect(void) bool USBHostSerial::connect() { - if (dev) + if (dev) { - for (uint8_t i = 0; i < MAX_DEVICE_CONNECTED; i++) + for (uint8_t i = 0; i < MAX_DEVICE_CONNECTED; i++) { USBDeviceConnected* d = host->getDevice(i); if (dev == d) @@ -56,15 +56,15 @@ bool USBHostSerial::connect() { } disconnect(); } - for (uint8_t i = 0; i < MAX_DEVICE_CONNECTED; i++) + for (uint8_t i = 0; i < MAX_DEVICE_CONNECTED; i++) { USBDeviceConnected* d = host->getDevice(i); if (d != NULL) { - + USB_DBG("Trying to connect serial device \r\n"); if(host->enumerate(d, this)) break; - + USBEndpoint* bulk_in = d->getEndpoint(port_intf, BULK_ENDPOINT, IN); USBEndpoint* bulk_out = d->getEndpoint(port_intf, BULK_ENDPOINT, OUT); if (bulk_in && bulk_out) @@ -84,7 +84,7 @@ bool USBHostSerial::connect() { /*virtual*/ bool USBHostSerial::parseInterface(uint8_t intf_nb, uint8_t intf_class, uint8_t intf_subclass, uint8_t intf_protocol) //Must return true if the interface should be parsed { - if (!ports_found && + if (!ports_found && CHECK_INTERFACE(intf_class, intf_subclass, intf_protocol)) { port_intf = intf_nb; ports_found = true; @@ -96,7 +96,7 @@ bool USBHostSerial::connect() { /*virtual*/ bool USBHostSerial::useEndpoint(uint8_t intf_nb, ENDPOINT_TYPE type, ENDPOINT_DIRECTION dir) //Must return true if the endpoint will be used { if (ports_found && (intf_nb == port_intf)) { - if (type == BULK_ENDPOINT) + if (type == BULK_ENDPOINT) return true; } return false; @@ -106,7 +106,7 @@ bool USBHostSerial::connect() { //------------------------------------------------------------------------------ -USBHostMultiSerial::USBHostMultiSerial() +USBHostMultiSerial::USBHostMultiSerial() { host = USBHost::getHostInst(); dev = NULL; @@ -127,7 +127,7 @@ bool USBHostMultiSerial::connected() void USBHostMultiSerial::disconnect(void) { - for (int port = 0; port < USBHOST_SERIAL; port ++) + for (int port = 0; port < USBHOST_SERIAL; port ++) { if (ports[port]) { @@ -141,9 +141,9 @@ void USBHostMultiSerial::disconnect(void) bool USBHostMultiSerial::connect() { - if (dev) + if (dev) { - for (uint8_t i = 0; i < MAX_DEVICE_CONNECTED; i++) + for (uint8_t i = 0; i < MAX_DEVICE_CONNECTED; i++) { USBDeviceConnected* d = host->getDevice(i); if (dev == d) @@ -151,16 +151,16 @@ bool USBHostMultiSerial::connect() { } disconnect(); } - for (uint8_t i = 0; i < MAX_DEVICE_CONNECTED; i++) + for (uint8_t i = 0; i < MAX_DEVICE_CONNECTED; i++) { USBDeviceConnected* d = host->getDevice(i); if (d != NULL) { - + USB_DBG("Trying to connect serial device \r\n"); if(host->enumerate(d, this)) break; - - for (int port = 0; port < ports_found; port ++) + + for (int port = 0; port < ports_found; port ++) { USBEndpoint* bulk_in = d->getEndpoint(port_intf[port], BULK_ENDPOINT, IN); USBEndpoint* bulk_out = d->getEndpoint(port_intf[port], BULK_ENDPOINT, OUT); @@ -186,7 +186,7 @@ bool USBHostMultiSerial::connect() { /*virtual*/ bool USBHostMultiSerial::parseInterface(uint8_t intf_nb, uint8_t intf_class, uint8_t intf_subclass, uint8_t intf_protocol) //Must return true if the interface should be parsed { - if ((ports_found < USBHOST_SERIAL) && + if ((ports_found < USBHOST_SERIAL) && CHECK_INTERFACE(intf_class, intf_subclass, intf_protocol)) { port_intf[ports_found++] = intf_nb; return true; @@ -197,7 +197,7 @@ bool USBHostMultiSerial::connect() { /*virtual*/ bool USBHostMultiSerial::useEndpoint(uint8_t intf_nb, ENDPOINT_TYPE type, ENDPOINT_DIRECTION dir) //Must return true if the endpoint will be used { if ((ports_found > 0) && (intf_nb == port_intf[ports_found-1])) { - if (type == BULK_ENDPOINT) + if (type == BULK_ENDPOINT) return true; } return false; @@ -209,7 +209,7 @@ bool USBHostMultiSerial::connect() { #define SET_LINE_CODING 0x20 -USBHostSerialPort::USBHostSerialPort(): circ_buf() +USBHostSerialPort::USBHostSerialPort(): circ_buf() { init(); } @@ -230,7 +230,7 @@ void USBHostSerialPort::init(void) circ_buf.flush(); } -void USBHostSerialPort::connect(USBHost* _host, USBDeviceConnected * _dev, +void USBHostSerialPort::connect(USBHost* _host, USBDeviceConnected * _dev, uint8_t _serial_intf, USBEndpoint* _bulk_in, USBEndpoint* _bulk_out) { host = _host; @@ -238,7 +238,7 @@ void USBHostSerialPort::connect(USBHost* _host, USBDeviceConnected * _dev, serial_intf = _serial_intf; bulk_in = _bulk_in; bulk_out = _bulk_out; - + USB_INFO("New Serial device: VID:%04x PID:%04x [dev: %p - intf: %d]", dev->getVid(), dev->getPid(), dev, serial_intf); dev->setName("Serial", serial_intf); host->registerDriver(dev, serial_intf, this, &USBHostSerialPort::init); @@ -289,7 +289,7 @@ void USBHostSerialPort::format(int bits, Parity parity, int stop_bits) { line_coding.data_bits = bits; line_coding.parity = parity; line_coding.stop_bits = (stop_bits == 1) ? 0 : 2; - + // set line coding host->controlWrite( dev, USB_RECIPIENT_INTERFACE | USB_HOST_TO_DEVICE | USB_REQUEST_TYPE_CLASS, @@ -311,12 +311,12 @@ int USBHostSerialPort::_getc() { int USBHostSerialPort::writeBuf(const char* b, int s) { int c = 0; - if (bulk_out) + if (bulk_out) { while (c < s) { int i = (s < size_bulk_out) ? s : size_bulk_out; - if (host->bulkWrite(dev, bulk_out, (uint8_t *)(b+c), i) == USB_TYPE_OK) + if (host->bulkWrite(dev, bulk_out, (uint8_t *)(b+c), i) == USB_TYPE_OK) c += i; } } @@ -326,7 +326,7 @@ int USBHostSerialPort::writeBuf(const char* b, int s) int USBHostSerialPort::readBuf(char* b, int s) { int i = 0; - if (bulk_in) + if (bulk_in) { for (i = 0; i < s; ) b[i++] = getc(); diff --git a/libraries/USBHost/USBHostSerial/USBHostSerial.h b/libraries/USBHost/USBHostSerial/USBHostSerial.h index 53466da249..94fc8ad7c5 100644 --- a/libraries/USBHost/USBHostSerial/USBHostSerial.h +++ b/libraries/USBHost/USBHostSerial/USBHostSerial.h @@ -25,7 +25,7 @@ #include "Stream.h" #include "MtxCircBuffer.h" -/** +/** * A class to communicate a USB virtual serial port */ class USBHostSerialPort : public Stream { @@ -39,7 +39,7 @@ public: RxIrq, TxIrq }; - + enum Parity { None = 0, Odd, @@ -48,7 +48,7 @@ public: Space }; - void connect(USBHost* _host, USBDeviceConnected * _dev, + void connect(USBHost* _host, USBDeviceConnected * _dev, uint8_t _serial_intf, USBEndpoint* _bulk_in, USBEndpoint* _bulk_out); /** @@ -56,7 +56,7 @@ public: * * @returns the number of bytes available */ - uint8_t available(); + uint8_t available(); /** * Attach a member function to call when a packet is received. @@ -90,13 +90,13 @@ public: } } } - + /** Set the baud rate of the serial port * * @param baudrate The baudrate of the serial port (default = 9600). */ void baud(int baudrate = 9600); - + /** Set the transmission format used by the Serial port * * @param bits The number of bits in a word (default = 8) @@ -110,7 +110,7 @@ public: protected: virtual int _getc(); virtual int _putc(int c); - + private: USBHost * host; USBDeviceConnected * dev; @@ -132,7 +132,7 @@ private: uint8_t parity; uint8_t data_bits; } PACKED LINE_CODING; - + LINE_CODING line_coding; void rxHandler(); @@ -145,18 +145,18 @@ private: #if (USBHOST_SERIAL <= 1) -class USBHostSerial : public IUSBEnumerator, public USBHostSerialPort +class USBHostSerial : public IUSBEnumerator, public USBHostSerialPort { -public: +public: USBHostSerial(); - + /** * Try to connect a serial device * * @return true if connection was successful */ bool connect(); - + void disconnect(); /** @@ -165,7 +165,7 @@ public: * @returns true if a serial device is connected */ bool connected(); - + protected: USBHost* host; USBDeviceConnected* dev; @@ -176,7 +176,7 @@ protected: virtual void setVidPid(uint16_t vid, uint16_t pid); virtual bool parseInterface(uint8_t intf_nb, uint8_t intf_class, uint8_t intf_subclass, uint8_t intf_protocol); //Must return true if the interface should be parsed virtual bool useEndpoint(uint8_t intf_nb, ENDPOINT_TYPE type, ENDPOINT_DIRECTION dir); //Must return true if the endpoint will be used - + private: bool dev_connected; }; @@ -184,13 +184,13 @@ private: #else // (USBHOST_SERIAL > 1) class USBHostMultiSerial : public IUSBEnumerator { -public: +public: USBHostMultiSerial(); virtual ~USBHostMultiSerial(); - - USBHostSerialPort* getPort(int port) - { - return port < USBHOST_SERIAL ? ports[port] : NULL; + + USBHostSerialPort* getPort(int port) + { + return port < USBHOST_SERIAL ? ports[port] : NULL; } /** @@ -199,7 +199,7 @@ public: * @return true if connection was successful */ bool connect(); - + void disconnect(); /** @@ -208,7 +208,7 @@ public: * @returns true if a serial device is connected */ bool connected(); - + protected: USBHost* host; USBDeviceConnected* dev; @@ -220,7 +220,7 @@ protected: virtual void setVidPid(uint16_t vid, uint16_t pid); virtual bool parseInterface(uint8_t intf_nb, uint8_t intf_class, uint8_t intf_subclass, uint8_t intf_protocol); //Must return true if the interface should be parsed virtual bool useEndpoint(uint8_t intf_nb, ENDPOINT_TYPE type, ENDPOINT_DIRECTION dir); //Must return true if the endpoint will be used - + private: bool dev_connected; }; diff --git a/libraries/ble/ble-api/GapAdvertisingData.cpp b/libraries/ble/ble-api/GapAdvertisingData.cpp deleted file mode 100644 index d52c9ea7c8..0000000000 --- a/libraries/ble/ble-api/GapAdvertisingData.cpp +++ /dev/null @@ -1,240 +0,0 @@ -/* mbed Microcontroller Library - * Copyright (c) 2006-2013 ARM Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include - -#include "GapAdvertisingData.h" - -/**************************************************************************/ -/*! - \brief Creates a new GapAdvertisingData instance - - \par EXAMPLE - - \code - - \endcode -*/ -/**************************************************************************/ -GapAdvertisingData::GapAdvertisingData(void) -{ - memset(_payload, 0, GAP_ADVERTISING_DATA_MAX_PAYLOAD); - _payloadLen = 0; - _appearance = GENERIC_TAG; -} - -/**************************************************************************/ -/*! - Destructor -*/ -/**************************************************************************/ -GapAdvertisingData::~GapAdvertisingData(void) -{ -} - -/**************************************************************************/ -/*! - \brief Adds advertising data based on the specified AD type (see - DataType) - - \args[in] advDataType The Advertising 'DataType' to add - \args[in] payload Pointer to the payload contents - \args[in] len Size of the payload in bytes - - \returns ble_error_t - - \retval BLE_ERROR_NONE - Everything executed properly - - \retval BLE_ERROR_BUFFER_OVERFLOW - The specified data would cause the advertising buffer - to overflow - - \par EXAMPLE - - \code - - \endcode -*/ -/**************************************************************************/ -ble_error_t GapAdvertisingData::addData(DataType advDataType, uint8_t * payload, uint8_t len) -{ - /* ToDo: Check if an AD type already exists and if the existing */ - /* value is exclusive or not (flags, etc.) */ - - /* Make sure we don't exceed the 31 byte payload limit */ - if (_payloadLen + len + 2 >= GAP_ADVERTISING_DATA_MAX_PAYLOAD) - return BLE_ERROR_BUFFER_OVERFLOW; - - /* Field length */ - memset(&_payload[_payloadLen], len+1, 1); - _payloadLen++; - - /* Field ID */ - memset(&_payload[_payloadLen], (uint8_t)advDataType, 1); - _payloadLen++; - - /* Payload */ - memcpy(&_payload[_payloadLen], payload, len); - _payloadLen += len; - - return BLE_ERROR_NONE; -} - -/**************************************************************************/ -/*! - \brief Helper function to add APPEARANCE data to the advertising - payload - - \args[in] appearance The APPEARANCE value to add - - \returns ble_error_t - - \retval BLE_ERROR_NONE - Everything executed properly - - \retval BLE_ERROR_BUFFER_OVERFLOW - The specified data would cause the advertising buffer - to overflow - - \par EXAMPLE - - \code - - \endcode -*/ -/**************************************************************************/ -ble_error_t GapAdvertisingData::addAppearance(Appearance appearance) -{ - _appearance = appearance; - return addData(GapAdvertisingData::APPEARANCE, (uint8_t*)&appearance, 2); -} - -/**************************************************************************/ -/*! - \brief Helper function to add FLAGS data to the advertising - payload - - \args[in] flag The FLAGS value to add - - \par LE_LIMITED_DISCOVERABLE - The peripheral is discoverable for a limited period of - time - - \par LE_GENERAL_DISCOVERABLE - The peripheral is permanently discoverable - - \par BREDR_NOT_SUPPORTED - This peripheral is a Bluetooth Low Energy only device - (no EDR support) - - \returns ble_error_t - - \retval BLE_ERROR_NONE - Everything executed properly - - \retval BLE_ERROR_BUFFER_OVERFLOW - The specified data would cause the advertising buffer - to overflow - - \par EXAMPLE - - \code - - \endcode -*/ -/**************************************************************************/ -ble_error_t GapAdvertisingData::addFlags(Flags flag) -{ - return addData(GapAdvertisingData::FLAGS, (uint8_t*)&flag, 1); -} - -/**************************************************************************/ -/*! - \brief Helper function to add TX_POWER_LEVEL data to the - advertising payload - - \args[in] flag The TX_POWER_LEVEL value to add - - \returns ble_error_t - - \retval BLE_ERROR_NONE - Everything executed properly - - \retval BLE_ERROR_BUFFER_OVERFLOW - The specified data would cause the advertising buffer - to overflow - - \par EXAMPLE - - \code - - \endcode -*/ -/**************************************************************************/ -ble_error_t GapAdvertisingData::addTxPower(int8_t txPower) -{ - /* ToDo: Basic error checking to make sure txPower is in range */ - return addData(GapAdvertisingData::TX_POWER_LEVEL, (uint8_t*)&txPower, 1); -} - -/**************************************************************************/ -/*! - \brief Clears the payload and resets the payload length counter -*/ -/**************************************************************************/ -void GapAdvertisingData::clear(void) -{ - memset(&_payload, 0, GAP_ADVERTISING_DATA_MAX_PAYLOAD); - _payloadLen = 0; -} - -/**************************************************************************/ -/*! - \brief Returns a pointer to the the current payload - - \returns A pointer to the payload -*/ -/**************************************************************************/ -uint8_t * GapAdvertisingData::getPayload(void) -{ - return (_payloadLen > 0) ? _payload : NULL; -} - -/**************************************************************************/ -/*! - \brief Returns the current payload length (0..31 bytes) - - \returns The payload length in bytes -*/ -/**************************************************************************/ -uint8_t GapAdvertisingData::getPayloadLen(void) -{ - return _payloadLen; -} - -/**************************************************************************/ -/*! - \brief Returns the 16-bit appearance value for this device - - \returns The 16-bit appearance value -*/ -/**************************************************************************/ -uint16_t GapAdvertisingData::getAppearance(void) -{ - return (uint16_t)_appearance; -} diff --git a/libraries/ble/ble-api/GapAdvertisingData.h b/libraries/ble/ble-api/GapAdvertisingData.h deleted file mode 100644 index 89b60dd208..0000000000 --- a/libraries/ble/ble-api/GapAdvertisingData.h +++ /dev/null @@ -1,212 +0,0 @@ -/* mbed Microcontroller Library - * Copyright (c) 2006-2013 ARM Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef __GAP_ADVERTISING_DATA_H__ -#define __GAP_ADVERTISING_DATA_H__ - -#include "blecommon.h" - -#define GAP_ADVERTISING_DATA_MAX_PAYLOAD (31) - -/**************************************************************************/ -/*! - \brief - This class provides several helper functions to generate properly - formatted GAP Advertising and Scan Response data payloads - - \note - See Bluetooth Specification 4.0 (Vol. 3), Part C, Section 11 and 18 - for further information on Advertising and Scan Response data. - - \par Advertising and Scan Response Payloads - Advertising data and Scan Response data are organized around a set of - data types called 'AD types' in Bluetooth 4.0 (see the Bluetooth Core - Specification v4.0, Vol. 3, Part C, Sections 11 and 18). - - \par - Each AD type has it's own standardized 'assigned number', as defined - by the Bluetooth SIG: - https://www.bluetooth.org/en-us/specification/assigned-numbers/generic-access-profile - - \par - For convenience sake, all appropriate AD types have been encapsulated - into GapAdvertisingData::DataType. - - \par - Before the AD Types and their payload (if any) can be inserted into - the Advertising or Scan Response frames, they need to be formatted as - follows: - - \li \c Record length (1 byte) - \li \c AD Type (1 byte) - \li \c AD payload (optional, only present if record length > 1) - - \par - This class takes care of properly formatting the payload, performs - some basic checks on the payload length, and tries to avoid common - errors like adding an exclusive AD field twice in the Advertising - or Scan Response payload. - - \par EXAMPLE - - \code - - // ToDo - - \endcode -*/ -/**************************************************************************/ -class GapAdvertisingData -{ - public: - /**********************************************************************/ - /*! - \brief - A list of Advertising Data types commonly used by peripherals. - These AD types are used to describe the capabilities of the - peripheral, and get inserted inside the advertising or scan - response payloads. - - \par Source - \li \c Bluetooth Core Specification 4.0 (Vol. 3), Part C, Section 11, 18 - \li \c https://www.bluetooth.org/en-us/specification/assigned-numbers/generic-access-profile - */ - /**********************************************************************/ - enum DataType - { - FLAGS = 0x01, /**< \ref Flags */ - INCOMPLETE_LIST_16BIT_SERVICE_IDS = 0x02, /**< Incomplete list of 16-bit Service IDs */ - COMPLETE_LIST_16BIT_SERVICE_IDS = 0x03, /**< Complete list of 16-bit Service IDs */ - INCOMPLETE_LIST_32BIT_SERVICE_IDS = 0x04, /**< Incomplete list of 32-bit Service IDs (not relevant for Bluetooth 4.0) */ - COMPLETE_LIST_32BIT_SERVICE_IDS = 0x05, /**< Complete list of 32-bit Service IDs (not relevant for Bluetooth 4.0) */ - INCOMPLETE_LIST_128BIT_SERVICE_IDS = 0x06, /**< Incomplete list of 128-bit Service IDs */ - COMPLETE_LIST_128BIT_SERVICE_IDS = 0x07, /**< Complete list of 128-bit Service IDs */ - SHORTENED_LOCAL_NAME = 0x08, /**< Shortened Local Name */ - COMPLETE_LOCAL_NAME = 0x09, /**< Complete Local Name */ - TX_POWER_LEVEL = 0x0A, /**< TX Power Level (in dBm) */ - DEVICE_ID = 0x10, /**< Device ID */ - SLAVE_CONNECTION_INTERVAL_RANGE = 0x12, /**< Slave Connection Interval Range */ - SERVICE_DATA = 0x16, /**< Service Data */ - APPEARANCE = 0x19, /**< \ref Appearance */ - ADVERTISING_INTERVAL = 0x1A, /**< Advertising Interval */ - MANUFACTURER_SPECIFIC_DATA = 0xFF /**< Manufacturer Specific Data */ - }; - - /**********************************************************************/ - /*! - \brief - A list of values for the FLAGS AD Type - - \note - You can use more than one value in the FLAGS AD Type (ex. - LE_GENERAL_DISCOVERABLE and BREDR_NOT_SUPPORTED). - - \par Source - \li \c Bluetooth Core Specification 4.0 (Vol. 3), Part C, Section 18.1 - */ - /**********************************************************************/ - enum Flags - { - LE_LIMITED_DISCOVERABLE = 0x01, /**< Peripheral device is discoverable for a limited period of time */ - LE_GENERAL_DISCOVERABLE = 0x02, /**< Peripheral device is discoverable at any moment */ - BREDR_NOT_SUPPORTED = 0x04, /**< Peripheral device is LE only */ - SIMULTANEOUS_LE_BREDR_C = 0x08, /**< Not relevant - central mode only */ - SIMULTANEOUS_LE_BREDR_H = 0x10 /**< Not relevant - central mode only */ - }; - - /**********************************************************************/ - /*! - \brief - A list of values for the APPEARANCE AD Type, which describes the - physical shape or appearance of the device - - \par Source - \li \c Bluetooth Core Specification Supplement, Part A, Section 1.12 - \li \c Bluetooth Core Specification 4.0 (Vol. 3), Part C, Section 12.2 - \li \c https://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.gap.appearance.xml - */ - /**********************************************************************/ - enum Appearance - { - UNKNOWN = 0, /**< Unknown of unspecified appearance type */ - GENERIC_PHONE = 64, /**< Generic Phone */ - GENERIC_COMPUTER = 128, /**< Generic Computer */ - GENERIC_WATCH = 192, /**< Generic Watch */ - WATCH_SPORTS_WATCH = 193, /**< Sports Watch */ - GENERIC_CLOCK = 256, /**< Generic Clock */ - GENERIC_DISPLAY = 320, /**< Generic Display */ - GENERIC_REMOTE_CONTROL = 384, /**< Generic Remote Control */ - GENERIC_EYE_GLASSES = 448, /**< Generic Eye Glasses */ - GENERIC_TAG = 512, /**< Generic Tag */ - GENERIC_KEYRING = 576, /**< Generic Keyring */ - GENERIC_MEDIA_PLAYER = 640, /**< Generic Media Player */ - GENERIC_BARCODE_SCANNER = 704, /**< Generic Barcode Scanner */ - GENERIC_THERMOMETER = 768, /**< Generic Thermometer */ - THERMOMETER_EAR = 769, /**< Ear Thermometer */ - GENERIC_HEART_RATE_SENSOR = 832, /**< Generic Heart Rate Sensor */ - HEART_RATE_SENSOR_HEART_RATE_BELT = 833, /**< Belt Heart Rate Sensor */ - GENERIC_BLOOD_PRESSURE = 896, /**< Generic Blood Pressure */ - BLOOD_PRESSURE_ARM = 897, /**< Arm Blood Pressure */ - BLOOD_PRESSURE_WRIST = 898, /**< Wrist Blood Pressure */ - HUMAN_INTERFACE_DEVICE_HID = 960, /**< Human Interface Device (HID) */ - KEYBOARD = 961, /**< Keyboard */ - MOUSE = 962, /**< Mouse */ - JOYSTICK = 963, /**< Joystick */ - GAMEPAD = 964, /**< Gamepad */ - DIGITIZER_TABLET = 965, /**< Digitizer Tablet */ - CARD_READER = 966, /**< Card Read */ - DIGITAL_PEN = 967, /**< Digital Pen */ - BARCODE_SCANNER = 968, /**< Barcode Scanner */ - GENERIC_GLUCOSE_METER = 1024, /**< Generic Glucose Meter */ - GENERIC_RUNNING_WALKING_SENSOR = 1088, /**< Generic Running/Walking Sensor */ - RUNNING_WALKING_SENSOR_IN_SHOE = 1089, /**< In Shoe Running/Walking Sensor */ - RUNNING_WALKING_SENSOR_ON_SHOE = 1090, /**< On Shoe Running/Walking Sensor */ - RUNNING_WALKING_SENSOR_ON_HIP = 1091, /**< On Hip Running/Walking Sensor */ - GENERIC_CYCLING = 1152, /**< Generic Cycling */ - CYCLING_CYCLING_COMPUTER = 1153, /**< Cycling Computer */ - CYCLING_SPEED_SENSOR = 1154, /**< Cycling Speed Senspr */ - CYCLING_CADENCE_SENSOR = 1155, /**< Cycling Cadence Sensor */ - CYCLING_POWER_SENSOR = 1156, /**< Cycling Power Sensor */ - CYCLING_SPEED_AND_CADENCE_SENSOR = 1157, /**< Cycling Speed and Cadence Sensor */ - PULSE_OXIMETER_GENERIC = 3136, /**< Generic Pulse Oximeter */ - PULSE_OXIMETER_FINGERTIP = 3137, /**< Fingertip Pulse Oximeter */ - PULSE_OXIMETER_WRIST_WORN = 3138, /**< Wrist Worn Pulse Oximeter */ - OUTDOOR_GENERIC = 5184, /**< Generic Outdoor */ - OUTDOOR_LOCATION_DISPLAY_DEVICE = 5185, /**< Outdoor Location Display Device */ - OUTDOOR_LOCATION_AND_NAVIGATION_DISPLAY_DEVICE = 5186, /**< Outdoor Location and Navigation Display Device */ - OUTDOOR_LOCATION_POD = 5187, /**< Outdoor Location Pod */ - OUTDOOR_LOCATION_AND_NAVIGATION_POD = 5188 /**< Outdoor Location and Navigation Pod */ - }; - - GapAdvertisingData(void); - virtual ~GapAdvertisingData(void); - - ble_error_t addData(DataType, uint8_t *, uint8_t); - ble_error_t addAppearance(Appearance appearance = GENERIC_TAG); - ble_error_t addFlags(Flags flag = LE_GENERAL_DISCOVERABLE); - ble_error_t addTxPower(int8_t txPower); - void clear(void); - uint8_t * getPayload(void); - uint8_t getPayloadLen(void); - uint16_t getAppearance(void); - - private: - uint8_t _payload[GAP_ADVERTISING_DATA_MAX_PAYLOAD]; - uint8_t _payloadLen; - uint16_t _appearance; -}; - -#endif diff --git a/libraries/ble/ble-api/GapAdvertisingParams.cpp b/libraries/ble/ble-api/GapAdvertisingParams.cpp deleted file mode 100644 index 348e52d46d..0000000000 --- a/libraries/ble/ble-api/GapAdvertisingParams.cpp +++ /dev/null @@ -1,168 +0,0 @@ -/* mbed Microcontroller Library - * Copyright (c) 2006-2013 ARM Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include - -#include "blecommon.h" -#include "GapAdvertisingParams.h" - -/**************************************************************************/ -/*! - \brief - Instantiates a new GapAdvertisingParams instance - - \param[in] advType - The GAP advertising mode to use for this device. Valid - values are defined in AdvertisingType: - - \par ADV_NON_CONNECTABLE_UNDIRECTED - All connections to the peripheral device will be refused. - - \par ADV_CONNECTABLE_DIRECTED - Only connections from a pre-defined central device will be - accepted. - - \par ADV_CONNECTABLE_UNDIRECTED - Any central device can connect to this peripheral. - - \par ADV_SCANNABLE_UNDIRECTED - Any central device can connect to this peripheral, and - the secondary Scan Response payload will be included or - available to central devices. - - \par - See Bluetooth Core Specification 4.0 (Vol. 3), Part C, - Section 9.3 and Core Specification 4.0 (Vol. 6), Part B, - Section 2.3.1 for further information on GAP connection - modes - - \param[in] interval - Advertising interval between 0x0020 and 0x4000 in 0.625ms - units (20ms to 10.24s). If using non-connectable mode - (ADV_NON_CONNECTABLE_UNDIRECTED) this min value is - 0x00A0 (100ms). - - \par - Increasing this value will allow central devices to detect - your peripheral faster at the expense of more power being - used by the radio due to the higher data transmit rate. - - \par - This field must be set to 0 if connectionMode is equal - to ADV_CONNECTABLE_DIRECTED - - \par - See Bluetooth Core Specification, Vol 3., Part C, - Appendix A for suggested advertising intervals. - - \param[in] timeout - Advertising timeout between 0x1 and 0x3FFF (1 and 16383) - in seconds. Enter 0 to disable the advertising timeout. - - \par EXAMPLE - - \code - - \endcode -*/ -/**************************************************************************/ -GapAdvertisingParams::GapAdvertisingParams(AdvertisingType advType, uint16_t interval, uint16_t timeout) -{ - _advType = advType; - _interval = interval; - _timeout = timeout; - - /* Interval checks */ - if (_advType == ADV_CONNECTABLE_DIRECTED) - { - /* Interval must be 0 in directed connectable mode */ - _interval = 0; - } - else if (_advType == ADV_NON_CONNECTABLE_UNDIRECTED) - { - /* Min interval is slightly larger than in other modes */ - if (_interval < GAP_ADV_PARAMS_INTERVAL_MIN_NONCON) - { - _interval = GAP_ADV_PARAMS_INTERVAL_MIN_NONCON; - } - if (_interval > GAP_ADV_PARAMS_INTERVAL_MAX) - { - _interval = GAP_ADV_PARAMS_INTERVAL_MAX; - } - } - else - { - /* Stay within interval limits */ - if (_interval < GAP_ADV_PARAMS_INTERVAL_MIN) - { - _interval = GAP_ADV_PARAMS_INTERVAL_MIN; - } - if (_interval > GAP_ADV_PARAMS_INTERVAL_MAX) - { - _interval = GAP_ADV_PARAMS_INTERVAL_MAX; - } - } - - /* Timeout checks */ - if (timeout) - { - /* Stay within timeout limits */ - if (_timeout > GAP_ADV_PARAMS_TIMEOUT_MAX) - { - _timeout = GAP_ADV_PARAMS_TIMEOUT_MAX; - } - } -} - -/**************************************************************************/ -/*! - Destructor -*/ -/**************************************************************************/ -GapAdvertisingParams::~GapAdvertisingParams(void) -{ -} - -/**************************************************************************/ -/*! - \brief returns the current Advertising Type value -*/ -/**************************************************************************/ -GapAdvertisingParams::AdvertisingType GapAdvertisingParams::getAdvertisingType(void) -{ - return _advType; -} - -/**************************************************************************/ -/*! - \brief returns the current Advertising Delay (in units of 0.625ms) -*/ -/**************************************************************************/ -uint16_t GapAdvertisingParams::getInterval(void) -{ - return _interval; -} - -/**************************************************************************/ -/*! - \brief returns the current Advertising Timeout (in seconds) -*/ -/**************************************************************************/ -uint16_t GapAdvertisingParams::getTimeout(void) -{ - return _timeout; -} diff --git a/libraries/ble/ble-api/GapAdvertisingParams.h b/libraries/ble/ble-api/GapAdvertisingParams.h deleted file mode 100644 index 639980165e..0000000000 --- a/libraries/ble/ble-api/GapAdvertisingParams.h +++ /dev/null @@ -1,89 +0,0 @@ -/* mbed Microcontroller Library - * Copyright (c) 2006-2013 ARM Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - -#ifndef __GAP_ADVERTISING_PARAMS_H__ -#define __GAP_ADVERTISING_PARAMS_H__ - -#include "blecommon.h" - -#define GAP_ADV_PARAMS_INTERVAL_MIN (0x0020) -#define GAP_ADV_PARAMS_INTERVAL_MIN_NONCON (0x00A0) -#define GAP_ADV_PARAMS_INTERVAL_MAX (0x1000) -#define GAP_ADV_PARAMS_TIMEOUT_MAX (0x3FFF) - -/**************************************************************************/ -/*! - \brief - This class provides a wrapper for the core advertising parameters, - including the advertising type (Connectable Undirected, - Non Connectable Undirected, etc.), as well as the advertising and - timeout intervals. - - \par - See the following for more information on advertising types: - - \li \c Bluetooth Core Specification 4.0 (Vol. 6), Part B, Section 2.3.1 - \li \c Bluetooth Core Specification 4.0 (Vol. 3), Part C, Section 9.3 - - \par EXAMPLE - - \code - - // ToDo - - \endcode -*/ -/**************************************************************************/ -class GapAdvertisingParams -{ - public: - /**************************************************************************/ - /*! - \brief - Encapsulates the peripheral advertising modes, which determine how - the device appears to other central devices in hearing range - - \par - See the following for more information on advertising types: - - \li \c Bluetooth Core Specification 4.0 (Vol. 6), Part B, Section 2.3.1 - \li \c Bluetooth Core Specification 4.0 (Vol. 3), Part C, Section 9.3 - */ - /**************************************************************************/ - enum AdvertisingType - { - ADV_CONNECTABLE_UNDIRECTED, /**< Vol 3, Part C, Section 9.3.4 and Vol 6, Part B, Section 2.3.1.1 */ - ADV_CONNECTABLE_DIRECTED, /**< Vol 3, Part C, Section 9.3.3 and Vol 6, Part B, Section 2.3.1.2 */ - ADV_SCANNABLE_UNDIRECTED, /**< Include support for Scan Response payloads, see Vol 6, Part B, Section 2.3.1.4 */ - ADV_NON_CONNECTABLE_UNDIRECTED /**< Vol 3, Part C, Section 9.3.2 and Vol 6, Part B, Section 2.3.1.3 */ - }; - - GapAdvertisingParams(AdvertisingType advType = GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED, - uint16_t interval = GAP_ADV_PARAMS_INTERVAL_MIN_NONCON, - uint16_t timeout = 0); - virtual ~GapAdvertisingParams(void); - - virtual AdvertisingType getAdvertisingType(void); - virtual uint16_t getInterval(void); - virtual uint16_t getTimeout(void); - - private: - AdvertisingType _advType; - uint16_t _interval; - uint16_t _timeout; -}; - -#endif diff --git a/libraries/ble/ble-api/GattCharacteristic.cpp b/libraries/ble/ble-api/GattCharacteristic.cpp deleted file mode 100644 index 46a20cd50f..0000000000 --- a/libraries/ble/ble-api/GattCharacteristic.cpp +++ /dev/null @@ -1,65 +0,0 @@ -/* mbed Microcontroller Library - * Copyright (c) 2006-2013 ARM Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include - -#include "GattCharacteristic.h" - -/**************************************************************************/ -/*! - @brief Creates a new GattCharacteristic using the specified 16-bit - UUID, value length, and properties - - @note The UUID value must be unique in the service and is normally >1 - - @param[in] id - The 16-bit UUID to use for this characteristic - @param[in] minLen - The min length in bytes of this characteristic's value - @param[in] maxLen - The max length in bytes of this characteristic's value - @param[in] props - The 8-bit bit field containing the characteristic's - properties - - @section EXAMPLE - - @code - - // UUID = 0x2A19, Min length 2, Max len = 2, Properties = write - GattCharacteristic c = GattCharacteristic( 0x2A19, 2, 2, BLE_GATT_CHAR_PROPERTIES_WRITE ); - - @endcode -*/ -/**************************************************************************/ -GattCharacteristic::GattCharacteristic(uint16_t id, uint16_t minLen, uint16_t maxLen, uint8_t props) -{ - uuid = id; - memcpy(&properties, &props, 1); - lenMin = minLen; - lenMax = maxLen; -// handle = 0; -} - -/**************************************************************************/ -/*! - Destructor -*/ -/**************************************************************************/ -GattCharacteristic::~GattCharacteristic(void) -{ -} diff --git a/libraries/ble/ble-api/GattCharacteristic.h b/libraries/ble/ble-api/GattCharacteristic.h deleted file mode 100644 index c3be061bd5..0000000000 --- a/libraries/ble/ble-api/GattCharacteristic.h +++ /dev/null @@ -1,318 +0,0 @@ -/* mbed Microcontroller Library - * Copyright (c) 2006-2013 ARM Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -#ifndef __GATT_CHARACTERISTIC_H__ -#define __GATT_CHARACTERISTIC_H__ - -#include "blecommon.h" -#include "UUID.h" - -#include "ble_gatts.h" -/* ToDo: Update to use 16-bit or 128-bit UUIDs! */ - -/**************************************************************************/ -/*! - \brief GATT characteristic -*/ -/**************************************************************************/ -class GattCharacteristic -{ - public: - enum - { - UUID_BATTERY_LEVEL_STATE_CHAR = 0x2A1B, - UUID_BATTERY_POWER_STATE_CHAR = 0x2A1A, - UUID_REMOVABLE_CHAR = 0x2A3A, - UUID_SERVICE_REQUIRED_CHAR = 0x2A3B, - UUID_ALERT_CATEGORY_ID_CHAR = 0x2A43, - UUID_ALERT_CATEGORY_ID_BIT_MASK_CHAR = 0x2A42, - UUID_ALERT_LEVEL_CHAR = 0x2A06, - UUID_ALERT_NOTIFICATION_CONTROL_POINT_CHAR = 0x2A44, - UUID_ALERT_STATUS_CHAR = 0x2A3F, - UUID_BATTERY_LEVEL_CHAR = 0x2A19, - UUID_BLOOD_PRESSURE_FEATURE_CHAR = 0x2A49, - UUID_BLOOD_PRESSURE_MEASUREMENT_CHAR = 0x2A35, - UUID_BODY_SENSOR_LOCATION_CHAR = 0x2A38, - UUID_BOOT_KEYBOARD_INPUT_REPORT_CHAR = 0x2A22, - UUID_BOOT_KEYBOARD_OUTPUT_REPORT_CHAR = 0x2A32, - UUID_BOOT_MOUSE_INPUT_REPORT_CHAR = 0x2A33, - UUID_CURRENT_TIME_CHAR = 0x2A2B, - UUID_DATE_TIME_CHAR = 0x2A08, - UUID_DAY_DATE_TIME_CHAR = 0x2A0A, - UUID_DAY_OF_WEEK_CHAR = 0x2A09, - UUID_DST_OFFSET_CHAR = 0x2A0D, - UUID_EXACT_TIME_256_CHAR = 0x2A0C, - UUID_FIRMWARE_REVISION_STRING_CHAR = 0x2A26, - UUID_GLUCOSE_FEATURE_CHAR = 0x2A51, - UUID_GLUCOSE_MEASUREMENT_CHAR = 0x2A18, - UUID_GLUCOSE_MEASUREMENT_CONTEXT_CHAR = 0x2A34, - UUID_HARDWARE_REVISION_STRING_CHAR = 0x2A27, - UUID_HEART_RATE_CONTROL_POINT_CHAR = 0x2A39, - UUID_HEART_RATE_MEASUREMENT_CHAR = 0x2A37, - UUID_HID_CONTROL_POINT_CHAR = 0x2A4C, - UUID_HID_INFORMATION_CHAR = 0x2A4A, - UUID_IEEE_REGULATORY_CERTIFICATION_DATA_LIST_CHAR = 0x2A2A, - UUID_INTERMEDIATE_CUFF_PRESSURE_CHAR = 0x2A36, - UUID_INTERMEDIATE_TEMPERATURE_CHAR = 0x2A1E, - UUID_LOCAL_TIME_INFORMATION_CHAR = 0x2A0F, - UUID_MANUFACTURER_NAME_STRING_CHAR = 0x2A29, - UUID_MEASUREMENT_INTERVAL_CHAR = 0x2A21, - UUID_MODEL_NUMBER_STRING_CHAR = 0x2A24, - UUID_UNREAD_ALERT_CHAR = 0x2A45, - UUID_NEW_ALERT_CHAR = 0x2A46, - UUID_PNP_ID_CHAR = 0x2A50, - UUID_PROTOCOL_MODE_CHAR = 0x2A4E, - UUID_RECORD_ACCESS_CONTROL_POINT_CHAR = 0x2A52, - UUID_REFERENCE_TIME_INFORMATION_CHAR = 0x2A14, - UUID_REPORT_CHAR = 0x2A4D, - UUID_REPORT_MAP_CHAR = 0x2A4B, - UUID_RINGER_CONTROL_POINT_CHAR = 0x2A40, - UUID_RINGER_SETTING_CHAR = 0x2A41, - UUID_SCAN_INTERVAL_WINDOW_CHAR = 0x2A4F, - UUID_SCAN_REFRESH_CHAR = 0x2A31, - UUID_SERIAL_NUMBER_STRING_CHAR = 0x2A25, - UUID_SOFTWARE_REVISION_STRING_CHAR = 0x2A28, - UUID_SUPPORTED_NEW_ALERT_CATEGORY_CHAR = 0x2A47, - UUID_SUPPORTED_UNREAD_ALERT_CATEGORY_CHAR = 0x2A48, - UUID_SYSTEM_ID_CHAR = 0x2A23, - UUID_TEMPERATURE_MEASUREMENT_CHAR = 0x2A1C, - UUID_TEMPERATURE_TYPE_CHAR = 0x2A1D, - UUID_TIME_ACCURACY_CHAR = 0x2A12, - UUID_TIME_SOURCE_CHAR = 0x2A13, - UUID_TIME_UPDATE_CONTROL_POINT_CHAR = 0x2A16, - UUID_TIME_UPDATE_STATE_CHAR = 0x2A17, - UUID_TIME_WITH_DST_CHAR = 0x2A11, - UUID_TIME_ZONE_CHAR = 0x2A0E, - UUID_TX_POWER_LEVEL_CHAR = 0x2A07, - UUID_CSC_FEATURE_CHAR = 0x2A5C, - UUID_CSC_MEASUREMENT_CHAR = 0x2A5B, - UUID_RSC_FEATURE_CHAR = 0x2A54, - UUID_RSC_MEASUREMENT_CHAR = 0x2A53, - }; - - /**************************************************************************/ - /*! - \brief Standard GATT characteristic presentation format unit types. - These unit types are used to decribe what the raw numeric - data in a characteristic actually represents. - - \note See https://developer.bluetooth.org/gatt/units/Pages/default.aspx - */ - /**************************************************************************/ - typedef enum ble_gatt_unit_e - { - BLE_GATT_UNIT_NONE = 0x2700, /**< No specified unit type */ - BLE_GATT_UNIT_LENGTH_METRE = 0x2701, /**< Length, Metre */ - BLE_GATT_UNIT_MASS_KILOGRAM = 0x2702, /**< Mass, Kilogram */ - BLE_GATT_UNIT_TIME_SECOND = 0x2703, /**< Time, Second */ - BLE_GATT_UNIT_ELECTRIC_CURRENT_AMPERE = 0x2704, /**< Electric Current, Ampere */ - BLE_GATT_UNIT_THERMODYNAMIC_TEMPERATURE_KELVIN = 0x2705, /**< Thermodynamic Temperature, Kelvin */ - BLE_GATT_UNIT_AMOUNT_OF_SUBSTANCE_MOLE = 0x2706, /**< Amount of Substance, Mole */ - BLE_GATT_UNIT_LUMINOUS_INTENSITY_CANDELA = 0x2707, /**< Luminous Intensity, Candela */ - BLE_GATT_UNIT_AREA_SQUARE_METRES = 0x2710, /**< Area, Square Metres */ - BLE_GATT_UNIT_VOLUME_CUBIC_METRES = 0x2711, /**< Volume, Cubic Metres*/ - BLE_GATT_UNIT_VELOCITY_METRES_PER_SECOND = 0x2712, /**< Velocity, Metres per Second*/ - BLE_GATT_UNIT_ACCELERATION_METRES_PER_SECOND_SQUARED = 0x2713, /**< Acceleration, Metres per Second Squared */ - BLE_GATT_UNIT_WAVENUMBER_RECIPROCAL_METRE = 0x2714, /**< Wave Number Reciprocal, Metre */ - BLE_GATT_UNIT_DENSITY_KILOGRAM_PER_CUBIC_METRE = 0x2715, /**< Density, Kilogram per Cubic Metre */ - BLE_GATT_UNIT_SURFACE_DENSITY_KILOGRAM_PER_SQUARE_METRE = 0x2716, /**< */ - BLE_GATT_UNIT_SPECIFIC_VOLUME_CUBIC_METRE_PER_KILOGRAM = 0x2717, /**< */ - BLE_GATT_UNIT_CURRENT_DENSITY_AMPERE_PER_SQUARE_METRE = 0x2718, /**< */ - BLE_GATT_UNIT_MAGNETIC_FIELD_STRENGTH_AMPERE_PER_METRE = 0x2719, /**< Magnetic Field Strength, Ampere per Metre */ - BLE_GATT_UNIT_AMOUNT_CONCENTRATION_MOLE_PER_CUBIC_METRE = 0x271A, /**< */ - BLE_GATT_UNIT_MASS_CONCENTRATION_KILOGRAM_PER_CUBIC_METRE = 0x271B, /**< */ - BLE_GATT_UNIT_LUMINANCE_CANDELA_PER_SQUARE_METRE = 0x271C, /**< */ - BLE_GATT_UNIT_REFRACTIVE_INDEX = 0x271D, /**< */ - BLE_GATT_UNIT_RELATIVE_PERMEABILITY = 0x271E, /**< */ - BLE_GATT_UNIT_PLANE_ANGLE_RADIAN = 0x2720, /**< */ - BLE_GATT_UNIT_SOLID_ANGLE_STERADIAN = 0x2721, /**< */ - BLE_GATT_UNIT_FREQUENCY_HERTZ = 0x2722, /**< Frequency, Hertz */ - BLE_GATT_UNIT_FORCE_NEWTON = 0x2723, /**< Force, Newton */ - BLE_GATT_UNIT_PRESSURE_PASCAL = 0x2724, /**< Pressure, Pascal */ - BLE_GATT_UNIT_ENERGY_JOULE = 0x2725, /**< Energy, Joule */ - BLE_GATT_UNIT_POWER_WATT = 0x2726, /**< Power, Watt */ - BLE_GATT_UNIT_ELECTRIC_CHARGE_COULOMB = 0x2727, /**< Electrical Charge, Coulomb */ - BLE_GATT_UNIT_ELECTRIC_POTENTIAL_DIFFERENCE_VOLT = 0x2728, /**< Electrical Potential Difference, Voltage */ - BLE_GATT_UNIT_CAPACITANCE_FARAD = 0x2729, /**< */ - BLE_GATT_UNIT_ELECTRIC_RESISTANCE_OHM = 0x272A, /**< */ - BLE_GATT_UNIT_ELECTRIC_CONDUCTANCE_SIEMENS = 0x272B, /**< */ - BLE_GATT_UNIT_MAGNETIC_FLEX_WEBER = 0x272C, /**< */ - BLE_GATT_UNIT_MAGNETIC_FLEX_DENSITY_TESLA = 0x272D, /**< */ - BLE_GATT_UNIT_INDUCTANCE_HENRY = 0x272E, /**< */ - BLE_GATT_UNIT_THERMODYNAMIC_TEMPERATURE_DEGREE_CELSIUS = 0x272F, /**< */ - BLE_GATT_UNIT_LUMINOUS_FLUX_LUMEN = 0x2730, /**< */ - BLE_GATT_UNIT_ILLUMINANCE_LUX = 0x2731, /**< */ - BLE_GATT_UNIT_ACTIVITY_REFERRED_TO_A_RADIONUCLIDE_BECQUEREL = 0x2732, /**< */ - BLE_GATT_UNIT_ABSORBED_DOSE_GRAY = 0x2733, /**< */ - BLE_GATT_UNIT_DOSE_EQUIVALENT_SIEVERT = 0x2734, /**< */ - BLE_GATT_UNIT_CATALYTIC_ACTIVITY_KATAL = 0x2735, /**< */ - BLE_GATT_UNIT_DYNAMIC_VISCOSITY_PASCAL_SECOND = 0x2740, /**< */ - BLE_GATT_UNIT_MOMENT_OF_FORCE_NEWTON_METRE = 0x2741, /**< */ - BLE_GATT_UNIT_SURFACE_TENSION_NEWTON_PER_METRE = 0x2742, /**< */ - BLE_GATT_UNIT_ANGULAR_VELOCITY_RADIAN_PER_SECOND = 0x2743, /**< */ - BLE_GATT_UNIT_ANGULAR_ACCELERATION_RADIAN_PER_SECOND_SQUARED = 0x2744, /**< */ - BLE_GATT_UNIT_HEAT_FLUX_DENSITY_WATT_PER_SQUARE_METRE = 0x2745, /**< */ - BLE_GATT_UNIT_HEAT_CAPACITY_JOULE_PER_KELVIN = 0x2746, /**< */ - BLE_GATT_UNIT_SPECIFIC_HEAT_CAPACITY_JOULE_PER_KILOGRAM_KELVIN = 0x2747, /**< */ - BLE_GATT_UNIT_SPECIFIC_ENERGY_JOULE_PER_KILOGRAM = 0x2748, /**< */ - BLE_GATT_UNIT_THERMAL_CONDUCTIVITY_WATT_PER_METRE_KELVIN = 0x2749, /**< */ - BLE_GATT_UNIT_ENERGY_DENSITY_JOULE_PER_CUBIC_METRE = 0x274A, /**< */ - BLE_GATT_UNIT_ELECTRIC_FIELD_STRENGTH_VOLT_PER_METRE = 0x274B, /**< */ - BLE_GATT_UNIT_ELECTRIC_CHARGE_DENSITY_COULOMB_PER_CUBIC_METRE = 0x274C, /**< */ - BLE_GATT_UNIT_SURFACE_CHARGE_DENSITY_COULOMB_PER_SQUARE_METRE = 0x274D, /**< */ - BLE_GATT_UNIT_ELECTRIC_FLUX_DENSITY_COULOMB_PER_SQUARE_METRE = 0x274E, /**< */ - BLE_GATT_UNIT_PERMITTIVITY_FARAD_PER_METRE = 0x274F, /**< */ - BLE_GATT_UNIT_PERMEABILITY_HENRY_PER_METRE = 0x2750, /**< */ - BLE_GATT_UNIT_MOLAR_ENERGY_JOULE_PER_MOLE = 0x2751, /**< */ - BLE_GATT_UNIT_MOLAR_ENTROPY_JOULE_PER_MOLE_KELVIN = 0x2752, /**< */ - BLE_GATT_UNIT_EXPOSURE_COULOMB_PER_KILOGRAM = 0x2753, /**< */ - BLE_GATT_UNIT_ABSORBED_DOSE_RATE_GRAY_PER_SECOND = 0x2754, /**< */ - BLE_GATT_UNIT_RADIANT_INTENSITY_WATT_PER_STERADIAN = 0x2755, /**< */ - BLE_GATT_UNIT_RADIANCE_WATT_PER_SQUARE_METRE_STERADIAN = 0x2756, /**< */ - BLE_GATT_UNIT_CATALYTIC_ACTIVITY_CONCENTRATION_KATAL_PER_CUBIC_METRE = 0x2757, /**< */ - BLE_GATT_UNIT_TIME_MINUTE = 0x2760, /**< Time, Minute */ - BLE_GATT_UNIT_TIME_HOUR = 0x2761, /**< Time, Hour */ - BLE_GATT_UNIT_TIME_DAY = 0x2762, /**< Time, Day */ - BLE_GATT_UNIT_PLANE_ANGLE_DEGREE = 0x2763, /**< */ - BLE_GATT_UNIT_PLANE_ANGLE_MINUTE = 0x2764, /**< */ - BLE_GATT_UNIT_PLANE_ANGLE_SECOND = 0x2765, /**< */ - BLE_GATT_UNIT_AREA_HECTARE = 0x2766, /**< */ - BLE_GATT_UNIT_VOLUME_LITRE = 0x2767, /**< */ - BLE_GATT_UNIT_MASS_TONNE = 0x2768, /**< */ - BLE_GATT_UNIT_PRESSURE_BAR = 0x2780, /**< Pressure, Bar */ - BLE_GATT_UNIT_PRESSURE_MILLIMETRE_OF_MERCURY = 0x2781, /**< Pressure, Millimetre of Mercury */ - BLE_GATT_UNIT_LENGTH_ANGSTROM = 0x2782, /**< */ - BLE_GATT_UNIT_LENGTH_NAUTICAL_MILE = 0x2783, /**< */ - BLE_GATT_UNIT_AREA_BARN = 0x2784, /**< */ - BLE_GATT_UNIT_VELOCITY_KNOT = 0x2785, /**< */ - BLE_GATT_UNIT_LOGARITHMIC_RADIO_QUANTITY_NEPER = 0x2786, /**< */ - BLE_GATT_UNIT_LOGARITHMIC_RADIO_QUANTITY_BEL = 0x2787, /**< */ - BLE_GATT_UNIT_LENGTH_YARD = 0x27A0, /**< Length, Yard */ - BLE_GATT_UNIT_LENGTH_PARSEC = 0x27A1, /**< Length, Parsec */ - BLE_GATT_UNIT_LENGTH_INCH = 0x27A2, /**< Length, Inch */ - BLE_GATT_UNIT_LENGTH_FOOT = 0x27A3, /**< Length, Foot */ - BLE_GATT_UNIT_LENGTH_MILE = 0x27A4, /**< Length, Mile */ - BLE_GATT_UNIT_PRESSURE_POUND_FORCE_PER_SQUARE_INCH = 0x27A5, /**< */ - BLE_GATT_UNIT_VELOCITY_KILOMETRE_PER_HOUR = 0x27A6, /**< Velocity, Kilometre per Hour */ - BLE_GATT_UNIT_VELOCITY_MILE_PER_HOUR = 0x27A7, /**< Velocity, Mile per Hour */ - BLE_GATT_UNIT_ANGULAR_VELOCITY_REVOLUTION_PER_MINUTE = 0x27A8, /**< Angular Velocity, Revolution per Minute */ - BLE_GATT_UNIT_ENERGY_GRAM_CALORIE = 0x27A9, /**< Energy, Gram Calorie */ - BLE_GATT_UNIT_ENERGY_KILOGRAM_CALORIE = 0x27AA, /**< Energy, Kilogram Calorie */ - BLE_GATT_UNIT_ENERGY_KILOWATT_HOUR = 0x27AB, /**< Energy, Killowatt Hour */ - BLE_GATT_UNIT_THERMODYNAMIC_TEMPERATURE_DEGREE_FAHRENHEIT = 0x27AC, /**< */ - BLE_GATT_UNIT_PERCENTAGE = 0x27AD, /**< Percentage */ - BLE_GATT_UNIT_PER_MILLE = 0x27AE, /**< */ - BLE_GATT_UNIT_PERIOD_BEATS_PER_MINUTE = 0x27AF, /**< */ - BLE_GATT_UNIT_ELECTRIC_CHARGE_AMPERE_HOURS = 0x27B0, /**< */ - BLE_GATT_UNIT_MASS_DENSITY_MILLIGRAM_PER_DECILITRE = 0x27B1, /**< */ - BLE_GATT_UNIT_MASS_DENSITY_MILLIMOLE_PER_LITRE = 0x27B2, /**< */ - BLE_GATT_UNIT_TIME_YEAR = 0x27B3, /**< Time, Year */ - BLE_GATT_UNIT_TIME_MONTH = 0x27B4, /**< Time, Month */ - BLE_GATT_UNIT_CONCENTRATION_COUNT_PER_CUBIC_METRE = 0x27B5, /**< */ - BLE_GATT_UNIT_IRRADIANCE_WATT_PER_SQUARE_METRE = 0x27B6 /**< */ - } ble_gatt_unit_t; - - /**************************************************************************/ - /*! - \brief Standard GATT number types - - \note See Bluetooth Specification 4.0 (Vol. 3), Part G, Section 3.3.3.5.2 - \note See http://developer.bluetooth.org/gatt/descriptors/Pages/DescriptorViewer.aspx?u=org.bluetooth.descriptor.gatt.characteristic_presentation_format.xml - */ - /**************************************************************************/ - typedef enum ble_gatt_format_e - { - BLE_GATT_FORMAT_RFU = 0x00, /**< Reserved For Future Use. */ - BLE_GATT_FORMAT_BOOLEAN = 0x01, /**< Boolean. */ - BLE_GATT_FORMAT_2BIT = 0x02, /**< Unsigned 2-bit integer. */ - BLE_GATT_FORMAT_NIBBLE = 0x03, /**< Unsigned 4-bit integer. */ - BLE_GATT_FORMAT_UINT8 = 0x04, /**< Unsigned 8-bit integer. */ - BLE_GATT_FORMAT_UINT12 = 0x05, /**< Unsigned 12-bit integer. */ - BLE_GATT_FORMAT_UINT16 = 0x06, /**< Unsigned 16-bit integer. */ - BLE_GATT_FORMAT_UINT24 = 0x07, /**< Unsigned 24-bit integer. */ - BLE_GATT_FORMAT_UINT32 = 0x08, /**< Unsigned 32-bit integer. */ - BLE_GATT_FORMAT_UINT48 = 0x09, /**< Unsigned 48-bit integer. */ - BLE_GATT_FORMAT_UINT64 = 0x0A, /**< Unsigned 64-bit integer. */ - BLE_GATT_FORMAT_UINT128 = 0x0B, /**< Unsigned 128-bit integer. */ - BLE_GATT_FORMAT_SINT8 = 0x0C, /**< Signed 2-bit integer. */ - BLE_GATT_FORMAT_SINT12 = 0x0D, /**< Signed 12-bit integer. */ - BLE_GATT_FORMAT_SINT16 = 0x0E, /**< Signed 16-bit integer. */ - BLE_GATT_FORMAT_SINT24 = 0x0F, /**< Signed 24-bit integer. */ - BLE_GATT_FORMAT_SINT32 = 0x10, /**< Signed 32-bit integer. */ - BLE_GATT_FORMAT_SINT48 = 0x11, /**< Signed 48-bit integer. */ - BLE_GATT_FORMAT_SINT64 = 0x12, /**< Signed 64-bit integer. */ - BLE_GATT_FORMAT_SINT128 = 0x13, /**< Signed 128-bit integer. */ - BLE_GATT_FORMAT_FLOAT32 = 0x14, /**< IEEE-754 32-bit floating point. */ - BLE_GATT_FORMAT_FLOAT64 = 0x15, /**< IEEE-754 64-bit floating point. */ - BLE_GATT_FORMAT_SFLOAT = 0x16, /**< IEEE-11073 16-bit SFLOAT. */ - BLE_GATT_FORMAT_FLOAT = 0x17, /**< IEEE-11073 32-bit FLOAT. */ - BLE_GATT_FORMAT_DUINT16 = 0x18, /**< IEEE-20601 format. */ - BLE_GATT_FORMAT_UTF8S = 0x19, /**< UTF-8 string. */ - BLE_GATT_FORMAT_UTF16S = 0x1A, /**< UTF-16 string. */ - BLE_GATT_FORMAT_STRUCT = 0x1B /**< Opaque Structure. */ - } ble_gatt_format_t; - - /**************************************************************************/ - /*! - \brief Standard GATT characteritic properties - - \note See Bluetooth Specification 4.0 (Vol. 3), Part G, Section 3.3.1.1 - and Section 3.3.3.1 for Extended Properties - */ - /**************************************************************************/ - typedef enum ble_gatt_char_properties_e - { - BLE_GATT_CHAR_PROPERTIES_BROADCAST = 0x01, /**< Permits broadcasts of the Characteristic Value using Server Characteristic Configuration Descriptor. */ - BLE_GATT_CHAR_PROPERTIES_READ = 0x02, /**< Permits reads of the Characteristic Value. */ - BLE_GATT_CHAR_PROPERTIES_WRITE_WITHOUT_RESPONSE = 0x04, /**< Permits writes of the Characteristic Value without response. */ - BLE_GATT_CHAR_PROPERTIES_WRITE = 0x08, /**< Permits writes of the Characteristic Value with response. */ - BLE_GATT_CHAR_PROPERTIES_NOTIFY = 0x10, /**< Permits notifications of a Characteristic Value without acknowledgement. */ - BLE_GATT_CHAR_PROPERTIES_INDICATE = 0x20, /**< Permits indications of a Characteristic Value with acknowledgement. */ - BLE_GATT_CHAR_PROPERTIES_AUTHENTICATED_SIGNED_WRITES = 0x40, /**< Permits signed writes to the Characteristic Value. */ - BLE_GATT_CHAR_PROPERTIES_EXTENDED_PROPERTIES = 0x80 /**< Additional characteristic properties are defined in the Characteristic Extended Properties Descriptor */ - } ble_gatt_char_properties_t; - - /**************************************************************************/ - /*! - \brief GATT presentation format wrapper - - \note See Bluetooth Specification 4.0 (Vol. 3), Part G, Section 3.3.3.5 - \note See https://developer.bluetooth.org/gatt/descriptors/Pages/DescriptorViewer.aspx?u=org.bluetooth.descriptor.gatt.characteristic_presentation_format.xml - */ - /**************************************************************************/ - typedef struct PresentationFormat - { - uint8_t gatt_format; /**< Format of the value, see @ref ble_gatt_format_t. */ - int8_t exponent; /**< Exponent for integer data types. Ex. if Exponent = -3 and the char value is 3892, the actual value is 3.892 */ - uint16_t gatt_unit; /**< UUID from Bluetooth Assigned Numbers, see @ref ble_gatt_unit_t. */ - uint8_t gatt_namespace; /**< Namespace from Bluetooth Assigned Numbers, normally '1', see @ref BLE_GATT_CPF_NAMESPACES. */ - uint16_t gatt_nsdesc; /**< Namespace description from Bluetooth Assigned Numbers, normally '0', see @ref BLE_GATT_CPF_NAMESPACES. */ - } presentation_format_t; - - GattCharacteristic(uint16_t uuid=0, uint16_t minLen=1, uint16_t maxLen=1, uint8_t properties=0); - virtual ~GattCharacteristic(void); - - uint16_t uuid; /* Characteristic UUID */ - uint16_t lenMin; /* Minimum length of the value */ - uint16_t lenMax; /* Maximum length of the value */ - uint16_t handle; - uint8_t properties; - - private: -}; - -#endif diff --git a/libraries/ble/ble-api/GattService.cpp b/libraries/ble/ble-api/GattService.cpp deleted file mode 100644 index 7c7795bbf9..0000000000 --- a/libraries/ble/ble-api/GattService.cpp +++ /dev/null @@ -1,111 +0,0 @@ -/* mbed Microcontroller Library - * Copyright (c) 2006-2013 ARM Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -#include -#include - -#include "GattService.h" - -/**************************************************************************/ -/*! - @brief Creates a new GattService using the specified 128-bit UUID - - @note The UUID value must be unique on the device - - @param[in] uuid - The 16 byte (128-bit) UUID to use for this characteristic - - @section EXAMPLE - - @code - - @endcode -*/ -/**************************************************************************/ -GattService::GattService(uint8_t base_uuid[16]) -{ - primaryServiceID.update(base_uuid); - characteristicCount = 0; - handle = 0; -} - -/**************************************************************************/ -/*! - @brief Creates a new GattService using the specified 16-bit BLE UUID - - @param[in] ble_uuid - The standardised 16-bit (2 byte) BLE UUID to use for this - characteristic - - @section EXAMPLE - - @code - - @endcode -*/ -/**************************************************************************/ -GattService::GattService(uint16_t ble_uuid) -{ - primaryServiceID.update( ble_uuid ); - characteristicCount = 0; - handle = 0; -} - -/**************************************************************************/ -/*! - @brief Destructor -*/ -/**************************************************************************/ -GattService::~GattService(void) -{ -} - -/**************************************************************************/ -/*! - @brief Adds a GattCharacterisic to the service. - - @note This function will not update the .handle field in the - GattCharacteristic. This value is updated when the parent - service is added via the radio driver. - - @param[in] characteristic - The GattCharacteristic object describing the characteristic - to add to this service - - @returns BLE_ERROR_NONE (0) if everything executed correctly, or an - error code if there was a problem - @retval BLE_ERROR_NONE - Everything executed correctly - - @section EXAMPLE - - @code - - @endcode -*/ -/**************************************************************************/ -ble_error_t GattService::addCharacteristic(GattCharacteristic & characteristic) -{ - /* ToDo: Make sure we don't overflow the array, etc. */ - /* ToDo: Make sure this characteristic UUID doesn't already exist */ - /* ToDo: Basic validation */ - - characteristics[characteristicCount] = &characteristic; - characteristicCount++; - - return BLE_ERROR_NONE; -} diff --git a/libraries/ble/ble-api/GattService.h b/libraries/ble/ble-api/GattService.h deleted file mode 100644 index 4350117a1a..0000000000 --- a/libraries/ble/ble-api/GattService.h +++ /dev/null @@ -1,70 +0,0 @@ -/* mbed Microcontroller Library - * Copyright (c) 2006-2013 ARM Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. -*/ - - -#ifndef __GATT_SERVICE_H__ -#define __GATT_SERVICE_H__ - -#include "blecommon.h" -#include "UUID.h" -#include "GattCharacteristic.h" - -#define BLE_SERVICE_MAX_CHARACTERISTICS (5) - -/**************************************************************************/ -/*! - \brief GATT service -*/ -/**************************************************************************/ -class GattService -{ - private: - - public: - GattService(uint8_t[16]); /* 128-bit Base UUID */ - GattService(uint16_t); /* 16-bit BLE UUID */ - virtual ~GattService(void); - - UUID primaryServiceID; - uint8_t characteristicCount; - GattCharacteristic* characteristics[BLE_SERVICE_MAX_CHARACTERISTICS]; - uint16_t handle; - - ble_error_t addCharacteristic(GattCharacteristic &); - - enum { - UUID_ALERT_NOTIFICATION_SERVICE = 0x1811, - UUID_BATTERY_SERVICE = 0x180F, - UUID_BLOOD_PRESSURE_SERVICE = 0x1810, - UUID_CURRENT_TIME_SERVICE = 0x1805, - UUID_CYCLING_SPEED_AND_CADENCE = 0x1816, - UUID_DEVICE_INFORMATION_SERVICE = 0x180A, - UUID_GLUCOSE_SERVICE = 0x1808, - UUID_HEALTH_THERMOMETER_SERVICE = 0x1809, - UUID_HEART_RATE_SERVICE = 0x180D, - UUID_HUMAN_INTERFACE_DEVICE_SERVICE = 0x1812, - UUID_IMMEDIATE_ALERT_SERVICE = 0x1802, - UUID_LINK_LOSS_SERVICE = 0x1803, - UUID_NEXT_DST_CHANGE_SERVICE = 0x1807, - UUID_PHONE_ALERT_STATUS_SERVICE = 0x180E, - UUID_REFERENCE_TIME_UPDATE_SERVICE = 0x1806, - UUID_RUNNING_SPEED_AND_CADENCE = 0x1814, - UUID_SCAN_PARAMETERS_SERVICE = 0x1813, - UUID_TX_POWER_SERVICE = 0x1804 - }; -}; - -#endif diff --git a/libraries/ble/ble-api/UUID.cpp b/libraries/ble/ble-api/UUID.cpp deleted file mode 100644 index 4a4fb35a64..0000000000 --- a/libraries/ble/ble-api/UUID.cpp +++ /dev/null @@ -1,194 +0,0 @@ -/* mbed Microcontroller Library - * Copyright (c) 2006-2013 ARM Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -#include -#include - -#include "UUID.h" - -/**************************************************************************/ -/*! - @brief Creates an empty 128-bit UUID - - @note This UUID must be assigned a valid value via the 'update' - function before it can be safely used! -*/ -/**************************************************************************/ -UUID::UUID(void) -{ - memset(base, 0, 16); - value = 0; - type = UUID_TYPE_SHORT; -} - -/**************************************************************************/ -/*! - @brief Creates a new 128-bit UUID - - @note The UUID is a unique 128-bit (16 byte) ID used to identify - different service or characteristics on the BLE device. - - @note When creating a UUID, the constructor will check if all bytes - except bytes 2/3 are equal to 0. If only bytes 2/3 have a - value, the UUID will be treated as a short/BLE UUID, and the - .type field will be set to UUID::UUID_TYPE_SHORT. If any - of the bytes outside byte 2/3 have a non-zero value, the UUID - will be considered a 128-bit ID, and .type will be assigned - as UUID::UUID_TYPE_LONG. - - @param[in] uuid_base - The 128-bit (16-byte) UUID value. For 128-bit values, - assign all 16 bytes. For 16-bit values, assign the - 16-bits to byte 2 and 3, and leave the rest of the bytes - as 0. - - @section EXAMPLE - - @code - - // Create a short UUID (0x180F) - uint8_t shortID[16] = { 0, 0, 0x0F, 0x18, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; - UUID ble_uuid = UUID(shortID); - // ble_uuid.type = UUID_TYPE_SHORT - // ble_uuid.value = 0x180F - - // Creeate a long UUID - uint8_t longID[16] = { 0x00, 0x11, 0x22, 0x33, - 0x44, 0x55, 0x66, 0x77, - 0x88, 0x99, 0xAA, 0xBB, - 0xCC, 0xDD, 0xEE, 0xFF }; - UUID custom_uuid = UUID(longID); - // custom_uuid.type = UUID_TYPE_LONG - // custom_uuid.value = 0x3322 - // custom_uuid.base = 00 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF - - @endcode -*/ -/**************************************************************************/ -UUID::UUID(uint8_t const uuid_base[16]) -{ - memcpy(base, uuid_base, 16); - value = (uint16_t)((uuid_base[3] << 8) | (uuid_base[2])); - - /* Check if this is a short of a long UUID */ - if (uuid_base[0] + uuid_base[1] + - uuid_base[4] + uuid_base[5] + uuid_base[6] + uuid_base[7] + - uuid_base[8] + uuid_base[9] + uuid_base[10] + uuid_base[11] + - uuid_base[12] + uuid_base[13] + uuid_base[14] + uuid_base[15] == 0) - { - type = UUID_TYPE_SHORT; - } - else - { - type = UUID_TYPE_LONG; - } -} - -/**************************************************************************/ -/*! - @brief Creates a short (16-bit) UUID - - @param[in] ble_uuid - The 16-bit BLE UUID value. -*/ -/**************************************************************************/ -UUID::UUID(uint16_t const ble_uuid) -{ - memset(base, 0, 16); - memcpy(base+2, (uint8_t *)&ble_uuid, 2); - value = ble_uuid; - type = UUID_TYPE_SHORT; -} - -/**************************************************************************/ -/*! - @brief UUID destructor -*/ -/**************************************************************************/ -UUID::~UUID(void) -{ -} - -/**************************************************************************/ -/*! - @brief Updates the value of the UUID - - @args[in] uuid_base - The 128-bit value to use when updating the UUID. For - 16-bit IDs, insert the ID in bytes 2/3 in LSB format. - - @returns BLE_ERROR_NONE (0) if everything executed correctly, or an - error code if there was a problem - @retval BLE_ERROR_NONE - Everything executed correctly - - @section EXAMPLE - - @code - - @endcode -*/ -/**************************************************************************/ -ble_error_t UUID::update(uint8_t const uuid_base[16]) -{ - memcpy(base, uuid_base, 16); - value = (uint16_t)((uuid_base[3] << 8) | (uuid_base[2])); - - /* Check if this is a short of a long UUID */ - if (uuid_base[0] + uuid_base[1] + - uuid_base[4] + uuid_base[5] + uuid_base[6] + uuid_base[7] + - uuid_base[8] + uuid_base[9] + uuid_base[10] + uuid_base[11] + - uuid_base[12] + uuid_base[13] + uuid_base[14] + uuid_base[15] == 0) - { - type = UUID_TYPE_SHORT; - } - else - { - type = UUID_TYPE_LONG; - } - - return BLE_ERROR_NONE; -} - -/**************************************************************************/ -/*! - @brief Updates the value of the UUID - - @args[in] ble_uuid - The 16-bit value to use when updating the UUID. - - @returns BLE_ERROR_NONE (0) if everything executed correctly, or an - error code if there was a problem - @retval BLE_ERROR_NONE - Everything executed correctly - - @section EXAMPLE - - @code - - @endcode -*/ -/**************************************************************************/ -ble_error_t UUID::update(uint16_t const ble_uuid) -{ - memset(base, 0, 16); - memcpy(base+2, (uint8_t *)&ble_uuid, 2); - value = ble_uuid; - type = UUID_TYPE_SHORT; - - return BLE_ERROR_NONE; -} diff --git a/libraries/ble/ble-api/UUID.h b/libraries/ble/ble-api/UUID.h deleted file mode 100644 index 70019235a1..0000000000 --- a/libraries/ble/ble-api/UUID.h +++ /dev/null @@ -1,47 +0,0 @@ -/* mbed Microcontroller Library - * Copyright (c) 2006-2013 ARM Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - -#ifndef __UUID_H__ -#define __UUID_H__ - -#include "blecommon.h" - -class UUID -{ -private: - -public: - enum - { - UUID_TYPE_SHORT = 0, // Short BLE UUID - UUID_TYPE_LONG = 1 // Full 128-bit UUID - }; - - UUID(void); - UUID(uint8_t const[16]); - UUID(uint16_t const); - virtual ~UUID(void); - - uint8_t type; // UUID_TYPE_SHORT or UUID_TYPE_LONG - uint8_t base[16]; // in case of custom - uint16_t value; // 16 bit uuid (byte 2-3 using with base) - - ble_error_t update(uint8_t const[16]); - ble_error_t update(uint16_t const); -}; - -#endif diff --git a/libraries/ble/ble-api/blecommon.h b/libraries/ble/ble-api/blecommon.h deleted file mode 100644 index 30d8e28d70..0000000000 --- a/libraries/ble/ble-api/blecommon.h +++ /dev/null @@ -1,48 +0,0 @@ -/* mbed Microcontroller Library - * Copyright (c) 2006-2013 ARM Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef __BLE_COMMON_H__ -#define __BLE_COMMON_H__ - -#define NRF51 -#define DEBUG_NRF_USER -#define BLE_STACK_SUPPORT_REQD -#define BOARD_PCA10001 - -#ifdef __cplusplus -extern "C" { -#endif - -#include - -/**************************************************************************/ -/*! - \brief Error codes for the BLE API -*/ -/**************************************************************************/ -typedef enum ble_error_e -{ - BLE_ERROR_NONE = 0, /**< No error */ - BLE_ERROR_BUFFER_OVERFLOW = 1, /**< The requested action would cause a buffer overflow and has been aborted */ - BLE_ERROR_NOT_IMPLEMENTED = 2, /**< Requested a feature that isn't yet implement or isn't supported by the target HW */ - BLE_ERROR_PARAM_OUT_OF_RANGE = 3 /**< One of the supplied parameters is outside the valid range */ -} ble_error_t; - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/libraries/ble/ble-api/hw/BLEDevice.h b/libraries/ble/ble-api/hw/BLEDevice.h deleted file mode 100644 index 0a2030e331..0000000000 --- a/libraries/ble/ble-api/hw/BLEDevice.h +++ /dev/null @@ -1,41 +0,0 @@ -/* mbed Microcontroller Library - * Copyright (c) 2006-2013 ARM Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef __BLE_DEVICE_H__ -#define __BLE_DEVICE_H__ - -#include "mbed.h" -#include "blecommon.h" -#include "hw/Gap.h" -#include "hw/GattServer.h" - -/**************************************************************************/ -/*! - \brief - The base class used to abstract away BLE capable radio transceivers - or SOCs, to enable this BLE API to work with any radio transparently. -*/ -/**************************************************************************/ -class BLEDevice -{ - public: - virtual Gap& getGap() = 0; - virtual GattServer& getGattServer() = 0; - virtual ble_error_t init() = 0; - virtual ble_error_t reset(void) = 0; -}; - -#endif diff --git a/libraries/ble/ble-api/hw/Gap.h b/libraries/ble/ble-api/hw/Gap.h deleted file mode 100644 index 7907dc66f2..0000000000 --- a/libraries/ble/ble-api/hw/Gap.h +++ /dev/null @@ -1,84 +0,0 @@ -/* mbed Microcontroller Library - * Copyright (c) 2006-2013 ARM Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef __GAP_H__ -#define __GAP_H__ - -#include "mbed.h" -#include "blecommon.h" -#include "GapAdvertisingData.h" -#include "GapAdvertisingParams.h" -#include "GapEvents.h" - -/**************************************************************************/ -/*! - \brief - The base class used to abstract GAP functionality to a specific radio - transceiver, SOC or BLE Stack. -*/ -/**************************************************************************/ -class Gap -{ - private: - GapEvents *m_pEventHandler; - - public: - typedef enum addr_type_e{ - ADDR_TYPE_PUBLIC = 0, - ADDR_TYPE_RANDOM_STATIC, - ADDR_TYPE_RANDOM_PRIVATE_RESOLVABLE, - ADDR_TYPE_RANDOM_PRIVATE_NON_RESOLVABLE - } addr_type_t; - - /* These functions must be defined in the sub-class */ - virtual ble_error_t setAddress(addr_type_t type, uint8_t address[6]) = 0; - virtual ble_error_t setAdvertisingData(GapAdvertisingData &, GapAdvertisingData &) = 0; - virtual ble_error_t startAdvertising(GapAdvertisingParams &) = 0; - virtual ble_error_t stopAdvertising(void) = 0; - virtual ble_error_t disconnect(void) = 0; - - /* Describes the current state of the device (more than one bit can be set) */ - typedef struct GapState_s - { - unsigned advertising : 1; /**< The device is current advertising */ - unsigned connected : 1; /**< The peripheral is connected to a central device */ - } GapState_t; - - /* Event callback handlers */ - void setEventHandler(GapEvents *pEventHandler) {m_pEventHandler = pEventHandler;} - void handleEvent(GapEvents::gapEvent_e type) { - if (NULL == m_pEventHandler) - return; - switch(type) { - case GapEvents::GAP_EVENT_TIMEOUT: - state.advertising = 0; - m_pEventHandler->onTimeout(); - break; - case GapEvents::GAP_EVENT_CONNECTED: - state.connected = 1; - m_pEventHandler->onConnected(); - break; - case GapEvents::GAP_EVENT_DISCONNECTED: - state.connected = 0; - m_pEventHandler->onDisconnected(); - break; - } - } - - GapState_t state; -}; - -#endif diff --git a/libraries/ble/ble-api/hw/GapEvents.h b/libraries/ble/ble-api/hw/GapEvents.h deleted file mode 100644 index feba3d83f5..0000000000 --- a/libraries/ble/ble-api/hw/GapEvents.h +++ /dev/null @@ -1,71 +0,0 @@ -/* mbed Microcontroller Library - * Copyright (c) 2006-2013 ARM Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef __GAP_EVENTS_H__ -#define __GAP_EVENTS_H__ - -#include "blecommon.h" -#include "mbed.h" - -/**************************************************************************/ -/*! - \brief - The base class used to abstract away the callback events that can be - triggered with the GAP. -*/ -/**************************************************************************/ -class GapEvents { - public: - /******************************************************************/ - /*! - \brief - Identifies GAP events generated by the radio HW when an event - callback occurs - */ - /******************************************************************/ - typedef enum gapEvent_e - { - GAP_EVENT_TIMEOUT = 1, /**< Advertising timed out before a connection was established */ - GAP_EVENT_CONNECTED = 2, /**< A connection was established with a central device */ - GAP_EVENT_DISCONNECTED = 3 /**< A connection was closed or lost with a central device */ - } gapEvent_t; - - /******************************************************************/ - /*! - \brief - Advertising timed out before a connection was established - */ - /******************************************************************/ - virtual void onTimeout(void) {} - - /******************************************************************/ - /*! - \brief - A connection was established with a central device - */ - /******************************************************************/ - virtual void onConnected(void) {} - - /******************************************************************/ - /*! - \brief - A connection was closed or lost with a central device - */ - /******************************************************************/ - virtual void onDisconnected(void) {} -}; - -#endif diff --git a/libraries/ble/ble-api/hw/GattServer.h b/libraries/ble/ble-api/hw/GattServer.h deleted file mode 100644 index 1855842dab..0000000000 --- a/libraries/ble/ble-api/hw/GattServer.h +++ /dev/null @@ -1,76 +0,0 @@ -/* mbed Microcontroller Library - * Copyright (c) 2006-2013 ARM Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef __GATT_SERVER_H__ -#define __GATT_SERVER_H__ - -#include "mbed.h" -#include "blecommon.h" -#include "GattService.h" -#include "GattServerEvents.h" - -/**************************************************************************/ -/*! - \brief - The base class used to abstract GATT Server functionality to a specific - radio transceiver, SOC or BLE Stack. -*/ -/**************************************************************************/ -class GattServer -{ - private: - GattServerEvents *m_pEventHandler; - - public: - /* These functions must be defined in the sub-class */ - virtual ble_error_t addService(GattService &) = 0; - virtual ble_error_t readValue(uint16_t, uint8_t[], uint16_t) = 0; - virtual ble_error_t updateValue(uint16_t, uint8_t[], uint16_t, bool localOnly = false) = 0; - - // ToDo: For updateValue, check the CCCD to see if the value we are - // updating has the notify or indicate bits sent, and if BOTH are set - // be sure to call sd_ble_gatts_hvx() twice with notify then indicate! - // Strange use case, but valid and must be covered! - - /* Event callback handlers */ - void setEventHandler(GattServerEvents *pEventHandler) {m_pEventHandler = pEventHandler;} - void handleEvent(GattServerEvents::gattEvent_e type, uint16_t charHandle) { - if (NULL == m_pEventHandler) - return; - switch(type) { - case GattServerEvents::GATT_EVENT_DATA_SENT: - m_pEventHandler->onDataSent(charHandle); - break; - case GattServerEvents::GATT_EVENT_DATA_WRITTEN: - m_pEventHandler->onDataWritten(charHandle); - break; - case GattServerEvents::GATT_EVENT_UPDATES_ENABLED: - m_pEventHandler->onUpdatesEnabled(charHandle); - break; - case GattServerEvents::GATT_EVENT_UPDATES_DISABLED: - m_pEventHandler->onUpdatesDisabled(charHandle); - break; - case GattServerEvents::GATT_EVENT_CONFIRMATION_RECEIVED: - m_pEventHandler->onConfirmationReceived(charHandle); - break; - } - } - - uint8_t serviceCount; - uint8_t characteristicCount; -}; - -#endif diff --git a/libraries/ble/ble-api/hw/GattServerEvents.h b/libraries/ble/ble-api/hw/GattServerEvents.h deleted file mode 100644 index a2219965a3..0000000000 --- a/libraries/ble/ble-api/hw/GattServerEvents.h +++ /dev/null @@ -1,91 +0,0 @@ -/* mbed Microcontroller Library - * Copyright (c) 2006-2013 ARM Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef __GATT_SERVER_EVENTS_H__ -#define __GATT_SERVER_EVENTS_H__ - -#include "blecommon.h" -#include "mbed.h" - -/**************************************************************************/ -/*! - \brief - The base class used to abstract away the callback events that can be - triggered with the GATT Server. -*/ -/**************************************************************************/ -class GattServerEvents { - public: - /******************************************************************/ - /*! - \brief - Identifies GATT events generated by the radio HW when an event - callback occurs - */ - /******************************************************************/ - typedef enum gattEvent_e - { - GATT_EVENT_DATA_SENT = 1, /**< Fired when a msg was successfully sent out (notify only?) */ - GATT_EVENT_DATA_WRITTEN = 2, /**< Client wrote data to Server (separate into char and descriptor writes?) */ - GATT_EVENT_UPDATES_ENABLED = 3, /**< Notify/Indicate Enabled in CCCD */ - GATT_EVENT_UPDATES_DISABLED = 4, /**< Notify/Indicate Disabled in CCCD */ - GATT_EVENT_CONFIRMATION_RECEIVED = 5 /**< Response received from Indicate message */ - } gattEvent_t; - - /******************************************************************/ - /*! - \brief - A message was successfully transmitted - */ - /******************************************************************/ - virtual void onDataSent(uint16_t charHandle) {} - - /******************************************************************/ - /*! - \brief - The GATT client (the phone, tablet, etc.) wrote data to a - characteristic or descriptor on the GATT Server (the peripheral - device). - */ - /******************************************************************/ - virtual void onDataWritten(uint16_t charHandle) {} - - /******************************************************************/ - /*! - \brief - A Notify or Indicate flag was enabled in the CCCD - */ - /******************************************************************/ - virtual void onUpdatesEnabled(uint16_t charHandle) {} - - /******************************************************************/ - /*! - \brief - A Notify or Indicate flag was disabled in the CCCD - */ - /******************************************************************/ - virtual void onUpdatesDisabled(uint16_t charHandle) {} - - /******************************************************************/ - /*! - \brief - A confirmation response was received from an Indicate message - */ - /******************************************************************/ - virtual void onConfirmationReceived(uint16_t charHandle) {} -}; - -#endif diff --git a/libraries/ble/nRF51822/btle/btle.cpp b/libraries/ble/nRF51822/btle/btle.cpp deleted file mode 100644 index 1870ebbaaa..0000000000 --- a/libraries/ble/nRF51822/btle/btle.cpp +++ /dev/null @@ -1,220 +0,0 @@ -/* mbed Microcontroller Library - * Copyright (c) 2006-2013 ARM Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include "common/common.h" - -#include "app_timer.h" -#include "btle.h" - -#include "ble_stack_handler_types.h" -#include "ble_radio_notification.h" -#include "ble_flash.h" -#include "ble_bondmngr.h" -#include "ble_conn_params.h" - -#include "btle_gap.h" -#include "btle_advertising.h" -#include "custom/custom_helper.h" - -#include "nordic_common.h" -#include "softdevice_handler.h" -#include "pstorage.h" - -#include "hw/GapEvents.h" -#include "nRF51Gap.h" -#include "nRF51GattServer.h" - -static void service_error_callback(uint32_t nrf_error); -void assert_nrf_callback(uint16_t line_num, const uint8_t * p_file_name); -void app_error_handler(uint32_t error_code, uint32_t line_num, const uint8_t * p_file_name); - -static error_t bond_manager_init(void); - -static void btle_handler(ble_evt_t * p_ble_evt); - -/**************************************************************************/ -/*! - -*/ -/**************************************************************************/ -static void sys_evt_dispatch(uint32_t sys_evt) -{ - pstorage_sys_event_handler(sys_evt); -} - -/**************************************************************************/ -/*! - @brief Initialises BTLE and the underlying HW/SoftDevice - - @returns -*/ -/**************************************************************************/ -error_t btle_init(void) -{ - APP_TIMER_INIT(0, 8, 5, false); - SOFTDEVICE_HANDLER_INIT(NRF_CLOCK_LFCLKSRC_XTAL_20_PPM, false); - - ASSERT_STATUS( softdevice_ble_evt_handler_set(btle_handler) ); - ASSERT_STATUS( softdevice_sys_evt_handler_set(sys_evt_dispatch) ); - - bond_manager_init(); - btle_gap_init(); - - return ERROR_NONE; -} - -/**************************************************************************/ -/*! - @brief - - @param[in] p_ble_evt - - @returns -*/ -/**************************************************************************/ -static void btle_handler(ble_evt_t * p_ble_evt) -{ - /* Library service handlers */ - ble_bondmngr_on_ble_evt(p_ble_evt); - ble_conn_params_on_ble_evt(p_ble_evt); - - /* Custom event handler */ - switch (p_ble_evt->header.evt_id) - { - case BLE_GAP_EVT_CONNECTED: - nRF51Gap::getInstance().setConnectionHandle( p_ble_evt->evt.gap_evt.conn_handle ); - nRF51Gap::getInstance().handleEvent(GapEvents::GAP_EVENT_CONNECTED); - break; - - case BLE_GAP_EVT_DISCONNECTED: - // Since we are not in a connection and have not started advertising, store bonds - nRF51Gap::getInstance().setConnectionHandle (BLE_CONN_HANDLE_INVALID); - ASSERT_STATUS_RET_VOID ( ble_bondmngr_bonded_centrals_store() ); - nRF51Gap::getInstance().handleEvent(GapEvents::GAP_EVENT_DISCONNECTED); - break; - - case BLE_GAP_EVT_SEC_PARAMS_REQUEST: - { - ble_gap_sec_params_t sec_params = { 0 }; - - sec_params.timeout = 30 ; /**< Timeout for Pairing Request or Security Request (in seconds). */ - sec_params.bond = 1 ; /**< Perform bonding. */ - sec_params.mitm = CFG_BLE_SEC_PARAM_MITM ; - sec_params.io_caps = CFG_BLE_SEC_PARAM_IO_CAPABILITIES ; - sec_params.oob = CFG_BLE_SEC_PARAM_OOB ; - sec_params.min_key_size = CFG_BLE_SEC_PARAM_MIN_KEY_SIZE ; - sec_params.max_key_size = CFG_BLE_SEC_PARAM_MAX_KEY_SIZE ; - - ASSERT_STATUS_RET_VOID ( sd_ble_gap_sec_params_reply(nRF51Gap::getInstance().getConnectionHandle(), BLE_GAP_SEC_STATUS_SUCCESS, &sec_params) ); - } - break; - - case BLE_GAP_EVT_TIMEOUT: - if (p_ble_evt->evt.gap_evt.params.timeout.src == BLE_GAP_TIMEOUT_SRC_ADVERTISEMENT) - { - nRF51Gap::getInstance().handleEvent(GapEvents::GAP_EVENT_TIMEOUT); - } - break; - - case BLE_GATTC_EVT_TIMEOUT: - case BLE_GATTS_EVT_TIMEOUT: - // Disconnect on GATT Server and Client timeout events. - // ASSERT_STATUS_RET_VOID (sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION)); - break; - - default: - break; - } - - nRF51GattServer::getInstance().hwCallback(p_ble_evt); -} - -/**************************************************************************/ -/*! - @brief Initialises the bond manager - - @note Bond data will be cleared on reset if the bond delete - button is pressed during initialisation (the button is - defined as CFG_BLE_BOND_DELETE_BUTTON_NUM). - - @returns -*/ -/**************************************************************************/ -static error_t bond_manager_init(void) -{ - ble_bondmngr_init_t bond_para = { 0 }; - - ASSERT_STATUS ( pstorage_init() ); - - bond_para.flash_page_num_bond = CFG_BLE_BOND_FLASH_PAGE_BOND ; - bond_para.flash_page_num_sys_attr = CFG_BLE_BOND_FLASH_PAGE_SYS_ATTR ; - //bond_para.bonds_delete = boardButtonCheck(CFG_BLE_BOND_DELETE_BUTTON_NUM) ; - bond_para.evt_handler = NULL ; - bond_para.error_handler = service_error_callback ; - - ASSERT_STATUS( ble_bondmngr_init( &bond_para ) ); - - /* Init radio active/inactive notification to flash (to only perform flashing when the radio is inactive) */ - // ASSERT_STATUS( ble_radio_notification_init(NRF_APP_PRIORITY_HIGH, - // NRF_RADIO_NOTIFICATION_DISTANCE_4560US, - // ble_flash_on_radio_active_evt) ); - - return ERROR_NONE; -} - -/**************************************************************************/ -/*! - @brief - @param[in] nrf_error - @returns -*/ -/**************************************************************************/ -static void service_error_callback(uint32_t nrf_error) -{ - ASSERT_STATUS_RET_VOID( nrf_error ); -} - -/**************************************************************************/ -/*! - @brief Callback when an error occurs inside the SoftDevice - - @param[in] line_num - @param[in] p-file_name - - @returns -*/ -/**************************************************************************/ -void assert_nrf_callback(uint16_t line_num, const uint8_t * p_file_name) -{ - ASSERT(false, (void) 0); -} - -/**************************************************************************/ -/*! - @brief Handler for general errors above the SoftDevice layer. - Typically we can' recover from this so we do a reset. - - @param[in] error_code - @param[in] line_num - @param[in] p-file_name - - @returns -*/ -/**************************************************************************/ -void app_error_handler(uint32_t error_code, uint32_t line_num, const uint8_t * p_file_name) -{ - ASSERT_STATUS_RET_VOID( error_code ); - NVIC_SystemReset(); -} diff --git a/libraries/ble/nRF51822/btle/btle.h b/libraries/ble/nRF51822/btle/btle.h deleted file mode 100644 index c6ca78d700..0000000000 --- a/libraries/ble/nRF51822/btle/btle.h +++ /dev/null @@ -1,35 +0,0 @@ -/* mbed Microcontroller Library - * Copyright (c) 2006-2013 ARM Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef _BTLE_H_ -#define _BTLE_H_ - -#ifdef __cplusplus - extern "C" { -#endif - -#include "common/common.h" - -#include "ble_srv_common.h" -#include "ble.h" - -error_t btle_init(void); - -#ifdef __cplusplus - } -#endif - -#endif diff --git a/libraries/ble/nRF51822/btle/btle_advertising.cpp b/libraries/ble/nRF51822/btle/btle_advertising.cpp deleted file mode 100644 index 39ea6d8b96..0000000000 --- a/libraries/ble/nRF51822/btle/btle_advertising.cpp +++ /dev/null @@ -1,43 +0,0 @@ -/* mbed Microcontroller Library - * Copyright (c) 2006-2013 ARM Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include "common/common.h" - -#include "ble_advdata.h" -#include "btle.h" - -/**************************************************************************/ -/*! - @brief Starts the advertising process - - @returns -*/ -/**************************************************************************/ -error_t btle_advertising_start(void) -{ - ble_gap_adv_params_t adv_para = { 0 }; - - /* Set the default advertising parameters */ - adv_para.type = BLE_GAP_ADV_TYPE_ADV_IND ; - adv_para.p_peer_addr = NULL ; /* Undirected advertising */ - adv_para.fp = BLE_GAP_ADV_FP_ANY ; - adv_para.p_whitelist = NULL ; - adv_para.interval = (CFG_GAP_ADV_INTERVAL_MS*8)/5 ; /* Advertising interval in units of 0.625 ms */ - adv_para.timeout = CFG_GAP_ADV_TIMEOUT_S ; - - ASSERT_STATUS( sd_ble_gap_adv_start(&adv_para) ); - - return ERROR_NONE; -} diff --git a/libraries/ble/nRF51822/btle/btle_advertising.h b/libraries/ble/nRF51822/btle/btle_advertising.h deleted file mode 100644 index 61ea01f24c..0000000000 --- a/libraries/ble/nRF51822/btle/btle_advertising.h +++ /dev/null @@ -1,24 +0,0 @@ -/* mbed Microcontroller Library - * Copyright (c) 2006-2013 ARM Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef _BTLE_ADVERTISING_H_ -#define _BTLE_ADVERTISING_H_ - -#include "common/common.h" - -error_t btle_advertising_start(void); - -#endif diff --git a/libraries/ble/nRF51822/btle/btle_gap.cpp b/libraries/ble/nRF51822/btle/btle_gap.cpp deleted file mode 100644 index 6144078f1d..0000000000 --- a/libraries/ble/nRF51822/btle/btle_gap.cpp +++ /dev/null @@ -1,90 +0,0 @@ -/* mbed Microcontroller Library - * Copyright (c) 2006-2013 ARM Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include "common/common.h" - -#include "app_timer.h" -#include "ble_gap.h" -#include "ble_conn_params.h" - -static inline uint32_t msec_to_1_25msec(uint32_t interval_ms) ATTR_ALWAYS_INLINE ATTR_CONST; -static void error_callback(uint32_t nrf_error); - -/**************************************************************************/ -/*! - @brief Initialise GAP in the underlying SoftDevice - - @returns -*/ -/**************************************************************************/ -error_t btle_gap_init(void) -{ - ble_gap_conn_params_t gap_conn_params = { 0 }; - - gap_conn_params.min_conn_interval = msec_to_1_25msec(CFG_GAP_CONNECTION_MIN_INTERVAL_MS) ; // in 1.25ms unit - gap_conn_params.max_conn_interval = msec_to_1_25msec(CFG_GAP_CONNECTION_MAX_INTERVAL_MS) ; // in 1.25ms unit - gap_conn_params.slave_latency = CFG_GAP_CONNECTION_SLAVE_LATENCY ; - gap_conn_params.conn_sup_timeout = CFG_GAP_CONNECTION_SUPERVISION_TIMEOUT_MS / 10 ; // in 10ms unit - - ble_gap_conn_sec_mode_t sec_mode; - BLE_GAP_CONN_SEC_MODE_SET_OPEN(&sec_mode); // no security is needed - - ASSERT_STATUS( sd_ble_gap_device_name_set(&sec_mode, (const uint8_t *) CFG_GAP_LOCAL_NAME, strlen(CFG_GAP_LOCAL_NAME)) ); - ASSERT_STATUS( sd_ble_gap_appearance_set(CFG_GAP_APPEARANCE) ); - ASSERT_STATUS( sd_ble_gap_ppcp_set(&gap_conn_params) ); - ASSERT_STATUS( sd_ble_gap_tx_power_set(CFG_BLE_TX_POWER_LEVEL) ); - - /* Connection Parameters */ - enum { - FIRST_UPDATE_DELAY = APP_TIMER_TICKS(5000, CFG_TIMER_PRESCALER), - NEXT_UPDATE_DELAY = APP_TIMER_TICKS(5000, CFG_TIMER_PRESCALER), - MAX_UPDATE_COUNT = 3 - }; - - ble_conn_params_init_t cp_init = { 0 }; - - cp_init.p_conn_params = NULL ; - cp_init.first_conn_params_update_delay = FIRST_UPDATE_DELAY ; - cp_init.next_conn_params_update_delay = NEXT_UPDATE_DELAY ; - cp_init.max_conn_params_update_count = MAX_UPDATE_COUNT ; - cp_init.start_on_notify_cccd_handle = BLE_GATT_HANDLE_INVALID ; - cp_init.disconnect_on_fail = true ; - cp_init.evt_handler = NULL ; - cp_init.error_handler = error_callback; - - ASSERT_STATUS ( ble_conn_params_init(&cp_init) ); - - return ERROR_NONE; -} - -/**************************************************************************/ -/*! - @brief Converts msecs to an integer representing 1.25ms units - - @param[in] ms - The number of milliseconds to conver to 1.25ms units - - @returns The number of 1.25ms units in the supplied number of ms -*/ -/**************************************************************************/ -static inline uint32_t msec_to_1_25msec(uint32_t interval_ms) -{ - return (interval_ms * 4) / 5 ; -} - -static void error_callback(uint32_t nrf_error) -{ - ASSERT_STATUS_RET_VOID( nrf_error ); -} diff --git a/libraries/ble/nRF51822/btle/btle_gap.h b/libraries/ble/nRF51822/btle/btle_gap.h deleted file mode 100644 index 03fce0c61b..0000000000 --- a/libraries/ble/nRF51822/btle/btle_gap.h +++ /dev/null @@ -1,24 +0,0 @@ -/* mbed Microcontroller Library - * Copyright (c) 2006-2013 ARM Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef _BTLE_GAP_H_ -#define _BTLE_GAP_H_ - -#include "common/common.h" - -error_t btle_gap_init(void); - -#endif diff --git a/libraries/ble/nRF51822/btle/custom/custom_helper.cpp b/libraries/ble/nRF51822/btle/custom/custom_helper.cpp deleted file mode 100644 index d8a38478e9..0000000000 --- a/libraries/ble/nRF51822/btle/custom/custom_helper.cpp +++ /dev/null @@ -1,163 +0,0 @@ -/* mbed Microcontroller Library - * Copyright (c) 2006-2013 ARM Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - - #include "custom_helper.h" - -/**************************************************************************/ -/*! - @brief Adds the base UUID to the custom service. All UUIDs used - by this service are based on this 128-bit UUID. - - @note This UUID needs to be added to the SoftDevice stack before - adding the service's primary service via - 'sd_ble_gatts_service_add' - - @param[in] p_uuid_base A pointer to the 128-bit UUID array (8*16) - - @returns The UUID type. - A return value of 0 should be considered an error. - - @retval 0x00 BLE_UUID_TYPE_UNKNOWN - @retval 0x01 BLE_UUID_TYPE_BLE - @retval 0x02 BLE_UUID_TYPE_VENDOR_BEGIN - - @section EXAMPLE - @code - - // Take note that bytes 2/3 are blank since these are used to identify - // the primary service and individual characteristics - #define CFG_CUSTOM_UUID_BASE "\x6E\x40\x00\x00\xB5\xA3\xF3\x93\xE0\xA9\xE5\x0E\x24\xDC\xCA\x9E" - - uint8_t uuid_type = custom_add_uuid_base(CFG_CUSTOM_UUID_BASE); - ASSERT(uuid_type > 0, ERROR_NOT_FOUND); - - // We can now safely add the primary service and any characteristics - // for our custom service ... - - @endcode -*/ -/**************************************************************************/ -uint8_t custom_add_uuid_base(uint8_t const * const p_uuid_base) -{ - ble_uuid128_t base_uuid; - uint8_t uuid_type = 0; - - /* Reverse the bytes since ble_uuid128_t is LSB */ - for(uint8_t i=0; i<16; i++) - { - base_uuid.uuid128[i] = p_uuid_base[15-i]; - } - - ASSERT_INT( ERROR_NONE, sd_ble_uuid_vs_add( &base_uuid, &uuid_type ), 0); - - return uuid_type; -} - -/**************************************************************************/ -/*! - -*/ -/**************************************************************************/ -error_t custom_decode_uuid_base(uint8_t const * const p_uuid_base, ble_uuid_t * p_uuid) -{ - uint8_t uuid_base_le[16]; - - /* Reverse the bytes since ble_uuid128_t is LSB */ - for(uint8_t i=0; i<16; i++) - { - uuid_base_le[i] = p_uuid_base[15-i]; - } - - ASSERT_STATUS( sd_ble_uuid_decode(16, uuid_base_le, p_uuid) ); - - return ERROR_NONE; -} - -/**************************************************************************/ -/*! - @brief Adds a new characteristic to the custom service, assigning - properties, a UUID add-on value, etc. - - @param[in] service_handle - @param[in] p_uuid The 16-bit value to add to the base UUID - for this characteristic (normally >1 - since 1 is typically used by the primary - service). - @param[in] char_props The characteristic properties, as - defined by ble_gatt_char_props_t - @param[in] max_length The maximum length of this characeristic - @param[in] p_char_handle - - @returns - @retval ERROR_NONE Everything executed normally -*/ -/**************************************************************************/ -error_t custom_add_in_characteristic(uint16_t service_handle, ble_uuid_t* p_uuid, uint8_t properties, - uint8_t *p_data, uint16_t min_length, uint16_t max_length, - ble_gatts_char_handles_t* p_char_handle) -{ - /* Characteristic metadata */ - ble_gatts_attr_md_t cccd_md; - ble_gatt_char_props_t char_props; - - memcpy(&char_props, &properties, 1); - - if ( char_props.notify || char_props.indicate ) - { - /* Notification requires cccd */ - memclr_( &cccd_md, sizeof(ble_gatts_attr_md_t) ); - cccd_md.vloc = BLE_GATTS_VLOC_STACK; - BLE_GAP_CONN_SEC_MODE_SET_OPEN(&cccd_md.read_perm); - BLE_GAP_CONN_SEC_MODE_SET_OPEN(&cccd_md.write_perm); - } - - ble_gatts_char_md_t char_md = { 0 }; - - char_md.char_props = char_props; - char_md.p_cccd_md = (char_props.notify || char_props.indicate ) ? &cccd_md : NULL; - - /* Attribute declaration */ - ble_gatts_attr_md_t attr_md = { 0 }; - - attr_md.vloc = BLE_GATTS_VLOC_STACK; - attr_md.vlen = (min_length == max_length) ? 0 : 1; - - if ( char_props.read || char_props.notify || char_props.indicate ) - { - BLE_GAP_CONN_SEC_MODE_SET_OPEN(&attr_md.read_perm); - } - - if ( char_props.write ) - { - BLE_GAP_CONN_SEC_MODE_SET_OPEN(&attr_md.write_perm); - } - - ble_gatts_attr_t attr_char_value = { 0 }; - - attr_char_value.p_uuid = p_uuid; - attr_char_value.p_attr_md = &attr_md; - attr_char_value.init_len = min_length; - attr_char_value.max_len = max_length; - attr_char_value.p_value = p_data; - - - ASSERT_STATUS ( sd_ble_gatts_characteristic_add(service_handle, - &char_md, - &attr_char_value, - p_char_handle) ); - - return ERROR_NONE; -} diff --git a/libraries/ble/nRF51822/btle/custom/custom_helper.h b/libraries/ble/nRF51822/btle/custom/custom_helper.h deleted file mode 100644 index d77129653b..0000000000 --- a/libraries/ble/nRF51822/btle/custom/custom_helper.h +++ /dev/null @@ -1,38 +0,0 @@ -/* mbed Microcontroller Library - * Copyright (c) 2006-2013 ARM Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef _CUSTOM_HELPER_H_ -#define _CUSTOM_HELPER_H_ - -#ifdef __cplusplus - extern "C" { -#endif - -#include "common/common.h" -#include "ble.h" - -uint8_t custom_add_uuid_base(uint8_t const * const p_uuid_base); -error_t custom_decode_uuid(uint8_t const * const p_uuid_base, ble_uuid_t * p_uuid); - -error_t custom_add_in_characteristic(uint16_t service_handle, ble_uuid_t* p_uuid, uint8_t properties, - uint8_t *p_data, uint16_t min_length, uint16_t max_length, - ble_gatts_char_handles_t* p_char_handle); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/libraries/ble/nRF51822/common/ansi_escape.h b/libraries/ble/nRF51822/common/ansi_escape.h deleted file mode 100644 index 8a9377097c..0000000000 --- a/libraries/ble/nRF51822/common/ansi_escape.h +++ /dev/null @@ -1,103 +0,0 @@ -/**************************************************************************/ -/*! - @file ansi_esc_code.h - @author hathach (tinyusb.org) - - @section LICENSE - - Software License Agreement (BSD License) - - Copyright (c) 2013, hathach (tinyusb.org) - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - 1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - 3. Neither the name of the copyright holders nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY - EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - INCLUDING NEGLIGENCE OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - This file is part of the tinyusb stack. -*/ -/**************************************************************************/ - -/** \file - * \brief TBD - * - * \note TBD - */ - -/** \ingroup TBD - * \defgroup TBD - * \brief TBD - * - * @{ - */ - -#ifndef _ANSI_ESC_CODE_H_ -#define _ANSI_ESC_CODE_H_ - - -#ifdef __cplusplus - extern "C" { -#endif - -#define CSI_CODE(seq) "\33[" seq -#define CSI_SGR(x) CSI_CODE(#x) "m" - -//------------- Cursor movement -------------// -#define ANSI_CURSOR_UP(n) CSI_CODE(#n "A") -#define ANSI_CURSOR_DOWN(n) CSI_CODE(#n "B") -#define ANSI_CURSOR_FORWARD(n) CSI_CODE(#n "C") -#define ANSI_CURSOR_BACKWARD(n) CSI_CODE(#n "D") -#define ANSI_CURSOR_LINE_DOWN(n) CSI_CODE(#n "E") -#define ANSI_CURSOR_LINE_UP(n) CSI_CODE(#n "F") -#define ANSI_CURSOR_POSITION(n, m) CSI_CODE(#n ";" #m "H") - -#define ANSI_ERASE_SCREEN(n) CSI_CODE(#n "J") -#define ANSI_ERASE_LINE(n) CSI_CODE(#n "K") - -/** text color */ -#define ANSI_TEXT_BLACK CSI_SGR(30) -#define ANSI_TEXT_RED CSI_SGR(31) -#define ANSI_TEXT_GREEN CSI_SGR(32) -#define ANSI_TEXT_YELLOW CSI_SGR(33) -#define ANSI_TEXT_BLUE CSI_SGR(34) -#define ANSI_TEXT_MAGENTA CSI_SGR(35) -#define ANSI_TEXT_CYAN CSI_SGR(36) -#define ANSI_TEXT_WHITE CSI_SGR(37) -#define ANSI_TEXT_DEFAULT CSI_SGR(39) - -/** background color */ -#define ANSI_BG_BLACK CSI_SGR(40) -#define ANSI_BG_RED CSI_SGR(41) -#define ANSI_BG_GREEN CSI_SGR(42) -#define ANSI_BG_YELLOW CSI_SGR(43) -#define ANSI_BG_BLUE CSI_SGR(44) -#define ANSI_BG_MAGENTA CSI_SGR(45) -#define ANSI_BG_CYAN CSI_SGR(46) -#define ANSI_BG_WHITE CSI_SGR(47) -#define ANSI_BG_DEFAULT CSI_SGR(49) - -#ifdef __cplusplus - } -#endif - -#endif /* _TUSB_ANSI_ESC_CODE_H_ */ - -/** @} */ diff --git a/libraries/ble/nRF51822/common/assertion.h b/libraries/ble/nRF51822/common/assertion.h deleted file mode 100644 index 698e27dd02..0000000000 --- a/libraries/ble/nRF51822/common/assertion.h +++ /dev/null @@ -1,200 +0,0 @@ -/**************************************************************************/ -/*! - @file assertion.h - @author hathach (tinyusb.org) - - @section LICENSE - - Software License Agreement (BSD License) - - Copyright (c) 2013, K. Townsend (microBuilder.eu) - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - 1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - 3. Neither the name of the copyright holders nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY - EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - INCLUDING NEGLIGENCE OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -/**************************************************************************/ - -/** \file - * \brief TBD - * - * \note TBD - */ - -/** \ingroup TBD - * \defgroup TBD - * \brief TBD - * - * @{ - */ - -#ifndef _ASSERTION_H_ -#define _ASSERTION_H_ - -#include "projectconfig.h" - -#ifdef __cplusplus -extern "C" -{ -#endif - -static inline void debugger_breakpoint(void) ATTR_ALWAYS_INLINE; -static inline void debugger_breakpoint(void) -{ -#ifndef _TEST_ - __asm("BKPT #0\n"); -#endif -} - -//--------------------------------------------------------------------+ -// Compile-time Assert -//--------------------------------------------------------------------+ -#if defined __COUNTER__ && __COUNTER__ != __COUNTER__ - #define _ASSERT_COUNTER __COUNTER__ -#else - #define _ASSERT_COUNTER __LINE__ -#endif - -#define ASSERT_STATIC(const_expr, message) enum { XSTRING_CONCAT_(static_assert_, _ASSERT_COUNTER) = 1/(!!(const_expr)) } - -//--------------------------------------------------------------------+ -// Assert Helper -//--------------------------------------------------------------------+ -//#ifndef _TEST_ -// #define ASSERT_MESSAGE(format, ...)\ -// _PRINTF("Assert at %s: %s: %d: " format "\n", __BASE_FILE__, __PRETTY_FUNCTION__, __LINE__, __VA_ARGS__) -//#else -// #define ASSERT_MESSAGE(format, ...)\ -// _PRINTF("%d:note: Assert " format "\n", __LINE__, __VA_ARGS__) -//#endif - -#if CFG_DEBUG == 3 - #define ASSERT_MESSAGE(format, ...) debugger_breakpoint() -#elif CFG_DEBUG == 2 - #define ASSERT_MESSAGE(format, ...) printf("Assert at %s: %s: %d: " format "\n", __BASE_FILE__, __PRETTY_FUNCTION__, __LINE__, __VA_ARGS__) -#else - #define ASSERT_MESSAGE(format, ...) -#endif - -#define ASSERT_ERROR_HANDLER(x, para) \ - return (x) - -#define ASSERT_DEFINE_WITH_HANDLER(error_handler, handler_para, setup_statement, condition, error, format, ...) \ - do{\ - setup_statement;\ - if (!(condition)) {\ - ASSERT_MESSAGE(format, __VA_ARGS__);\ - error_handler(error, handler_para);\ - }\ - }while(0) - -#define ASSERT_DEFINE(...) ASSERT_DEFINE_WITH_HANDLER(ASSERT_ERROR_HANDLER, NULL, __VA_ARGS__) - -//--------------------------------------------------------------------+ -// error_t Status Assert TODO use ASSERT_DEFINE -//--------------------------------------------------------------------+ -#define ASSERT_STATUS_MESSAGE(sts, message) \ - ASSERT_DEFINE(error_t status = (error_t)(sts),\ - ERROR_NONE == status, status, "%s: %s", ErrorStr[status], message) - -#define ASSERT_STATUS(sts) \ - ASSERT_DEFINE(error_t status = (error_t)(sts),\ - ERROR_NONE == status, status, "error = %d", status) - -#define ASSERT_STATUS_RET_VOID(sts) \ - ASSERT_DEFINE(error_t status = (error_t)(sts),\ - ERROR_NONE == status, (void) 0, "error = %d", status) - -//--------------------------------------------------------------------+ -// Logical Assert -//--------------------------------------------------------------------+ -#define ASSERT(...) ASSERT_TRUE(__VA_ARGS__) -#define ASSERT_TRUE(condition , error) ASSERT_DEFINE( , (condition), error, "%s", "evaluated to false") -#define ASSERT_FALSE(condition , error) ASSERT_DEFINE( ,!(condition), error, "%s", "evaluated to true") - -//--------------------------------------------------------------------+ -// Pointer Assert -//--------------------------------------------------------------------+ -#define ASSERT_PTR(...) ASSERT_PTR_NOT_NULL(__VA_ARGS__) -#define ASSERT_PTR_NOT_NULL(pointer, error) ASSERT_DEFINE( , NULL != (pointer), error, "%s", "pointer is NULL") -#define ASSERT_PTR_NULL(pointer, error) ASSERT_DEFINE( , NULL == (pointer), error, "%s", "pointer is not NULL") - -//--------------------------------------------------------------------+ -// Integral Assert -//--------------------------------------------------------------------+ -#define ASSERT_XXX_EQUAL(type_format, expected, actual, error) \ - ASSERT_DEFINE(\ - uint32_t exp = (expected); uint32_t act = (actual),\ - exp==act,\ - error,\ - "expected " type_format ", actual " type_format, exp, act) - -#define ASSERT_XXX_WITHIN(type_format, lower, upper, actual, error) \ - ASSERT_DEFINE(\ - uint32_t low = (lower); uint32_t up = (upper); uint32_t act = (actual),\ - (low <= act) && (act <= up),\ - error,\ - "expected within " type_format " - " type_format ", actual " type_format, low, up, act) - -//--------------------------------------------------------------------+ -// Integer Assert -//--------------------------------------------------------------------+ -#define ASSERT_INT(...) ASSERT_INT_EQUAL(__VA_ARGS__) -#define ASSERT_INT_EQUAL(...) ASSERT_XXX_EQUAL("%d", __VA_ARGS__) -#define ASSERT_INT_WITHIN(...) ASSERT_XXX_WITHIN("%d", __VA_ARGS__) - -//--------------------------------------------------------------------+ -// Hex Assert -//--------------------------------------------------------------------+ -#define ASSERT_HEX(...) ASSERT_HEX_EQUAL(__VA_ARGS__) -#define ASSERT_HEX_EQUAL(...) ASSERT_XXX_EQUAL("0x%x", __VA_ARGS__) -#define ASSERT_HEX_WITHIN(...) ASSERT_XXX_WITHIN("0x%x", __VA_ARGS__) - -//--------------------------------------------------------------------+ -// Bin Assert -//--------------------------------------------------------------------+ -#define BIN8_PRINTF_PATTERN "%d%d%d%d%d%d%d%d" -#define BIN8_PRINTF_CONVERT(byte) \ - ((byte) & 0x80 ? 1 : 0), \ - ((byte) & 0x40 ? 1 : 0), \ - ((byte) & 0x20 ? 1 : 0), \ - ((byte) & 0x10 ? 1 : 0), \ - ((byte) & 0x08 ? 1 : 0), \ - ((byte) & 0x04 ? 1 : 0), \ - ((byte) & 0x02 ? 1 : 0), \ - ((byte) & 0x01 ? 1 : 0) - -#define ASSERT_BIN8(...) ASSERT_BIN8_EQUAL(__VA_ARGS__) -#define ASSERT_BIN8_EQUAL(expected, actual, error)\ - ASSERT_DEFINE(\ - uint8_t exp = (expected); uint8_t act = (actual),\ - exp==act,\ - error,\ - "expected " BIN8_PRINTF_PATTERN ", actual " BIN8_PRINTF_PATTERN, BIN8_PRINTF_CONVERT(exp), BIN8_PRINTF_CONVERT(act) ) - -#ifdef __cplusplus -} -#endif - -#endif /* _ASSERTION_H_ */ - -/** @} */ diff --git a/libraries/ble/nRF51822/common/binary.h b/libraries/ble/nRF51822/common/binary.h deleted file mode 100644 index 585787eb2f..0000000000 --- a/libraries/ble/nRF51822/common/binary.h +++ /dev/null @@ -1,96 +0,0 @@ -/**************************************************************************/ -/*! - @file binary.h - @author hathach (tinyusb.org) - - @section LICENSE - - Software License Agreement (BSD License) - - Copyright (c) 2013, K. Townsend (microBuilder.eu) - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - 1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - 3. Neither the name of the copyright holders nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY - EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - INCLUDING NEGLIGENCE OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -/**************************************************************************/ - -/** \ingroup TBD - * \defgroup TBD - * \brief TBD - * - * @{ - */ - -#ifndef _BINARY_H_ -#define _BINARY_H_ - -#ifdef __cplusplus - extern "C" { -#endif - -/// n-th Bit -#define BIT(n) (1 << (n)) - -/// set n-th bit of x to 1 -#define BIT_SET(x, n) ( (x) | BIT(n) ) - -/// clear n-th bit of x -#define BIT_CLR(x, n) ( (x) & (~BIT(n)) ) - -/// test n-th bit of x -#define BIT_TEST(x, n) ( (x) & BIT(n) ) - -#if defined(__GNUC__) && !defined(__CC_ARM) // keil does not support binary format - -#define BIN8(x) ((uint8_t) (0b##x)) -#define BIN16(b1, b2) ((uint16_t) (0b##b1##b2)) -#define BIN32(b1, b2, b3, b4) ((uint32_t) (0b##b1##b2##b3##b4)) - -#else - -// internal macro of B8, B16, B32 -#define _B8__(x) (((x&0x0000000FUL)?1:0) \ - +((x&0x000000F0UL)?2:0) \ - +((x&0x00000F00UL)?4:0) \ - +((x&0x0000F000UL)?8:0) \ - +((x&0x000F0000UL)?16:0) \ - +((x&0x00F00000UL)?32:0) \ - +((x&0x0F000000UL)?64:0) \ - +((x&0xF0000000UL)?128:0)) - -#define BIN8(d) ((uint8_t) _B8__(0x##d##UL)) -#define BIN16(dmsb,dlsb) (((uint16_t)BIN8(dmsb)<<8) + BIN8(dlsb)) -#define BIN32(dmsb,db2,db3,dlsb) \ - (((uint32_t)BIN8(dmsb)<<24) \ - + ((uint32_t)BIN8(db2)<<16) \ - + ((uint32_t)BIN8(db3)<<8) \ - + BIN8(dlsb)) -#endif - -#ifdef __cplusplus -} -#endif - -#endif /* _BINARY_H_ */ - -/** @} */ diff --git a/libraries/ble/nRF51822/common/ble_error.h b/libraries/ble/nRF51822/common/ble_error.h deleted file mode 100644 index 36deb33080..0000000000 --- a/libraries/ble/nRF51822/common/ble_error.h +++ /dev/null @@ -1,151 +0,0 @@ -/**************************************************************************/ -/*! - @file ble_error.h - @author hathach (tinyusb.org) - - @section LICENSE - - Software License Agreement (BSD License) - - Copyright (c) 2013, K. Townsend (microBuilder.eu) - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - 1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - 3. Neither the name of the copyright holders nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY - EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -/**************************************************************************/ - -/** \file - * \brief Error Header - * - * \note TBD - */ - -/** \ingroup Group_Common - * \defgroup Group_Error Error Codes - * @{ - */ - -#ifndef _BLE_ERROR_H_ -#define _BLE_ERROR_H_ - -#include "projectconfig.h" - -#ifdef __cplusplus - extern "C" { -#endif - -typedef enum -{ - /*======================================================================= - NORDIC GLOBAL ERRORS 0x0000 .. 0x00FF - ----------------------------------------------------------------------- - Errors mapped from nrf_error.h - -----------------------------------------------------------------------*/ - ERROR_NONE = 0x0000 , ///< Successful command - ERROR_SVC_HANDLER_MISSING = 0x0001 , ///< SVC handler is missing - ERROR_SOFTDEVICE_NOT_ENABLED = 0x0002 , ///< SoftDevice has not been enabled - ERROR_INTERNAL = 0x0003 , ///< Internal Error - ERROR_NO_MEM = 0x0004 , ///< No Memory for operation - ERROR_NOT_FOUND = 0x0005 , ///< Not found - ERROR_NOT_SUPPORTED = 0x0006 , ///< Not supported - ERROR_INVALID_PARAM = 0x0007 , ///< Invalid Parameter - ERROR_INVALID_STATE = 0x0008 , ///< Invalid state, operation disallowed in this state - ERROR_INVALID_LENGTH = 0x0009 , ///< Invalid Length - ERROR_INVALID_FLAGS = 0x000A , ///< Invalid Flags - ERROR_INVALID_DATA = 0x000B , ///< Invalid Data - ERROR_DATA_SIZE = 0x000C , ///< Data size exceeds limit - ERROR_TIMEOUT = 0x000D , ///< Operation timed out - ERROR_NULL = 0x000E , ///< Null Pointer - ERROR_FORBIDDEN = 0x000F , ///< Forbidden Operation - ERROR_INVALID_ADDR = 0x0010 , ///< Bad Memory Address - ERROR_BUSY = 0x0011 , ///< Busy - /*=======================================================================*/ - - ERROR_INVALIDPARAMETER = 0x0100 , /**< An invalid parameter value was provided */ - ERROR_I2C_XFER_FAILED = 0x0101 , /**< an failed attempt to make I2C transfer */ - - /*======================================================================= - SIMPLE BINARY PROTOCOL ERRORS 0x0120 .. 0x013F - ----------------------------------------------------------------------- - Errors relating to the simple binary protocol (/src//protocol) - -----------------------------------------------------------------------*/ - ERROR_PROT_INVALIDMSGTYPE = 0x121, /**< Unexpected msg type encountered */ - ERROR_PROT_INVALIDCOMMANDID = 0x122, /**< Unknown or out of range command ID */ - ERROR_PROT_INVALIDPAYLOAD = 0x123, /**< Message payload has a problem (invalid len, etc.) */ - /*=======================================================================*/ - - //------------- based on Nordic SDM nrf_error_sdm.h -------------// - ERROR_SDM_LFCLK_SOURCE_UNKNOWN = 0x1000 , ///< Unknown lfclk source - ERROR_SDM_INCORRECT_INTERRUPT_CONFIGURATION = 0x1001 , ///< Incorrect interrupt configuration (can be caused by using illegal priority levels, or having enabled SoftDevice interrupts) - ERROR_SDM_INCORRECT_CLENR0 = 0x1002 , ///< Incorrect CLENR0 (can be caused by erronous SoftDevice flashing) - - //------------- based on Nordic SOC nrf_error_soc.h -------------// - /* Mutex Errors */ - ERROR_SOC_MUTEX_ALREADY_TAKEN = 0x2000 , ///< Mutex already taken - - /* NVIC errors */ - ERROR_SOC_NVIC_INTERRUPT_NOT_AVAILABLE = 0x2001 , ///< NVIC interrupt not available - ERROR_SOC_NVIC_INTERRUPT_PRIORITY_NOT_ALLOWED = 0x2002 , ///< NVIC interrupt priority not allowed - ERROR_SOC_NVIC_SHOULD_NOT_RETURN = 0x2003 , ///< NVIC should not return - - /* Power errors */ - ERROR_SOC_POWER_MODE_UNKNOWN = 0x2004 , ///< Power mode unknown - ERROR_SOC_POWER_POF_THRESHOLD_UNKNOWN = 0x2005 , ///< Power POF threshold unknown - ERROR_SOC_POWER_OFF_SHOULD_NOT_RETURN = 0x2006 , ///< Power off should not return - - /* Rand errors */ - ERROR_SOC_RAND_NOT_ENOUGH_VALUES = 0x2007 , ///< RAND not enough values - - /* PPI errors */ - ERROR_SOC_PPI_INVALID_CHANNEL = 0x2008 , ///< Invalid PPI Channel - ERROR_SOC_PPI_INVALID_GROUP = 0x2009 , ///< Invalid PPI Group - - //------------- based on Nordic STK (ble) ble_err.h -------------// - ERROR_BLE_INVALID_CONN_HANDLE = 0x3001 , /**< Invalid connection handle. */ - ERROR_BLE_INVALID_ATTR_HANDLE = 0x3002 , /**< Invalid attribute handle. */ - ERROR_BLE_NO_TX_BUFFERS = 0x3003 , /**< Buffer capacity exceeded. */ - - // L2CAP - ERROR_BLE_L2CAP_CID_IN_USE = 0x3100 , /**< CID already in use. */ - - // GAP - ERROR_BLE_GAP_UUID_LIST_MISMATCH = 0x3200 , /**< UUID list does not contain an integral number of UUIDs. */ - ERROR_BLE_GAP_DISCOVERABLE_WITH_WHITELIST = 0x3201 , /**< Use of Whitelist not permitted with discoverable advertising. */ - ERROR_BLE_GAP_INVALID_BLE_ADDR = 0x3202 , /**< The upper two bits of the address do not correspond to the specified address type. */ - - // GATTC - ERROR_BLE_GATTC_PROC_NOT_PERMITTED = 0x3300 , - - // GATTS - ERROR_BLEGATTS_INVALID_ATTR_TYPE = 0x3400 , /**< Invalid attribute type. */ - ERROR_BLEGATTS_SYS_ATTR_MISSING = 0x3401 , /**< System Attributes missing. */ - -}error_t; - -#ifdef __cplusplus - } -#endif - -#endif /* _BLE_ERROR_H_ */ - - /** @} */ diff --git a/libraries/ble/nRF51822/common/common.h b/libraries/ble/nRF51822/common/common.h deleted file mode 100644 index 6002c6dfb7..0000000000 --- a/libraries/ble/nRF51822/common/common.h +++ /dev/null @@ -1,236 +0,0 @@ -/**************************************************************************/ -/*! - @file common.h - @author hathach (tinyusb.org) - - @section LICENSE - - Software License Agreement (BSD License) - - Copyright (c) 2013, K. Townsend (microBuilder.eu) - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - 1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - 3. Neither the name of the copyright holders nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY - EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - INCLUDING NEGLIGENCE OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -/**************************************************************************/ - -/** \defgroup Group_Common Common Files - * @{ - * - * \defgroup Group_CommonH common.h - * - * @{ - */ - -#ifndef _COMMON_H_ -#define _COMMON_H_ - -#ifdef __cplusplus - extern "C" { -#endif - -//--------------------------------------------------------------------+ -// INCLUDES -//--------------------------------------------------------------------+ - -//------------- Standard Header -------------// -#include -#include -#include -#include -#include - -//------------- General Header -------------// -#include "projectconfig.h" -#include "compiler.h" -#include "assertion.h" -#include "binary.h" -#include "ble_error.h" - -//------------- MCU header -------------// -//#include "nrf.h" - -//--------------------------------------------------------------------+ -// TYPEDEFS -//--------------------------------------------------------------------+ -typedef unsigned char byte_t; -typedef float float32_t; -typedef double float64_t; - -//--------------------------------------------------------------------+ -// MACROS -//--------------------------------------------------------------------+ -#define STRING_(x) #x // stringify without expand -#define XSTRING_(x) STRING_(x) // expand then stringify -#define STRING_CONCAT_(a, b) a##b // concat without expand -#define XSTRING_CONCAT_(a, b) STRING_CONCAT_(a, b) // expand then concat - -#define U16_HIGH_U8(u16) ((uint8_t) (((u16) >> 8) & 0x00ff)) -#define U16_LOW_U8(u16) ((uint8_t) ((u16) & 0x00ff)) -#define U16_TO_U8S_BE(u16) U16_HIGH_U8(u16), U16_LOW_U8(u16) -#define U16_TO_U8S_LE(u16) U16_LOW_U8(u16), U16_HIGH_U8(u16) - -#define U32_B1_U8(u32) ((uint8_t) (((u32) >> 24) & 0x000000ff)) // MSB -#define U32_B2_U8(u32) ((uint8_t) (((u32) >> 16) & 0x000000ff)) -#define U32_B3_U8(u32) ((uint8_t) (((u32) >> 8) & 0x000000ff)) -#define U32_B4_U8(u32) ((uint8_t) ((u32) & 0x000000ff)) // LSB - -#define U32_TO_U8S_BE(u32) U32_B1_U8(u32), U32_B2_U8(u32), U32_B3_U8(u32), U32_B4_U8(u32) -#define U32_TO_U8S_LE(u32) U32_B4_U8(u32), U32_B3_U8(u32), U32_B2_U8(u32), U32_B1_U8(u32) - -//--------------------------------------------------------------------+ -// INLINE FUNCTION -//--------------------------------------------------------------------+ -#define memclr_(buffer, size) memset(buffer, 0, size) - -//------------- Conversion -------------// -/// form an uint32_t from 4 x uint8_t -static inline uint32_t u32_from_u8(uint8_t b1, uint8_t b2, uint8_t b3, uint8_t b4) ATTR_ALWAYS_INLINE ATTR_CONST; -static inline uint32_t u32_from_u8(uint8_t b1, uint8_t b2, uint8_t b3, uint8_t b4) -{ - return (b1 << 24) + (b2 << 16) + (b3 << 8) + b4; -} - -static inline uint8_t u16_high_u8(uint16_t u16) ATTR_CONST ATTR_ALWAYS_INLINE; -static inline uint8_t u16_high_u8(uint16_t u16) -{ - return (uint8_t) ((u16 >> 8) & 0x00ff); -} - -static inline uint8_t u16_low_u8(uint16_t u16) ATTR_CONST ATTR_ALWAYS_INLINE; -static inline uint8_t u16_low_u8(uint16_t u16) -{ - return (uint8_t) (u16 & 0x00ff); -} - -//------------- Min -------------// -static inline uint8_t min8_of(uint8_t x, uint8_t y) ATTR_ALWAYS_INLINE ATTR_CONST; -static inline uint8_t min8_of(uint8_t x, uint8_t y) -{ - return (x < y) ? x : y; -} - -static inline uint16_t min16_of(uint16_t x, uint16_t y) ATTR_ALWAYS_INLINE ATTR_CONST; -static inline uint16_t min16_of(uint16_t x, uint16_t y) -{ - return (x < y) ? x : y; -} - -static inline uint32_t min32_of(uint32_t x, uint32_t y) ATTR_ALWAYS_INLINE ATTR_CONST; -static inline uint32_t min32_of(uint32_t x, uint32_t y) -{ - return (x < y) ? x : y; -} - -//------------- Max -------------// -static inline uint32_t max32_of(uint32_t x, uint32_t y) ATTR_ALWAYS_INLINE ATTR_CONST; -static inline uint32_t max32_of(uint32_t x, uint32_t y) -{ - return (x > y) ? x : y; -} - -//------------- Align -------------// -static inline uint32_t align32 (uint32_t value) ATTR_ALWAYS_INLINE ATTR_CONST; -static inline uint32_t align32 (uint32_t value) -{ - return (value & 0xFFFFFFE0UL); -} - -static inline uint32_t align16 (uint32_t value) ATTR_ALWAYS_INLINE ATTR_CONST; -static inline uint32_t align16 (uint32_t value) -{ - return (value & 0xFFFFFFF0UL); -} - -static inline uint32_t align_n (uint32_t alignment, uint32_t value) ATTR_ALWAYS_INLINE ATTR_CONST; -static inline uint32_t align_n (uint32_t alignment, uint32_t value) -{ - return value & (~(alignment-1)); -} - -static inline uint32_t align4k (uint32_t value) ATTR_ALWAYS_INLINE ATTR_CONST; -static inline uint32_t align4k (uint32_t value) -{ - return (value & 0xFFFFF000UL); -} - -static inline uint32_t offset4k(uint32_t value) ATTR_ALWAYS_INLINE ATTR_CONST; -static inline uint32_t offset4k(uint32_t value) -{ - return (value & 0xFFFUL); -} - -//------------- Mathematics -------------// -/// inclusive range checking -static inline bool is_in_range(uint32_t lower, uint32_t value, uint32_t upper) ATTR_ALWAYS_INLINE ATTR_CONST; -static inline bool is_in_range(uint32_t lower, uint32_t value, uint32_t upper) -{ - return (lower <= value) && (value <= upper); -} - -/// exclusive range checking -static inline bool is_in_range_exclusive(uint32_t lower, uint32_t value, uint32_t upper) ATTR_ALWAYS_INLINE ATTR_CONST; -static inline bool is_in_range_exclusive(uint32_t lower, uint32_t value, uint32_t upper) -{ - return (lower < value) && (value < upper); -} - -static inline uint8_t log2_of(uint32_t value) ATTR_ALWAYS_INLINE ATTR_CONST; -static inline uint8_t log2_of(uint32_t value) -{ - uint8_t result = 0; // log2 of a value is its MSB's position - - while (value >>= 1) - { - result++; - } - return result; -} - -// return the number of set bits in value -static inline uint8_t cardinality_of(uint32_t value) ATTR_ALWAYS_INLINE ATTR_CONST; -static inline uint8_t cardinality_of(uint32_t value) -{ - // Brian Kernighan's method goes through as many iterations as there are set bits. So if we have a 32-bit word with only - // the high bit set, then it will only go once through the loop - // Published in 1988, the C Programming Language 2nd Ed. (by Brian W. Kernighan and Dennis M. Ritchie) - // mentions this in exercise 2-9. On April 19, 2006 Don Knuth pointed out to me that this method - // "was first published by Peter Wegner in CACM 3 (1960), 322. (Also discovered independently by Derrick Lehmer and - // published in 1964 in a book edited by Beckenbach.)" - uint8_t count; - for (count = 0; value; count++) - { - value &= value - 1; // clear the least significant bit set - } - - return count; -} - -#ifdef __cplusplus - } -#endif - -#endif /* _COMMON_H_ */ - -/** @} */ -/** @} */ diff --git a/libraries/ble/nRF51822/common/compiler.h b/libraries/ble/nRF51822/common/compiler.h deleted file mode 100644 index 3096cd8079..0000000000 --- a/libraries/ble/nRF51822/common/compiler.h +++ /dev/null @@ -1,152 +0,0 @@ -/**************************************************************************/ -/*! - @file compiler.h - @author hathach (tinyusb.org) - - @section LICENSE - - Software License Agreement (BSD License) - - Copyright (c) 2013, K. Townsend (microBuilder.eu) - All rights reserved. - - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - 1. Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - 3. Neither the name of the copyright holders nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ''AS IS'' AND ANY - EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY - DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION HOWEVER CAUSED AND - ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - INCLUDING NEGLIGENCE OR OTHERWISE ARISING IN ANY WAY OUT OF THE USE OF THIS - SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ -/**************************************************************************/ - -/** \file - * \brief GCC Header - */ - -/** \ingroup Group_Compiler - * \defgroup Group_GCC GNU GCC - * @{ - */ - -#ifndef _COMPILER_GCC_H_ -#define _COMPILER_GCC_H_ - -#ifdef __cplusplus - extern "C" { -#endif - -#include "projectconfig.h" - -//#ifndef __GNUC__ -// #define ATTR_ALWAYS_INLINE -// #define ATTR_CONST -//#else - -#ifdef _TEST_ - #define ATTR_ALWAYS_INLINE - #define STATIC_ - #define INLINE_ -#else - #define STATIC_ static - #define INLINE_ inline - - #if CFG_DEBUG == 3 - #define ATTR_ALWAYS_INLINE // no inline for debug = 3 - #endif -#endif - -#define ALIGN_OF(x) __alignof__(x) - -/// Normally, the compiler places the objects it generates in sections like data or bss & function in text. Sometimes, however, you need additional sections, or you need certain particular variables to appear in special sections, for example to map to special hardware. The section attribute specifies that a variable (or function) lives in a particular section -#define ATTR_SECTION(section) __attribute__ ((#section)) - -/// If this attribute is used on a function declaration and a call to such a function is not eliminated through dead code elimination or other optimizations, an error that includes message is diagnosed. This is useful for compile-time checking -#define ATTR_ERROR(Message) __attribute__ ((error(Message))) - -/// If this attribute is used on a function declaration and a call to such a function is not eliminated through dead code elimination or other optimizations, a warning that includes message is diagnosed. This is useful for compile-time checking -#define ATTR_WARNING(Message) __attribute__ ((warning(Message))) - -/** - * \defgroup Group_VariableAttr Variable Attributes - * @{ - */ - -/// This attribute specifies a minimum alignment for the variable or structure field, measured in bytes -#define ATTR_ALIGNED(Bytes) __attribute__ ((aligned(Bytes))) - -/// The packed attribute specifies that a variable or structure field should have the smallest possible alignment—one byte for a variable, and one bit for a field, unless you specify a larger value with the aligned attribute -#define ATTR_PACKED __attribute__ ((packed)) - -#define ATTR_PREPACKED - -#define ATTR_PACKED_STRUCT(x) x __attribute__ ((packed)) -/** @} */ - -/** - * \defgroup Group_FuncAttr Function Attributes - * @{ - */ - -#ifndef ATTR_ALWAYS_INLINE -/// Generally, functions are not inlined unless optimization is specified. For functions declared inline, this attribute inlines the function even if no optimization level is specified -#define ATTR_ALWAYS_INLINE __attribute__ ((always_inline)) -#endif - -/// The nonnull attribute specifies that some function parameters should be non-null pointers. f the compiler determines that a null pointer is passed in an argument slot marked as non-null, and the -Wnonnull option is enabled, a warning is issued. All pointer arguments are marked as non-null -#define ATTR_NON_NULL __attribute__ ((nonull)) - -/// Many functions have no effects except the return value and their return value depends only on the parameters and/or global variables. Such a function can be subject to common subexpression elimination and loop optimization just as an arithmetic operator would be. These functions should be declared with the attribute pure -#define ATTR_PURE __attribute__ ((pure)) - -/// Many functions do not examine any values except their arguments, and have no effects except the return value. Basically this is just slightly more strict class than the pure attribute below, since function is not allowed to read global memory. -/// Note that a function that has pointer arguments and examines the data pointed to must not be declared const. Likewise, a function that calls a non-const function usually must not be const. It does not make sense for a const function to return void -#define ATTR_CONST __attribute__ ((const)) - -/// The deprecated attribute results in a warning if the function is used anywhere in the source file. This is useful when identifying functions that are expected to be removed in a future version of a program. The warning also includes the location of the declaration of the deprecated function, to enable users to easily find further information about why the function is deprecated, or what they should do instead. Note that the warnings only occurs for uses -#define ATTR_DEPRECATED __attribute__ ((deprecated)) - -/// Same as the deprecated attribute with optional message in the warning -#define ATTR_DEPRECATED_MESS(mess) __attribute__ ((deprecated(mess))) - -/// The weak attribute causes the declaration to be emitted as a weak symbol rather than a global. This is primarily useful in defining library functions that can be overridden in user code -#define ATTR_WEAK __attribute__ ((weak)) - -/// The alias attribute causes the declaration to be emitted as an alias for another symbol, which must be specified -#define ATTR_ALIAS(func) __attribute__ ((alias(#func))) - -/// The weakref attribute marks a declaration as a weak reference. It is equivalent with weak + alias attribute, but require function is static -#define ATTR_WEAKREF(func) __attribute__ ((weakref(#func))) - -/// The warn_unused_result attribute causes a warning to be emitted if a caller of the function with this attribute does not use its return value. This is useful for functions where not checking the result is either a security problem or always a bug -#define ATTR_WARN_UNUSED_RESULT __attribute__ ((warn_unused_result)) - -/// This attribute, attached to a function, means that code must be emitted for the function even if it appears that the function is not referenced. This is useful, for example, when the function is referenced only in inline assembly. -#define ATTR_USED __attribute__ ((used)) - -/// This attribute, attached to a function, means that the function is meant to be possibly unused. GCC does not produce a warning for this function. -#define ATTR_UNUSED __attribute__ ((unused)) - -/** @} */ - -#ifdef __cplusplus - } -#endif - -#endif /* _COMPILER_GCC_H_ */ - -/// @} diff --git a/libraries/ble/nRF51822/nRF51822n.cpp b/libraries/ble/nRF51822/nRF51822n.cpp deleted file mode 100644 index 0d005f03c3..0000000000 --- a/libraries/ble/nRF51822/nRF51822n.cpp +++ /dev/null @@ -1,89 +0,0 @@ -/* mbed Microcontroller Library - * Copyright (c) 2006-2013 ARM Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "mbed.h" -#include "nRF51822n.h" - -#include "btle/btle.h" - -/**************************************************************************/ -/*! - @brief Constructor -*/ -/**************************************************************************/ -nRF51822n::nRF51822n(void) -{ -} - -/**************************************************************************/ -/*! - @brief Destructor -*/ -/**************************************************************************/ -nRF51822n::~nRF51822n(void) -{ -} - -/**************************************************************************/ -/*! - @brief Initialises anything required to start using BLE - - @returns ble_error_t - - @retval BLE_ERROR_NONE - Everything executed properly - - @section EXAMPLE - - @code - - @endcode -*/ -/**************************************************************************/ -ble_error_t nRF51822n::init(void) -{ - /* ToDo: Clear memory contents, reset the SD, etc. */ - btle_init(); - - return BLE_ERROR_NONE; -} - -/**************************************************************************/ -/*! - @brief Resets the BLE HW, removing any existing services and - characteristics - - @returns ble_error_t - - @retval BLE_ERROR_NONE - Everything executed properly - - @section EXAMPLE - - @code - - @endcode -*/ -/**************************************************************************/ -ble_error_t nRF51822n::reset(void) -{ - wait(0.5); - - /* Wait for the radio to come back up */ - wait(1); - - return BLE_ERROR_NONE; -} diff --git a/libraries/ble/nRF51822/nRF51822n.h b/libraries/ble/nRF51822/nRF51822n.h deleted file mode 100644 index f12f059559..0000000000 --- a/libraries/ble/nRF51822/nRF51822n.h +++ /dev/null @@ -1,49 +0,0 @@ -/* mbed Microcontroller Library - * Copyright (c) 2006-2013 ARM Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef __NRF51822_H__ -#define __NRF51822_H__ - -#define NRF51 -#define DEBUG_NRF_USER -#define BLE_STACK_SUPPORT_REQD -#define BOARD_PCA10001 - -#include "mbed.h" -#include "blecommon.h" -#include "hw/BLEDevice.h" -#include "nRF51Gap.h" -#include "nRF51GattServer.h" - -/**************************************************************************/ -/*! - \brief - -*/ -/**************************************************************************/ -class nRF51822n : public BLEDevice -{ - public: - nRF51822n(void); - virtual ~nRF51822n(void); - - virtual Gap& getGap() { return nRF51Gap::getInstance(); }; - virtual GattServer& getGattServer() { return nRF51GattServer::getInstance(); }; - virtual ble_error_t init(void); - virtual ble_error_t reset(void); -}; - -#endif diff --git a/libraries/ble/nRF51822/nRF51Gap.cpp b/libraries/ble/nRF51822/nRF51Gap.cpp deleted file mode 100644 index b7a2291a31..0000000000 --- a/libraries/ble/nRF51822/nRF51Gap.cpp +++ /dev/null @@ -1,284 +0,0 @@ -/* mbed Microcontroller Library - * Copyright (c) 2006-2013 ARM Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "nRF51Gap.h" -#include "mbed.h" - -#include "common/common.h" -#include "ble_advdata.h" -#include "ble_hci.h" - -/**************************************************************************/ -/*! - @brief Sets the advertising parameters and payload for the device - - @param[in] params - Basic advertising details, including the advertising - delay, timeout and how the device should be advertised - @params[in] advData - The primary advertising data payload - @params[in] scanResponse - The optional Scan Response payload if the advertising - type is set to \ref GapAdvertisingParams::ADV_SCANNABLE_UNDIRECTED - in \ref GapAdveritinngParams - - @returns \ref ble_error_t - - @retval BLE_ERROR_NONE - Everything executed properly - - @retval BLE_ERROR_BUFFER_OVERFLOW - The proposed action would cause a buffer overflow. All - advertising payloads must be <= 31 bytes, for example. - - @retval BLE_ERROR_NOT_IMPLEMENTED - A feature was requested that is not yet supported in the - nRF51 firmware or hardware. - - @retval BLE_ERROR_PARAM_OUT_OF_RANGE - One of the proposed values is outside the valid range. - - @section EXAMPLE - - @code - - @endcode -*/ -/**************************************************************************/ -ble_error_t nRF51Gap::setAdvertisingData(GapAdvertisingData & advData, GapAdvertisingData & scanResponse) -{ - /* Make sure we don't exceed the advertising payload length */ - if (advData.getPayloadLen() > GAP_ADVERTISING_DATA_MAX_PAYLOAD) - { - return BLE_ERROR_BUFFER_OVERFLOW; - } - - /* Make sure we have a payload! */ - if (advData.getPayloadLen() == 0) - { - return BLE_ERROR_PARAM_OUT_OF_RANGE; - } - - /* Check the scan response payload limits */ - //if ((params.getAdvertisingType() == GapAdvertisingParams::ADV_SCANNABLE_UNDIRECTED)) - //{ - // /* Check if we're within the upper limit */ - // if (advData.getPayloadLen() > GAP_ADVERTISING_DATA_MAX_PAYLOAD) - // { - // return BLE_ERROR_BUFFER_OVERFLOW; - // } - // /* Make sure we have a payload! */ - // if (advData.getPayloadLen() == 0) - // { - // return BLE_ERROR_PARAM_OUT_OF_RANGE; - // } - //} - - /* Send advertising data! */ - ASSERT( ERROR_NONE == sd_ble_gap_adv_data_set(advData.getPayload(), advData.getPayloadLen(), - scanResponse.getPayload(), scanResponse.getPayloadLen()), BLE_ERROR_PARAM_OUT_OF_RANGE); - - /* Make sure the GAP Service appearance value is aligned with the appearance from GapAdvertisingData */ - ASSERT( ERROR_NONE == sd_ble_gap_appearance_set(advData.getAppearance()), BLE_ERROR_PARAM_OUT_OF_RANGE); - - /* ToDo: Perform some checks on the payload, for example the Scan Response can't */ - /* contains a flags AD type, etc. */ - - return BLE_ERROR_NONE; -} - -/**************************************************************************/ -/*! - @brief Starts the BLE HW, initialising any services that were - added before this function was called. - - @note All services must be added before calling this function! - - @returns ble_error_t - - @retval BLE_ERROR_NONE - Everything executed properly - - @section EXAMPLE - - @code - - @endcode -*/ -/**************************************************************************/ -ble_error_t nRF51Gap::startAdvertising(GapAdvertisingParams & params) -{ - /* Make sure we support the advertising type */ - if (params.getAdvertisingType() == GapAdvertisingParams::ADV_CONNECTABLE_DIRECTED) - { - /* ToDo: This requires a propery security implementation, etc. */ - return BLE_ERROR_NOT_IMPLEMENTED; - } - - /* Check interval range */ - if (params.getAdvertisingType() == GapAdvertisingParams::ADV_NON_CONNECTABLE_UNDIRECTED) - { - /* Min delay is slightly longer for unconnectable devices */ - if ((params.getInterval() < GAP_ADV_PARAMS_INTERVAL_MIN_NONCON) || - (params.getInterval() > GAP_ADV_PARAMS_INTERVAL_MAX)) - { - return BLE_ERROR_PARAM_OUT_OF_RANGE; - } - } - else - { - if ((params.getInterval() < GAP_ADV_PARAMS_INTERVAL_MIN) || - (params.getInterval() > GAP_ADV_PARAMS_INTERVAL_MAX)) - { - return BLE_ERROR_PARAM_OUT_OF_RANGE; - } - } - - /* Check timeout is zero for Connectable Directed */ - if ((params.getAdvertisingType() == GapAdvertisingParams::ADV_CONNECTABLE_DIRECTED) && - (params.getTimeout() != 0)) - { - /* Timeout must be 0 with this type, although we'll never get here */ - /* since this isn't implemented yet anyway */ - return BLE_ERROR_PARAM_OUT_OF_RANGE; - } - - /* Check timeout for other advertising types */ - if ((params.getAdvertisingType() != GapAdvertisingParams::ADV_CONNECTABLE_DIRECTED) && - (params.getTimeout() > GAP_ADV_PARAMS_TIMEOUT_MAX)) - { - return BLE_ERROR_PARAM_OUT_OF_RANGE; - } - - /* Start Advertising */ - ble_gap_adv_params_t adv_para = { 0 }; - - adv_para.type = params.getAdvertisingType() ; - adv_para.p_peer_addr = NULL ; // Undirected advertisement - adv_para.fp = BLE_GAP_ADV_FP_ANY ; - adv_para.p_whitelist = NULL ; - adv_para.interval = params.getInterval() ; // advertising interval (in units of 0.625 ms) - adv_para.timeout = params.getTimeout() ; - - ASSERT( ERROR_NONE == sd_ble_gap_adv_start(&adv_para), BLE_ERROR_PARAM_OUT_OF_RANGE); - - state.advertising = 1; - - return BLE_ERROR_NONE; -} - -/**************************************************************************/ -/*! - @brief Stops the BLE HW and disconnects from any devices - - @returns ble_error_t - - @retval BLE_ERROR_NONE - Everything executed properly - - @section EXAMPLE - - @code - - @endcode -*/ -/**************************************************************************/ -ble_error_t nRF51Gap::stopAdvertising(void) -{ - /* Stop Advertising */ - ASSERT( ERROR_NONE == sd_ble_gap_adv_stop(), BLE_ERROR_PARAM_OUT_OF_RANGE); - - state.advertising = 0; - - return BLE_ERROR_NONE; -} - -/**************************************************************************/ -/*! - @brief Disconnects if we are connected to a central device - - @returns ble_error_t - - @retval BLE_ERROR_NONE - Everything executed properly - - @section EXAMPLE - - @code - - @endcode -*/ -/**************************************************************************/ -ble_error_t nRF51Gap::disconnect(void) -{ - state.advertising = 0; - state.connected = 0; - - /* Disconnect if we are connected to a central device */ - ASSERT_INT(ERROR_NONE, sd_ble_gap_disconnect(m_connectionHandle, BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION), - BLE_ERROR_PARAM_OUT_OF_RANGE); - - return BLE_ERROR_NONE; -} - -/**************************************************************************/ -/*! - @brief Sets the 16-bit connection handle -*/ -/**************************************************************************/ -void nRF51Gap::setConnectionHandle(uint16_t con_handle) -{ - m_connectionHandle = con_handle; -} - -/**************************************************************************/ -/*! - @brief Gets the 16-bit connection handle -*/ -/**************************************************************************/ -uint16_t nRF51Gap::getConnectionHandle(void) -{ - return m_connectionHandle; -} - -/**************************************************************************/ -/*! - @brief Sets the BLE device address - - @returns ble_error_t - - @section EXAMPLE - - @code - - uint8_t device_address[6] = { 0xca, 0xfe, 0xf0, 0xf0, 0xf0, 0xf0 }; - nrf.getGap().setAddress(Gap::ADDR_TYPE_RANDOM_STATIC, device_address); - - @endcode -*/ -/**************************************************************************/ -ble_error_t nRF51Gap::setAddress(addr_type_t type, uint8_t address[6]) -{ - if ( type > ADDR_TYPE_RANDOM_PRIVATE_NON_RESOLVABLE) return BLE_ERROR_PARAM_OUT_OF_RANGE; - - ble_gap_addr_t dev_addr; - dev_addr.addr_type = type; - memcpy(dev_addr.addr, address, 6); - - ASSERT_INT(ERROR_NONE, sd_ble_gap_address_set(&dev_addr), BLE_ERROR_PARAM_OUT_OF_RANGE); - - return BLE_ERROR_NONE; -} diff --git a/libraries/ble/nRF51822/nRF51Gap.h b/libraries/ble/nRF51822/nRF51Gap.h deleted file mode 100644 index a010e947c7..0000000000 --- a/libraries/ble/nRF51822/nRF51Gap.h +++ /dev/null @@ -1,59 +0,0 @@ -/* mbed Microcontroller Library - * Copyright (c) 2006-2013 ARM Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef __NRF51822_GAP_H__ -#define __NRF51822_GAP_H__ - -#include "mbed.h" -#include "blecommon.h" -#include "ble.h" -#include "GapAdvertisingParams.h" -#include "GapAdvertisingData.h" -#include "hw/Gap.h" - -/**************************************************************************/ -/*! - \brief - -*/ -/**************************************************************************/ -class nRF51Gap : public Gap -{ - public: - static nRF51Gap& getInstance() - { - static nRF51Gap m_instance; - return m_instance; - } - - /* Functions that must be implemented from Gap */ - virtual ble_error_t setAddress(addr_type_t type, uint8_t address[6]); - virtual ble_error_t setAdvertisingData(GapAdvertisingData &, GapAdvertisingData &); - virtual ble_error_t startAdvertising(GapAdvertisingParams &); - virtual ble_error_t stopAdvertising(void); - virtual ble_error_t disconnect(void); - - void setConnectionHandle(uint16_t con_handle); - uint16_t getConnectionHandle(void); - - private: - uint16_t m_connectionHandle; - nRF51Gap() { m_connectionHandle = BLE_CONN_HANDLE_INVALID; }; - nRF51Gap(nRF51Gap const&); - void operator=(nRF51Gap const&); -}; - -#endif diff --git a/libraries/ble/nRF51822/nRF51GattServer.cpp b/libraries/ble/nRF51822/nRF51GattServer.cpp deleted file mode 100644 index 943161d0d5..0000000000 --- a/libraries/ble/nRF51822/nRF51GattServer.cpp +++ /dev/null @@ -1,241 +0,0 @@ -/* mbed Microcontroller Library - * Copyright (c) 2006-2013 ARM Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "nRF51GattServer.h" -#include "mbed.h" - -#include "common/common.h" -#include "btle/custom/custom_helper.h" - -#include "nRF51Gap.h" - -/**************************************************************************/ -/*! - @brief Adds a new service to the GATT table on the peripheral - - @returns ble_error_t - - @retval BLE_ERROR_NONE - Everything executed properly - - @section EXAMPLE - - @code - - @endcode -*/ -/**************************************************************************/ -ble_error_t nRF51GattServer::addService(GattService & service) -{ - /* ToDo: Make sure we don't overflow the array, etc. */ - /* ToDo: Make sure this service UUID doesn't already exist (?) */ - /* ToDo: Basic validation */ - - /* Add the service to the nRF51 */ - ble_uuid_t uuid; - - if (service.primaryServiceID.type == UUID::UUID_TYPE_SHORT) - { - /* 16-bit BLE UUID */ - uuid.type = BLE_UUID_TYPE_BLE; - } - else - { - /* 128-bit Custom UUID */ - uuid.type = custom_add_uuid_base( service.primaryServiceID.base ); - } - - uuid.uuid = service.primaryServiceID.value; - - ASSERT( ERROR_NONE == sd_ble_gatts_service_add(BLE_GATTS_SRVC_TYPE_PRIMARY, &uuid, &service.handle), BLE_ERROR_PARAM_OUT_OF_RANGE ); - - /* Add characteristics to the service */ - for (uint8_t i = 0; i < service.characteristicCount; i++) - { - GattCharacteristic * p_char = service.characteristics[i]; - - uuid.uuid = p_char->uuid; - ASSERT ( ERROR_NONE == custom_add_in_characteristic(service.handle, &uuid, p_char->properties, - NULL, p_char->lenMin, p_char->lenMax, &nrfCharacteristicHandles[characteristicCount]), BLE_ERROR_PARAM_OUT_OF_RANGE ); - - /* Update the characteristic handle */ - p_char->handle = characteristicCount; - p_characteristics[characteristicCount++] = p_char; - } - - serviceCount++; - - return BLE_ERROR_NONE; -} - -/**************************************************************************/ -/*! - @brief Reads the value of a characteristic, based on the service - and characteristic index fields - - @param[in] charHandle - The handle of the GattCharacteristic to read from - @param[in] buffer - Buffer to hold the the characteristic's value - (raw byte array in LSB format) - @param[in] len - The number of bytes read into the buffer - - @returns ble_error_t - - @retval BLE_ERROR_NONE - Everything executed properly - - @section EXAMPLE - - @code - - @endcode -*/ -/**************************************************************************/ -ble_error_t nRF51GattServer::readValue(uint16_t charHandle, uint8_t buffer[], uint16_t len) -{ - ASSERT( ERROR_NONE == sd_ble_gatts_value_get(nrfCharacteristicHandles[charHandle].value_handle, 0, &len, buffer), BLE_ERROR_PARAM_OUT_OF_RANGE); - - return BLE_ERROR_NONE; -} - -/**************************************************************************/ -/*! - @brief Updates the value of a characteristic, based on the service - and characteristic index fields - - @param[in] charHandle - The handle of the GattCharacteristic to write to - @param[in] buffer - Data to use when updating the characteristic's value - (raw byte array in LSB format) - @param[in] len - The number of bytes in buffer - - @returns ble_error_t - - @retval BLE_ERROR_NONE - Everything executed properly - - @section EXAMPLE - - @code - - @endcode -*/ -/**************************************************************************/ -ble_error_t nRF51GattServer::updateValue(uint16_t charHandle, uint8_t buffer[], uint16_t len, bool localOnly) -{ - uint16_t gapConnectionHandle = nRF51Gap::getInstance().getConnectionHandle(); - - if (localOnly) - { - /* Only update locally regardless of notify/indicate */ - ASSERT_INT( ERROR_NONE, sd_ble_gatts_value_set(nrfCharacteristicHandles[charHandle].value_handle, 0, &len, buffer), BLE_ERROR_PARAM_OUT_OF_RANGE ); - } - - if ((p_characteristics[charHandle]->properties & (GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_INDICATE | GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY)) && - (gapConnectionHandle != BLE_CONN_HANDLE_INVALID) ) - { - /* HVX update for the characteristic value */ - ble_gatts_hvx_params_t hvx_params; - - hvx_params.handle = nrfCharacteristicHandles[charHandle].value_handle; - hvx_params.type = (p_characteristics[charHandle]->properties & GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY) ? BLE_GATT_HVX_NOTIFICATION : BLE_GATT_HVX_INDICATION; - hvx_params.offset = 0; - hvx_params.p_data = buffer; - hvx_params.p_len = &len; - - error_t error = (error_t) sd_ble_gatts_hvx(gapConnectionHandle, &hvx_params); - - /* ERROR_INVALID_STATE, ERROR_BUSY, ERROR_GATTS_SYS_ATTR_MISSING and ERROR_NO_TX_BUFFERS the ATT table has been updated. */ - if ( (error != ERROR_NONE ) && (error != ERROR_INVALID_STATE) && - (error != ERROR_BLE_NO_TX_BUFFERS ) && (error != ERROR_BUSY ) && - (error != ERROR_BLEGATTS_SYS_ATTR_MISSING ) ) - { - ASSERT_INT( ERROR_NONE, sd_ble_gatts_value_set(nrfCharacteristicHandles[charHandle].value_handle, 0, &len, buffer), BLE_ERROR_PARAM_OUT_OF_RANGE ); - } - } else - { - ASSERT_INT( ERROR_NONE, sd_ble_gatts_value_set(nrfCharacteristicHandles[charHandle].value_handle, 0, &len, buffer), BLE_ERROR_PARAM_OUT_OF_RANGE ); - } - - return BLE_ERROR_NONE; -} - -/**************************************************************************/ -/*! - @brief Callback handler for events getting pushed up from the SD -*/ -/**************************************************************************/ -void nRF51GattServer::hwCallback(ble_evt_t * p_ble_evt) -{ - uint16_t handle_value; - GattServerEvents::gattEvent_t event; - - switch (p_ble_evt->header.evt_id) - { - case BLE_GATTS_EVT_WRITE: - /* There are 2 use case here: Values being updated & CCCD (indicate/notify) enabled */ - - /* 1.) Handle CCCD changes */ - handle_value = p_ble_evt->evt.gatts_evt.params.write.handle; - for(uint8_t i=0; iproperties & (GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_INDICATE | GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY)) && - (nrfCharacteristicHandles[i].cccd_handle == handle_value) ) - { - uint16_t cccd_value = (p_ble_evt->evt.gatts_evt.params.write.data[1] << 8) | p_ble_evt->evt.gatts_evt.params.write.data[0]; /* Little Endian but M0 may be mis-aligned */ - - if ( ((p_characteristics[i]->properties & GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_INDICATE) && (cccd_value & BLE_GATT_HVX_INDICATION )) || - ((p_characteristics[i]->properties & GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY ) && (cccd_value & BLE_GATT_HVX_NOTIFICATION))) - { - event = GattServerEvents::GATT_EVENT_UPDATES_ENABLED; - } else - { - event = GattServerEvents::GATT_EVENT_UPDATES_DISABLED; - } - - handleEvent(event, i); - return; - } - } - - /* 2.) Changes to the characteristic value will be handled with other events below */ - event = GattServerEvents::GATT_EVENT_DATA_WRITTEN; - break; - - case BLE_GATTS_EVT_HVC: - /* Indication confirmation received */ - event = GattServerEvents::GATT_EVENT_CONFIRMATION_RECEIVED; - handle_value = p_ble_evt->evt.gatts_evt.params.hvc.handle; - break; - - default: - return; - } - - /* Find index (charHandle) in the pool */ - for(uint8_t i=0; i -#include "nrf51.h" -#include "nrf51_bitfields.h" -#include "nrf_soc.h" -#include "app_error.h" -//#include "nrf_delay.h" -#include "mbed.h" -#include "app_util.h" - - -#define RTC1_IRQ_PRI APP_IRQ_PRIORITY_LOW /**< Priority of the RTC1 interrupt (used for checking for timeouts and executing timeout handlers). */ -#define SWI0_IRQ_PRI APP_IRQ_PRIORITY_LOW /**< Priority of the SWI0 interrupt (used for updating the timer list). */ - -// The current design assumes that both interrupt handlers run at the same interrupt level. -// If this is to be changed, protection must be added to prevent them from interrupting each other -// (e.g. by using guard/trigger flags). -STATIC_ASSERT(RTC1_IRQ_PRI == SWI0_IRQ_PRI); - -#define MAX_RTC_COUNTER_VAL 0x00FFFFFF /**< Maximum value of the RTC counter. */ - -#define APP_HIGH_USER_ID 0 /**< User Id for the Application High "user". */ -#define APP_LOW_USER_ID 1 /**< User Id for the Application Low "user". */ -#define THREAD_MODE_USER_ID 2 /**< User Id for the Thread Mode "user". */ - -#define RTC_COMPARE_OFFSET_MIN 3 /**< Minimum offset between the current RTC counter value and the Capture Compare register. Although the nRF51 Series User Specification recommends this value to be 2, we use 3 to be safer.*/ - -#define MAX_RTC_TASKS_DELAY 47 /**< Maximum delay until an RTC task is executed. */ - -/**@brief Timer allocation state type. */ -typedef enum -{ - STATE_FREE, /**< The timer node is available. */ - STATE_ALLOCATED /**< The timer node has been allocated. */ -} timer_alloc_state_t; - -/**@brief Timer node type. The nodes will be used form a linked list of running timers. */ -typedef struct -{ - timer_alloc_state_t state; /**< Timer allocation state. */ - app_timer_mode_t mode; /**< Timer mode. */ - uint32_t ticks_to_expire; /**< Number of ticks from previous timer interrupt to timer expiry. */ - uint32_t ticks_at_start; /**< Current RTC counter value when the timer was started. */ - uint32_t ticks_first_interval; /**< Number of ticks in the first timer interval. */ - uint32_t ticks_periodic_interval; /**< Timer period (for repeating timers). */ - bool is_running; /**< True if timer is running, False otherwise. */ - app_timer_timeout_handler_t p_timeout_handler; /**< Pointer to function to be executed when the timer expires. */ - void * p_context; /**< General purpose pointer. Will be passed to the timeout handler when the timer expires. */ - app_timer_id_t next; /**< Id of next timer in list of running timers. */ -} timer_node_t; - -STATIC_ASSERT(sizeof(timer_node_t) <= APP_TIMER_NODE_SIZE); -STATIC_ASSERT(sizeof(timer_node_t) % 4 == 0); - -/**@brief Set of available timer operation types. */ -typedef enum -{ - TIMER_USER_OP_TYPE_NONE, /**< Invalid timer operation type. */ - TIMER_USER_OP_TYPE_START, /**< Timer operation type Start. */ - TIMER_USER_OP_TYPE_STOP, /**< Timer operation type Stop. */ - TIMER_USER_OP_TYPE_STOP_ALL /**< Timer operation type Stop All. */ -} timer_user_op_type_t; - -/**@brief Structure describing a timer start operation. */ -typedef struct -{ - uint32_t ticks_at_start; /**< Current RTC counter value when the timer was started. */ - uint32_t ticks_first_interval; /**< Number of ticks in the first timer interval. */ - uint32_t ticks_periodic_interval; /**< Timer period (for repeating timers). */ - void * p_context; /**< General purpose pointer. Will be passed to the timeout handler when the timer expires. */ -} timer_user_op_start_t; - -/**@brief Structure describing a timer operation. */ -typedef struct -{ - timer_user_op_type_t op_type; /**< Timer operation type. */ - app_timer_id_t timer_id; /**< Id of timer on which the operation is to be performed. */ - union - { - timer_user_op_start_t start; /**< Structure describing a timer start operation. */ - } params; -} timer_user_op_t; - -STATIC_ASSERT(sizeof(timer_user_op_t) <= APP_TIMER_USER_OP_SIZE); -STATIC_ASSERT(sizeof(timer_user_op_t) % 4 == 0); - -/**@brief Structure describing a timer user. - * - * @details For each user of the timer module, there will be a timer operations queue. This queue - * will hold timer operations issued by this user until the timer interrupt handler - * processes these operations. For the current implementation, there will be one user for - * each interrupt level available to the application (APP_HIGH, APP_LOW and THREAD_MODE), - * but the module can easily be modified to e.g. have one queue per process when using an - * RTOS. The purpose of the queues is to be able to have a completely lockless timer - * implementation. - */ -typedef struct -{ - uint8_t first; /**< Index of first entry to have been inserted in the queue (i.e. the next entry to be executed). */ - uint8_t last; /**< Index of last entry to have been inserted in the queue. */ - uint8_t user_op_queue_size; /**< Queue size. */ - timer_user_op_t * p_user_op_queue; /**< Queue buffer. */ -} timer_user_t; - -STATIC_ASSERT(sizeof(timer_user_t) == APP_TIMER_USER_SIZE); -STATIC_ASSERT(sizeof(timer_user_t) % 4 == 0); - -/**@brief User id type. - * - * @details In the current implementation, this will automatically be generated from the current - * interrupt level. - */ -typedef uint32_t timer_user_id_t; - -#define TIMER_NULL ((app_timer_id_t)(0 - 1)) /**< Invalid timer id. */ -#define CONTEXT_QUEUE_SIZE_MAX (2) /**< Timer internal elapsed ticks queue size. */ - -static uint8_t m_node_array_size; /**< Size of timer node array. */ -static timer_node_t * mp_nodes = NULL; /**< Array of timer nodes. */ -static uint8_t m_user_array_size; /**< Size of timer user array. */ -static timer_user_t * mp_users; /**< Array of timer users. */ -static app_timer_id_t m_timer_id_head; /**< First timer in list of running timers. */ -static uint32_t m_ticks_latest; /**< Last known RTC counter value. */ -static uint32_t m_ticks_elapsed[CONTEXT_QUEUE_SIZE_MAX]; /**< Timer internal elapsed ticks queue. */ -static uint8_t m_ticks_elapsed_q_read_ind; /**< Timer internal elapsed ticks queue read index. */ -static uint8_t m_ticks_elapsed_q_write_ind; /**< Timer internal elapsed ticks queue write index. */ -static app_timer_evt_schedule_func_t m_evt_schedule_func; /**< Pointer to function for propagating timeout events to the scheduler. */ - - -/**@brief Function for initializing the RTC1 counter. - * - * @param[in] prescaler Value of the RTC1 PRESCALER register. Set to 0 for no prescaling. - */ -static void rtc1_init(uint32_t prescaler) -{ - NRF_RTC1->PRESCALER = prescaler; - NVIC_SetPriority(RTC1_IRQn, RTC1_IRQ_PRI); -} - - -/**@brief Function for starting the RTC1 timer. - */ -static void rtc1_start(void) -{ - NRF_RTC1->EVTENSET = RTC_EVTEN_COMPARE0_Msk; - NRF_RTC1->INTENSET = RTC_INTENSET_COMPARE0_Msk; - - NVIC_ClearPendingIRQ(RTC1_IRQn); - NVIC_EnableIRQ(RTC1_IRQn); - - NRF_RTC1->TASKS_START = 1; - wait(0.0000001 * MAX_RTC_TASKS_DELAY); -} - - -/**@brief Function for stopping the RTC1 timer. - */ -static void rtc1_stop(void) -{ - NVIC_DisableIRQ(RTC1_IRQn); - - NRF_RTC1->EVTENCLR = RTC_EVTEN_COMPARE0_Msk; - NRF_RTC1->INTENCLR = RTC_INTENSET_COMPARE0_Msk; - - NRF_RTC1->TASKS_STOP = 1; - wait(0.0000001 * MAX_RTC_TASKS_DELAY); -} - - -/**@brief Function for returning the current value of the RTC1 counter. - * - * @return Current value of the RTC1 counter. - */ -static __INLINE uint32_t rtc1_counter_get(void) -{ - return NRF_RTC1->COUNTER; -} - - -/**@brief Function for computing the difference between two RTC1 counter values. - * - * @return Number of ticks elapsed from ticks_old to ticks_now. - */ -static __INLINE uint32_t ticks_diff_get(uint32_t ticks_now, uint32_t ticks_old) -{ - return ((ticks_now - ticks_old) & MAX_RTC_COUNTER_VAL); -} - - -/**@brief Function for setting the RTC1 Capture Compare register 0, and enabling the corresponding - * event. - * - * @param[in] value New value of Capture Compare register 0. - */ -static __INLINE void rtc1_compare0_set(uint32_t value) -{ - NRF_RTC1->CC[0] = value; -} - - -/**@brief Function for inserting a timer in the timer list. - * - * @param[in] timer_id Id of timer to insert. - */ -static void timer_list_insert(app_timer_id_t timer_id) -{ - timer_node_t * p_timer = &mp_nodes[timer_id]; - - if (m_timer_id_head == TIMER_NULL) - { - m_timer_id_head = timer_id; - } - else - { - if (p_timer->ticks_to_expire <= mp_nodes[m_timer_id_head].ticks_to_expire) - { - mp_nodes[m_timer_id_head].ticks_to_expire -= p_timer->ticks_to_expire; - - p_timer->next = m_timer_id_head; - m_timer_id_head = timer_id; - } - else - { - app_timer_id_t previous; - app_timer_id_t current; - uint32_t ticks_to_expire; - - ticks_to_expire = p_timer->ticks_to_expire; - previous = m_timer_id_head; - current = m_timer_id_head; - - while ((current != TIMER_NULL) && (ticks_to_expire > mp_nodes[current].ticks_to_expire)) - { - ticks_to_expire -= mp_nodes[current].ticks_to_expire; - previous = current; - current = mp_nodes[current].next; - } - - if (current != TIMER_NULL) - { - mp_nodes[current].ticks_to_expire -= ticks_to_expire; - } - - p_timer->ticks_to_expire = ticks_to_expire; - p_timer->next = current; - mp_nodes[previous].next = timer_id; - } - } -} - - -/**@brief Function for removing a timer from the timer queue. - * - * @param[in] timer_id Id of timer to remove. - */ -static void timer_list_remove(app_timer_id_t timer_id) -{ - app_timer_id_t previous; - app_timer_id_t current; - uint32_t timeout; - - // Find the timer's position in timer list - previous = m_timer_id_head; - current = previous; - - while (current != TIMER_NULL) - { - if (current == timer_id) - { - break; - } - previous = current; - current = mp_nodes[current].next; - } - - // Timer not in active list - if (current == TIMER_NULL) - { - return; - } - - // Timer is the first in the list - if (previous == current) - { - m_timer_id_head = mp_nodes[m_timer_id_head].next; - } - - // Remaining timeout between next timeout - timeout = mp_nodes[current].ticks_to_expire; - - // Link previous timer with next of this timer, i.e. removing the timer from list - mp_nodes[previous].next = mp_nodes[current].next; - - // If this is not the last timer, increment the next timer by this timer timeout - current = mp_nodes[previous].next; - if (current != TIMER_NULL) - { - mp_nodes[current].ticks_to_expire += timeout; - } -} - - -/**@brief Function for scheduling a check for timeouts by generating a RTC1 interrupt. - */ -static void timer_timeouts_check_sched(void) -{ - NVIC_SetPendingIRQ(RTC1_IRQn); -} - - -/**@brief Function for scheduling a timer list update by generating a SWI0 interrupt. - */ -static void timer_list_handler_sched(void) -{ - NVIC_SetPendingIRQ(SWI0_IRQn); -} - - -/**@brief Function for executing an application timeout handler, either by calling it directly, or - * by passing an event to the @ref app_scheduler. - * - * @param[in] p_timer Pointer to expired timer. - */ -static void timeout_handler_exec(timer_node_t * p_timer) -{ - if (m_evt_schedule_func != NULL) - { - uint32_t err_code = m_evt_schedule_func(p_timer->p_timeout_handler, p_timer->p_context); - APP_ERROR_CHECK(err_code); - } - else - { - p_timer->p_timeout_handler(p_timer->p_context); - } -} - - -/**@brief Function for checking for expired timers. - */ -static void timer_timeouts_check(void) -{ - // Handle expired of timer - if (m_timer_id_head != TIMER_NULL) - { - app_timer_id_t timer_id; - uint32_t ticks_elapsed; - uint32_t ticks_expired; - - // Initialize actual elapsed ticks being consumed to 0 - ticks_expired = 0; - - // ticks_elapsed is collected here, job will use it - ticks_elapsed = ticks_diff_get(rtc1_counter_get(), m_ticks_latest); - - // Auto variable containing the head of timers expiring - timer_id = m_timer_id_head; - - // Expire all timers within ticks_elapsed and collect ticks_expired - while (timer_id != TIMER_NULL) - { - timer_node_t * p_timer; - - // Auto variable for current timer node - p_timer = &mp_nodes[timer_id]; - - // Do nothing if timer did not expire - if (ticks_elapsed < p_timer->ticks_to_expire) - { - break; - } - - // Decrement ticks_elapsed and collect expired ticks - ticks_elapsed -= p_timer->ticks_to_expire; - ticks_expired += p_timer->ticks_to_expire; - - // Move to next timer - timer_id = p_timer->next; - - // Execute Task - timeout_handler_exec(p_timer); - } - - // Prepare to queue the ticks expired in the m_ticks_elapsed queue. - if (m_ticks_elapsed_q_read_ind == m_ticks_elapsed_q_write_ind) - { - // The read index of the queue is equal to the write index. This means the new - // value of ticks_expired should be stored at a new location in the m_ticks_elapsed - // queue (which is implemented as a double buffer). - - // Check if there will be a queue overflow. - if (++m_ticks_elapsed_q_write_ind == CONTEXT_QUEUE_SIZE_MAX) - { - // There will be a queue overflow. Hence the write index should point to the start - // of the queue. - m_ticks_elapsed_q_write_ind = 0; - } - } - - // Queue the ticks expired. - m_ticks_elapsed[m_ticks_elapsed_q_write_ind] = ticks_expired; - - timer_list_handler_sched(); - } -} - - -/**@brief Function for acquiring the number of ticks elapsed. - * - * @param[out] p_ticks_elapsed Number of ticks elapsed. - * - * @return TRUE if elapsed ticks was read from queue, FALSE otherwise. - */ -static bool elapsed_ticks_acquire(uint32_t * p_ticks_elapsed) -{ - // Pick the elapsed value from queue - if (m_ticks_elapsed_q_read_ind != m_ticks_elapsed_q_write_ind) - { - // Dequeue elapsed value - m_ticks_elapsed_q_read_ind++; - if (m_ticks_elapsed_q_read_ind == CONTEXT_QUEUE_SIZE_MAX) - { - m_ticks_elapsed_q_read_ind = 0; - } - - *p_ticks_elapsed = m_ticks_elapsed[m_ticks_elapsed_q_read_ind]; - - m_ticks_latest += *p_ticks_elapsed; - m_ticks_latest &= MAX_RTC_COUNTER_VAL; - - return true; - } - else - { - // No elapsed value in queue - *p_ticks_elapsed = 0; - return false; - } -} - - -/**@brief Function for handling the timer list deletions. - * - * @return TRUE if Capture Compare register must be updated, FALSE otherwise. - */ -static bool list_deletions_handler(void) -{ - app_timer_id_t timer_id_old_head; - uint8_t user_id; - - // Remember the old head, so as to decide if new compare needs to be set - timer_id_old_head = m_timer_id_head; - - user_id = m_user_array_size; - while (user_id--) - { - timer_user_t * p_user = &mp_users[user_id]; - uint8_t user_ops_first = p_user->first; - - while (user_ops_first != p_user->last) - { - timer_node_t * p_timer; - timer_user_op_t * p_user_op = &p_user->p_user_op_queue[user_ops_first]; - - // Traverse to next operation in queue - user_ops_first++; - if (user_ops_first == p_user->user_op_queue_size) - { - user_ops_first = 0; - } - - switch (p_user_op->op_type) - { - case TIMER_USER_OP_TYPE_STOP: - // Delete node if timer is running - p_timer = &mp_nodes[p_user_op->timer_id]; - if (p_timer->is_running) - { - timer_list_remove(p_user_op->timer_id); - p_timer->is_running = false; - } - break; - - case TIMER_USER_OP_TYPE_STOP_ALL: - // Delete list of running timers, and mark all timers as not running - while (m_timer_id_head != TIMER_NULL) - { - timer_node_t * p_head = &mp_nodes[m_timer_id_head]; - - p_head->is_running = false; - m_timer_id_head = p_head->next; - } - break; - - default: - // No implementation needed. - break; - } - } - } - - // Detect change in head of the list - return (m_timer_id_head != timer_id_old_head); -} - - -/**@brief Function for updating the timer list for expired timers. - * - * @param[in] ticks_elapsed Number of elapsed ticks. - * @param[in] ticks_previous Previous known value of the RTC counter. - * @param[out] p_restart_list_head List of repeating timers to be restarted. - */ -static void expired_timers_handler(uint32_t ticks_elapsed, - uint32_t ticks_previous, - app_timer_id_t * p_restart_list_head) -{ - uint32_t ticks_expired = 0; - - while (m_timer_id_head != TIMER_NULL) - { - timer_node_t * p_timer; - app_timer_id_t id_expired; - - // Auto variable for current timer node - p_timer = &mp_nodes[m_timer_id_head]; - - // Do nothing if timer did not expire - if (ticks_elapsed < p_timer->ticks_to_expire) - { - p_timer->ticks_to_expire -= ticks_elapsed; - break; - } - - // Decrement ticks_elapsed and collect expired ticks - ticks_elapsed -= p_timer->ticks_to_expire; - ticks_expired += p_timer->ticks_to_expire; - - // Timer expired, set ticks_to_expire zero - p_timer->ticks_to_expire = 0; - p_timer->is_running = false; - - // Remove the expired timer from head - id_expired = m_timer_id_head; - m_timer_id_head = p_timer->next; - - // Timer will be restarted if periodic - if (p_timer->ticks_periodic_interval != 0) - { - p_timer->ticks_at_start = (ticks_previous + ticks_expired) & MAX_RTC_COUNTER_VAL; - p_timer->ticks_first_interval = p_timer->ticks_periodic_interval; - p_timer->next = *p_restart_list_head; - *p_restart_list_head = id_expired; - } - } -} - - -/**@brief Function for handling timer list insertions. - * - * @param[in] p_restart_list_head List of repeating timers to be restarted. - * - * @return TRUE if Capture Compare register must be updated, FALSE otherwise. - */ -static bool list_insertions_handler(app_timer_id_t restart_list_head) -{ - app_timer_id_t timer_id_old_head; - uint8_t user_id; - - // Remember the old head, so as to decide if new compare needs to be set - timer_id_old_head = m_timer_id_head; - - user_id = m_user_array_size; - while (user_id--) - { - timer_user_t * p_user = &mp_users[user_id]; - - // Handle insertions of timers - while ((restart_list_head != TIMER_NULL) || (p_user->first != p_user->last)) - { - app_timer_id_t id_start; - timer_node_t * p_timer; - - if (restart_list_head != TIMER_NULL) - { - id_start = restart_list_head; - p_timer = &mp_nodes[id_start]; - restart_list_head = p_timer->next; - } - else - { - timer_user_op_t * p_user_op = &p_user->p_user_op_queue[p_user->first]; - - p_user->first++; - if (p_user->first == p_user->user_op_queue_size) - { - p_user->first = 0; - } - - id_start = p_user_op->timer_id; - p_timer = &mp_nodes[id_start]; - - if ((p_user_op->op_type != TIMER_USER_OP_TYPE_START) || p_timer->is_running) - { - continue; - } - - p_timer->ticks_at_start = p_user_op->params.start.ticks_at_start; - p_timer->ticks_first_interval = p_user_op->params.start.ticks_first_interval; - p_timer->ticks_periodic_interval = p_user_op->params.start.ticks_periodic_interval; - p_timer->p_context = p_user_op->params.start.p_context; - } - - // Prepare the node to be inserted - if ( - ((p_timer->ticks_at_start - m_ticks_latest) & MAX_RTC_COUNTER_VAL) - < - (MAX_RTC_COUNTER_VAL / 2) - ) - { - p_timer->ticks_to_expire = ticks_diff_get(p_timer->ticks_at_start, m_ticks_latest) + - p_timer->ticks_first_interval; - } - else - { - uint32_t delta_current_start; - - delta_current_start = ticks_diff_get(m_ticks_latest, p_timer->ticks_at_start); - if (p_timer->ticks_first_interval > delta_current_start) - { - p_timer->ticks_to_expire = p_timer->ticks_first_interval - delta_current_start; - } - else - { - p_timer->ticks_to_expire = 0; - } - } - - p_timer->ticks_at_start = 0; - p_timer->ticks_first_interval = 0; - p_timer->is_running = true; - p_timer->next = TIMER_NULL; - - // Insert into list - timer_list_insert(id_start); - } - } - - return (m_timer_id_head != timer_id_old_head); -} - - -/**@brief Function for updating the Capture Compare register. - */ -static void compare_reg_update(app_timer_id_t timer_id_head_old) -{ - // Setup the timeout for timers on the head of the list - if (m_timer_id_head != TIMER_NULL) - { - uint32_t ticks_to_expire = mp_nodes[m_timer_id_head].ticks_to_expire; - uint32_t pre_counter_val = rtc1_counter_get(); - uint32_t cc = m_ticks_latest; - uint32_t ticks_elapsed = ticks_diff_get(pre_counter_val, cc) + RTC_COMPARE_OFFSET_MIN; - - if (timer_id_head_old == TIMER_NULL) - { - // No timers were already running, start RTC - rtc1_start(); - } - - cc += (ticks_elapsed < ticks_to_expire) ? ticks_to_expire : ticks_elapsed; - cc &= MAX_RTC_COUNTER_VAL; - - rtc1_compare0_set(cc); - - uint32_t post_counter_val = rtc1_counter_get(); - - if ( - (ticks_diff_get(post_counter_val, pre_counter_val) + RTC_COMPARE_OFFSET_MIN) - > - ticks_diff_get(cc, pre_counter_val) - ) - { - // When this happens the COMPARE event may not be triggered by the RTC. - // The nRF51 Series User Specification states that if the COUNTER value is N - // (i.e post_counter_val = N), writing N or N+1 to a CC register may not trigger a - // COMPARE event. Hence the RTC interrupt is forcefully pended by calling the following - // function. - timer_timeouts_check_sched(); - } - } - else - { - // No timers are running, stop RTC - rtc1_stop(); - } -} - - -/**@brief Function for handling changes to the timer list. - */ -static void timer_list_handler(void) -{ - app_timer_id_t restart_list_head = TIMER_NULL; - uint32_t ticks_elapsed; - uint32_t ticks_previous; - bool ticks_have_elapsed; - bool compare_update; - app_timer_id_t timer_id_head_old; - - // Back up the previous known tick and previous list head - ticks_previous = m_ticks_latest; - timer_id_head_old = m_timer_id_head; - - // Get number of elapsed ticks - ticks_have_elapsed = elapsed_ticks_acquire(&ticks_elapsed); - - // Handle list deletions - compare_update = list_deletions_handler(); - - // Handle expired timers - if (ticks_have_elapsed) - { - expired_timers_handler(ticks_elapsed, ticks_previous, &restart_list_head); - compare_update = true; - } - - // Handle list insertions - if (list_insertions_handler(restart_list_head)) - { - compare_update = true; - } - - // Update compare register if necessary - if (compare_update) - { - compare_reg_update(timer_id_head_old); - } -} - - -/**@brief Function for enqueueing a new operations queue entry. - * - * @param[in] p_user User that the entry is to be enqueued for. - * @param[in] last_index Index of the next last index to be enqueued. - */ -static void user_op_enque(timer_user_t * p_user, app_timer_id_t last_index) -{ - p_user->last = last_index; -} - - -/**@brief Function for allocating a new operations queue entry. - * - * @param[in] p_user User that the entry is to be allocated for. - * @param[out] p_last_index Index of the next last index to be enqueued. - * - * @return Pointer to allocated queue entry, or NULL if queue is full. - */ -static timer_user_op_t * user_op_alloc(timer_user_t * p_user, app_timer_id_t * p_last_index) -{ - app_timer_id_t last; - timer_user_op_t * p_user_op; - - last = p_user->last + 1; - if (last == p_user->user_op_queue_size) - { - // Overflow case. - last = 0; - } - if (last == p_user->first) - { - // Queue is full. - return NULL; - } - - *p_last_index = last; - p_user_op = &p_user->p_user_op_queue[p_user->last]; - - return p_user_op; -} - - -/**@brief Function for scheduling a Timer Start operation. - * - * @param[in] user_id Id of user calling this function. - * @param[in] timer_id Id of timer to start. - * @param[in] timeout_initial Time (in ticks) to first timer expiry. - * @param[in] timeout_periodic Time (in ticks) between periodic expiries. - * @param[in] p_context General purpose pointer. Will be passed to the timeout handler when - * the timer expires. - * @return NRF_SUCCESS on success, otherwise an error code. - */ -static uint32_t timer_start_op_schedule(timer_user_id_t user_id, - app_timer_id_t timer_id, - uint32_t timeout_initial, - uint32_t timeout_periodic, - void * p_context) -{ - app_timer_id_t last_index; - - timer_user_op_t * p_user_op = user_op_alloc(&mp_users[user_id], &last_index); - if (p_user_op == NULL) - { - return NRF_ERROR_NO_MEM; - } - - p_user_op->op_type = TIMER_USER_OP_TYPE_START; - p_user_op->timer_id = timer_id; - p_user_op->params.start.ticks_at_start = rtc1_counter_get(); - p_user_op->params.start.ticks_first_interval = timeout_initial; - p_user_op->params.start.ticks_periodic_interval = timeout_periodic; - p_user_op->params.start.p_context = p_context; - - user_op_enque(&mp_users[user_id], last_index); - - timer_list_handler_sched(); - - return NRF_SUCCESS; -} - - -/**@brief Function for scheduling a Timer Stop operation. - * - * @param[in] user_id Id of user calling this function. - * @param[in] timer_id Id of timer to stop. - * - * @return NRF_SUCCESS on successful scheduling a timer stop operation. NRF_ERROR_NO_MEM when there - * is no memory left to schedule the timer stop operation. - */ -static uint32_t timer_stop_op_schedule(timer_user_id_t user_id, app_timer_id_t timer_id) -{ - app_timer_id_t last_index; - - timer_user_op_t * p_user_op = user_op_alloc(&mp_users[user_id], &last_index); - if (p_user_op == NULL) - { - return NRF_ERROR_NO_MEM; - } - - p_user_op->op_type = TIMER_USER_OP_TYPE_STOP; - p_user_op->timer_id = timer_id; - - user_op_enque(&mp_users[user_id], last_index); - - timer_list_handler_sched(); - - return NRF_SUCCESS; -} - - -/**@brief Function for scheduling a Timer Stop All operation. - * - * @param[in] user_id Id of user calling this function. - */ -static uint32_t timer_stop_all_op_schedule(timer_user_id_t user_id) -{ - app_timer_id_t last_index; - - timer_user_op_t * p_user_op = user_op_alloc(&mp_users[user_id], &last_index); - if (p_user_op == NULL) - { - return NRF_ERROR_NO_MEM; - } - - p_user_op->op_type = TIMER_USER_OP_TYPE_STOP_ALL; - p_user_op->timer_id = TIMER_NULL; - - user_op_enque(&mp_users[user_id], last_index); - - timer_list_handler_sched(); - - return NRF_SUCCESS; -} - - -/**@brief Function for handling the RTC1 interrupt. - * - * @details Checks for timeouts, and executes timeout handlers for expired timers. - */ -extern "C" void RTC1_IRQHandler(void) -{ - // Clear all events (also unexpected ones) - NRF_RTC1->EVENTS_COMPARE[0] = 0; - NRF_RTC1->EVENTS_COMPARE[1] = 0; - NRF_RTC1->EVENTS_COMPARE[2] = 0; - NRF_RTC1->EVENTS_COMPARE[3] = 0; - NRF_RTC1->EVENTS_TICK = 0; - NRF_RTC1->EVENTS_OVRFLW = 0; - - // Check for expired timers - timer_timeouts_check(); -} - -/**@brief Function for handling the SWI0 interrupt. - * - * @details Performs all updates to the timer list. - */ -extern "C" void SWI0_IRQHandler(void) -{ - timer_list_handler(); -} - -uint32_t app_timer_init(uint32_t prescaler, - uint8_t max_timers, - uint8_t op_queues_size, - void * p_buffer, - app_timer_evt_schedule_func_t evt_schedule_func) -{ - int i; - - // Check that buffer is correctly aligned - if (!is_word_aligned(p_buffer)) - { - return NRF_ERROR_INVALID_PARAM; - } - // Check for NULL buffer - if (p_buffer == NULL) - { - return NRF_ERROR_INVALID_PARAM; - } - - // Stop RTC to prevent any running timers from expiring (in case of reinitialization) - rtc1_stop(); - - m_evt_schedule_func = evt_schedule_func; - - // Initialize timer node array - m_node_array_size = max_timers; - mp_nodes = (timer_node_t *) p_buffer; - - for (i = 0; i < max_timers; i++) - { - mp_nodes[i].state = STATE_FREE; - mp_nodes[i].is_running = false; - } - - // Skip timer node array - p_buffer = &((uint8_t *)p_buffer)[max_timers * sizeof(timer_node_t)]; - - // Initialize users array - m_user_array_size = APP_TIMER_INT_LEVELS; - mp_users = (timer_user_t *) p_buffer; - - // Skip user array - p_buffer = &((uint8_t *)p_buffer)[APP_TIMER_INT_LEVELS * sizeof(timer_user_t)]; - - // Initialize operation queues - for (i = 0; i < APP_TIMER_INT_LEVELS; i++) - { - timer_user_t * p_user = &mp_users[i]; - - p_user->first = 0; - p_user->last = 0; - p_user->user_op_queue_size = op_queues_size; - p_user->p_user_op_queue = (timer_user_op_t *) p_buffer; - - // Skip operation queue - p_buffer = &((uint8_t *)p_buffer)[op_queues_size * sizeof(timer_user_op_t)]; - } - - m_timer_id_head = TIMER_NULL; - m_ticks_elapsed_q_read_ind = 0; - m_ticks_elapsed_q_write_ind = 0; - - NVIC_ClearPendingIRQ(SWI0_IRQn); - NVIC_SetPriority(SWI0_IRQn, SWI0_IRQ_PRI); - NVIC_EnableIRQ(SWI0_IRQn); - - rtc1_init(prescaler); - - m_ticks_latest = rtc1_counter_get(); - - return NRF_SUCCESS; -} - - -uint32_t app_timer_create(app_timer_id_t * p_timer_id, - app_timer_mode_t mode, - app_timer_timeout_handler_t timeout_handler) -{ - int i; - - // Check state and parameters - if (mp_nodes == NULL) - { - return NRF_ERROR_INVALID_STATE; - } - if (timeout_handler == NULL) - { - return NRF_ERROR_INVALID_PARAM; - } - if (p_timer_id == NULL) - { - return NRF_ERROR_INVALID_PARAM; - } - - // Find free timer - for (i = 0; i < m_node_array_size; i++) - { - if (mp_nodes[i].state == STATE_FREE) - { - mp_nodes[i].state = STATE_ALLOCATED; - mp_nodes[i].mode = mode; - mp_nodes[i].p_timeout_handler = timeout_handler; - - *p_timer_id = i; - return NRF_SUCCESS; - } - } - - return NRF_ERROR_NO_MEM; -} - - -/**@brief Function for creating a timer user id from the current interrupt level. - * - * @return Timer user id. -*/ -static timer_user_id_t user_id_get(void) -{ - timer_user_id_t ret; - - STATIC_ASSERT(APP_TIMER_INT_LEVELS == 3); - - switch (current_int_priority_get()) - { - case APP_IRQ_PRIORITY_HIGH: - ret = APP_HIGH_USER_ID; - break; - - case APP_IRQ_PRIORITY_LOW: - ret = APP_LOW_USER_ID; - break; - - default: - ret = THREAD_MODE_USER_ID; - break; - } - - return ret; -} - - -uint32_t app_timer_start(app_timer_id_t timer_id, uint32_t timeout_ticks, void * p_context) -{ - uint32_t timeout_periodic; - - // Check state and parameters - if (mp_nodes == NULL) - { - return NRF_ERROR_INVALID_STATE; - } - if ((timer_id >= m_node_array_size) || (timeout_ticks < APP_TIMER_MIN_TIMEOUT_TICKS)) - { - return NRF_ERROR_INVALID_PARAM; - } - if (mp_nodes[timer_id].state != STATE_ALLOCATED) - { - return NRF_ERROR_INVALID_STATE; - } - - // Schedule timer start operation - timeout_periodic = (mp_nodes[timer_id].mode == APP_TIMER_MODE_REPEATED) ? timeout_ticks : 0; - - return timer_start_op_schedule(user_id_get(), - timer_id, - timeout_ticks, - timeout_periodic, - p_context); -} - - -uint32_t app_timer_stop(app_timer_id_t timer_id) -{ - // Check state and parameters - if (mp_nodes == NULL) - { - return NRF_ERROR_INVALID_STATE; - } - if (timer_id >= m_node_array_size) - { - return NRF_ERROR_INVALID_PARAM; - } - if (mp_nodes[timer_id].state != STATE_ALLOCATED) - { - return NRF_ERROR_INVALID_STATE; - } - - // Schedule timer stop operation - return timer_stop_op_schedule(user_id_get(), timer_id); -} - - -uint32_t app_timer_stop_all(void) -{ - // Check state - if (mp_nodes == NULL) - { - return NRF_ERROR_INVALID_STATE; - } - - return timer_stop_all_op_schedule(user_id_get()); -} - - -uint32_t app_timer_cnt_get(uint32_t * p_ticks) -{ - *p_ticks = rtc1_counter_get(); - return NRF_SUCCESS; -} - - -uint32_t app_timer_cnt_diff_compute(uint32_t ticks_to, - uint32_t ticks_from, - uint32_t * p_ticks_diff) -{ - *p_ticks_diff = ticks_diff_get(ticks_to, ticks_from); - return NRF_SUCCESS; -} diff --git a/libraries/ble/nRF51822/nordic/app_common/crc16.cpp b/libraries/ble/nRF51822/nordic/app_common/crc16.cpp deleted file mode 100644 index ec156f6993..0000000000 --- a/libraries/ble/nRF51822/nordic/app_common/crc16.cpp +++ /dev/null @@ -1,31 +0,0 @@ -/* Copyright (c) 2013 Nordic Semiconductor. All Rights Reserved. - * - * The information contained herein is property of Nordic Semiconductor ASA. - * Terms and conditions of usage are described in detail in NORDIC - * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. - * - * Licensees are granted free, non-transferable use of the information. NO - * WARRANTY of ANY KIND is provided. This heading must NOT be removed from - * the file. - * - */ - -#include "crc16.h" -#include - -uint16_t crc16_compute(const uint8_t * p_data, uint32_t size, const uint16_t * p_crc) -{ - uint32_t i; - uint16_t crc = (p_crc == NULL) ? 0xffff : *p_crc; - - for (i = 0; i < size; i++) - { - crc = (unsigned char)(crc >> 8) | (crc << 8); - crc ^= p_data[i]; - crc ^= (unsigned char)(crc & 0xff) >> 4; - crc ^= (crc << 8) << 4; - crc ^= ((crc & 0xff) << 4) << 1; - } - - return crc; -} diff --git a/libraries/ble/nRF51822/nordic/app_common/pstorage.cpp b/libraries/ble/nRF51822/nordic/app_common/pstorage.cpp deleted file mode 100644 index e979918611..0000000000 --- a/libraries/ble/nRF51822/nordic/app_common/pstorage.cpp +++ /dev/null @@ -1,759 +0,0 @@ -/* Copyright (c) 2013 Nordic Semiconductor. All Rights Reserved. - * - * The information contained herein is property of Nordic Semiconductor ASA. - * Terms and conditions of usage are described in detail in NORDIC - * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. - * - * Licensees are granted free, non-transferable use of the information. NO - * WARRANTY of ANY KIND is provided. This heading must NOT be removed from - * the file. - * - */ - -#include -#include -#include -#include "nordic_common.h" -#include "nrf_error.h" -#include "nrf_assert.h" -//#include "nrf.h" -#include "nrf_soc.h" -#include "app_util.h" -#include "pstorage.h" - - -#define INVALID_OPCODE 0x00 /**< Invalid op code identifier. */ -#define SOC_MAX_WRITE_SIZE 1024 /**< Maximum write size allowed for a single call to \ref sd_flash_write as specified in the SoC API. */ - -/** - * @defgroup api_param_check API Parameters check macros. - * - * @details Macros that verify parameters passed to the module in the APIs. These macros - * could be mapped to nothing in final versions of code to save execution and size. - * - * @{ - */ -/** - * @brief Check if the input pointer is NULL, if it is returns NRF_ERROR_NULL. - */ -#define NULL_PARAM_CHECK(PARAM) \ - if ((PARAM) == NULL) \ - { \ - return NRF_ERROR_NULL; \ - } - -/** - * @brief Verifies the module identifier supplied by the application is within permissible - * range. - */ -#define MODULE_ID_RANGE_CHECK(ID) \ - if ((((ID)->module_id) >= PSTORAGE_MAX_APPLICATIONS) || \ - (m_app_table[(ID)->module_id].cb == NULL)) \ - { \ - return NRF_ERROR_INVALID_PARAM; \ - } - -/** - * @brief Verifies the block identifier supplied by the application is within the permissible - * range. - */ -#define BLOCK_ID_RANGE_CHECK(ID) \ - if (((ID)->block_id) >= (m_app_table[(ID)->module_id].base_id + \ - (m_app_table[(ID)->module_id].block_count * MODULE_BLOCK_SIZE(ID)))) \ - { \ - return NRF_ERROR_INVALID_PARAM; \ - } - - -/** - * @brief Verifies the block size requested by the application can be supported by the module. - */ -#define BLOCK_SIZE_CHECK(X) \ - if (((X) > PSTORAGE_MAX_BLOCK_SIZE) || ((X) < PSTORAGE_MIN_BLOCK_SIZE)) \ - { \ - return NRF_ERROR_INVALID_PARAM; \ - } - -/** - * @brief Verifies block size requested by Application in registration API. - */ -#define BLOCK_COUNT_CHECK(COUNT, SIZE) \ - if (((COUNT) == 0) || ((m_next_page_addr + ((COUNT) *(SIZE)) > PSTORAGE_DATA_END_ADDR))) \ - { \ - return NRF_ERROR_INVALID_PARAM; \ - } - -/** - * @brief Verifies size parameter provided by application in API. - */ -#define SIZE_CHECK(ID, SIZE) \ - if(((SIZE) == 0) || ((SIZE) > MODULE_BLOCK_SIZE(ID))) \ - { \ - return NRF_ERROR_INVALID_PARAM; \ - } - -/** - * @brief Verifies offset parameter provided by application in API. - */ -#define OFFSET_CHECK(ID, OFFSET, SIZE) \ - if(((SIZE) + (OFFSET)) > MODULE_BLOCK_SIZE(ID)) \ - { \ - return NRF_ERROR_INVALID_PARAM; \ - } - -#ifdef PSTORAGE_RAW_MODE_ENABLE - -/** - * @brief Verifies the module identifier supplied by the application is registered for raw mode. - */ -#define MODULE_RAW_ID_RANGE_CHECK(ID) \ - if ((PSTORAGE_MAX_APPLICATIONS+1 != ((ID)->module_id)) || \ - (m_raw_app_table.cb == NULL)) \ - { \ - return NRF_ERROR_INVALID_PARAM; \ - } - -#endif // PSTORAGE_RAW_MODE_ENABLE - -/**@} */ - -/**@brief Verify module's initialization status. - * - * @details Verify module's initialization status. Returns NRF_ERROR_INVALID_STATE in case a - * module API is called without initializing the module. - */ -#define VERIFY_MODULE_INITIALIZED() \ - do \ - { \ - if (!m_module_initialized) \ - { \ - return NRF_ERROR_INVALID_STATE; \ - } \ - } while(0) - -/**@brief Macro to fetch the block size registered for the module. */ -#define MODULE_BLOCK_SIZE(ID) (m_app_table[(ID)->module_id].block_size) - -/**@} */ - -/** - * @brief Application registration information. - * - * @details Define application specific information that application needs to maintain to be able - * to process requests from each one of them. - */ -typedef struct -{ - pstorage_ntf_cb_t cb; /**< Callback registered with the module to be notified of result of flash access. */ - pstorage_block_t base_id; /**< Base block id assigned to the module */ - pstorage_size_t block_size; /**< Size of block for the module */ - pstorage_size_t block_count; /**< Number of block requested by application */ - pstorage_size_t no_of_pages; /**< Variable to remember how many pages have been allocated for this module. This information is used for clearing of block, so that application does not need to have knowledge of number of pages its using. */ -} pstorage_module_table_t; - -#ifdef PSTORAGE_RAW_MODE_ENABLE -/** - * @brief Application registration information. - * - * @details Define application specific information that application registered for raw mode. - */ -typedef struct -{ - pstorage_ntf_cb_t cb; /**< Callback registered with the module to be notified of result of flash access. */ - uint16_t no_of_pages; /**< Variable to remember how many pages have been allocated for this module. This information is used for clearing of block, so that application does not need to have knowledge of number of pages its using. */ -} pstorage_raw_module_table_t; -#endif // PSTORAGE_RAW_MODE_ENABLE - - - - -/** - * @brief Defines command queue element. - * - * @details Defines command queue element. Each element encapsulates needed information to process - * a flash access command. - */ -typedef struct -{ - uint8_t op_code; /**< Identifies flash access operation being queued. Element is free is op-code is INVALID_OPCODE */ - pstorage_size_t size; /**< Identifies size in bytes requested for the operation. */ - pstorage_size_t offset; /**< Offset requested by the application for access operation. */ - pstorage_handle_t storage_addr; /**< Address/Identifier for persistent memory. */ - uint8_t * p_data_addr; /**< Address/Identifier for data memory. This is assumed to be resident memory. */ -} cmd_queue_element_t; - - -/** - * @brief Defines command queue, an element is free is op_code field is not invalid. - * - * @details Defines commands enqueued for flash access. At any point of time, this queue has one or - * more flash access operation pending if the count field is not zero. When the queue is - * not empty, the rp (read pointer) field points to the flash access command in progress - * or to requested next. The queue implements a simple first in first out algorithm. - * Data addresses are assumed to be resident. - */ -typedef struct -{ - uint8_t rp; /**< Read pointer, pointing to flash access that is ongoing or to be requested next. */ - uint8_t count; /**< Number of elements in the queue. */ - bool flash_access; /**< Flag to ensure an flash event received is for an request issued by the module. */ - cmd_queue_element_t cmd[PSTORAGE_CMD_QUEUE_SIZE]; /**< Array to maintain flash access operation details */ -}cmd_queue_t; - -static cmd_queue_t m_cmd_queue; /**< Flash operation request queue. */ -static pstorage_module_table_t m_app_table[PSTORAGE_MAX_APPLICATIONS]; /**< Registered application information table. */ - -#ifdef PSTORAGE_RAW_MODE_ENABLE -static pstorage_raw_module_table_t m_raw_app_table; /**< Registered application information table for raw mode. */ -#endif // PSTORAGE_RAW_MODE_ENABLE - -static pstorage_size_t m_next_app_instance; /**< Points to the application module instance that can be allocated next */ -static uint32_t m_next_page_addr; /**< Points to the flash address that can be allocated to a module next, this is needed as blocks of a module can span across flash pages. */ -static bool m_module_initialized = false; /**< Flag for checking if module has been initialized. */ -static pstorage_size_t m_round_val; /**< Round value for multiple round operations. For erase operations, the round value will contain current round counter which is identical to number of pages erased. For store operations, the round value contains current round of operation * SOC_MAX_WRITE_SIZE to ensure each store to the SoC Flash API is within the SoC limit. */ - -static uint32_t process_cmd(void); -static void app_notify (uint32_t reason); - -/** - * @defgroup utility_functions Utility internal functions. - * @{ - * @details Utility functions needed for interfacing with flash through SoC APIs. - * SoC APIs are non blocking and provide the result of flash access through an event. - * - * @note Only one flash access operation is permitted at a time by SoC. Hence a queue is - * maintained by this module. - */ - -/** - * @brief Initializes command queue element. - */ -static void cmd_queue_init_element(uint32_t index) -{ - // Internal function and checks on range of index can be avoided - m_cmd_queue.cmd[index].op_code = INVALID_OPCODE; - m_cmd_queue.cmd[index].size = 0; - m_cmd_queue.cmd[index].storage_addr.module_id = PSTORAGE_MAX_APPLICATIONS; - m_cmd_queue.cmd[index].storage_addr.block_id = 0; - m_cmd_queue.cmd[index].p_data_addr = NULL; - m_cmd_queue.cmd[index].offset = 0; -} - - -/** - * @brief Initializes command queue. - */ -static void cmd_queue_init (void) -{ - uint32_t cmd_index; - - m_round_val = 0; - m_cmd_queue.rp = 0; - m_cmd_queue.count = 0; - m_cmd_queue.flash_access = false; - - for(cmd_index = 0; cmd_index < PSTORAGE_CMD_QUEUE_SIZE; cmd_index++) - { - cmd_queue_init_element(cmd_index); - } -} - - -/** - * @brief Routine to enqueue a flash access operation. - */ -static uint32_t cmd_queue_enqueue(uint8_t opcode, pstorage_handle_t * p_storage_addr,uint8_t * p_data_addr, pstorage_size_t size, pstorage_size_t offset) -{ - uint32_t retval; - uint8_t write_index = 0; - retval = NRF_ERROR_NO_MEM; - - // Check if flash access is ongoing. - if ((m_cmd_queue.flash_access == false) && (m_cmd_queue.count == 0)) - { - m_cmd_queue.rp = 0; - m_cmd_queue.cmd[m_cmd_queue.rp].op_code = opcode; - m_cmd_queue.cmd[m_cmd_queue.rp].p_data_addr = p_data_addr; - m_cmd_queue.cmd[m_cmd_queue.rp].storage_addr = (*p_storage_addr); - m_cmd_queue.cmd[m_cmd_queue.rp].size = size; - m_cmd_queue.cmd[m_cmd_queue.rp].offset = offset; - m_cmd_queue.count++; - retval = process_cmd(); - if ((retval == NRF_SUCCESS) || (retval == NRF_ERROR_BUSY)) - { - // In case of busy error code, it is possible to attempt to access flash - retval = NRF_SUCCESS; - } - } - else if (m_cmd_queue.count != PSTORAGE_CMD_QUEUE_SIZE) - { - // Enqueue the command if it is queue is not full - write_index = m_cmd_queue.rp + m_cmd_queue.count; - - if (write_index >= PSTORAGE_CMD_QUEUE_SIZE) - { - write_index -= PSTORAGE_CMD_QUEUE_SIZE; - } - - m_cmd_queue.cmd[write_index].op_code = opcode; - m_cmd_queue.cmd[write_index].p_data_addr = p_data_addr; - m_cmd_queue.cmd[write_index].storage_addr = (*p_storage_addr); - m_cmd_queue.cmd[write_index].size = size; - m_cmd_queue.cmd[write_index].offset = offset; - m_cmd_queue.count++; - - retval = NRF_SUCCESS; - - } - - return retval; -} - - -/** - * @brief Dequeues a command element. - */ -static uint32_t cmd_queue_dequeue(void) -{ - uint32_t retval; - - cmd_queue_element_t * p_cmd = &m_cmd_queue.cmd[m_cmd_queue.rp]; - // Update count and read pointer to process any queued requests - if(m_round_val >= p_cmd->size) - { - // Initialize/free the element as it is now processed. - cmd_queue_init_element(m_cmd_queue.rp); - m_round_val = 0; - m_cmd_queue.count--; - m_cmd_queue.rp++; - } - - retval = NRF_SUCCESS; - - // If any flash operation is enqueued, schedule - if (m_cmd_queue.count) - { - retval = process_cmd(); - - if (retval != NRF_SUCCESS) - { - // Flash could be accessed by modules other than Bond Manager, hence a busy error is - // acceptable, but any other error needs to be indicated to the bond manager - if (retval != NRF_ERROR_BUSY) - { - app_notify (retval); - } - else - { - // In case of busy next trigger will be a success or a failure event - } - } - } - else - { - // No flash access request pending - } - - return retval; -} - - -/** - * @brief Routine to notify application of any errors. - */ -static void app_notify (uint32_t result) -{ - pstorage_ntf_cb_t ntf_cb; - uint8_t op_code = m_cmd_queue.cmd[m_cmd_queue.rp].op_code; - -#ifdef PSTORAGE_RAW_MODE_ENABLE - if(m_cmd_queue.cmd[m_cmd_queue.rp].storage_addr.module_id == (PSTORAGE_MAX_APPLICATIONS + 1)) - { - ntf_cb = m_raw_app_table.cb; - } - else -#endif // PSTORAGE_RAW_MODE_ENABLE - { - ntf_cb = m_app_table[m_cmd_queue.cmd[m_cmd_queue.rp].storage_addr.module_id].cb; - } - - // Indicate result to client. - // For PSTORAGE_CLEAR_OP_CODE no size is returned as the size field is used only internally - // for clients registering multiple pages. - ntf_cb(&m_cmd_queue.cmd[m_cmd_queue.rp].storage_addr, - op_code, - result, - m_cmd_queue.cmd[m_cmd_queue.rp].p_data_addr, - op_code == PSTORAGE_CLEAR_OP_CODE ? 0 : m_cmd_queue.cmd[m_cmd_queue.rp].size); -} - - -/** - * @brief Handles Flash Access Result Events. - */ -void pstorage_sys_event_handler (uint32_t sys_evt) -{ - uint32_t retval; - - retval = NRF_SUCCESS; - - // Its possible the flash access was not initiated by bond manager, hence - // event is processed only if the event triggered was for an operation requested by the - // bond manager. - if (m_cmd_queue.flash_access == true) - { - cmd_queue_element_t * p_cmd; - m_cmd_queue.flash_access = false; - switch (sys_evt) - { - case NRF_EVT_FLASH_OPERATION_SUCCESS: - p_cmd = &m_cmd_queue.cmd[m_cmd_queue.rp]; - if ((p_cmd->op_code != PSTORAGE_CLEAR_OP_CODE) || (m_round_val >= p_cmd->size)) - { - app_notify(retval); - } - // Schedule any queued flash access operations - retval = cmd_queue_dequeue (); - if (retval != NRF_SUCCESS) - { - app_notify(retval); - } - - break; - case NRF_EVT_FLASH_OPERATION_ERROR: - app_notify(NRF_ERROR_TIMEOUT); - break; - default: - // No implementation needed. - break; - } - } -} - - -/** - * @brief Routine called to actually issue the flash access request to the SoftDevice. - */ -static uint32_t process_cmd(void) -{ - uint32_t retval; - uint32_t storage_addr; - cmd_queue_element_t * p_cmd; - - retval = NRF_ERROR_FORBIDDEN; - - p_cmd = &m_cmd_queue.cmd[m_cmd_queue.rp]; - - storage_addr = p_cmd->storage_addr.block_id; - - if (p_cmd->op_code == PSTORAGE_CLEAR_OP_CODE) - { - // Calculate page number before copy. - uint32_t page_number; - - page_number = ((storage_addr / PSTORAGE_FLASH_PAGE_SIZE) + - m_round_val); - - retval = sd_flash_page_erase(page_number); - - if (NRF_SUCCESS == retval) - { - m_round_val++; - } - } - else if (p_cmd->op_code == PSTORAGE_STORE_OP_CODE) - { - uint32_t size; - uint8_t * p_data_addr = p_cmd->p_data_addr; - - p_data_addr += m_round_val; - - storage_addr += (p_cmd->offset + m_round_val); - - size = p_cmd->size - m_round_val; - - if (size < SOC_MAX_WRITE_SIZE) - { - retval = sd_flash_write(((uint32_t *)storage_addr), - (uint32_t *)p_data_addr, - size / sizeof(uint32_t)); - } - else - { - retval = sd_flash_write(((uint32_t *)storage_addr), - (uint32_t *)p_data_addr, - SOC_MAX_WRITE_SIZE / sizeof(uint32_t)); - } - - - if (retval == NRF_SUCCESS) - { - m_round_val += SOC_MAX_WRITE_SIZE; - } - } - else - { - // Should never reach here. - } - - if (retval == NRF_SUCCESS) - { - m_cmd_queue.flash_access = true; - } - - return retval; -} -/** @} */ - - -/** - * @brief Module initialization routine to be called once by the application. - */ -uint32_t pstorage_init(void) -{ - unsigned int index; - cmd_queue_init(); - - m_next_app_instance = 0; - m_next_page_addr = PSTORAGE_DATA_START_ADDR; - m_round_val = 0; - - for(index = 0; index < PSTORAGE_MAX_APPLICATIONS; index++) - { - m_app_table[index].cb = NULL; - m_app_table[index].block_size = 0; - m_app_table[index].no_of_pages = 0; - m_app_table[index].block_count = 0; - } - -#ifdef PSTORAGE_RAW_MODE_ENABLE - m_raw_app_table.cb = NULL; - m_raw_app_table.no_of_pages = 0; -#endif //PSTORAGE_RAW_MODE_ENABLE - - m_module_initialized = true; - return NRF_SUCCESS; -} - -/** - * @brief Registration routine to request persistent memory of certain sizes based on - * application module requirements. - */ -uint32_t pstorage_register(pstorage_module_param_t * p_module_param, - pstorage_handle_t * p_block_id) -{ - uint16_t page_count; - uint32_t total_size; - - VERIFY_MODULE_INITIALIZED(); - NULL_PARAM_CHECK(p_module_param); - NULL_PARAM_CHECK(p_block_id); - NULL_PARAM_CHECK(p_module_param->cb); - BLOCK_SIZE_CHECK(p_module_param->block_size); - BLOCK_COUNT_CHECK(p_module_param->block_count, p_module_param->block_size); - - if (m_next_app_instance == PSTORAGE_MAX_APPLICATIONS) - { - return NRF_ERROR_NO_MEM; - } - - p_block_id->module_id = m_next_app_instance; - p_block_id->block_id = m_next_page_addr; - m_app_table[m_next_app_instance].base_id = p_block_id->block_id; - m_app_table[m_next_app_instance].cb = p_module_param->cb; - m_app_table[m_next_app_instance].block_size = p_module_param->block_size; - m_app_table[m_next_app_instance].block_count = p_module_param->block_count; - - // Calculate number of flash pages allocated for the device. - page_count = 0; - total_size = p_module_param->block_size * p_module_param->block_count; - do - { - page_count++; - if (total_size > PSTORAGE_FLASH_PAGE_SIZE) - { - total_size -= PSTORAGE_FLASH_PAGE_SIZE; - } - else - { - total_size = 0; - } - m_next_page_addr += PSTORAGE_FLASH_PAGE_SIZE; - }while(total_size >= PSTORAGE_FLASH_PAGE_SIZE); - - m_app_table[m_next_app_instance].no_of_pages = page_count; - m_next_app_instance++; - - return NRF_SUCCESS; -} - - -/** - * @brief API to get the next block identifier. - */ -uint32_t pstorage_block_identifier_get(pstorage_handle_t * p_base_id, - pstorage_size_t block_num, - pstorage_handle_t * p_block_id) -{ - pstorage_handle_t temp_id; - - VERIFY_MODULE_INITIALIZED(); - NULL_PARAM_CHECK(p_base_id); - NULL_PARAM_CHECK(p_block_id); - MODULE_ID_RANGE_CHECK(p_base_id); - - temp_id = (*p_base_id); - temp_id.block_id += (block_num * MODULE_BLOCK_SIZE(p_base_id)); - BLOCK_ID_RANGE_CHECK(&temp_id); - (*p_block_id) = temp_id; - - return NRF_SUCCESS; -} - - -/** - * @brief API to store data persistently. - */ -uint32_t pstorage_store(pstorage_handle_t * p_dest, - uint8_t * p_src, - pstorage_size_t size, - pstorage_size_t offset) -{ - VERIFY_MODULE_INITIALIZED(); - NULL_PARAM_CHECK(p_src); - NULL_PARAM_CHECK(p_dest); - MODULE_ID_RANGE_CHECK (p_dest); - BLOCK_ID_RANGE_CHECK(p_dest); - SIZE_CHECK(p_dest,size); - OFFSET_CHECK(p_dest,offset,size); - - // Verify word alignment. - if ((!is_word_aligned(p_src)) || (!is_word_aligned(p_src+offset))) - { - return NRF_ERROR_INVALID_ADDR; - } - - return cmd_queue_enqueue(PSTORAGE_STORE_OP_CODE, p_dest, p_src, size, offset); -} - - -/** - * @brief API to load data from persistent memory. - */ -uint32_t pstorage_load(uint8_t * p_dest, - pstorage_handle_t * p_src, - pstorage_size_t size, - pstorage_size_t offset) -{ - VERIFY_MODULE_INITIALIZED(); - NULL_PARAM_CHECK(p_src); - NULL_PARAM_CHECK(p_dest); - MODULE_ID_RANGE_CHECK (p_src); - BLOCK_ID_RANGE_CHECK(p_src); - SIZE_CHECK(p_src,size); - OFFSET_CHECK(p_src,offset,size); - - // Verify word alignment. - if ((!is_word_aligned (p_dest)) || (!is_word_aligned (p_dest + offset))) - { - return NRF_ERROR_INVALID_ADDR; - } - - memcpy (p_dest, (((uint8_t *)p_src->block_id) + offset), size); - - return NRF_SUCCESS; -} - - -/** - * @brief API to clear data in blocks of persistent memory. - */ -uint32_t pstorage_clear(pstorage_handle_t * p_dest, pstorage_size_t size) -{ - uint32_t retval; - uint32_t pages; - - VERIFY_MODULE_INITIALIZED(); - NULL_PARAM_CHECK(p_dest); - MODULE_ID_RANGE_CHECK(p_dest); - BLOCK_ID_RANGE_CHECK(p_dest); - - pages = m_app_table[p_dest->module_id].no_of_pages; - - retval = cmd_queue_enqueue(PSTORAGE_CLEAR_OP_CODE, p_dest, NULL , pages , 0); - - return retval; -} - - -#ifdef PSTORAGE_RAW_MODE_ENABLE - -/** - * @brief Registration routine to request persistent memory of certain sizes based on - * application module requirements. - */ -uint32_t pstorage_raw_register(pstorage_module_param_t * p_module_param, - pstorage_handle_t * p_block_id) -{ - VERIFY_MODULE_INITIALIZED(); - NULL_PARAM_CHECK(p_module_param); - NULL_PARAM_CHECK(p_block_id); - NULL_PARAM_CHECK(p_module_param->cb); - - if (m_raw_app_table.cb != NULL) - { - return NRF_ERROR_NO_MEM; - } - - p_block_id->module_id = PSTORAGE_MAX_APPLICATIONS + 1; - m_raw_app_table.cb = p_module_param->cb; - - return NRF_SUCCESS; -} - - -/** - * @brief API to store data persistently. - */ -uint32_t pstorage_raw_store(pstorage_handle_t * p_dest, - uint8_t * p_src, - uint32_t size, - uint32_t offset) -{ - VERIFY_MODULE_INITIALIZED(); - NULL_PARAM_CHECK(p_src); - NULL_PARAM_CHECK(p_dest); - MODULE_RAW_ID_RANGE_CHECK(p_dest); - - // Verify word alignment. - if ((!is_word_aligned(p_src)) || (!is_word_aligned(p_src+offset))) - { - return NRF_ERROR_INVALID_ADDR; - } - - return cmd_queue_enqueue(PSTORAGE_STORE_OP_CODE, p_dest, p_src, size, offset); -} - - -/** - * @brief API to clear data in blocks of persistent memory. - */ -uint32_t pstorage_raw_clear(pstorage_handle_t * p_dest, uint32_t size) -{ - uint32_t retval; - uint32_t pages; - - VERIFY_MODULE_INITIALIZED(); - NULL_PARAM_CHECK(p_dest); - MODULE_RAW_ID_RANGE_CHECK(p_dest); - - retval = NRF_SUCCESS; - - pages = CEIL_DIV(size, PSTORAGE_FLASH_PAGE_SIZE); - - retval = cmd_queue_enqueue(PSTORAGE_CLEAR_OP_CODE, p_dest, NULL , pages, 0); - - return retval; -} - -#endif // PSTORAGE_RAW_MODE_ENABLE diff --git a/libraries/ble/nRF51822/nordic/ble/ble_advdata.cpp b/libraries/ble/nRF51822/nordic/ble/ble_advdata.cpp deleted file mode 100644 index 4b8de1516a..0000000000 --- a/libraries/ble/nRF51822/nordic/ble/ble_advdata.cpp +++ /dev/null @@ -1,624 +0,0 @@ -/* Copyright (c) 2012 Nordic Semiconductor. All Rights Reserved. - * - * The information contained herein is property of Nordic Semiconductor ASA. - * Terms and conditions of usage are described in detail in NORDIC - * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. - * - * Licensees are granted free, non-transferable use of the information. NO - * WARRANTY of ANY KIND is provided. This heading must NOT be removed from - * the file. - * - */ - -#include "ble_advdata.h" -#include "nordic_common.h" -#include "nrf_error.h" -#include "ble_gap.h" -#include "ble_srv_common.h" -#include "app_util.h" - - -// Offset from where advertisement data other than flags information can start. -#define ADV_FLAG_OFFSET 2 - -// Offset for Advertising Data. -// Offset is 2 as each Advertising Data contain 1 octet of Adveritising Data Type and -// one octet Advertising Data Length. -#define ADV_DATA_OFFSET 2 - -// NOTE: For now, Security Manager TK Value and Security Manager Out of Band Flags (OOB) are omitted -// from the advertising data. - - -static uint32_t name_encode(const ble_advdata_t * p_advdata, - uint8_t * p_encoded_data, - uint8_t * p_len) -{ - uint32_t err_code; - uint16_t rem_adv_data_len; - uint16_t actual_length; - uint8_t adv_data_format; - uint8_t adv_offset; - - adv_offset = *p_len; - - - // Check for buffer overflow. - if ((adv_offset + ADV_DATA_OFFSET > BLE_GAP_ADV_MAX_SIZE) || - ((p_advdata->short_name_len + ADV_DATA_OFFSET) > BLE_GAP_ADV_MAX_SIZE)) - { - return NRF_ERROR_DATA_SIZE; - } - actual_length = rem_adv_data_len = (BLE_GAP_ADV_MAX_SIZE - adv_offset - ADV_FLAG_OFFSET); - - // Get GAP device name and length - err_code = sd_ble_gap_device_name_get(&p_encoded_data[adv_offset + ADV_DATA_OFFSET], - &actual_length); - if (err_code != NRF_SUCCESS) - { - return err_code; - } - - // Check if device internd to use short name and it can fit available data size. - if ((p_advdata->name_type == BLE_ADVDATA_FULL_NAME) && (actual_length <= rem_adv_data_len)) - { - // Complete device name can fit, setting Complete Name in Adv Data. - adv_data_format = BLE_GAP_AD_TYPE_COMPLETE_LOCAL_NAME; - rem_adv_data_len = actual_length; - } - else - { - // Else short name needs to be used. Or application has requested use of short name. - adv_data_format = BLE_GAP_AD_TYPE_SHORT_LOCAL_NAME; - - // If application has set a preference on the short name size, it needs to be considered, - // else fit what can be fit. - if ((p_advdata->short_name_len != 0) && (p_advdata->short_name_len <= rem_adv_data_len)) - { - // Short name fits available size. - rem_adv_data_len = p_advdata->short_name_len; - } - // Else whatever can fit the data buffer will be packed. - else - { - rem_adv_data_len = actual_length; - } - } - - // Complete name field in encoded data. - p_encoded_data[adv_offset++] = rem_adv_data_len + 1; - p_encoded_data[adv_offset++] = adv_data_format; - (*p_len) += (rem_adv_data_len + ADV_DATA_OFFSET); - - return NRF_SUCCESS; -} - - -static uint32_t appearance_encode(uint8_t * p_encoded_data, uint8_t * p_len) -{ - uint32_t err_code; - uint16_t appearance; - - // Check for buffer overflow. - if ((*p_len) + 4 > BLE_GAP_ADV_MAX_SIZE) - { - return NRF_ERROR_DATA_SIZE; - } - - // Get GAP appearance field. - err_code = sd_ble_gap_appearance_get(&appearance); - if (err_code != NRF_SUCCESS) - { - return err_code; - } - - // Encode Length, AD Type and Appearance. - p_encoded_data[(*p_len)++] = 3; - p_encoded_data[(*p_len)++] = BLE_GAP_AD_TYPE_APPEARANCE; - - (*p_len) += uint16_encode(appearance, &p_encoded_data[*p_len]); - - return NRF_SUCCESS; -} - - -static uint32_t uint8_array_encode(const uint8_array_t * p_uint8_array, - uint8_t adv_type, - uint8_t * p_encoded_data, - uint8_t * p_len) -{ - // Check parameter consistency. - if (p_uint8_array->p_data == NULL) - { - return NRF_ERROR_INVALID_PARAM; - } - - // Check for buffer overflow. - if ((*p_len) + ADV_DATA_OFFSET + p_uint8_array->size > BLE_GAP_ADV_MAX_SIZE) - { - return NRF_ERROR_DATA_SIZE; - } - - // Encode Length and AD Type. - p_encoded_data[(*p_len)++] = 1 + p_uint8_array->size; - p_encoded_data[(*p_len)++] = adv_type; - - // Encode array. - memcpy(&p_encoded_data[*p_len], p_uint8_array->p_data, p_uint8_array->size); - (*p_len) += p_uint8_array->size; - - return NRF_SUCCESS; -} - - -static uint32_t tx_power_level_encode(int8_t tx_power_level, - uint8_t * p_encoded_data, - uint8_t * p_len) -{ - // Check for buffer overflow. - if ((*p_len) + 3 > BLE_GAP_ADV_MAX_SIZE) - { - return NRF_ERROR_DATA_SIZE; - } - - // Encode TX Power Level. - p_encoded_data[(*p_len)++] = 2; - p_encoded_data[(*p_len)++] = BLE_GAP_AD_TYPE_TX_POWER_LEVEL; - p_encoded_data[(*p_len)++] = (uint8_t)tx_power_level; - - return NRF_SUCCESS; -} - - -static uint32_t uuid_list_sized_encode(const ble_advdata_uuid_list_t * p_uuid_list, - uint8_t adv_type, - uint8_t uuid_size, - uint8_t * p_encoded_data, - uint8_t * p_len) -{ - int i; - bool is_heading_written = false; - uint8_t start_pos = *p_len; - - for (i = 0; i < p_uuid_list->uuid_cnt; i++) - { - uint32_t err_code; - uint8_t encoded_size; - ble_uuid_t uuid = p_uuid_list->p_uuids[i]; - - // Find encoded uuid size. - err_code = sd_ble_uuid_encode(&uuid, &encoded_size, NULL); - if (err_code != NRF_SUCCESS) - { - return err_code; - } - - // Check size. - if (encoded_size == uuid_size) - { - uint8_t heading_bytes = (is_heading_written) ? 0 : 2; - - // Check for buffer overflow - if (*p_len + encoded_size + heading_bytes > BLE_GAP_ADV_MAX_SIZE) - { - return NRF_ERROR_DATA_SIZE; - } - - if (!is_heading_written) - { - // Write AD structure heading. - (*p_len)++; - p_encoded_data[(*p_len)++] = adv_type; - is_heading_written = true; - } - - // Write UUID. - err_code = sd_ble_uuid_encode(&uuid, &encoded_size, &p_encoded_data[*p_len]); - if (err_code != NRF_SUCCESS) - { - return err_code; - } - (*p_len) += encoded_size; - } - } - - if (is_heading_written) - { - // Write length. - p_encoded_data[start_pos] = (*p_len) - (start_pos + 1); - } - - return NRF_SUCCESS; -} - - -static uint32_t uuid_list_encode(const ble_advdata_uuid_list_t * p_uuid_list, - uint8_t adv_type_16, - uint8_t adv_type_128, - uint8_t * p_encoded_data, - uint8_t * p_len) -{ - uint32_t err_code; - - // Encode 16 bit UUIDs. - err_code = uuid_list_sized_encode(p_uuid_list, - adv_type_16, - sizeof(uint16_le_t), - p_encoded_data, - p_len); - if (err_code != NRF_SUCCESS) - { - return err_code; - } - - // Encode 128 bit UUIDs. - err_code = uuid_list_sized_encode(p_uuid_list, - adv_type_128, - sizeof(ble_uuid128_t), - p_encoded_data, - p_len); - if (err_code != NRF_SUCCESS) - { - return err_code; - } - - return NRF_SUCCESS; -} - - -static uint32_t conn_int_check(const ble_advdata_conn_int_t *p_conn_int) -{ - // Check Minimum Connection Interval. - if ((p_conn_int->min_conn_interval < 0x0006) || - ( - (p_conn_int->min_conn_interval > 0x0c80) && - (p_conn_int->min_conn_interval != 0xffff) - ) - ) - { - return NRF_ERROR_INVALID_PARAM; - } - - // Check Maximum Connection Interval. - if ((p_conn_int->max_conn_interval < 0x0006) || - ( - (p_conn_int->max_conn_interval > 0x0c80) && - (p_conn_int->max_conn_interval != 0xffff) - ) - ) - { - return NRF_ERROR_INVALID_PARAM; - } - - // Make sure Minimum Connection Interval is not bigger than Maximum Connection Interval. - if ((p_conn_int->min_conn_interval != 0xffff) && - (p_conn_int->max_conn_interval != 0xffff) && - (p_conn_int->min_conn_interval > p_conn_int->max_conn_interval) - ) - { - return NRF_ERROR_INVALID_PARAM; - } - - return NRF_SUCCESS; -} - - -static uint32_t conn_int_encode(const ble_advdata_conn_int_t * p_conn_int, - uint8_t * p_encoded_data, - uint8_t * p_len) -{ - uint32_t err_code; - - // Check for buffer overflow. - if ((*p_len) + ADV_DATA_OFFSET + 2 * sizeof(uint16_le_t) > BLE_GAP_ADV_MAX_SIZE) - { - return NRF_ERROR_DATA_SIZE; - } - - // Check parameters. - err_code = conn_int_check(p_conn_int); - if (err_code != NRF_SUCCESS) - { - return err_code; - } - - // Encode Length and AD Type. - p_encoded_data[(*p_len)++] = 1 + 2 * sizeof(uint16_le_t); - p_encoded_data[(*p_len)++] = BLE_GAP_AD_TYPE_SLAVE_CONNECTION_INTERVAL_RANGE; - - // Encode Minimum and Maximum Connection Intervals. - (*p_len) += uint16_encode(p_conn_int->min_conn_interval, &p_encoded_data[*p_len]); - (*p_len) += uint16_encode(p_conn_int->max_conn_interval, &p_encoded_data[*p_len]); - - return NRF_SUCCESS; -} - - -static uint32_t manuf_specific_data_encode(const ble_advdata_manuf_data_t * p_manuf_sp_data, - uint8_t * p_encoded_data, - uint8_t * p_len) -{ - uint8_t data_size = sizeof(uint16_le_t) + p_manuf_sp_data->data.size; - - // Check for buffer overflow. - if ((*p_len) + ADV_DATA_OFFSET + data_size > BLE_GAP_ADV_MAX_SIZE) - { - return NRF_ERROR_DATA_SIZE; - } - - // Encode Length and AD Type. - p_encoded_data[(*p_len)++] = 1 + data_size; - p_encoded_data[(*p_len)++] = BLE_GAP_AD_TYPE_MANUFACTURER_SPECIFIC_DATA; - - // Encode Company Identifier. - (*p_len) += uint16_encode(p_manuf_sp_data->company_identifier, &p_encoded_data[*p_len]); - - // Encode additional manufacturer specific data. - if (p_manuf_sp_data->data.size > 0) - { - if (p_manuf_sp_data->data.p_data == NULL) - { - return NRF_ERROR_INVALID_PARAM; - } - memcpy(&p_encoded_data[*p_len], p_manuf_sp_data->data.p_data, p_manuf_sp_data->data.size); - (*p_len) += p_manuf_sp_data->data.size; - } - - return NRF_SUCCESS; -} - - -static uint32_t service_data_encode(const ble_advdata_t * p_advdata, - uint8_t * p_encoded_data, - uint8_t * p_len) -{ - uint8_t i; - - // Check parameter consistency. - if (p_advdata->p_service_data_array == NULL) - { - return NRF_ERROR_INVALID_PARAM; - } - - for (i = 0; i < p_advdata->service_data_count; i++) - { - ble_advdata_service_data_t * p_service_data; - uint8_t data_size; - - p_service_data = &p_advdata->p_service_data_array[i]; - data_size = sizeof(uint16_le_t) + p_service_data->data.size; - - // Encode Length and AD Type. - p_encoded_data[(*p_len)++] = 1 + data_size; - p_encoded_data[(*p_len)++] = BLE_GAP_AD_TYPE_SERVICE_DATA; - - // Encode service UUID. - (*p_len) += uint16_encode(p_service_data->service_uuid, &p_encoded_data[*p_len]); - - // Encode additional service data. - if (p_service_data->data.size > 0) - { - if (p_service_data->data.p_data == NULL) - { - return NRF_ERROR_INVALID_PARAM; - } - memcpy(&p_encoded_data[*p_len], p_service_data->data.p_data, p_service_data->data.size); - (*p_len) += p_service_data->data.size; - } - } - - return NRF_SUCCESS; -} - - -static uint32_t adv_data_encode(const ble_advdata_t * p_advdata, - uint8_t * p_encoded_data, - uint8_t * p_len) -{ - uint32_t err_code = NRF_SUCCESS; - - *p_len = 0; - - // Encode name. - if (p_advdata->name_type != BLE_ADVDATA_NO_NAME) - { - err_code = name_encode(p_advdata, p_encoded_data, p_len); - if (err_code != NRF_SUCCESS) - { - return err_code; - } - } - - // Encode appearance. - if (p_advdata->include_appearance) - { - err_code = appearance_encode(p_encoded_data, p_len); - if (err_code != NRF_SUCCESS) - { - return err_code; - } - } - - // Encode flags. - if (p_advdata->flags.size > 0) - { - err_code = uint8_array_encode(&p_advdata->flags, - BLE_GAP_AD_TYPE_FLAGS, - p_encoded_data, - p_len); - if (err_code != NRF_SUCCESS) - { - return err_code; - } - } - - // Encode TX power level. - if (p_advdata->p_tx_power_level != NULL) - { - err_code = tx_power_level_encode(*p_advdata->p_tx_power_level, p_encoded_data, p_len); - if (err_code != NRF_SUCCESS) - { - return err_code; - } - } - - // Encode 'more available' uuid list. - if (p_advdata->uuids_more_available.uuid_cnt > 0) - { - err_code = uuid_list_encode(&p_advdata->uuids_more_available, - BLE_GAP_AD_TYPE_16BIT_SERVICE_UUID_MORE_AVAILABLE, - BLE_GAP_AD_TYPE_128BIT_SERVICE_UUID_MORE_AVAILABLE, - p_encoded_data, - p_len); - if (err_code != NRF_SUCCESS) - { - return err_code; - } - } - - // Encode 'complete' uuid list. - if (p_advdata->uuids_complete.uuid_cnt > 0) - { - err_code = uuid_list_encode(&p_advdata->uuids_complete, - BLE_GAP_AD_TYPE_16BIT_SERVICE_UUID_COMPLETE, - BLE_GAP_AD_TYPE_128BIT_SERVICE_UUID_COMPLETE, - p_encoded_data, - p_len); - if (err_code != NRF_SUCCESS) - { - return err_code; - } - } - - // Encode 'solicited service' uuid list. - if (p_advdata->uuids_solicited.uuid_cnt > 0) - { - err_code = uuid_list_encode(&p_advdata->uuids_solicited, - BLE_GAP_AD_TYPE_SOLICITED_SERVICE_UUIDS_16BIT, - BLE_GAP_AD_TYPE_SOLICITED_SERVICE_UUIDS_128BIT, - p_encoded_data, - p_len); - if (err_code != NRF_SUCCESS) - { - return err_code; - } - } - - // Encode Slave Connection Interval Range. - if (p_advdata->p_slave_conn_int != NULL) - { - err_code = conn_int_encode(p_advdata->p_slave_conn_int, p_encoded_data, p_len); - if (err_code != NRF_SUCCESS) - { - return err_code; - } - } - - // Encode Manufacturer Specific Data. - if (p_advdata->p_manuf_specific_data != NULL) - { - err_code = manuf_specific_data_encode(p_advdata->p_manuf_specific_data, - p_encoded_data, - p_len); - if (err_code != NRF_SUCCESS) - { - return err_code; - } - } - - // Encode Service Data. - if (p_advdata->service_data_count > 0) - { - err_code = service_data_encode(p_advdata, p_encoded_data, p_len); - if (err_code != NRF_SUCCESS) - { - return err_code; - } - } - - return err_code; -} - - -static uint32_t advdata_check(const ble_advdata_t * p_advdata) -{ - // Flags must be included in advertising data, and the BLE_GAP_ADV_FLAG_BR_EDR_NOT_SUPPORTED flag must be set. - if ((p_advdata->flags.size == 0) || - (p_advdata->flags.p_data == NULL) || - ((p_advdata->flags.p_data[0] & BLE_GAP_ADV_FLAG_BR_EDR_NOT_SUPPORTED) == 0) - ) - { - return NRF_ERROR_INVALID_PARAM; - } - - return NRF_SUCCESS; -} - - -static uint32_t srdata_check(const ble_advdata_t * p_srdata) -{ - // Flags shall not be included in the scan response data. - if (p_srdata->flags.size > 0) - { - return NRF_ERROR_INVALID_PARAM; - } - - return NRF_SUCCESS; -} - - -uint32_t ble_advdata_set(const ble_advdata_t * p_advdata, const ble_advdata_t * p_srdata) -{ - uint32_t err_code; - uint8_t len_advdata = 0; - uint8_t len_srdata = 0; - uint8_t encoded_advdata[BLE_GAP_ADV_MAX_SIZE]; - uint8_t encoded_srdata[BLE_GAP_ADV_MAX_SIZE]; - uint8_t * p_encoded_advdata; - uint8_t * p_encoded_srdata; - - // Encode advertising data (if supplied). - if (p_advdata != NULL) - { - err_code = advdata_check(p_advdata); - if (err_code != NRF_SUCCESS) - { - return err_code; - } - - err_code = adv_data_encode(p_advdata, encoded_advdata, &len_advdata); - if (err_code != NRF_SUCCESS) - { - return err_code; - } - p_encoded_advdata = encoded_advdata; - } - else - { - p_encoded_advdata = NULL; - } - - // Encode scan response data (if supplied). - if (p_srdata != NULL) - { - err_code = srdata_check(p_srdata); - if (err_code != NRF_SUCCESS) - { - return err_code; - } - - err_code = adv_data_encode(p_srdata, encoded_srdata, &len_srdata); - if (err_code != NRF_SUCCESS) - { - return err_code; - } - p_encoded_srdata = encoded_srdata; - } - else - { - p_encoded_srdata = NULL; - } - - // Pass encoded advertising data and/or scan response data to the stack. - return sd_ble_gap_adv_data_set(p_encoded_advdata, len_advdata, p_encoded_srdata, len_srdata); -} diff --git a/libraries/ble/nRF51822/nordic/ble/ble_advdata_parser.cpp b/libraries/ble/nRF51822/nordic/ble/ble_advdata_parser.cpp deleted file mode 100644 index 4e5c73d4e7..0000000000 --- a/libraries/ble/nRF51822/nordic/ble/ble_advdata_parser.cpp +++ /dev/null @@ -1,21 +0,0 @@ -#include "ble_advdata_parser.h" - -uint32_t ble_advdata_parser_field_find(uint8_t type, uint8_t * p_advdata, uint8_t * len, uint8_t ** pp_field_data) -{ - uint32_t index = 0; - - while (index < *len) - { - uint8_t field_length = p_advdata[index]; - uint8_t field_type = p_advdata[index+1]; - - if (field_type == type) - { - *pp_field_data = &p_advdata[index+2]; - *len = field_length-1; - return NRF_SUCCESS; - } - index += field_length+1; - } - return NRF_ERROR_NOT_FOUND; -} diff --git a/libraries/ble/nRF51822/nordic/ble/ble_bondmngr.cpp b/libraries/ble/nRF51822/nordic/ble/ble_bondmngr.cpp deleted file mode 100644 index 2696661cdf..0000000000 --- a/libraries/ble/nRF51822/nordic/ble/ble_bondmngr.cpp +++ /dev/null @@ -1,1594 +0,0 @@ -/* Copyright (c) 2012 Nordic Semiconductor. All Rights Reserved. - * - * The information contained herein is property of Nordic Semiconductor ASA. - * Terms and conditions of usage are described in detail in NORDIC - * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. - * - * Licensees are granted free, non-transferable use of the information. NO - * WARRANTY of ANY KIND is provided. This heading must NOT be removed from - * the file. - * - */ - -#include "ble_bondmngr.h" -#include -#include -#include -#include "nordic_common.h" -#include "nrf_error.h" -#include "ble_gap.h" -#include "ble_srv_common.h" -#include "app_util.h" -#include "nrf_assert.h" -//#include "nrf.h" -#include "nrf51_bitfields.h" -#include "crc16.h" -#include "pstorage.h" -#include "ble_bondmngr_cfg.h" - -#define CCCD_SIZE 6 /**< Number of bytes needed for storing the state of one CCCD. */ -#define CRC_SIZE 2 /**< Size of CRC in sys_attribute data. */ -#define SYS_ATTR_BUFFER_MAX_LEN (((BLE_BONDMNGR_CCCD_COUNT + 1) * CCCD_SIZE) + CRC_SIZE) /**< Size of sys_attribute data. */ -#define MAX_NUM_CENTRAL_WHITE_LIST MIN(BLE_BONDMNGR_MAX_BONDED_CENTRALS, 8) /**< Maximum number of whitelisted centrals supported.*/ -#define MAX_BONDS_IN_FLASH 10 /**< Maximum number of bonds that can be stored in flash. */ -#define BOND_MANAGER_DATA_SIGNATURE 0x53240000 - -/**@defgroup ble_bond_mngr_sec_access Bond Manager Security Status Access Macros - * @brief The following group of macros abstract access to Security Status with a peer. - * @{ - */ - -#define SEC_STATUS_INIT_VAL 0x00 /**< Initialization value for security status flags. */ -#define ENC_STATUS_SET_VAL 0x01 /**< Bitmask for encryption status. */ -#define BOND_IN_PROGRESS_SET_VAL 0x02 /**< Bitmask for 'bonding in progress'. */ - - -/**@brief Macro for setting the Encryption Status for current link. - * - * @details Macro for setting the Encryption Status for current link. - */ -#define ENCRYPTION_STATUS_SET() \ - do \ - { \ - m_sec_con_status |= ENC_STATUS_SET_VAL; \ - } while (0) - -/**@brief Macro for getting the Encryption Status for current link. - * - * @details Macro for getting the Encryption Status for current link. - */ -#define ENCRYPTION_STATUS_GET() \ - (((m_sec_con_status & ENC_STATUS_SET_VAL) == 0) ? false : true) - -/**@brief Macro for resetting the Encryption Status for current link. - * - * @details Macro for resetting the Encryption Status for current link. - */ -#define ENCRYPTION_STATUS_RESET() \ - do \ - { \ - m_sec_con_status &= (~ENC_STATUS_SET_VAL); \ - } while (0) - - -/**@brief Macro for resetting the Bonding In Progress status for current link. - * - * @details Macro for resetting the Bonding In Progress status for current link. - */ -#define BONDING_IN_PROGRESS_STATUS_SET() \ - do \ - { \ - m_sec_con_status |= BOND_IN_PROGRESS_SET_VAL; \ - } while (0) - -/**@brief Macro for setting the Bonding In Progress status for current link. - * - * @details Macro for setting the Bonding In Progress status for current link. - */ -#define BONDING_IN_PROGRESS_STATUS_GET() \ - (((m_sec_con_status & BOND_IN_PROGRESS_SET_VAL) == 0) ? false: true) - -/**@brief Macro for resetting the Bonding In Progress status for current link. - * - * @details Macro for resetting the Bonding In Progress status for current link. - */ -#define BONDING_IN_PROGRESS_STATUS_RESET() \ - do \ - { \ - m_sec_con_status &= (~BOND_IN_PROGRESS_SET_VAL); \ - } while (0) - -/**@brief Macro for resetting all security status flags for current link. - * - * @details Macro for resetting all security status flags for current link. - */ -#define SECURITY_STATUS_RESET() \ - do \ - { \ - m_sec_con_status = SEC_STATUS_INIT_VAL; \ - } while (0) - -/** @} */ - -/**@brief Verify module's initialization status. - * - * @details Verify module's initialization status. Returns NRF_INVALID_STATE in case a module API - * is called without initializing the module. - */ -#define VERIFY_MODULE_INITIALIZED() \ - do \ - { \ - if (!m_is_bondmngr_initialized) \ - { \ - return NRF_ERROR_INVALID_STATE; \ - } \ - } while(0) - - -/**@brief This structure contains the Bonding Information for one central. - */ -typedef struct -{ - int32_t central_handle; /**< Central's handle (NOTE: Size is 32 bits just to make struct size dividable by 4). */ - ble_gap_evt_auth_status_t auth_status; /**< Central authentication data. */ - ble_gap_evt_sec_info_request_t central_id_info; /**< Central identification info. */ - ble_gap_addr_t central_addr; /**< Central's address. */ -} central_bond_t; - -STATIC_ASSERT(sizeof(central_bond_t) % 4 == 0); - -/**@brief This structure contains the System Attributes information related to one central. - */ -typedef struct -{ - int32_t central_handle; /**< Central's handle (NOTE: Size is 32 bits just to make struct size dividable by 4). */ - uint8_t sys_attr[SYS_ATTR_BUFFER_MAX_LEN]; /**< Central sys_attribute data. */ - uint32_t sys_attr_size; /**< Central sys_attribute data's size (NOTE: Size is 32 bits just to make struct size dividable by 4). */ -} central_sys_attr_t; - -STATIC_ASSERT(sizeof(central_sys_attr_t) % 4 == 0); - -/**@brief This structure contains the Bonding Information and System Attributes related to one - * central. - */ -typedef struct -{ - central_bond_t bond; /**< Bonding information. */ - central_sys_attr_t sys_attr; /**< System attribute information. */ -} central_t; - -/**@brief This structure contains the whitelisted addresses. - */ -typedef struct -{ - int8_t central_handle; /**< Central's handle. */ - ble_gap_addr_t * p_addr; /**< Pointer to the central's address if BLE_GAP_ADDR_TYPE_PUBLIC. */ -} whitelist_addr_t; - -/**@brief This structure contains the whitelisted IRKs. - */ -typedef struct -{ - int8_t central_handle; /**< Central's handle. */ - ble_gap_irk_t * p_irk; /**< Pointer to the central's irk if available. */ -} whitelist_irk_t; - -static bool m_is_bondmngr_initialized = false; /**< Flag for checking if module has been initialized. */ -static ble_bondmngr_init_t m_bondmngr_config; /**< Configuration as specified by the application. */ -static uint16_t m_conn_handle; /**< Current connection handle. */ -static central_t m_central; /**< Current central data. */ -static central_t m_centrals_db[BLE_BONDMNGR_MAX_BONDED_CENTRALS]; /**< Pointer to start of bonded centrals database. */ -static uint8_t m_centrals_in_db_count; /**< Number of bonded centrals. */ -static whitelist_addr_t m_whitelist_addr[MAX_NUM_CENTRAL_WHITE_LIST]; /**< List of central's addresses for the whitelist. */ -static whitelist_irk_t m_whitelist_irk[MAX_NUM_CENTRAL_WHITE_LIST]; /**< List of central's IRKs for the whitelist. */ -static uint8_t m_addr_count; /**< Number of addresses in the whitelist. */ -static uint8_t m_irk_count; /**< Number of IRKs in the whitelist. */ -static uint16_t m_crc_bond_info; /**< Combined CRC for all Bonding Information currently stored in flash. */ -static uint16_t m_crc_sys_attr; /**< Combined CRC for all System Attributes currently stored in flash. */ -static pstorage_handle_t mp_flash_bond_info; /**< Pointer to flash location to write next Bonding Information. */ -static pstorage_handle_t mp_flash_sys_attr; /**< Pointer to flash location to write next System Attribute information. */ -static uint8_t m_bond_info_in_flash_count; /**< Number of Bonding Information currently stored in flash. */ -static uint8_t m_sys_attr_in_flash_count; /**< Number of System Attributes currently stored in flash. */ -static uint8_t m_sec_con_status; /**< Variable to denote security status.*/ -static bool m_bond_loaded; /**< Variable to indicate if the bonding information of the currently connected central is available in the RAM.*/ -static bool m_sys_attr_loaded; /**< Variable to indicate if the system attribute information of the currently connected central is loaded from the database and set in the S110 SoftDevice.*/ -static uint32_t m_bond_crc_array[BLE_BONDMNGR_MAX_BONDED_CENTRALS]; -static uint32_t m_sys_crc_array[BLE_BONDMNGR_MAX_BONDED_CENTRALS]; - -/**@brief Function for extracting the CRC from an encoded 32 bit number that typical resides in - * the flash memory - * - * @param[in] header Header containing CRC and magic number. - * @param[out] p_crc Extracted CRC. - * - * @retval NRF_SUCCESS CRC successfully extracted. - * @retval NRF_ERROR_NOT_FOUND Flash seems to be empty. - * @retval NRF_ERROR_INVALID_DATA Header does not contain the magic number. - */ -static uint32_t crc_extract(uint32_t header, uint16_t * p_crc) -{ - if ((header & 0xFFFF0000U) == BOND_MANAGER_DATA_SIGNATURE) - { - *p_crc = (uint16_t)(header & 0x0000FFFFU); - - return NRF_SUCCESS; - } - else if (header == 0xFFFFFFFFU) - { - return NRF_ERROR_NOT_FOUND; - } - else - { - return NRF_ERROR_INVALID_DATA; - } -} - - -/**@brief Function for storing the Bonding Information of the specified central to the flash. - * - * @param[in] p_bond Bonding information to be stored. - * - * @return NRF_SUCCESS on success, an error_code otherwise. - */ -static uint32_t bond_info_store(central_bond_t * p_bond) -{ - uint32_t err_code; - pstorage_handle_t dest_block; - - // Check if flash is full - if (m_bond_info_in_flash_count >= MAX_BONDS_IN_FLASH) - { - return NRF_ERROR_NO_MEM; - } - - // Check if this is the first bond to be stored - if (m_bond_info_in_flash_count == 0) - { - // Initialize CRC - m_crc_bond_info = crc16_compute(NULL, 0, NULL); - } - - // Get block pointer from base - err_code = pstorage_block_identifier_get(&mp_flash_bond_info,m_bond_info_in_flash_count,&dest_block); - if (err_code != NRF_SUCCESS) - { - return err_code; - } - - // Write Bonding Information - err_code = pstorage_store(&dest_block, - (uint8_t *)p_bond, - sizeof(central_bond_t), - sizeof(uint32_t)); - - if (err_code != NRF_SUCCESS) - { - return err_code; - } - m_crc_bond_info = crc16_compute((uint8_t *)p_bond, - sizeof(central_bond_t), - &m_crc_bond_info); - - // Write header - m_bond_crc_array[m_bond_info_in_flash_count] = (BOND_MANAGER_DATA_SIGNATURE | m_crc_bond_info); - - err_code = pstorage_store (&dest_block, (uint8_t *)&m_bond_crc_array[m_bond_info_in_flash_count],sizeof(uint32_t),0); - if (err_code != NRF_SUCCESS) - { - return err_code; - } - - m_bond_info_in_flash_count++; - return NRF_SUCCESS; -} - - -/**@brief Function for storing the System Attributes related to a specified central in flash. - * - * @param[in] p_sys_attr System Attributes to be stored. - * - * @return NRF_SUCCESS on success, an error_code otherwise. - */ -static uint32_t sys_attr_store(central_sys_attr_t * p_sys_attr) -{ - uint32_t err_code; - pstorage_handle_t dest_block; - - // Check if flash is full. - if (m_sys_attr_in_flash_count >= MAX_BONDS_IN_FLASH) - { - return NRF_ERROR_NO_MEM; - } - - // Check if this is the first time any System Attributes is stored. - if (m_sys_attr_in_flash_count == 0) - { - // Initialize CRC - m_crc_sys_attr = crc16_compute(NULL, 0, NULL); - } - - - // Get block pointer from base - err_code = pstorage_block_identifier_get(&mp_flash_sys_attr,m_sys_attr_in_flash_count,&dest_block); - if (err_code != NRF_SUCCESS) - { - return err_code; - } - - // Write System Attributes in flash. - err_code = pstorage_store(&dest_block, - (uint8_t *)p_sys_attr, - sizeof(central_sys_attr_t), - sizeof(uint32_t)); - - if (err_code != NRF_SUCCESS) - { - return err_code; - } - m_crc_sys_attr = crc16_compute((uint8_t *)p_sys_attr, - sizeof(central_sys_attr_t), - &m_crc_sys_attr); - - // Write header. - m_sys_crc_array[m_sys_attr_in_flash_count] = (BOND_MANAGER_DATA_SIGNATURE | m_crc_sys_attr); - - err_code = pstorage_store (&dest_block, - (uint8_t *)&m_sys_crc_array[m_sys_attr_in_flash_count], - sizeof(uint32_t), - 0); - if (err_code != NRF_SUCCESS) - { - return err_code; - } - - m_sys_attr_in_flash_count++; - - - return NRF_SUCCESS; -} - - -/**@brief Function for loading the Bonding Information of one central from flash. - * - * @param[out] p_bond Loaded Bonding Information. - * - * @return NRF_SUCCESS on success, otherwise an error code. - */ -static uint32_t bonding_info_load_from_flash(central_bond_t * p_bond) -{ - pstorage_handle_t source_block; - uint32_t err_code; - uint32_t crc; - uint16_t crc_header; - - // Check if this is the first bond to be loaded, in which case the - // m_bond_info_in_flash_count variable would have the intial value 0. - if (m_bond_info_in_flash_count == 0) - { - // Initialize CRC. - m_crc_bond_info = crc16_compute(NULL, 0, NULL); - } - - // Get block pointer from base - err_code = pstorage_block_identifier_get(&mp_flash_bond_info, - m_bond_info_in_flash_count, - &source_block); - if (err_code != NRF_SUCCESS) - { - return err_code; - } - - err_code = pstorage_load((uint8_t *)&crc, &source_block, sizeof(uint32_t), 0); - if (err_code != NRF_SUCCESS) - { - return err_code; - } - - // Extract CRC from header. - err_code = crc_extract(crc, &crc_header); - if (err_code != NRF_SUCCESS) - { - return err_code; - } - - // Load central. - err_code = pstorage_load((uint8_t *)p_bond, - &source_block, - sizeof(central_bond_t), - sizeof(uint32_t)); - if (err_code != NRF_SUCCESS) - { - return err_code; - } - - // Check CRC. - m_crc_bond_info = crc16_compute((uint8_t *)p_bond, - sizeof(central_bond_t), - &m_crc_bond_info); - if (m_crc_bond_info == crc_header) - { - m_bond_info_in_flash_count++; - return NRF_SUCCESS; - } - else - { - return NRF_ERROR_INVALID_DATA; - } -} - - - -/**@brief Function for loading the System Attributes related to one central from flash. - * - * @param[out] p_sys_attr Loaded System Attributes. - * - * @return NRF_SUCCESS on success, otherwise an error code. - */ -static uint32_t sys_attr_load_from_flash(central_sys_attr_t * p_sys_attr) -{ - pstorage_handle_t source_block; - uint32_t err_code; - uint32_t crc; - uint16_t crc_header; - - // Check if this is the first time System Attributes is loaded from flash, in which case the - // m_sys_attr_in_flash_count variable would have the initial value 0. - if (m_sys_attr_in_flash_count == 0) - { - // Initialize CRC. - m_crc_sys_attr = crc16_compute(NULL, 0, NULL); - } - - // Get block pointer from base - err_code = pstorage_block_identifier_get(&mp_flash_sys_attr, - m_sys_attr_in_flash_count, - &source_block); - if (err_code != NRF_SUCCESS) - { - return err_code; - } - - err_code = pstorage_load((uint8_t *)&crc, &source_block, sizeof(uint32_t), 0); - if (err_code != NRF_SUCCESS) - { - return err_code; - } - - // Extract CRC from header. - err_code = crc_extract(crc, &crc_header); - if (err_code != NRF_SUCCESS) - { - return err_code; - } - - err_code = pstorage_load((uint8_t *)p_sys_attr, - &source_block, - sizeof(central_sys_attr_t), - sizeof(uint32_t)); - if (err_code != NRF_SUCCESS) - { - return err_code; - } - - // Check CRC. - m_crc_sys_attr = crc16_compute((uint8_t *)p_sys_attr, - sizeof(central_sys_attr_t), - &m_crc_sys_attr); - - if (m_crc_sys_attr == crc_header) - { - m_sys_attr_in_flash_count++; - return NRF_SUCCESS; - } - else - { - return NRF_ERROR_INVALID_DATA; - } -} - - -/**@brief Function for erasing the flash pages that contain Bonding Information and System - * Attributes. - * - * @return NRF_SUCCESS on success, otherwise an error code. - */ -static uint32_t flash_pages_erase(void) -{ - uint32_t err_code; - - err_code = pstorage_clear(&mp_flash_bond_info, MAX_BONDS_IN_FLASH); - - if (err_code == NRF_SUCCESS) - { - err_code = pstorage_clear(&mp_flash_sys_attr, MAX_BONDS_IN_FLASH); - } - - return err_code; -} - - -/**@brief Function for checking if Bonding Information in RAM is different from that in - * flash. - * - * @return TRUE if Bonding Information in flash and RAM are different, FALSE otherwise. - */ -static bool bond_info_changed(void) -{ - int i; - uint16_t crc = crc16_compute(NULL, 0, NULL); - - // Compute CRC for all bonds in database. - for (i = 0; i < m_centrals_in_db_count; i++) - { - crc = crc16_compute((uint8_t *)&m_centrals_db[i].bond, - sizeof(central_bond_t), - &crc); - } - - // Compare the computed CRS to CRC stored in flash. - return (crc != m_crc_bond_info); -} - - -/**@brief Function for checking if System Attributes in RAM is different from that in flash. - * - * @return TRUE if System Attributes in flash and RAM are different, FALSE otherwise. - */ -static bool sys_attr_changed(void) -{ - int i; - uint16_t crc = crc16_compute(NULL, 0, NULL); - - // Compute CRC for all System Attributes in database. - for (i = 0; i < m_centrals_in_db_count; i++) - { - crc = crc16_compute((uint8_t *)&m_centrals_db[i].sys_attr, - sizeof(central_sys_attr_t), - &crc); - } - - // Compare the CRC of System Attributes in flash with that of the System Attributes in memory. - return (crc != m_crc_sys_attr); -} - - -/**@brief Function for setting the System Attributes for specified central to the SoftDevice, or - * clearing the System Attributes if central is a previously unknown. - * - * @param[in] p_central Central for which the System Attributes is to be set. - * - * @return NRF_SUCCESS on success, otherwise an error code. - */ -static uint32_t central_sys_attr_set(central_t * p_central) -{ - uint8_t * p_sys_attr; - - if (m_central.sys_attr.sys_attr_size != 0) - { - if (m_central.sys_attr.sys_attr_size > SYS_ATTR_BUFFER_MAX_LEN) - { - return NRF_ERROR_INTERNAL; - } - - p_sys_attr = m_central.sys_attr.sys_attr; - } - else - { - p_sys_attr = NULL; - } - - return sd_ble_gatts_sys_attr_set(m_conn_handle, p_sys_attr, m_central.sys_attr.sys_attr_size); -} - - -/**@brief Function for updating the whitelist data structures. - */ -static void update_whitelist(void) -{ - int i; - - for (i = 0, m_addr_count = 0, m_irk_count = 0; i < m_centrals_in_db_count; i++) - { - central_bond_t * p_bond = &m_centrals_db[i].bond; - - if (p_bond->auth_status.central_kex.irk) - { - m_whitelist_irk[m_irk_count].central_handle = p_bond->central_handle; - m_whitelist_irk[m_irk_count].p_irk = &(p_bond->auth_status.central_keys.irk); - - m_irk_count++; - } - - if (p_bond->central_addr.addr_type != BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_RESOLVABLE) - { - m_whitelist_addr[m_addr_count].central_handle = p_bond->central_handle; - m_whitelist_addr[m_addr_count].p_addr = &(p_bond->central_addr); - - m_addr_count++; - } - } -} - - -/**@brief Function for handling the authentication status event related to a new central. - * - * @details This function adds the new central to the database and stores the central's Bonding - * Information to flash. It also notifies the application when the new bond is created, - * and sets the System Attributes to prepare the stack for connection with the new - * central. - * - * @param[in] p_auth_status New authentication status. - * - * @return NRF_SUCCESS on success, otherwise an error code. - */ -static uint32_t on_auth_status_from_new_central(ble_gap_evt_auth_status_t * p_auth_status) -{ - uint32_t err_code; - - if (m_centrals_in_db_count >= BLE_BONDMNGR_MAX_BONDED_CENTRALS) - { - return NRF_ERROR_NO_MEM; - } - - // Update central. - m_central.bond.auth_status = *p_auth_status; - m_central.bond.central_id_info.div = p_auth_status->periph_keys.enc_info.div; - m_central.sys_attr.sys_attr_size = 0; - - // Add new central to database. - m_central.bond.central_handle = m_centrals_in_db_count; - m_centrals_db[m_centrals_in_db_count++] = m_central; - - update_whitelist(); - - m_bond_loaded = true; - - // Clear System Attributes. - err_code = sd_ble_gatts_sys_attr_set(m_conn_handle, NULL, 0); - if (err_code != NRF_SUCCESS) - { - return err_code; - } - - // Write new central's Bonding Information to flash. - err_code = bond_info_store(&m_central.bond); - if ((err_code == NRF_ERROR_NO_MEM) && (m_bondmngr_config.evt_handler != NULL)) - { - ble_bondmngr_evt_t evt; - - evt.evt_type = BLE_BONDMNGR_EVT_BOND_FLASH_FULL; - evt.central_handle = m_central.bond.central_handle; - evt.central_id = m_central.bond.central_id_info.div; - - m_bondmngr_config.evt_handler(&evt); - } - else if (err_code != NRF_SUCCESS) - { - return err_code; - } - - // Pass the event to application. - if (m_bondmngr_config.evt_handler != NULL) - { - ble_bondmngr_evt_t evt; - - evt.evt_type = BLE_BONDMNGR_EVT_NEW_BOND; - evt.central_handle = m_central.bond.central_handle; - evt.central_id = m_central.bond.central_id_info.div; - - m_bondmngr_config.evt_handler(&evt); - } - - return NRF_SUCCESS; -} - - -/**@brief Function for updating the current central's entry in the database. - */ -static uint32_t central_update(void) -{ - uint32_t err_code; - int32_t central_handle = m_central.bond.central_handle; - - if ((central_handle >= 0) && (central_handle < m_centrals_in_db_count)) - { - // Update the database based on whether the bond and system attributes have - // been loaded or not to avoid overwriting information that was not used in the - // connection session. - if (m_bond_loaded) - { - m_centrals_db[central_handle].bond = m_central.bond; - } - - if (m_sys_attr_loaded) - { - m_centrals_db[central_handle].sys_attr = m_central.sys_attr; - } - - update_whitelist(); - - err_code = NRF_SUCCESS; - } - else - { - err_code = NRF_ERROR_INTERNAL; - } - - return err_code; -} - - -/**@brief Function for searching for the central in the database of known centrals. - * - * @details If the central is found, the variable m_central will be populated with all the - * information (Bonding Information and System Attributes) related to that central. - * - * @param[in] central_id Central Identifier. - * @return NRF_SUCCESS on success, otherwise an error code. - */ -static uint32_t central_find_in_db(uint16_t central_id) -{ - int i; - - for (i = 0; i < m_centrals_in_db_count; i++) - { - if (central_id == m_centrals_db[i].bond.central_id_info.div) - { - m_central = m_centrals_db[i]; - return NRF_SUCCESS; - } - } - - return NRF_ERROR_NOT_FOUND; -} - - -/**@brief Function for loading all Bonding Information and System Attributes from flash. - * - * @return NRF_SUCCESS on success, otherwise an error code. - */ -static uint32_t load_all_from_flash(void) -{ - uint32_t err_code; - int i; - - m_centrals_in_db_count = 0; - - while (m_centrals_in_db_count < BLE_BONDMNGR_MAX_BONDED_CENTRALS) - { - central_bond_t central_bond_info; - int central_handle; - - // Load Bonding Information. - err_code = bonding_info_load_from_flash(¢ral_bond_info); - if (err_code == NRF_ERROR_NOT_FOUND) - { - // No more bonds in flash. - break; - } - else if (err_code != NRF_SUCCESS) - { - return err_code; - } - - central_handle = central_bond_info.central_handle; - if (central_handle > m_centrals_in_db_count) - { - // Central handle value(s) missing in flash. This should never happen. - return NRF_ERROR_INVALID_DATA; - } - else - { - // Add/update Bonding Information in central array. - m_centrals_db[central_handle].bond = central_bond_info; - if (central_handle == m_centrals_in_db_count) - { - // New central handle, clear System Attributes. - m_centrals_db[central_handle].sys_attr.sys_attr_size = 0; - m_centrals_db[central_handle].sys_attr.central_handle = INVALID_CENTRAL_HANDLE; - m_centrals_in_db_count++; - } - else - { - // Entry was updated, do nothing. - } - } - } - - // Load System Attributes for all previously known centrals. - for (i = 0; i < m_centrals_in_db_count; i++) - { - central_sys_attr_t central_sys_attr; - - // Load System Attributes. - err_code = sys_attr_load_from_flash(¢ral_sys_attr); - if (err_code == NRF_ERROR_NOT_FOUND) - { - // No more System Attributes in flash. - break; - } - else if (err_code != NRF_SUCCESS) - { - return err_code; - } - - if (central_sys_attr.central_handle > m_centrals_in_db_count) - { - // Central handle value(s) missing in flash. This should never happen. - return NRF_ERROR_INVALID_DATA; - } - else - { - // Add/update Bonding Information in central array. - m_centrals_db[central_sys_attr.central_handle].sys_attr = central_sys_attr; - } - } - - // Initialize the remaining empty bond entries in the memory. - for (i = m_centrals_in_db_count; i < BLE_BONDMNGR_MAX_BONDED_CENTRALS; i++) - { - m_centrals_db[i].bond.central_handle = INVALID_CENTRAL_HANDLE; - m_centrals_db[i].sys_attr.sys_attr_size = 0; - m_centrals_db[i].sys_attr.central_handle = INVALID_CENTRAL_HANDLE; - } - - // Update whitelist data structures. - update_whitelist(); - - return NRF_SUCCESS; -} - - -/**@brief Function for handling the connected event received from the BLE stack. - * - * @param[in] p_ble_evt Event received from the BLE stack. - */ -static void on_connect(ble_evt_t * p_ble_evt) -{ - m_conn_handle = p_ble_evt->evt.gap_evt.conn_handle; - - m_central.bond.central_handle = INVALID_CENTRAL_HANDLE; - m_central.bond.central_addr = p_ble_evt->evt.gap_evt.params.connected.peer_addr; - m_central.sys_attr.sys_attr_size = 0; - - if (p_ble_evt->evt.gap_evt.params.connected.irk_match) - { - uint8_t irk_idx = p_ble_evt->evt.gap_evt.params.connected.irk_match_idx; - - if ((irk_idx >= MAX_NUM_CENTRAL_WHITE_LIST) || - (m_whitelist_irk[irk_idx].central_handle >= BLE_BONDMNGR_MAX_BONDED_CENTRALS)) - { - m_bondmngr_config.error_handler(NRF_ERROR_INTERNAL); - } - else - { - m_central = m_centrals_db[m_whitelist_irk[irk_idx].central_handle]; - } - } - else - { - int i; - - for (i = 0; i < m_addr_count; i++) - { - ble_gap_addr_t * p_cur_addr = m_whitelist_addr[i].p_addr; - - if (memcmp(p_cur_addr->addr, m_central.bond.central_addr.addr, BLE_GAP_ADDR_LEN) == 0) - { - m_central = m_centrals_db[m_whitelist_addr[i].central_handle]; - break; - } - } - } - - if (m_central.bond.central_handle != INVALID_CENTRAL_HANDLE) - { - // Reset bond and system attributes loaded variables. - m_bond_loaded = false; - m_sys_attr_loaded = false; - - // Do not set the system attributes of the central on connection. - if (m_bondmngr_config.evt_handler != NULL) - { - ble_bondmngr_evt_t evt; - - evt.evt_type = BLE_BONDMNGR_EVT_CONN_TO_BONDED_CENTRAL; - evt.central_handle = m_central.bond.central_handle; - evt.central_id = m_central.bond.central_id_info.div; - - m_bondmngr_config.evt_handler(&evt); - } - } -} - - -/**@brief Function for handling the 'System Attributes Missing' event received from the - * SoftDevice. - * - * @param[in] p_ble_evt Event received from the BLE stack. - */ -static void on_sys_attr_missing(ble_evt_t * p_ble_evt) -{ - uint32_t err_code; - - if ( - (m_central.bond.central_handle == INVALID_CENTRAL_HANDLE) || - !ENCRYPTION_STATUS_GET() || - BONDING_IN_PROGRESS_STATUS_GET() - ) - { - err_code = sd_ble_gatts_sys_attr_set(m_conn_handle, NULL, 0); - } - else - { - // Current central is valid, use its data. Set the corresponding sys_attr. - err_code = central_sys_attr_set(&m_central); - if (err_code == NRF_SUCCESS) - { - // Set System Attributes loaded status variable. - m_sys_attr_loaded = true; - } - } - - if (err_code != NRF_SUCCESS) - { - m_bondmngr_config.error_handler(err_code); - } -} - - -/**@brief Function for handling the new authentication status event, received from the - * SoftDevice, related to an already bonded central. - * - * @details This function also writes the updated Bonding Information to flash and notifies the - * application. - * - * @param[in] p_auth_status Updated authentication status. - */ -static void auth_status_update(ble_gap_evt_auth_status_t * p_auth_status) -{ - uint32_t err_code; - - // Authentication status changed, update Bonding Information. - m_central.bond.auth_status = *p_auth_status; - m_central.bond.central_id_info.div = p_auth_status->periph_keys.enc_info.div; - - memset(&(m_centrals_db[m_central.bond.central_handle]), 0, sizeof(central_t)); - m_centrals_db[m_central.bond.central_handle] = m_central; - - // Write updated Bonding Information to flash. - err_code = bond_info_store(&m_central.bond); - if ((err_code == NRF_ERROR_NO_MEM) && (m_bondmngr_config.evt_handler != NULL)) - { - ble_bondmngr_evt_t evt; - - evt.evt_type = BLE_BONDMNGR_EVT_BOND_FLASH_FULL; - evt.central_handle = m_central.bond.central_handle; - evt.central_id = m_central.bond.central_id_info.div; - - m_bondmngr_config.evt_handler(&evt); - } - else if (err_code != NRF_SUCCESS) - { - m_bondmngr_config.error_handler(err_code); - } - - // Pass the event to the application. - if (m_bondmngr_config.evt_handler != NULL) - { - ble_bondmngr_evt_t evt; - - evt.evt_type = BLE_BONDMNGR_EVT_AUTH_STATUS_UPDATED; - evt.central_handle = m_central.bond.central_handle; - evt.central_id = m_central.bond.central_id_info.div; - - m_bondmngr_config.evt_handler(&evt); - } -} - - -/**@brief Function for handling the Authentication Status event received from the BLE stack. - * - * @param[in] p_ble_evt Event received from the BLE stack. - */ -static void on_auth_status(ble_gap_evt_auth_status_t * p_auth_status) -{ - if (p_auth_status->auth_status != BLE_GAP_SEC_STATUS_SUCCESS) - { - return; - } - - // Verify if its pairing and not bonding - if (!ENCRYPTION_STATUS_GET()) - { - return; - } - - if (m_central.bond.central_handle == INVALID_CENTRAL_HANDLE) - { - uint32_t err_code = central_find_in_db(p_auth_status->periph_keys.enc_info.div); - - if (err_code == NRF_SUCCESS) - { - // Possible DIV Collision indicate error to application, - // not storing the new LTK - err_code = NRF_ERROR_FORBIDDEN; - } - else - { - // Add the new device to data base - err_code = on_auth_status_from_new_central(p_auth_status); - } - - if (err_code != NRF_SUCCESS) - { - m_bondmngr_config.error_handler(err_code); - } - } - else - { - m_bond_loaded = true; - - // Receiving a auth status again when already in have existing information! - auth_status_update(p_auth_status); - } -} - - -/**@brief Function for handling the Security Info Request event received from the BLE stack. - * - * @param[in] p_ble_evt Event received from the BLE stack. - */ -static void on_sec_info_request(ble_evt_t * p_ble_evt) -{ - uint32_t err_code; - - err_code = central_find_in_db(p_ble_evt->evt.gap_evt.params.sec_info_request.div); - if (err_code == NRF_SUCCESS) - { - // Bond information has been found and loaded for security procedures. Reflect this in the - // status variable - m_bond_loaded = true; - - // Central found in the list of bonded central. Use the encryption info for this central. - err_code = sd_ble_gap_sec_info_reply(m_conn_handle, - &m_central.bond.auth_status.periph_keys.enc_info, - NULL); - if (err_code != NRF_SUCCESS) - { - m_bondmngr_config.error_handler(err_code); - } - - // Do not set the sys_attr yet, should be set only when sec_update is successful. - } - else if (err_code == NRF_ERROR_NOT_FOUND) - { - m_central.bond.central_id_info = p_ble_evt->evt.gap_evt.params.sec_info_request; - - // New central. - err_code = sd_ble_gap_sec_info_reply(m_conn_handle, NULL, NULL); - if (err_code != NRF_SUCCESS) - { - m_bondmngr_config.error_handler(err_code); - } - - // Initialize the sys_attr. - err_code = sd_ble_gatts_sys_attr_set(m_conn_handle, NULL, 0); - } - - if (err_code != NRF_SUCCESS) - { - m_bondmngr_config.error_handler(err_code); - } -} - - -/**@brief Function for handling the Connection Security Update event received from the BLE - * stack. - * - * @param[in] p_ble_evt Event received from the BLE stack. - */ -static void on_sec_update(ble_gap_evt_conn_sec_update_t * p_sec_update) -{ - uint8_t security_mode = p_sec_update->conn_sec.sec_mode.sm; - uint8_t security_level = p_sec_update->conn_sec.sec_mode.lv; - - if (((security_mode == 1) && (security_level > 1)) || - ((security_mode == 2) && (security_level != 0))) - { - ENCRYPTION_STATUS_SET(); - - uint32_t err_code = central_sys_attr_set(&m_central); - - if (err_code != NRF_SUCCESS) - { - m_bondmngr_config.error_handler(err_code); - } - else - { - m_sys_attr_loaded = true; - } - - if (m_bondmngr_config.evt_handler != NULL) - { - ble_bondmngr_evt_t evt; - - evt.evt_type = BLE_BONDMNGR_EVT_ENCRYPTED; - evt.central_handle = m_central.bond.central_handle; - evt.central_id = m_central.bond.central_id_info.div; - - m_bondmngr_config.evt_handler(&evt); - } - } -} - - -/**@brief Function for handling the Connection Security Parameters Request event received from - * the BLE stack. - * - * @param[in] p_ble_evt Event received from the BLE stack. - */ -static void on_sec_param_request(ble_gap_evt_sec_params_request_t * p_sec_update) -{ - if (p_sec_update->peer_params.bond) - { - BONDING_IN_PROGRESS_STATUS_SET(); - - if (m_central.bond.central_handle != INVALID_CENTRAL_HANDLE) - { - // Bonding request received from a bonded central, make all system attributes null - m_central.sys_attr.sys_attr_size = 0; - memset(m_central.sys_attr.sys_attr, 0, SYS_ATTR_BUFFER_MAX_LEN); - } - } -} - - -void ble_bondmngr_on_ble_evt(ble_evt_t * p_ble_evt) -{ - if (!m_is_bondmngr_initialized) - { - m_bondmngr_config.error_handler(NRF_ERROR_INVALID_STATE); - } - - switch (p_ble_evt->header.evt_id) - { - case BLE_GAP_EVT_CONNECTED: - on_connect(p_ble_evt); - break; - - // NOTE: All actions to be taken on the Disconnected event are performed in - // ble_bondmngr_bonded_centrals_store(). This function must be called from the - // Disconnected handler of the application before advertising is restarted (to make - // sure the flash blocks are cleared while the radio is inactive). - case BLE_GAP_EVT_DISCONNECTED: - SECURITY_STATUS_RESET(); - break; - - case BLE_GATTS_EVT_SYS_ATTR_MISSING: - on_sys_attr_missing(p_ble_evt); - break; - - case BLE_GAP_EVT_AUTH_STATUS: - on_auth_status(&p_ble_evt->evt.gap_evt.params.auth_status); - break; - - case BLE_GAP_EVT_SEC_INFO_REQUEST: - on_sec_info_request(p_ble_evt); - break; - - case BLE_GAP_EVT_SEC_PARAMS_REQUEST: - on_sec_param_request(&p_ble_evt->evt.gap_evt.params.sec_params_request); - break; - - case BLE_GAP_EVT_CONN_SEC_UPDATE: - on_sec_update(&p_ble_evt->evt.gap_evt.params.conn_sec_update); - break; - - default: - // No implementation needed. - break; - } -} - - -uint32_t ble_bondmngr_bonded_centrals_store(void) -{ - uint32_t err_code; - int i; - - VERIFY_MODULE_INITIALIZED(); - - if (m_central.bond.central_handle != INVALID_CENTRAL_HANDLE) - { - // Fetch System Attributes from stack. - uint16_t sys_attr_size = SYS_ATTR_BUFFER_MAX_LEN; - - err_code = sd_ble_gatts_sys_attr_get(m_conn_handle, - m_central.sys_attr.sys_attr, - &sys_attr_size); - if (err_code != NRF_SUCCESS) - { - return err_code; - } - - m_central.sys_attr.central_handle = m_central.bond.central_handle; - m_central.sys_attr.sys_attr_size = (uint16_t)sys_attr_size; - - // Update the current central. - err_code = central_update(); - if (err_code != NRF_SUCCESS) - { - return err_code; - } - } - - // Save Bonding Information if changed. - if (bond_info_changed()) - { - // Erase flash page. - err_code = pstorage_clear(&mp_flash_bond_info,MAX_BONDS_IN_FLASH); - if (err_code != NRF_SUCCESS) - { - return err_code; - } - - // Store bond information for all centrals. - m_bond_info_in_flash_count = 0; - for (i = 0; i < m_centrals_in_db_count; i++) - { - err_code = bond_info_store(&m_centrals_db[i].bond); - if (err_code != NRF_SUCCESS) - { - return err_code; - } - } - } - - // Save System Attributes, if changed. - if (sys_attr_changed()) - { - // Erase flash page. - err_code = pstorage_clear(&mp_flash_sys_attr, MAX_BONDS_IN_FLASH); - if (err_code != NRF_SUCCESS) - { - return err_code; - } - - // Store System Attributes for all centrals. - m_sys_attr_in_flash_count = 0; - for (i = 0; i < m_centrals_in_db_count; i++) - { - err_code = sys_attr_store(&m_centrals_db[i].sys_attr); - if (err_code != NRF_SUCCESS) - { - return err_code; - } - } - } - - m_conn_handle = BLE_CONN_HANDLE_INVALID; - m_central.bond.central_handle = INVALID_CENTRAL_HANDLE; - m_central.sys_attr.central_handle = INVALID_CENTRAL_HANDLE; - m_central.sys_attr.sys_attr_size = 0; - m_bond_loaded = false; - m_sys_attr_loaded = false; - - return NRF_SUCCESS; -} - - -uint32_t ble_bondmngr_sys_attr_store(void) -{ - uint32_t err_code; - - if (m_central.sys_attr.sys_attr_size == 0) - { - // Connected to new central. So the flash block for System Attributes for this - // central is empty. Hence no erase is needed. - - uint16_t sys_attr_size = SYS_ATTR_BUFFER_MAX_LEN; - - // Fetch System Attributes from stack. - err_code = sd_ble_gatts_sys_attr_get(m_conn_handle, - m_central.sys_attr.sys_attr, - &sys_attr_size); - - if (err_code != NRF_SUCCESS) - { - return err_code; - } - - m_central.sys_attr.central_handle = m_central.bond.central_handle; - m_central.sys_attr.sys_attr_size = (uint16_t)sys_attr_size; - - // Copy the System Attributes to database. - m_centrals_db[m_central.bond.central_handle].sys_attr = m_central.sys_attr; - - // Write new central's System Attributes to flash. - return (sys_attr_store(&m_central.sys_attr)); - } - else - { - // Will not write to flash because System Attributes of an old central would already be - // in flash and so this operation needs a flash erase operation. - return NRF_ERROR_INVALID_STATE; - } -} - - -uint32_t ble_bondmngr_bonded_centrals_delete(void) -{ - VERIFY_MODULE_INITIALIZED(); - - m_centrals_in_db_count = 0; - m_bond_info_in_flash_count = 0; - m_sys_attr_in_flash_count = 0; - - return flash_pages_erase(); -} - - -uint32_t ble_bondmngr_central_addr_get(int8_t central_handle, ble_gap_addr_t * p_central_addr) -{ - if ( - (central_handle == INVALID_CENTRAL_HANDLE) || - (central_handle >= m_centrals_in_db_count) || - (p_central_addr == NULL) || - ( - m_centrals_db[central_handle].bond.central_addr.addr_type - == - BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_RESOLVABLE - ) - ) - { - return NRF_ERROR_INVALID_PARAM; - } - - *p_central_addr = m_centrals_db[central_handle].bond.central_addr; - return NRF_SUCCESS; -} - - -uint32_t ble_bondmngr_whitelist_get(ble_gap_whitelist_t * p_whitelist) -{ - static ble_gap_addr_t * s_addr[MAX_NUM_CENTRAL_WHITE_LIST]; - static ble_gap_irk_t * s_irk[MAX_NUM_CENTRAL_WHITE_LIST]; - - int i; - - for (i = 0; i < m_irk_count; i++) - { - s_irk[i] = m_whitelist_irk[i].p_irk; - } - for (i = 0; i < m_addr_count; i++) - { - s_addr[i] = m_whitelist_addr[i].p_addr; - } - - p_whitelist->addr_count = m_addr_count; - p_whitelist->pp_addrs = (m_addr_count != 0) ? s_addr : NULL; - p_whitelist->irk_count = m_irk_count; - p_whitelist->pp_irks = (m_irk_count != 0) ? s_irk : NULL; - - return NRF_SUCCESS; -} - - -static void bm_pstorage_cb_handler(pstorage_handle_t * handle, - uint8_t op_code, - uint32_t result, - uint8_t * p_data, - uint32_t data_len) -{ - if (result != NRF_SUCCESS) - { - m_bondmngr_config.error_handler(result); - } -} - - -uint32_t ble_bondmngr_init(ble_bondmngr_init_t * p_init) -{ - pstorage_module_param_t param; - uint32_t err_code; - - if (p_init->error_handler == NULL) - { - return NRF_ERROR_INVALID_PARAM; - } - - if (BLE_BONDMNGR_MAX_BONDED_CENTRALS > MAX_BONDS_IN_FLASH) - { - return NRF_ERROR_DATA_SIZE; - } - - param.block_size = sizeof (central_bond_t) + sizeof (uint32_t); - param.block_count = MAX_BONDS_IN_FLASH; - param.cb = bm_pstorage_cb_handler; - - // Blocks are requested twice, once for bond information and once for system attributes. - // The number of blocks requested has to be the maximum number of bonded devices that - // need to be supported. However, the size of blocks can be different if the sizes of - // system attributes and bonds are not too close. - err_code = pstorage_register(¶m, &mp_flash_bond_info); - if (err_code != NRF_SUCCESS) - { - return err_code; - } - - param.block_size = sizeof(central_sys_attr_t) + sizeof(uint32_t); - - err_code = pstorage_register(¶m, &mp_flash_sys_attr); - if (err_code != NRF_SUCCESS) - { - return err_code; - } - - m_bondmngr_config = *p_init; - - memset(&m_central, 0, sizeof(central_t)); - - m_central.bond.central_handle = INVALID_CENTRAL_HANDLE; - m_conn_handle = BLE_CONN_HANDLE_INVALID; - m_centrals_in_db_count = 0; - m_bond_info_in_flash_count = 0; - m_sys_attr_in_flash_count = 0; - - SECURITY_STATUS_RESET(); - - // Erase all stored centrals if specified. - if (m_bondmngr_config.bonds_delete) - { - err_code = flash_pages_erase(); - if (err_code != NRF_SUCCESS) - { - return err_code; - } - - m_centrals_in_db_count = 0; - int i; - for (i = m_centrals_in_db_count; i < BLE_BONDMNGR_MAX_BONDED_CENTRALS; i++) - { - m_centrals_db[i].bond.central_handle = INVALID_CENTRAL_HANDLE; - m_centrals_db[i].sys_attr.sys_attr_size = 0; - m_centrals_db[i].sys_attr.central_handle = INVALID_CENTRAL_HANDLE; - } - } - else - { - // Load bond manager data from flash. - err_code = load_all_from_flash(); - if (err_code != NRF_SUCCESS) - { - return err_code; - } - } - - m_is_bondmngr_initialized = true; - - return NRF_SUCCESS; -} - - -uint32_t ble_bondmngr_central_ids_get(uint16_t * p_central_ids, uint16_t * p_length) -{ - VERIFY_MODULE_INITIALIZED(); - int i; - if (p_length == NULL) - { - return NRF_ERROR_NULL; - } - - if (*p_length < m_centrals_in_db_count) - { - // Length of the input array is not enough to fit all known central identifiers. - return NRF_ERROR_DATA_SIZE; - } - - *p_length = m_centrals_in_db_count; - if (p_central_ids == NULL) - { - // Only the length field was required to be filled. - return NRF_SUCCESS; - } - - for (i = 0; i < m_centrals_in_db_count; i++) - { - p_central_ids[i] = m_centrals_db[i].bond.central_id_info.div; - } - - return NRF_SUCCESS; -} - - -uint32_t ble_bondmngr_bonded_central_delete(uint16_t central_id) -{ - VERIFY_MODULE_INITIALIZED(); - - int8_t central_handle_to_be_deleted = INVALID_CENTRAL_HANDLE; - uint8_t i; - - // Search for the handle of the central. - for (i = 0; i < m_centrals_in_db_count; i++) - { - if (m_centrals_db[i].bond.central_id_info.div == central_id) - { - central_handle_to_be_deleted = i; - break; - } - } - - if (central_handle_to_be_deleted == INVALID_CENTRAL_HANDLE) - { - // Central ID not found. - return NRF_ERROR_NOT_FOUND; - } - - // Delete the central in RAM. - for (i = central_handle_to_be_deleted; i < (m_centrals_in_db_count - 1); i++) - { - // Overwrite the current central entry with the next one. - m_centrals_db[i] = m_centrals_db[i + 1]; - - // Decrement the value of handle. - m_centrals_db[i].bond.central_handle--; - if (INVALID_CENTRAL_HANDLE != m_centrals_db[i].sys_attr.central_handle) - { - m_centrals_db[i].sys_attr.central_handle--; - } - } - - // Clear the last database entry. - memset(&(m_centrals_db[m_centrals_in_db_count - 1]), 0, sizeof(central_t)); - - m_centrals_in_db_count--; - - uint32_t err_code; - - // Reinitialize the pointers to the memory where bonding info and System Attributes are stored - // in flash. - // Refresh the data in the flash memory (both Bonding Information and System Attributes). - // Erase and rewrite bonding info and System Attributes. - - err_code = flash_pages_erase(); - if (err_code != NRF_SUCCESS) - { - return err_code; - } - - m_bond_info_in_flash_count = 0; - m_sys_attr_in_flash_count = 0; - - for (i = 0; i < m_centrals_in_db_count; i++) - { - err_code = bond_info_store(&(m_centrals_db[i].bond)); - if (err_code != NRF_SUCCESS) - { - return err_code; - } - } - - for (i = 0; i < m_centrals_in_db_count; i++) - { - err_code = sys_attr_store(&(m_centrals_db[i].sys_attr)); - if (err_code != NRF_SUCCESS) - { - return err_code; - } - } - - update_whitelist(); - - return NRF_SUCCESS; -} - - -uint32_t ble_bondmngr_is_link_encrypted (bool * status) -{ - VERIFY_MODULE_INITIALIZED(); - - (*status) = ENCRYPTION_STATUS_GET(); - - return NRF_SUCCESS; -} diff --git a/libraries/ble/nRF51822/nordic/ble/ble_conn_params.cpp b/libraries/ble/nRF51822/nordic/ble/ble_conn_params.cpp deleted file mode 100644 index 68772fd2a9..0000000000 --- a/libraries/ble/nRF51822/nordic/ble/ble_conn_params.cpp +++ /dev/null @@ -1,322 +0,0 @@ -/* Copyright (c) 2012 Nordic Semiconductor. All Rights Reserved. - * - * The information contained herein is property of Nordic Semiconductor ASA. - * Terms and conditions of usage are described in detail in NORDIC - * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. - * - * Licensees are granted free, non-transferable use of the information. NO - * WARRANTY of ANY KIND is provided. This heading must NOT be removed from - * the file. - * - */ - -#include "ble_conn_params.h" -#include -#include "nordic_common.h" -#include "ble_hci.h" -#include "app_timer.h" -#include "ble_srv_common.h" -#include "app_util.h" - - -static ble_conn_params_init_t m_conn_params_config; /**< Configuration as specified by the application. */ -static ble_gap_conn_params_t m_preferred_conn_params; /**< Connection parameters preferred by the application. */ -static uint8_t m_update_count; /**< Number of Connection Parameter Update messages that has currently been sent. */ -static uint16_t m_conn_handle; /**< Current connection handle. */ -static ble_gap_conn_params_t m_current_conn_params; /**< Connection parameters received in the most recent Connect event. */ -static app_timer_id_t m_conn_params_timer_id; /**< Connection parameters timer. */ - -static bool m_change_param = false; - -static bool is_conn_params_ok(ble_gap_conn_params_t * p_conn_params) -{ - // Check if interval is within the acceptable range. - // NOTE: Using max_conn_interval in the received event data because this contains - // the client's connection interval. - if ( - (p_conn_params->max_conn_interval >= m_preferred_conn_params.min_conn_interval) - && - (p_conn_params->max_conn_interval <= m_preferred_conn_params.max_conn_interval) - ) - { - return true; - } - else - { - return false; - } -} - - -static void update_timeout_handler(void * p_context) -{ - UNUSED_PARAMETER(p_context); - - if (m_conn_handle != BLE_CONN_HANDLE_INVALID) - { - // Check if we have reached the maximum number of attempts - m_update_count++; - if (m_update_count <= m_conn_params_config.max_conn_params_update_count) - { - uint32_t err_code; - - // Parameters are not ok, send connection parameters update request. - err_code = sd_ble_gap_conn_param_update(m_conn_handle, &m_preferred_conn_params); - if ((err_code != NRF_SUCCESS) && (m_conn_params_config.error_handler != NULL)) - { - m_conn_params_config.error_handler(err_code); - } - } - else - { - m_update_count = 0; - - // Negotiation failed, disconnect automatically if this has been configured - if (m_conn_params_config.disconnect_on_fail) - { - uint32_t err_code; - - err_code = sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_CONN_INTERVAL_UNACCEPTABLE); - if ((err_code != NRF_SUCCESS) && (m_conn_params_config.error_handler != NULL)) - { - m_conn_params_config.error_handler(err_code); - } - } - - // Notify the application that the procedure has failed - if (m_conn_params_config.evt_handler != NULL) - { - ble_conn_params_evt_t evt; - - evt.evt_type = BLE_CONN_PARAMS_EVT_FAILED; - m_conn_params_config.evt_handler(&evt); - } - } - } -} - - -uint32_t ble_conn_params_init(const ble_conn_params_init_t * p_init) -{ - uint32_t err_code; - - m_conn_params_config = *p_init; - m_change_param = false; - if (p_init->p_conn_params != NULL) - { - m_preferred_conn_params = *p_init->p_conn_params; - - // Set the connection params in stack - err_code = sd_ble_gap_ppcp_set(&m_preferred_conn_params); - if (err_code != NRF_SUCCESS) - { - return err_code; - } - } - else - { - // Fetch the connection params from stack - err_code = sd_ble_gap_ppcp_get(&m_preferred_conn_params); - if (err_code != NRF_SUCCESS) - { - return err_code; - } - } - - m_conn_handle = BLE_CONN_HANDLE_INVALID; - m_update_count = 0; - - return app_timer_create(&m_conn_params_timer_id, - APP_TIMER_MODE_SINGLE_SHOT, - update_timeout_handler); -} - - -uint32_t ble_conn_params_stop(void) -{ - return app_timer_stop(m_conn_params_timer_id); -} - - -static void conn_params_negotiation(void) -{ - // Start negotiation if the received connection parameters are not acceptable - if (!is_conn_params_ok(&m_current_conn_params)) - { - uint32_t err_code; - uint32_t timeout_ticks; - - if (m_change_param) - { - // Notify the application that the procedure has failed - if (m_conn_params_config.evt_handler != NULL) - { - ble_conn_params_evt_t evt; - - evt.evt_type = BLE_CONN_PARAMS_EVT_FAILED; - m_conn_params_config.evt_handler(&evt); - } - } - else - { - if (m_update_count == 0) - { - // First connection parameter update - timeout_ticks = m_conn_params_config.first_conn_params_update_delay; - } - else - { - timeout_ticks = m_conn_params_config.next_conn_params_update_delay; - } - - err_code = app_timer_start(m_conn_params_timer_id, timeout_ticks, NULL); - if ((err_code != NRF_SUCCESS) && (m_conn_params_config.error_handler != NULL)) - { - m_conn_params_config.error_handler(err_code); - } - } - } - else - { - // Notify the application that the procedure has succeded - if (m_conn_params_config.evt_handler != NULL) - { - ble_conn_params_evt_t evt; - - evt.evt_type = BLE_CONN_PARAMS_EVT_SUCCEEDED; - m_conn_params_config.evt_handler(&evt); - } - } - m_change_param = false; -} - - -static void on_connect(ble_evt_t * p_ble_evt) -{ - // Save connection parameters - m_conn_handle = p_ble_evt->evt.gap_evt.conn_handle; - m_current_conn_params = p_ble_evt->evt.gap_evt.params.connected.conn_params; - m_update_count = 0; // Connection parameter negotiation should re-start every connection - - // Check if we shall handle negotiation on connect - if (m_conn_params_config.start_on_notify_cccd_handle == BLE_GATT_HANDLE_INVALID) - { - conn_params_negotiation(); - } -} - - -static void on_disconnect(ble_evt_t * p_ble_evt) -{ - uint32_t err_code; - - m_conn_handle = BLE_CONN_HANDLE_INVALID; - - // Stop timer if running - m_update_count = 0; // Connection parameters updates should happen during every connection - - err_code = app_timer_stop(m_conn_params_timer_id); - if ((err_code != NRF_SUCCESS) && (m_conn_params_config.error_handler != NULL)) - { - m_conn_params_config.error_handler(err_code); - } -} - - -static void on_write(ble_evt_t * p_ble_evt) -{ - ble_gatts_evt_write_t * p_evt_write = &p_ble_evt->evt.gatts_evt.params.write; - - // Check if this the correct CCCD - if ( - (p_evt_write->handle == m_conn_params_config.start_on_notify_cccd_handle) - && - (p_evt_write->len == 2) - ) - { - // Check if this is a 'start notification' - if (ble_srv_is_notification_enabled(p_evt_write->data)) - { - // Do connection parameter negotiation if necessary - conn_params_negotiation(); - } - else - { - uint32_t err_code; - - // Stop timer if running - err_code = app_timer_stop(m_conn_params_timer_id); - if ((err_code != NRF_SUCCESS) && (m_conn_params_config.error_handler != NULL)) - { - m_conn_params_config.error_handler(err_code); - } - } - } -} - - -static void on_conn_params_update(ble_evt_t * p_ble_evt) -{ - // Copy the parameters - m_current_conn_params = p_ble_evt->evt.gap_evt.params.conn_param_update.conn_params; - - conn_params_negotiation(); -} - - -void ble_conn_params_on_ble_evt(ble_evt_t * p_ble_evt) -{ - switch (p_ble_evt->header.evt_id) - { - case BLE_GAP_EVT_CONNECTED: - on_connect(p_ble_evt); - break; - - case BLE_GAP_EVT_DISCONNECTED: - on_disconnect(p_ble_evt); - break; - - case BLE_GATTS_EVT_WRITE: - on_write(p_ble_evt); - break; - - case BLE_GAP_EVT_CONN_PARAM_UPDATE: - on_conn_params_update(p_ble_evt); - break; - - default: - // No implementation needed. - break; - } -} - -uint32_t ble_conn_params_change_conn_params(ble_gap_conn_params_t *new_params) -{ - uint32_t err_code; - - m_preferred_conn_params = *new_params; - // Set the connection params in stack - err_code = sd_ble_gap_ppcp_set(&m_preferred_conn_params); - if (err_code == NRF_SUCCESS) - { - if (!is_conn_params_ok(&m_current_conn_params)) - { - m_change_param = true; - err_code = sd_ble_gap_conn_param_update(m_conn_handle, &m_preferred_conn_params); - m_update_count = 1; - } - else - { - // Notify the application that the procedure has succeded - if (m_conn_params_config.evt_handler != NULL) - { - ble_conn_params_evt_t evt; - - evt.evt_type = BLE_CONN_PARAMS_EVT_SUCCEEDED; - m_conn_params_config.evt_handler(&evt); - } - err_code = NRF_SUCCESS; - } - } - return err_code; -} diff --git a/libraries/ble/nRF51822/nordic/ble/ble_debug_assert_handler.cpp b/libraries/ble/nRF51822/nordic/ble/ble_debug_assert_handler.cpp deleted file mode 100644 index 6ccbe33644..0000000000 --- a/libraries/ble/nRF51822/nordic/ble/ble_debug_assert_handler.cpp +++ /dev/null @@ -1,55 +0,0 @@ -/* Copyright (c) 2013 Nordic Semiconductor. All Rights Reserved. - * - * The information contained herein is property of Nordic Semiconductor ASA. - * Terms and conditions of usage are described in detail in NORDIC - * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. - * - * Licensees are granted free, non-transferable use of the information. NO - * WARRANTY of ANY KIND is provided. This heading must NOT be removed from - * the file. - * - */ - -#include "ble_debug_assert_handler.h" -#include -#include "nrf51.h" -#include "ble_error_log.h" -#include "nordic_common.h" - -#define MAX_LENGTH_FILENAME 128 /**< Max length of filename to copy for the debug error handlier. */ - - -// WARNING - DO NOT USE THIS FUNCTION IN END PRODUCT. - WARNING -// WARNING - FOR DEBUG PURPOSES ONLY. - WARNING -void ble_debug_assert_handler(uint32_t error_code, uint32_t line_num, const uint8_t * p_file_name) -{ - // Copying parameters to static variables because parameters may not be accessible in debugger. - static volatile uint8_t s_file_name[MAX_LENGTH_FILENAME]; - static volatile uint16_t s_line_num; - static volatile uint32_t s_error_code; - - strncpy((char *)s_file_name, (const char *)p_file_name, MAX_LENGTH_FILENAME - 1); - s_file_name[MAX_LENGTH_FILENAME - 1] = '\0'; - s_line_num = line_num; - s_error_code = error_code; - UNUSED_VARIABLE(s_file_name); - UNUSED_VARIABLE(s_line_num); - UNUSED_VARIABLE(s_error_code); - - // WARNING: The PRIMASK register is set to disable ALL interrups during writing the error log. - // - // Do not use __disable_irq() in normal operation. - __disable_irq(); - - // This function will write error code, filename, and line number to the flash. - // In addition, the Cortex-M0 stack memory will also be written to the flash. - //(void) ble_error_log_write(error_code, p_file_name, line_num); - - // For debug purposes, this function never returns. - // Attach a debugger for tracing the error cause. - for (;;) - { - // Do nothing. - } -} - diff --git a/libraries/ble/nRF51822/nordic/ble/ble_error_log.cpp b/libraries/ble/nRF51822/nordic/ble/ble_error_log.cpp deleted file mode 100644 index 788c5670ec..0000000000 --- a/libraries/ble/nRF51822/nordic/ble/ble_error_log.cpp +++ /dev/null @@ -1,61 +0,0 @@ -/* Copyright (c) 2012 Nordic Semiconductor. All Rights Reserved. - * - * The information contained herein is property of Nordic Semiconductor ASA. - * Terms and conditions of usage are described in detail in NORDIC - * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. - * - * Licensees are granted free, non-transferable use of the information. NO - * WARRANTY of ANY KIND is provided. This heading must NOT be removed from - * the file. - * - */ - -#include -#include -#include -#include -#include "ble_error_log.h" -#include "app_util.h" -#include "app_error.h" -#include "nrf_gpio.h" -#include "pstorage.h" - - -// Made static to avoid the error_log to go on the stack. -static ble_error_log_data_t m_ble_error_log; /**< . */ -//lint -esym(526,__Vectors) -extern uint32_t * __Vectors; /**< The initialization vector holds the address to __initial_sp that will be used when fetching the stack. */ - -static void fetch_stack(ble_error_log_data_t * error_log) -{ - // KTOWN: Temporarily removed 06022014 - /* - uint32_t * p_stack; - uint32_t * initial_sp; - uint32_t length; - - initial_sp = (uint32_t *) __Vectors; - p_stack = (uint32_t *) GET_SP(); - - length = ((uint32_t) initial_sp) - ((uint32_t) p_stack); - memcpy(error_log->stack_info, - p_stack, - (length > STACK_DUMP_LENGTH) ? STACK_DUMP_LENGTH : length); - */ -} - -uint32_t ble_error_log_write(uint32_t err_code, const uint8_t * p_message, uint16_t line_number) -{ - m_ble_error_log.failure = true; - m_ble_error_log.err_code = err_code; - m_ble_error_log.line_number = line_number; - - strncpy((char *)m_ble_error_log.message, (const char *)p_message, ERROR_MESSAGE_LENGTH - 1); - m_ble_error_log.message[ERROR_MESSAGE_LENGTH - 1] = '\0'; - - fetch_stack(&m_ble_error_log); - - // Write to flash removed, to be redone. - - return NRF_SUCCESS; -} diff --git a/libraries/ble/nRF51822/nordic/ble/ble_services/ble_srv_common.cpp b/libraries/ble/nRF51822/nordic/ble/ble_services/ble_srv_common.cpp deleted file mode 100644 index 84099f11b3..0000000000 --- a/libraries/ble/nRF51822/nordic/ble/ble_services/ble_srv_common.cpp +++ /dev/null @@ -1,41 +0,0 @@ -/* Copyright (c) 2012 Nordic Semiconductor. All Rights Reserved. - * - * The information contained herein is property of Nordic Semiconductor ASA. - * Terms and conditions of usage are described in detail in NORDIC - * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. - * - * Licensees are granted free, non-transferable use of the information. NO - * WARRANTY of ANY KIND is provided. This heading must NOT be removed from - * the file. - * - */ - -/* Attention! -* To maintain compliance with Nordic Semiconductor ASA’s Bluetooth profile -* qualification listings, this section of source code must not be modified. -*/ - -#include "ble_srv_common.h" -#include -#include "nordic_common.h" -#include "app_error.h" - - -uint8_t ble_srv_report_ref_encode(uint8_t * p_encoded_buffer, - const ble_srv_report_ref_t * p_report_ref) -{ - uint8_t len = 0; - - p_encoded_buffer[len++] = p_report_ref->report_id; - p_encoded_buffer[len++] = p_report_ref->report_type; - - APP_ERROR_CHECK_BOOL(len == BLE_SRV_ENCODED_REPORT_REF_LEN); - return len; -} - - -void ble_srv_ascii_to_utf8(ble_srv_utf8_str_t * p_utf8, char * p_ascii) -{ - p_utf8->length = (uint16_t)strlen(p_ascii); - p_utf8->p_str = (uint8_t *)p_ascii; -} diff --git a/libraries/ble/nRF51822/nordic/ble_bondmngr_cfg.h b/libraries/ble/nRF51822/nordic/ble_bondmngr_cfg.h deleted file mode 100644 index 55e73dc574..0000000000 --- a/libraries/ble/nRF51822/nordic/ble_bondmngr_cfg.h +++ /dev/null @@ -1,35 +0,0 @@ -/* Copyright (c) 2012 Nordic Semiconductor. All Rights Reserved. - * - * The information contained herein is property of Nordic Semiconductor ASA. - * Terms and conditions of usage are described in detail in NORDIC - * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. - * - * Licensees are granted free, non-transferable use of the information. NO - * WARRANTY of ANY KIND is provided. This heading must NOT be removed from - * the file. - * - */ - - /** @cond To make doxygen skip this file */ - -/** @file - * - * @defgroup ble_sdk_app_gls_bondmngr_cfg GLS Bond Manager Configuration - * @{ - * @ingroup ble_sdk_app_gls - * @brief Definition of bond manager configurable parameters - */ - -#ifndef BLE_BONDMNGR_CFG_H__ -#define BLE_BONDMNGR_CFG_H__ - -/**@brief Number of CCCDs used in the GLS application. */ -#define BLE_BONDMNGR_CCCD_COUNT 2 - -/**@brief Maximum number of bonded centrals. */ -#define BLE_BONDMNGR_MAX_BONDED_CENTRALS 7 - -#endif // BLE_BONDMNGR_CFG_H__ - -/** @} */ -/** @endcond */ diff --git a/libraries/ble/nRF51822/nordic/nordic_global.h b/libraries/ble/nRF51822/nordic/nordic_global.h deleted file mode 100644 index 89fb77c0e5..0000000000 --- a/libraries/ble/nRF51822/nordic/nordic_global.h +++ /dev/null @@ -1,26 +0,0 @@ -/* Copyright (c) 2014 Nordic Semiconductor. All Rights Reserved. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef _NORDIC_GLOBAL_H_ -#define _NORDIC_GLOBAL_H_ - -/* There are no global defines in mbed, so we need to define */ -/* mandatory conditional compilation flags here */ -#define NRF51 -#define DEBUG_NRF_USER -#define BLE_STACK_SUPPORT_REQD -#define BOARD_PCA10001 - -#endif diff --git a/libraries/ble/nRF51822/nordic/nrf-sdk/app_common/app_button.h b/libraries/ble/nRF51822/nordic/nrf-sdk/app_common/app_button.h deleted file mode 100644 index 29a00e218a..0000000000 --- a/libraries/ble/nRF51822/nordic/nrf-sdk/app_common/app_button.h +++ /dev/null @@ -1,174 +0,0 @@ -/* Copyright (c) 2012 Nordic Semiconductor. All Rights Reserved. - * - * The information contained herein is property of Nordic Semiconductor ASA. - * Terms and conditions of usage are described in detail in NORDIC - * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. - * - * Licensees are granted free, non-transferable use of the information. NO - * WARRANTY of ANY KIND is provided. This heading must NOT be removed from - * the file. - * - */ - -/** @file - * - * @defgroup app_button Button Handler - * @{ - * @ingroup app_common - * - * @brief Buttons handling module. - * - * @details The button handler uses the @ref app_gpiote to detect that a button has been - * pushed. To handle debouncing, it will start a timer in the GPIOTE event handler. - * The button will only be reported as pushed if the corresponding pin is still active when - * the timer expires. If there is a new GPIOTE event while the timer is running, the timer - * is restarted. - * Use the USE_SCHEDULER parameter of the APP_BUTTON_INIT() macro to select if the - * @ref app_scheduler is to be used or not. - * - * @note The app_button module uses the app_timer module. The user must ensure that the queue in - * app_timer is large enough to hold the app_timer_stop() / app_timer_start() operations - * which will be executed on each event from GPIOTE module (2 operations), as well as other - * app_timer operations queued simultaneously in the application. - * - * @note Even if the scheduler is not used, app_button.h will include app_scheduler.h, so when - * compiling, app_scheduler.h must be available in one of the compiler include paths. - */ - -#ifndef APP_BUTTON_H__ -#define APP_BUTTON_H__ - -#include -#include -#include "nordic_global.h" -#include "nrf.h" -#include "app_error.h" -#include "app_scheduler.h" -#include "nrf_gpio.h" - -#define APP_BUTTON_SCHED_EVT_SIZE sizeof(app_button_event_t) /**< Size of button events being passed through the scheduler (is to be used for computing the maximum size of scheduler events). */ - -/**@brief Button event handler type. */ -typedef void (*app_button_handler_t)(uint8_t pin_no); - -/**@brief Type of function for passing events from the Button Handler module to the scheduler. */ -typedef uint32_t (*app_button_evt_schedule_func_t) (app_button_handler_t button_handler, - uint8_t pin_no); - -/**@brief Button configuration structure. */ -typedef struct -{ - uint8_t pin_no; /**< Pin to be used as a button. */ - bool active_high; /**< TRUE if pin is active high, FALSE otherwise. */ - nrf_gpio_pin_pull_t pull_cfg; /**< Pull-up or -down configuration. */ - app_button_handler_t button_handler; /**< Handler to be called when button is pushed. */ -} app_button_cfg_t; - -/**@brief Macro for initializing the Button Handler module. - * - * @details It will initialize the specified pins as buttons, and configure the Button Handler - * module as a GPIOTE user (but it will not enable button detection). It will also connect - * the Button Handler module to the scheduler (if specified). - * - * @param[in] BUTTONS Array of buttons to be used (type app_button_cfg_t, must be - * static!). - * @param[in] BUTTON_COUNT Number of buttons. - * @param[in] DETECTION_DELAY Delay from a GPIOTE event until a button is reported as pushed. - * @param[in] USE_SCHEDULER TRUE if the application is using the event scheduler, - * FALSE otherwise. - */ -/*lint -emacro(506, APP_BUTTON_INIT) */ /* Suppress "Constant value Boolean */ -#define APP_BUTTON_INIT(BUTTONS, BUTTON_COUNT, DETECTION_DELAY, USE_SCHEDULER) \ - do \ - { \ - uint32_t ERR_CODE = app_button_init((BUTTONS), \ - (BUTTON_COUNT), \ - (DETECTION_DELAY), \ - (USE_SCHEDULER) ? app_button_evt_schedule : NULL); \ - APP_ERROR_CHECK(ERR_CODE); \ - } while (0) - -/**@brief Function for initializing the Buttons. - * - * @details This function will initialize the specified pins as buttons, and configure the Button - * Handler module as a GPIOTE user (but it will not enable button detection). - * - * @note Normally initialization should be done using the APP_BUTTON_INIT() macro, as that will take - * care of connecting the Buttons module to the scheduler (if specified). - * - * @note app_button_enable() function must be called in order to enable the button detection. - * - * @param[in] p_buttons Array of buttons to be used (NOTE: Must be static!). - * @param[in] button_count Number of buttons. - * @param[in] detection_delay Delay from a GPIOTE event until a button is reported as pushed. - * @param[in] evt_schedule_func Function for passing button events to the scheduler. Point to - * app_button_evt_schedule() to connect to the scheduler. Set to - * NULL to make the Buttons module call the event handler directly - * from the delayed button push detection timeout handler. - * - * @return NRF_SUCCESS on success, otherwise an error code. - */ -uint32_t app_button_init(app_button_cfg_t * p_buttons, - uint8_t button_count, - uint32_t detection_delay, - app_button_evt_schedule_func_t evt_schedule_func); - -/**@brief Function for enabling button detection. - * - * @retval NRF_ERROR_INVALID_PARAM GPIOTE has to many users. - * @retval NRF_ERROR_INVALID_STATE Button or GPIOTE not initialized. - * @retval NRF_SUCCESS Button detection successfully enabled. - */ -uint32_t app_button_enable(void); - -/**@brief Function for disabling button detection. - * - * @retval NRF_ERROR_INVALID_PARAM GPIOTE has to many users. - * @retval NRF_ERROR_INVALID_STATE Button or GPIOTE not initialized. - * @retval NRF_SUCCESS Button detection successfully enabled. - */ -uint32_t app_button_disable(void); - -/**@brief Function for checking if a button is currently being pushed. - * - * @param[in] pin_no Button pin to be checked. - * @param[out] p_is_pushed Button state. - * - * @retval NRF_SUCCESS State successfully read. - * @retval NRF_ERROR_INVALID_PARAM Invalid pin_no. - */ -uint32_t app_button_is_pushed(uint8_t pin_no, bool * p_is_pushed); - - -// Type and functions for connecting the Buttons module to the scheduler: - -/**@cond NO_DOXYGEN */ -typedef struct -{ - app_button_handler_t button_handler; - uint8_t pin_no; -} app_button_event_t; - -static __INLINE void app_button_evt_get(void * p_event_data, uint16_t event_size) -{ - app_button_event_t * p_buttons_event = (app_button_event_t *)p_event_data; - - APP_ERROR_CHECK_BOOL(event_size == sizeof(app_button_event_t)); - p_buttons_event->button_handler(p_buttons_event->pin_no); -} - -static __INLINE uint32_t app_button_evt_schedule(app_button_handler_t button_handler, - uint8_t pin_no) -{ - app_button_event_t buttons_event; - - buttons_event.button_handler = button_handler; - buttons_event.pin_no = pin_no; - - return app_sched_event_put(&buttons_event, sizeof(buttons_event), app_button_evt_get); -} -/**@endcond */ - -#endif // APP_BUTTON_H__ - -/** @} */ diff --git a/libraries/ble/nRF51822/nordic/nrf-sdk/app_common/app_error.h b/libraries/ble/nRF51822/nordic/nrf-sdk/app_common/app_error.h deleted file mode 100644 index 43fdf66019..0000000000 --- a/libraries/ble/nRF51822/nordic/nrf-sdk/app_common/app_error.h +++ /dev/null @@ -1,78 +0,0 @@ -/* Copyright (c) 2013 Nordic Semiconductor. All Rights Reserved. - * - * The information contained herein is property of Nordic Semiconductor ASA. - * Terms and conditions of usage are described in detail in NORDIC - * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. - * - * Licensees are granted free, non-transferable use of the information. NO - * WARRANTY of ANY KIND is provided. This heading must NOT be removed from - * the file. - * - */ - -/** @file - * - * @defgroup app_error Common application error handler - * @{ - * @ingroup app_common - * - * @brief Common application error handler and macros for utilizing a common error handler. - */ - -#ifndef APP_ERROR_H__ -#define APP_ERROR_H__ - -#include -#include -#include "nordic_global.h" -#include "nrf_error.h" - -/**@brief Function for error handling, which is called when an error has occurred. - * - * @param[in] error_code Error code supplied to the handler. - * @param[in] line_num Line number where the handler is called. - * @param[in] p_file_name Pointer to the file name. - */ -void app_error_handler(uint32_t error_code, uint32_t line_num, const uint8_t * p_file_name); - -/**@brief Macro for calling error handler function. - * - * @param[in] ERR_CODE Error code supplied to the error handler. - */ -#define APP_ERROR_HANDLER(ERR_CODE) \ - do \ - { \ - app_error_handler((ERR_CODE), __LINE__, (uint8_t*) __FILE__); \ - } while (0) - -/**@brief Macro for calling error handler function if supplied error code any other than NRF_SUCCESS. - * - * @param[in] ERR_CODE Error code supplied to the error handler. - */ -#define APP_ERROR_CHECK(ERR_CODE) \ - do \ - { \ - const uint32_t LOCAL_ERR_CODE = (ERR_CODE); \ - if (LOCAL_ERR_CODE != NRF_SUCCESS) \ - { \ - APP_ERROR_HANDLER(LOCAL_ERR_CODE); \ - } \ - } while (0) - -/**@brief Macro for calling error handler function if supplied boolean value is false. - * - * @param[in] BOOLEAN_VALUE Boolean value to be evaluated. - */ -#define APP_ERROR_CHECK_BOOL(BOOLEAN_VALUE) \ - do \ - { \ - const bool LOCAL_BOOLEAN_VALUE = (BOOLEAN_VALUE); \ - if (!LOCAL_BOOLEAN_VALUE) \ - { \ - APP_ERROR_HANDLER(0); \ - } \ - } while (0) - -#endif // APP_ERROR_H__ - -/** @} */ diff --git a/libraries/ble/nRF51822/nordic/nrf-sdk/app_common/app_fifo.h b/libraries/ble/nRF51822/nordic/nrf-sdk/app_common/app_fifo.h deleted file mode 100644 index 10640e5e1b..0000000000 --- a/libraries/ble/nRF51822/nordic/nrf-sdk/app_common/app_fifo.h +++ /dev/null @@ -1,84 +0,0 @@ -/* Copyright (c) 2013 Nordic Semiconductor. All Rights Reserved. - * - * The information contained herein is property of Nordic Semiconductor ASA. - * Terms and conditions of usage are described in detail in NORDIC - * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. - * - * Licensees are granted free, non-transferable use of the information. NO - * WARRANTY of ANY KIND is provided. This heading must NOT be removed from - * the file. - * - */ - -/**@file - * - * @defgroup app_fifo FIFO implementation - * @{ - * @ingroup app_common - * - * @brief FIFO implementation. - */ - -#ifndef APP_FIFO_H__ -#define APP_FIFO_H__ - -#include -#include -#include "nordic_global.h" -#include "nrf_error.h" - -/**@brief A FIFO instance structure. Keeps track of which bytes to read and write next. - * Also it keeps the information about which memory is allocated for the buffer - * and its size. This needs to be initialized by app_fifo_init() before use. - */ -typedef struct -{ - uint8_t * p_buf; /**< Pointer to FIFO buffer memory. */ - uint16_t buf_size_mask; /**< Read/write index mask. Also used for size checking. */ - volatile uint32_t read_pos; /**< Next read position in the FIFO buffer. */ - volatile uint32_t write_pos; /**< Next write position in the FIFO buffer. */ -} app_fifo_t; - -/**@brief Function for initializing the FIFO. - * - * @param[out] p_fifo FIFO object. - * @param[in] p_buf FIFO buffer for storing data. The buffer size has to be a power of two. - * @param[in] buf_size Size of the FIFO buffer provided, has to be a power of 2. - * - * @retval NRF_SUCCESS If initialization was successful. - * @retval NRF_ERROR_NULL If a NULL pointer is provided as buffer. - * @retval NRF_ERROR_INVALID_LENGTH If size of buffer provided is not a power of two. - */ -uint32_t app_fifo_init(app_fifo_t * p_fifo, uint8_t * p_buf, uint16_t buf_size); - -/**@brief Function for adding an element to the FIFO. - * - * @param[in] p_fifo Pointer to the FIFO. - * @param[in] byte Data byte to add to the FIFO. - * - * @retval NRF_SUCCESS If an element has been successfully added to the FIFO. - * @retval NRF_ERROR_NO_MEM If the FIFO is full. - */ -uint32_t app_fifo_put(app_fifo_t * p_fifo, uint8_t byte); - -/**@brief Function for getting the next element from the FIFO. - * - * @param[in] p_fifo Pointer to the FIFO. - * @param[out] p_byte Byte fetched from the FIFO. - * - * @retval NRF_SUCCESS If an element was returned. - * @retval NRF_ERROR_NOT_FOUND If there is no more elements in the queue. - */ -uint32_t app_fifo_get(app_fifo_t * p_fifo, uint8_t * p_byte); - -/**@brief Function for flushing the FIFO. - * - * @param[in] p_fifo Pointer to the FIFO. - * - * @retval NRF_SUCCESS If the FIFO flushed successfully. - */ -uint32_t app_fifo_flush(app_fifo_t * p_fifo); - -#endif // APP_FIFO_H__ - -/** @} */ diff --git a/libraries/ble/nRF51822/nordic/nrf-sdk/app_common/app_gpiote.h b/libraries/ble/nRF51822/nordic/nrf-sdk/app_common/app_gpiote.h deleted file mode 100644 index 6fab8b2f65..0000000000 --- a/libraries/ble/nRF51822/nordic/nrf-sdk/app_common/app_gpiote.h +++ /dev/null @@ -1,161 +0,0 @@ -/* Copyright (c) 2012 Nordic Semiconductor. All Rights Reserved. - * - * The information contained herein is property of Nordic Semiconductor ASA. - * Terms and conditions of usage are described in detail in NORDIC - * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. - * - * Licensees are granted free, non-transferable use of the information. NO - * WARRANTY of ANY KIND is provided. This heading must NOT be removed from - * the file. - * - */ - -/** @file - * - * @defgroup app_gpiote GPIOTE Handler - * @{ - * @ingroup app_common - * - * @brief GPIOTE handler module. - * - * @details The GPIOTE handler allows several modules ("users") to share the GPIOTE interrupt, - * each user defining a set of pins able to generate events to the user. - * When a GPIOTE interrupt occurs, the GPIOTE interrupt handler will call the event handler - * of each user for which at least one of the pins generated an event. - * - * The GPIOTE users are responsible for configuring all their corresponding pins, except - * the SENSE field, which should be initialized to GPIO_PIN_CNF_SENSE_Disabled. - * The SENSE field will be updated by the GPIOTE module when it is enabled or disabled, - * and also while it is enabled. - * - * The module specifies on which pins events should be generated if the pin(s) goes - * from low->high or high->low or both directions. - * - * @note Even if the application is using the @ref app_scheduler, the GPIOTE event handlers will - * be called directly from the GPIOTE interrupt handler. - */ - -#ifndef APP_GPIOTE_H__ -#define APP_GPIOTE_H__ - -#include -#include -#include "nordic_global.h" -#include "nrf.h" -#include "app_error.h" -#include "app_util.h" - -#define GPIOTE_USER_NODE_SIZE 20 /**< Size of app_gpiote.gpiote_user_t (only for use inside APP_GPIOTE_BUF_SIZE()). */ -#define NO_OF_PINS 32 /**< Number of GPIO pins on the nRF51 chip. */ - -/**@brief Compute number of bytes required to hold the GPIOTE data structures. - * - * @param[in] MAX_USERS Maximum number of GPIOTE users. - * - * @return Required buffer size (in bytes). - */ -#define APP_GPIOTE_BUF_SIZE(MAX_USERS) ((MAX_USERS) * GPIOTE_USER_NODE_SIZE) - -typedef uint8_t app_gpiote_user_id_t; - -/**@brief GPIOTE event handler type. */ -typedef void (*app_gpiote_event_handler_t)(uint32_t event_pins_low_to_high, - uint32_t event_pins_high_to_low); - -/**@brief Macro for initializing the GPIOTE module. - * - * @details It will handle dimensioning and allocation of the memory buffer required by the module, - * making sure that the buffer is correctly aligned. - * - * @param[in] MAX_USERS Maximum number of GPIOTE users. - * - * @note Since this macro allocates a buffer, it must only be called once (it is OK to call it - * several times as long as it is from the same location, e.g. to do a reinitialization). - */ -/*lint -emacro(506, APP_GPIOTE_INIT) */ /* Suppress "Constant value Boolean */ -#define APP_GPIOTE_INIT(MAX_USERS) \ - do \ - { \ - static uint32_t app_gpiote_buf[CEIL_DIV(APP_GPIOTE_BUF_SIZE(MAX_USERS), sizeof(uint32_t))];\ - uint32_t ERR_CODE = app_gpiote_init((MAX_USERS), app_gpiote_buf); \ - APP_ERROR_CHECK(ERR_CODE); \ - } while (0) - -/**@brief Function for initializing the GPIOTE module. - * - * @note Normally initialization should be done using the APP_GPIOTE_INIT() macro, as that will - * allocate the buffer needed by the GPIOTE module (including aligning the buffer correctly). - * - * @param[in] max_users Maximum number of GPIOTE users. - * @param[in] p_buffer Pointer to memory buffer for internal use in the app_gpiote - * module. The size of the buffer can be computed using the - * APP_GPIOTE_BUF_SIZE() macro. The buffer must be aligned to - * a 4 byte boundary. - * - * @retval NRF_SUCCESS Successful initialization. - * @retval NRF_ERROR_INVALID_PARAM Invalid parameter (buffer not aligned to a 4 byte - * boundary). - */ -uint32_t app_gpiote_init(uint8_t max_users, void * p_buffer); - -/**@brief Function for registering a GPIOTE user. - * - * @param[out] p_user_id Id for the new GPIOTE user. - * @param[in] pins_low_to_high_mask Mask defining which pins will generate events to this user - * when state is changed from low->high. - * @param[in] pins_high_to_low_mask Mask defining which pins will generate events to this user - * when state is changed from high->low. - * @param[in] event_handler Pointer to function to be executed when an event occurs. - * - * @retval NRF_SUCCESS Successful initialization. - * @retval NRF_ERROR_INVALID_PARAM Invalid parameter (buffer not aligned to a 4 byte boundary). - * @retval NRF_ERROR_INALID_STATE If @ref app_gpiote_init has not been called on the GPIOTE - * module. - * @retval NRF_ERROR_NO_MEM Returned if the application tries to register more users - * than defined when the GPIOTE module was initialized in - * @ref app_gpiote_init. - */ -uint32_t app_gpiote_user_register(app_gpiote_user_id_t * p_user_id, - uint32_t pins_low_to_high_mask, - uint32_t pins_high_to_low_mask, - app_gpiote_event_handler_t event_handler); - -/**@brief Function for informing the GPIOTE module that the specified user wants to use the GPIOTE module. - * - * @param[in] user_id Id of user to enable. - * - * @retval NRF_SUCCESS On success. - * @retval NRF_ERROR_INVALID_PARAM Invalid user_id provided, No a valid user. - * @retval NRF_ERROR_INALID_STATE If @ref app_gpiote_init has not been called on the GPIOTE - * module. - */ -uint32_t app_gpiote_user_enable(app_gpiote_user_id_t user_id); - -/**@brief Function for informing the GPIOTE module that the specified user is done using the GPIOTE module. - * - * @param[in] user_id Id of user to enable. - * - * @return NRF_SUCCESS On success. - * @retval NRF_ERROR_INVALID_PARAM Invalid user_id provided, No a valid user. - * @retval NRF_ERROR_INALID_STATE If @ref app_gpiote_init has not been called on the GPIOTE - * module. - */ -uint32_t app_gpiote_user_disable(app_gpiote_user_id_t user_id); - -/**@brief Function for getting the state of the pins which are registered for the specified user. - * - * @param[in] user_id Id of user to check. - * @param[out] p_pins Bit mask corresponding to the pins configured to generate events to - * the specified user. All bits corresponding to pins in the state - * 'high' will have value '1', all others will have value '0'. - * - * @return NRF_SUCCESS On success. - * @retval NRF_ERROR_INVALID_PARAM Invalid user_id provided, No a valid user. - * @retval NRF_ERROR_INALID_STATE If @ref app_gpiote_init has not been called on the GPIOTE - * module. - */ -uint32_t app_gpiote_pins_state_get(app_gpiote_user_id_t user_id, uint32_t * p_pins); - -#endif // APP_GPIOTE_H__ - -/** @} */ diff --git a/libraries/ble/nRF51822/nordic/nrf-sdk/app_common/app_scheduler.h b/libraries/ble/nRF51822/nordic/nrf-sdk/app_common/app_scheduler.h deleted file mode 100644 index 4b737d48f2..0000000000 --- a/libraries/ble/nRF51822/nordic/nrf-sdk/app_common/app_scheduler.h +++ /dev/null @@ -1,135 +0,0 @@ -/* Copyright (c) 2012 Nordic Semiconductor. All Rights Reserved. - * - * The information contained herein is property of Nordic Semiconductor ASA. - * Terms and conditions of usage are described in detail in NORDIC - * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. - * - * Licensees are granted free, non-transferable use of the information. NO - * WARRANTY of ANY KIND is provided. This heading must NOT be removed from - * the file. - * - */ - -/** @file - * - * @defgroup app_scheduler Scheduler - * @{ - * @ingroup app_common - * - * @brief The scheduler is used for transferring execution from the interrupt context to the main - * context. - * - * @details See @ref ble_sdk_apps_seq_diagrams for sequence diagrams illustrating the flow of events - * when using the Scheduler. - * - * @section app_scheduler_req Requirements: - * - * @subsection main_context_logic Logic in main context: - * - * - Define an event handler for each type of event expected. - * - Initialize the scheduler by calling the APP_SCHED_INIT() macro before entering the - * application main loop. - * - Call app_sched_execute() from the main loop each time the application wakes up because of an - * event (typically when sd_app_evt_wait() returns). - * - * @subsection int_context_logic Logic in interrupt context: - * - * - In the interrupt handler, call app_sched_event_put() - * with the appropriate data and event handler. This will insert an event into the - * scheduler's queue. The app_sched_execute() function will pull this event and call its - * handler in the main context. - * - * For an example usage of the scheduler, please see the implementations of - * @ref ble_sdk_app_hids_mouse and @ref ble_sdk_app_hids_keyboard. - * - * @image html scheduler_working.jpg The high level design of the scheduler - */ - -#ifndef APP_SCHEDULER_H__ -#define APP_SCHEDULER_H__ - -#include -#include "nordic_global.h" -#include "app_error.h" - -#define APP_SCHED_EVENT_HEADER_SIZE 8 /**< Size of app_scheduler.event_header_t (only for use inside APP_SCHED_BUF_SIZE()). */ - -/**@brief Compute number of bytes required to hold the scheduler buffer. - * - * @param[in] EVENT_SIZE Maximum size of events to be passed through the scheduler. - * @param[in] QUEUE_SIZE Number of entries in scheduler queue (i.e. the maximum number of events - * that can be scheduled for execution). - * - * @return Required scheduler buffer size (in bytes). - */ -#define APP_SCHED_BUF_SIZE(EVENT_SIZE, QUEUE_SIZE) \ - (((EVENT_SIZE) + APP_SCHED_EVENT_HEADER_SIZE) * ((QUEUE_SIZE) + 1)) - -/**@brief Scheduler event handler type. */ -typedef void (*app_sched_event_handler_t)(void * p_event_data, uint16_t event_size); - -/**@brief Macro for initializing the event scheduler. - * - * @details It will also handle dimensioning and allocation of the memory buffer required by the - * scheduler, making sure the buffer is correctly aligned. - * - * @param[in] EVENT_SIZE Maximum size of events to be passed through the scheduler. - * @param[in] QUEUE_SIZE Number of entries in scheduler queue (i.e. the maximum number of events - * that can be scheduled for execution). - * - * @note Since this macro allocates a buffer, it must only be called once (it is OK to call it - * several times as long as it is from the same location, e.g. to do a reinitialization). - */ -#define APP_SCHED_INIT(EVENT_SIZE, QUEUE_SIZE) \ - do \ - { \ - static uint32_t APP_SCHED_BUF[CEIL_DIV(APP_SCHED_BUF_SIZE((EVENT_SIZE), (QUEUE_SIZE)), \ - sizeof(uint32_t))]; \ - uint32_t ERR_CODE = app_sched_init((EVENT_SIZE), (QUEUE_SIZE), APP_SCHED_BUF); \ - APP_ERROR_CHECK(ERR_CODE); \ - } while (0) - -/**@brief Function for initializing the Scheduler. - * - * @details It must be called before entering the main loop. - * - * @param[in] max_event_size Maximum size of events to be passed through the scheduler. - * @param[in] queue_size Number of entries in scheduler queue (i.e. the maximum number of - * events that can be scheduled for execution). - * @param[in] p_event_buffer Pointer to memory buffer for holding the scheduler queue. It must - * be dimensioned using the APP_SCHED_BUFFER_SIZE() macro. The buffer - * must be aligned to a 4 byte boundary. - * - * @note Normally initialization should be done using the APP_SCHED_INIT() macro, as that will both - * allocate the scheduler buffer, and also align the buffer correctly. - * - * @retval NRF_SUCCESS Successful initialization. - * @retval NRF_ERROR_INVALID_PARAM Invalid parameter (buffer not aligned to a 4 byte - * boundary). - */ -uint32_t app_sched_init(uint16_t max_event_size, uint16_t queue_size, void * p_evt_buffer); - -/**@brief Function for executing all scheduled events. - * - * @details This function must be called from within the main loop. It will execute all events - * scheduled since the last time it was called. - */ -void app_sched_execute(void); - -/**@brief Function for scheduling an event. - * - * @details Puts an event into the event queue. - * - * @param[in] p_event_data Pointer to event data to be scheduled. - * @param[in] p_event_size Size of event data to be scheduled. - * @param[in] handler Event handler to receive the event. - * - * @return NRF_SUCCESS on success, otherwise an error code. - */ -uint32_t app_sched_event_put(void * p_event_data, - uint16_t event_size, - app_sched_event_handler_t handler); - -#endif // APP_SCHEDULER_H__ - -/** @} */ diff --git a/libraries/ble/nRF51822/nordic/nrf-sdk/app_common/app_timer.h b/libraries/ble/nRF51822/nordic/nrf-sdk/app_common/app_timer.h deleted file mode 100644 index 8343865577..0000000000 --- a/libraries/ble/nRF51822/nordic/nrf-sdk/app_common/app_timer.h +++ /dev/null @@ -1,294 +0,0 @@ -/* Copyright (c) 2012 Nordic Semiconductor. All Rights Reserved. - * - * The information contained herein is property of Nordic Semiconductor ASA. - * Terms and conditions of usage are described in detail in NORDIC - * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. - * - * Licensees are granted free, non-transferable use of the information. NO - * WARRANTY of ANY KIND is provided. This heading must NOT be removed from - * the file. - * - */ - -/** @file - * - * @defgroup app_timer Application Timer - * @{ - * @ingroup app_common - * - * @brief Application timer functionality. - * - * @details It enables the application to create multiple timer instances based on the RTC1 - * peripheral. Checking for timeouts and invokation of user timeout handlers is performed - * in the RTC1 interrupt handler. List handling is done using a software interrupt (SWI0). - * Both interrupt handlers are running in APP_LOW priority level. - * - * @note When calling app_timer_start() or app_timer_stop(), the timer operation is just queued, - * and the software interrupt is triggered. The actual timer start/stop operation is - * executed by the SWI0 interrupt handler. Since the SWI0 interrupt is running in APP_LOW, - * if the application code calling the timer function is running in APP_LOW or APP_HIGH, - * the timer operation will not be performed until the application handler has returned. - * This will be the case e.g. when stopping a timer from a timeout handler when not using - * the scheduler. - * - * @details Use the USE_SCHEDULER parameter of the APP_TIMER_INIT() macro to select if the - * @ref app_scheduler is to be used or not. - * - * @note Even if the scheduler is not used, app_timer.h will include app_scheduler.h, so when - * compiling, app_scheduler.h must be available in one of the compiler include paths. - */ - -#ifndef APP_TIMER_H__ -#define APP_TIMER_H__ - -#include -#include -#include -#include "nordic_global.h" -#include "app_error.h" -#include "app_util.h" -#include "app_scheduler.h" -#include "compiler_abstraction.h" - -#define APP_TIMER_SCHED_EVT_SIZE sizeof(app_timer_event_t) /**< Size of button events being passed through the scheduler (is to be used for computing the maximum size of scheduler events). */ -#define APP_TIMER_CLOCK_FREQ 32768 /**< Clock frequency of the RTC timer used to implement the app timer module. */ -#define APP_TIMER_MIN_TIMEOUT_TICKS 5 /**< Minimum value of the timeout_ticks parameter of app_timer_start(). */ - -#define APP_TIMER_NODE_SIZE 40 /**< Size of app_timer.timer_node_t (only for use inside APP_TIMER_BUF_SIZE()). */ -#define APP_TIMER_USER_OP_SIZE 24 /**< Size of app_timer.timer_user_op_t (only for use inside APP_TIMER_BUF_SIZE()). */ -#define APP_TIMER_USER_SIZE 8 /**< Size of app_timer.timer_user_t (only for use inside APP_TIMER_BUF_SIZE()). */ -#define APP_TIMER_INT_LEVELS 3 /**< Number of interrupt levels from where timer operations may be initiated (only for use inside APP_TIMER_BUF_SIZE()). */ - -/**@brief Compute number of bytes required to hold the application timer data structures. - * - * @param[in] MAX_TIMERS Maximum number of timers that can be created at any given time. - * @param[in] OP_QUEUE_SIZE Size of queues holding timer operations that are pending execution. - * NOTE: Due to the queue implementation, this size must be one more - * than the size that is actually needed. - * - * @return Required application timer buffer size (in bytes). - */ -#define APP_TIMER_BUF_SIZE(MAX_TIMERS, OP_QUEUE_SIZE) \ - ( \ - ((MAX_TIMERS) * APP_TIMER_NODE_SIZE) \ - + \ - ( \ - APP_TIMER_INT_LEVELS \ - * \ - (APP_TIMER_USER_SIZE + ((OP_QUEUE_SIZE) + 1) * APP_TIMER_USER_OP_SIZE) \ - ) \ - ) - -/**@brief Convert milliseconds to timer ticks. - * - * @note This macro uses 64 bit integer arithmetic, but as long as the macro parameters are - * constants (i.e. defines), the computation will be done by the preprocessor. - * - * @param[in] MS Milliseconds. - * @param[in] PRESCALER Value of the RTC1 PRESCALER register (must be the same value that was - * passed to APP_TIMER_INIT()). - * - * @note When using this macro, it is the responsibility of the developer to ensure that the - * values provided as input result in an output value that is supported by the - * @ref app_timer_start function. For example, when the ticks for 1 ms is needed, the - * maximum possible value of PRESCALER must be 6, when @ref APP_TIMER_CLOCK_FREQ is 32768. - * This will result in a ticks value as 5. Any higher value for PRESCALER will result in a - * ticks value that is not supported by this module. - * - * @return Number of timer ticks. - */ -#define APP_TIMER_TICKS(MS, PRESCALER)\ - ((uint32_t)ROUNDED_DIV((MS) * (uint64_t)APP_TIMER_CLOCK_FREQ, ((PRESCALER) + 1) * 1000)) - -/**@brief Timer id type. */ -typedef uint32_t app_timer_id_t; - -/**@brief Application timeout handler type. */ -typedef void (*app_timer_timeout_handler_t)(void * p_context); - -/**@brief Type of function for passing events from the timer module to the scheduler. */ -typedef uint32_t (*app_timer_evt_schedule_func_t) (app_timer_timeout_handler_t timeout_handler, - void * p_context); - -/**@brief Timer modes. */ -typedef enum -{ - APP_TIMER_MODE_SINGLE_SHOT, /**< The timer will expire only once. */ - APP_TIMER_MODE_REPEATED /**< The timer will restart each time it expires. */ -} app_timer_mode_t; - -/**@brief Macro for initializing the application timer module. - * - * @details It will handle dimensioning and allocation of the memory buffer required by the timer, - * making sure that the buffer is correctly aligned. It will also connect the timer module - * to the scheduler (if specified). - * - * @param[in] PRESCALER Value of the RTC1 PRESCALER register. This will decide the - * timer tick rate. Set to 0 for no prescaling. - * @param[in] MAX_TIMERS Maximum number of timers that can be created at any given time. - * @param[in] OP_QUEUES_SIZE Size of queues holding timer operations that are pending execution. - * @param[in] USE_SCHEDULER TRUE if the application is using the event scheduler, - * FALSE otherwise. - * - * @note Since this macro allocates a buffer, it must only be called once (it is OK to call it - * several times as long as it is from the same location, e.g. to do a reinitialization). - */ -/*lint -emacro(506, APP_TIMER_INIT) */ /* Suppress "Constant value Boolean */ -#define APP_TIMER_INIT(PRESCALER, MAX_TIMERS, OP_QUEUES_SIZE, USE_SCHEDULER) \ - do \ - { \ - static uint32_t APP_TIMER_BUF[CEIL_DIV(APP_TIMER_BUF_SIZE((MAX_TIMERS), \ - (OP_QUEUES_SIZE) + 1), \ - sizeof(uint32_t))]; \ - uint32_t ERR_CODE = app_timer_init((PRESCALER), \ - (MAX_TIMERS), \ - (OP_QUEUES_SIZE) + 1, \ - APP_TIMER_BUF, \ - (USE_SCHEDULER) ? app_timer_evt_schedule : NULL); \ - APP_ERROR_CHECK(ERR_CODE); \ - } while (0) - -/**@brief Function for initializing the timer module. - * - * @note Normally initialization should be done using the APP_TIMER_INIT() macro, as that will both - * allocate the buffers needed by the timer module (including aligning the buffers correctly, - * and also take care of connecting the timer module to the scheduler (if specified). - * - * @param[in] prescaler Value of the RTC1 PRESCALER register. Set to 0 for no prescaling. - * @param[in] max_timers Maximum number of timers that can be created at any given time. - * @param[in] op_queues_size Size of queues holding timer operations that are pending - * execution. NOTE: Due to the queue implementation, this size must - * be one more than the size that is actually needed. - * @param[in] p_buffer Pointer to memory buffer for internal use in the app_timer - * module. The size of the buffer can be computed using the - * APP_TIMER_BUF_SIZE() macro. The buffer must be aligned to a - * 4 byte boundary. - * @param[in] evt_schedule_func Function for passing timeout events to the scheduler. Point to - * app_timer_evt_schedule() to connect to the scheduler. Set to NULL - * to make the timer module call the timeout handler directly from - * the timer interrupt handler. - * - * @retval NRF_SUCCESS Successful initialization. - * @retval NRF_ERROR_INVALID_PARAM Invalid parameter (buffer not aligned to a 4 byte - * boundary or NULL). - */ -uint32_t app_timer_init(uint32_t prescaler, - uint8_t max_timers, - uint8_t op_queues_size, - void * p_buffer, - app_timer_evt_schedule_func_t evt_schedule_func); - -/**@brief Function for creating a timer instance. - * - * @param[out] p_timer_id Id of the newly created timer. - * @param[in] mode Timer mode. - * @param[in] timeout_handler Function to be executed when the timer expires. - * - * @retval NRF_SUCCESS Timer was successfully created. - * @retval NRF_ERROR_INVALID_PARAM Invalid parameter. - * @retval NRF_ERROR_INVALID_STATE Application timer module has not been initialized. - * @retval NRF_ERROR_NO_MEM Maximum number of timers has already been reached. - * - * @note This function does the timer allocation in the caller's context. It is also not protected - * by a critical region. Therefore care must be taken not to call it from several interrupt - * levels simultaneously. - */ -uint32_t app_timer_create(app_timer_id_t * p_timer_id, - app_timer_mode_t mode, - app_timer_timeout_handler_t timeout_handler); - -/**@brief Function for starting a timer. - * - * @param[in] timer_id Id of timer to start. - * @param[in] timeout_ticks Number of ticks (of RTC1, including prescaling) to timeout event - * (minimum 5 ticks). - * @param[in] p_context General purpose pointer. Will be passed to the timeout handler when - * the timer expires. - * - * @retval NRF_SUCCESS Timer was successfully started. - * @retval NRF_ERROR_INVALID_PARAM Invalid parameter. - * @retval NRF_ERROR_INVALID_STATE Application timer module has not been initialized, or timer - * has not been created. - * @retval NRF_ERROR_NO_MEM Timer operations queue was full. - * - * @note The minimum timeout_ticks value is 5. - * @note For multiple active timers, timeouts occurring in close proximity to each other (in the - * range of 1 to 3 ticks) will have a positive jitter of maximum 3 ticks. - * @note When calling this method on a timer which is already running, the second start operation - * will be ignored. - */ -uint32_t app_timer_start(app_timer_id_t timer_id, uint32_t timeout_ticks, void * p_context); - -/**@brief Function for stopping the specified timer. - * - * @param[in] timer_id Id of timer to stop. - * - * @retval NRF_SUCCESS Timer was successfully stopped. - * @retval NRF_ERROR_INVALID_PARAM Invalid parameter. - * @retval NRF_ERROR_INVALID_STATE Application timer module has not been initialized, or timer - * has not been created. - * @retval NRF_ERROR_NO_MEM Timer operations queue was full. - */ -uint32_t app_timer_stop(app_timer_id_t timer_id); - -/**@brief Function for stopping all running timers. - * - * @retval NRF_SUCCESS All timers were successfully stopped. - * @retval NRF_ERROR_INVALID_STATE Application timer module has not been initialized. - * @retval NRF_ERROR_NO_MEM Timer operations queue was full. - */ -uint32_t app_timer_stop_all(void); - -/**@brief Function for returning the current value of the RTC1 counter. - * - * @param[out] p_ticks Current value of the RTC1 counter. - * - * @retval NRF_SUCCESS Counter was successfully read. - */ -uint32_t app_timer_cnt_get(uint32_t * p_ticks); - -/**@brief Function for computing the difference between two RTC1 counter values. - * - * @param[in] ticks_to Value returned by app_timer_cnt_get(). - * @param[in] ticks_from Value returned by app_timer_cnt_get(). - * @param[out] p_ticks_diff Number of ticks from ticks_from to ticks_to. - * - * @retval NRF_SUCCESS Counter difference was successfully computed. - */ -uint32_t app_timer_cnt_diff_compute(uint32_t ticks_to, - uint32_t ticks_from, - uint32_t * p_ticks_diff); - - -// Type and functions for connecting the timer to the scheduler: - -/**@cond NO_DOXYGEN */ -typedef struct -{ - app_timer_timeout_handler_t timeout_handler; - void * p_context; -} app_timer_event_t; - -static __INLINE void app_timer_evt_get(void * p_event_data, uint16_t event_size) -{ - app_timer_event_t * p_timer_event = (app_timer_event_t *)p_event_data; - - APP_ERROR_CHECK_BOOL(event_size == sizeof(app_timer_event_t)); - p_timer_event->timeout_handler(p_timer_event->p_context); -} - -static __INLINE uint32_t app_timer_evt_schedule(app_timer_timeout_handler_t timeout_handler, - void * p_context) -{ - app_timer_event_t timer_event; - - timer_event.timeout_handler = timeout_handler; - timer_event.p_context = p_context; - - return app_sched_event_put(&timer_event, sizeof(timer_event), app_timer_evt_get); -} -/**@endcond */ - -#endif // APP_TIMER_H__ - -/** @} */ diff --git a/libraries/ble/nRF51822/nordic/nrf-sdk/app_common/app_uart.h b/libraries/ble/nRF51822/nordic/nrf-sdk/app_common/app_uart.h deleted file mode 100644 index 7dfba85300..0000000000 --- a/libraries/ble/nRF51822/nordic/nrf-sdk/app_common/app_uart.h +++ /dev/null @@ -1,285 +0,0 @@ -/* Copyright (c) 2013 Nordic Semiconductor. All Rights Reserved. - * - * The information contained herein is property of Nordic Semiconductor ASA. - * Terms and conditions of usage are described in detail in NORDIC - * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. - * - * Licensees are granted free, non-transferable use of the information. NO - * WARRANTY of ANY KIND is provided. This heading must NOT be removed from - * the file. - * - */ - -/**@file - * - * @defgroup app_uart UART module - * @{ - * @ingroup app_common - * - * @brief UART module interface. - */ - -#ifndef APP_UART_H__ -#define APP_UART_H__ - -#include -#include -#include "nordic_global.h" -#include "app_util.h" - -#define UART_PIN_DISCONNECTED 0xFFFFFFFF /**< Value indicating that no pin is connected to this UART register. */ - -/**@brief UART Flow Control modes for the peripheral. - */ -typedef enum -{ - APP_UART_FLOW_CONTROL_DISABLED, /**< UART Hw Flow Control is disabled. */ - APP_UART_FLOW_CONTROL_ENABLED, /**< Standard UART Hw Flow Control is enabled. */ - APP_UART_FLOW_CONTROL_LOW_POWER /**< Specialized UART Hw Flow Control is used. The Low Power setting allows the nRF51 to Power Off the UART module when CTS is in-active, and re-enabling the UART when the CTS signal becomes active. This allows the nRF51 to safe power by only using the UART module when it is needed by the remote site. */ -} app_uart_flow_control_t; - -/**@brief UART communication structure holding configuration settings for the peripheral. - */ -typedef struct -{ - uint8_t rx_pin_no; /**< RX pin number. */ - uint8_t tx_pin_no; /**< TX pin number. */ - uint8_t rts_pin_no; /**< RTS pin number, only used if flow control is enabled. */ - uint8_t cts_pin_no; /**< CTS pin number, only used if flow control is enabled. */ - app_uart_flow_control_t flow_control; /**< Flow control setting, if flow control is used, the system will use low power UART mode, based on CTS signal. */ - bool use_parity; /**< Even parity if TRUE, no parity if FALSE. */ - uint32_t baud_rate; /**< Baud rate configuration. */ -} app_uart_comm_params_t; - -/**@brief UART buffer for transmitting/receiving data. - */ -typedef struct -{ - uint8_t * rx_buf; /**< Pointer to the RX buffer. */ - uint32_t rx_buf_size; /**< Size of the RX buffer. */ - uint8_t * tx_buf; /**< Pointer to the TX buffer. */ - uint32_t tx_buf_size; /**< Size of the TX buffer. */ -} app_uart_buffers_t; - -/**@brief Enumeration describing current state of the UART. - * - * @details The connection state can be fetched by the application using the function call - * @ref app_uart_get_connection_state. - * When hardware flow control is used - * - APP_UART_CONNECTED: Communication is ongoing. - * - APP_UART_DISCONNECTED: No communication is ongoing. - * - * When no hardware flow control is used - * - APP_UART_CONNECTED: Always returned as bytes can always be received/transmitted. - */ -typedef enum -{ - APP_UART_DISCONNECTED, /**< State indicating that the UART is disconnected and cannot receive or transmit bytes. */ - APP_UART_CONNECTED /**< State indicating that the UART is connected and ready to receive or transmit bytes. If flow control is disabled, the state will always be connected. */ -} app_uart_connection_state_t; - -/**@brief Enumeration which defines events used by the UART module upon data reception or error. - * - * @details The event type is used to indicate the type of additional information in the event - * @ref app_uart_evt_t. - */ -typedef enum -{ - APP_UART_DATA_READY, /**< An event indicating that UART data has been received. The data is available in the FIFO and can be fetched using @ref app_uart_get. */ - APP_UART_FIFO_ERROR, /**< An error in the FIFO module used by the app_uart module has occured. The FIFO error code is stored in app_uart_evt_t.data.error_code field. */ - APP_UART_COMMUNICATION_ERROR, /**< An communication error has occured during reception. The error is stored in app_uart_evt_t.data.error_communication field. */ - APP_UART_TX_EMPTY, /**< An event indicating that UART has completed transmission of all available data in the TX FIFO. */ - APP_UART_DATA, /**< An event indicating that UART data has been received, and data is present in data field. This event is only used when no FIFO is configured. */ -} app_uart_evt_type_t; - -/**@brief Struct containing events from the UART module. - * - * @details The app_uart_evt_t is used to notify the application of asynchronous events when data - * are received on the UART peripheral or in case an error occured during data reception. - */ -typedef struct -{ - app_uart_evt_type_t evt_type; /**< Type of event. */ - union - { - uint32_t error_communication;/**< Field used if evt_type is: APP_UART_COMMUNICATION_ERROR. This field contains the value in the ERRORSRC register for the UART peripheral. The UART_ERRORSRC_x defines from @ref nrf51_bitfields.h can be used to parse the error code. See also the nRF51 Series Reference Manual for specification. */ - uint32_t error_code; /**< Field used if evt_type is: NRF_ERROR_x. Additional status/error code if the error event type is APP_UART_FIFO_ERROR. This error code refer to errors defined in nrf_error.h. */ - uint8_t value; /**< Field used if evt_type is: NRF_ERROR_x. Additional status/error code if the error event type is APP_UART_FIFO_ERROR. This error code refer to errors defined in nrf_error.h. */ - } data; -} app_uart_evt_t; - -/**@brief Function for handling app_uart event callback. - * - * @details Upon an event in the app_uart module this callback function will be called to notify - * the applicatioon about the event. - * - * @param[in] p_app_uart_event Pointer to UART event. - */ -typedef void (*app_uart_event_handler_t) (app_uart_evt_t * p_app_uart_event); - -/**@brief Macro for safe initialization of the UART module in a single user instance when using - * a FIFO together with UART. - * - * @param[in] P_COMM_PARAMS Pointer to a UART communication structure: app_uart_comm_params_t - * @param[in] RX_BUF_SIZE Size of desired RX buffer, must be a power of 2 or ZERO (No FIFO). - * @param[in] TX_BUF_SIZE Size of desired TX buffer, must be a power of 2 or ZERO (No FIFO). - * @param[in] EVENT_HANDLER Event handler function to be called when an event occurs in the - * UART module. - * @param[in] IRQ_PRIO IRQ priority, app_irq_priority_t, for the UART module irq handler. - * @param[out] ERR_CODE The return value of the UART initialization function will be - * written to this parameter. - * - * @note Since this macro allocates a buffer and registers the module as a GPIOTE user when flow - * control is enabled, it must only be called once. - */ -#define APP_UART_FIFO_INIT(P_COMM_PARAMS, RX_BUF_SIZE, TX_BUF_SIZE, EVT_HANDLER, IRQ_PRIO, ERR_CODE)\ - do \ - { \ - uint16_t APP_UART_UID = 0; \ - app_uart_buffers_t buffers; \ - static uint8_t rx_buf[RX_BUF_SIZE]; \ - static uint8_t tx_buf[TX_BUF_SIZE]; \ - \ - buffers.rx_buf = rx_buf; \ - buffers.rx_buf_size = sizeof(rx_buf); \ - buffers.tx_buf = tx_buf; \ - buffers.tx_buf_size = sizeof(tx_buf); \ - ERR_CODE = app_uart_init(P_COMM_PARAMS, &buffers, EVT_HANDLER, IRQ_PRIO, &APP_UART_UID); \ - } while (0) - -/**@brief Macro for safe initialization of the UART module in a single user instance. - * - * @param[in] P_COMM_PARAMS Pointer to a UART communication structure: app_uart_comm_params_t - * @param[in] EVENT_HANDLER Event handler function to be called when an event occurs in the - * UART module. - * @param[in] IRQ_PRIO IRQ priority, app_irq_priority_t, for the UART module irq handler. - * @param[out] ERR_CODE The return value of the UART initialization function will be - * written to this parameter. - * - * @note Since this macro allocates registers the module as a GPIOTE user when flow control is - * enabled, it must only be called once. - */ -#define APP_UART_INIT(P_COMM_PARAMS, EVT_HANDLER, IRQ_PRIO, ERR_CODE) \ - do \ - { \ - uint16_t APP_UART_UID = 0; \ - ERR_CODE = app_uart_init(P_COMM_PARAMS, NULL, EVT_HANDLER, IRQ_PRIO, &APP_UART_UID); \ - } while (0) - -/**@brief Function for initializing the UART module. Use this initialization when several instances of the UART - * module are needed. - * - * @details This initialization will return a UART user id for the caller. The UART user id must be - * used upon re-initialization of the UART or closing of the module for the user. - * If single instance usage is needed, the APP_UART_INIT() macro should be used instead. - * - * @note Normally single instance initialization should be done using the APP_UART_INIT() or - * APP_UART_INIT_FIFO() macro depending on whether the FIFO should be used by the UART, as - * that will allocate the buffers needed by the UART module (including aligning the buffer - * correctly). - - * @param[in] p_comm_params Pin and communication parameters. - * @param[in] p_buffers RX and TX buffers, NULL is FIFO is not used. - * @param[in] error_handler Function to be called in case of an error. - * @param[in] app_irq_priority Interrupt priority level. - * @param[in,out] p_uart_uid User id for the UART module. The p_uart_uid must be used if - * re-initialization and/or closing of the UART module is needed. - * If the value pointed to by p_uart_uid is zero, this is - * considdered a first time initialization. Otherwise this is - * considered a re-initialization for the user with id *p_uart_uid. - * - * @retval NRF_SUCCESS If successful initialization. - * @retval NRF_ERROR_INVALID_LENGTH If a provided buffer is not a power of two. - * @retval NRF_ERROR_NULL If one of the provided buffers is a NULL pointer. - * - * Those errors are propagated by the UART module to the caller upon registration when Hardware Flow - * Control is enabled. When Hardware Flow Control is not used, those errors cannot occur. - * @retval NRF_ERROR_INVALID_STATE The GPIOTE module is not in a valid state when registering - * the UART module as a user. - * @retval NRF_ERROR_INVALID_PARAM The UART module provides an invalid callback function when - * registering the UART module as a user. - * Or the value pointed to by *p_uart_uid is not a valid - * GPIOTE number. - * @retval NRF_ERROR_NO_MEM GPIOTE module has reached the maximum number of users. - */ -uint32_t app_uart_init(const app_uart_comm_params_t * p_comm_params, - app_uart_buffers_t * p_buffers, - app_uart_event_handler_t error_handler, - app_irq_priority_t irq_priority, - uint16_t * p_uart_uid); - -/**@brief Function for getting a byte from the UART. - * - * @details This function will get the next byte from the RX buffer. If the RX buffer is empty - * an error code will be returned and the app_uart module will generate an event upon - * reception of the first byte which is added to the RX buffer. - * - * @param[out] p_byte Pointer to an address where next byte received on the UART will be copied. - * - * @retval NRF_SUCCESS If a byte has been received and pushed to the pointer provided. - * @retval NRF_ERROR_NOT_FOUND If no byte is available in the RX buffer of the app_uart module. - */ -uint32_t app_uart_get(uint8_t * p_byte); - -/**@brief Function for putting a byte on the UART. - * - * @details This call is non-blocking. - * - * @param[in] byte Byte to be transmitted on the UART. - * - * @retval NRF_SUCCESS If the byte was succesfully put on the TX buffer for transmission. - * @retval NRF_ERROR_NO_MEM If no more space is available in the TX buffer. - * NRF_ERROR_NO_MEM may occur if flow control is enabled and CTS signal - * is high for a long period and the buffer fills up. - */ -uint32_t app_uart_put(uint8_t byte); - -/**@brief Function for getting the current state of the UART. - * - * @details If flow control is disabled, the state is assumed to always be APP_UART_CONNECTED. - * - * When using flow control the state will be controlled by the CTS. If CTS is set active - * by the remote side, or the app_uart module is in the process of transmitting a byte, - * app_uart is in APP_UART_CONNECTED state. If CTS is set inactive by remote side app_uart - * will not get into APP_UART_DISCONNECTED state until the last byte in the TXD register - * is fully transmitted. - * - * Internal states in the state machine are mapped to the general connected/disconnected - * states in the following ways: - * - * - UART_ON = CONNECTED - * - UART_READY = CONNECTED - * - UART_WAIT = CONNECTED - * - UART_OFF = DISCONNECTED. - * - * @param[out] p_connection_state Current connection state of the UART. - * - * @retval NRF_SUCCESS The connection state was succesfully retrieved. - */ -uint32_t app_uart_get_connection_state(app_uart_connection_state_t * p_connection_state); - -/**@brief Function for flushing the RX and TX buffers (Only valid if FIFO is used). - * This function does nothing if FIFO is not used. - * - * @retval NRF_SUCCESS Flushing completed (Current implementation will always succeed). - */ -uint32_t app_uart_flush(void); - -/**@brief Function for closing the UART module. - * - * @details This function will close any on-going UART transmissions and disable itself in the - * GPTIO module. - * - * @param[in] app_uart_uid User id for the UART module. The app_uart_uid must be identical to the - * UART id returned on initialization and which is currently in use. - - * @retval NRF_SUCCESS If successfully closed. - * @retval NRF_ERROR_INVALID_PARAM If an invalid user id is provided or the user id differs from - * the current active user. - */ -uint32_t app_uart_close(uint16_t app_uart_id); - - -#endif // APP_UART_H__ - -/** @} */ diff --git a/libraries/ble/nRF51822/nordic/nrf-sdk/app_common/app_util.h b/libraries/ble/nRF51822/nordic/nrf-sdk/app_common/app_util.h deleted file mode 100644 index 241cf25e01..0000000000 --- a/libraries/ble/nRF51822/nordic/nrf-sdk/app_common/app_util.h +++ /dev/null @@ -1,308 +0,0 @@ -/* Copyright (c) 2012 Nordic Semiconductor. All Rights Reserved. - * - * The information contained herein is property of Nordic Semiconductor ASA. - * Terms and conditions of usage are described in detail in NORDIC - * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. - * - * Licensees are granted free, non-transferable use of the information. NO - * WARRANTY of ANY KIND is provided. This heading must NOT be removed from - * the file. - * - */ - -/** @file - * - * @defgroup app_util Utility Functions and Definitions - * @{ - * @ingroup app_common - * - * @brief Various types and definitions available to all applications. - */ - -#ifndef APP_UTIL_H__ -#define APP_UTIL_H__ - -#include -#include "nordic_global.h" -#include "compiler_abstraction.h" -#include "nrf51.h" -#include "app_error.h" - -/**@brief The interrupt priorities available to the application while the softdevice is active. */ -typedef enum -{ - APP_IRQ_PRIORITY_HIGH = 1, - APP_IRQ_PRIORITY_LOW = 3 -} app_irq_priority_t; - -enum -{ - UNIT_0_625_MS = 625, /**< Number of microseconds in 0.625 milliseconds. */ - UNIT_1_25_MS = 1250, /**< Number of microseconds in 1.25 milliseconds. */ - UNIT_10_MS = 10000 /**< Number of microseconds in 10 milliseconds. */ -}; - -#define NRF_APP_PRIORITY_THREAD 4 /**< "Interrupt level" when running in Thread Mode. */ - -/**@cond NO_DOXYGEN */ -#define EXTERNAL_INT_VECTOR_OFFSET 16 -/**@endcond */ - -#define PACKED(TYPE) __packed TYPE - -/**@brief Macro for doing static (i.e. compile time) assertion. - * - * @note If the assertion fails when compiling using Keil, the compiler will report error message - * "error: #94: the size of an array must be greater than zero" (while gcc will list the - * symbol static_assert_failed, making the error message more readable). - * If the supplied expression can not be evaluated at compile time, Keil will report - * "error: #28: expression must have a constant value". - * - * @note The macro is intentionally implemented not using do while(0), allowing it to be used - * outside function blocks (e.g. close to global type- and variable declarations). - * If used in a code block, it must be used before any executable code in this block. - * - * @param[in] EXPR Constant expression to be verified. - */ - -#define STATIC_ASSERT(EXPR) typedef char static_assert_failed[(EXPR) ? 1 : -1] - -/**@brief type for holding an encoded (i.e. little endian) 16 bit unsigned integer. */ -typedef uint8_t uint16_le_t[2]; - -/**@brief type for holding an encoded (i.e. little endian) 32 bit unsigned integer. */ -typedef uint8_t uint32_le_t[4]; - -/**@brief Byte array type. */ -typedef struct -{ - uint16_t size; /**< Number of array entries. */ - uint8_t * p_data; /**< Pointer to array entries. */ -} uint8_array_t; - -/**@brief Macro for entering a critical region. - * - * @note Due to implementation details, there must exist one and only one call to - * CRITICAL_REGION_EXIT() for each call to CRITICAL_REGION_ENTER(), and they must be located - * in the same scope. - */ -#define CRITICAL_REGION_ENTER() \ - { \ - uint8_t IS_NESTED_CRITICAL_REGION = 0; \ - uint32_t CURRENT_INT_PRI = current_int_priority_get(); \ - if (CURRENT_INT_PRI != APP_IRQ_PRIORITY_HIGH) \ - { \ - uint32_t ERR_CODE = sd_nvic_critical_region_enter(&IS_NESTED_CRITICAL_REGION); \ - if (ERR_CODE == NRF_ERROR_SOFTDEVICE_NOT_ENABLED) \ - { \ - __disable_irq(); \ - } \ - else \ - { \ - APP_ERROR_CHECK(ERR_CODE); \ - } \ - } - -/**@brief Macro for leaving a critical region. - * - * @note Due to implementation details, there must exist one and only one call to - * CRITICAL_REGION_EXIT() for each call to CRITICAL_REGION_ENTER(), and they must be located - * in the same scope. - */ -#define CRITICAL_REGION_EXIT() \ - if (CURRENT_INT_PRI != APP_IRQ_PRIORITY_HIGH) \ - { \ - uint32_t ERR_CODE; \ - __enable_irq(); \ - ERR_CODE = sd_nvic_critical_region_exit(IS_NESTED_CRITICAL_REGION); \ - if (ERR_CODE != NRF_ERROR_SOFTDEVICE_NOT_ENABLED) \ - { \ - APP_ERROR_CHECK(ERR_CODE); \ - } \ - } \ - } - -/**@brief Perform rounded integer division (as opposed to truncating the result). - * - * @param[in] A Numerator. - * @param[in] B Denominator. - * - * @return Rounded (integer) result of dividing A by B. - */ -#define ROUNDED_DIV(A, B) (((A) + ((B) / 2)) / (B)) - -/**@brief Check if the integer provided is a power of two. - * - * @param[in] A Number to be tested. - * - * @return true if value is power of two. - * @return false if value not power of two. - */ -#define IS_POWER_OF_TWO(A) ( ((A) != 0) && ((((A) - 1) & (A)) == 0) ) - -/**@brief To convert ticks to millisecond - * @param[in] time Number of millseconds that needs to be converted. - * @param[in] resolution Units to be converted. - */ -#define MSEC_TO_UNITS(TIME, RESOLUTION) (((TIME) * 1000) / (RESOLUTION)) - - -/**@brief Perform integer division, making sure the result is rounded up. - * - * @details One typical use for this is to compute the number of objects with size B is needed to - * hold A number of bytes. - * - * @param[in] A Numerator. - * @param[in] B Denominator. - * - * @return Integer result of dividing A by B, rounded up. - */ -#define CEIL_DIV(A, B) \ - /*lint -save -e573 */ \ - ((((A) - 1) / (B)) + 1) \ - /*lint -restore */ - -/**@brief Function for encoding a uint16 value. - * - * @param[in] value Value to be encoded. - * @param[out] p_encoded_data Buffer where the encoded data is to be written. - * - * @return Number of bytes written. - */ -static __INLINE uint8_t uint16_encode(uint16_t value, uint8_t * p_encoded_data) -{ - p_encoded_data[0] = (uint8_t) ((value & 0x00FF) >> 0); - p_encoded_data[1] = (uint8_t) ((value & 0xFF00) >> 8); - return sizeof(uint16_t); -} - -/**@brief Function for encoding a uint32 value. - * - * @param[in] value Value to be encoded. - * @param[out] p_encoded_data Buffer where the encoded data is to be written. - * - * @return Number of bytes written. - */ -static __INLINE uint8_t uint32_encode(uint32_t value, uint8_t * p_encoded_data) -{ - p_encoded_data[0] = (uint8_t) ((value & 0x000000FF) >> 0); - p_encoded_data[1] = (uint8_t) ((value & 0x0000FF00) >> 8); - p_encoded_data[2] = (uint8_t) ((value & 0x00FF0000) >> 16); - p_encoded_data[3] = (uint8_t) ((value & 0xFF000000) >> 24); - return sizeof(uint32_t); -} - -/**@brief Function for decoding a uint16 value. - * - * @param[in] p_encoded_data Buffer where the encoded data is stored. - * - * @return Decoded value. - */ -static __INLINE uint16_t uint16_decode(const uint8_t * p_encoded_data) -{ - return ( (((uint16_t)((uint8_t *)p_encoded_data)[0])) | - (((uint16_t)((uint8_t *)p_encoded_data)[1]) << 8 )); -} - -/**@brief Function for decoding a uint32 value. - * - * @param[in] p_encoded_data Buffer where the encoded data is stored. - * - * @return Decoded value. - */ -static __INLINE uint32_t uint32_decode(const uint8_t * p_encoded_data) -{ - return ( (((uint32_t)((uint8_t *)p_encoded_data)[0]) << 0) | - (((uint32_t)((uint8_t *)p_encoded_data)[1]) << 8) | - (((uint32_t)((uint8_t *)p_encoded_data)[2]) << 16) | - (((uint32_t)((uint8_t *)p_encoded_data)[3]) << 24 )); -} - - -/**@brief Function for finding the current interrupt level. - * - * @return Current interrupt level. - * @retval APP_IRQ_PRIORITY_HIGH We are running in Application High interrupt level. - * @retval APP_IRQ_PRIORITY_LOW We are running in Application Low interrupt level. - * @retval APP_IRQ_PRIORITY_THREAD We are running in Thread Mode. - */ -static __INLINE uint8_t current_int_priority_get(void) -{ - uint32_t isr_vector_num = (SCB->ICSR & SCB_ICSR_VECTACTIVE_Msk); - if (isr_vector_num > 0) - { - int32_t irq_type = ((int32_t)isr_vector_num - EXTERNAL_INT_VECTOR_OFFSET); - return (NVIC_GetPriority((IRQn_Type)irq_type) & 0xFF); - } - else - { - return NRF_APP_PRIORITY_THREAD; - } -} - -/** @brief Function for converting the input voltage (in milli volts) into percentage of 3.0 Volts. - * - * @details The calculation is based on a linearized version of the battery's discharge - * curve. 3.0V returns 100% battery level. The limit for power failure is 2.1V and - * is considered to be the lower boundary. - * - * The discharge curve for CR2032 is non-linear. In this model it is split into - * 4 linear sections: - * - Section 1: 3.0V - 2.9V = 100% - 42% (58% drop on 100 mV) - * - Section 2: 2.9V - 2.74V = 42% - 18% (24% drop on 160 mV) - * - Section 3: 2.74V - 2.44V = 18% - 6% (12% drop on 300 mV) - * - Section 4: 2.44V - 2.1V = 6% - 0% (6% drop on 340 mV) - * - * These numbers are by no means accurate. Temperature and - * load in the actual application is not accounted for! - * - * @param[in] mvolts The voltage in mV - * - * @return Battery level in percent. -*/ -static __INLINE uint8_t battery_level_in_percent(const uint16_t mvolts) -{ - uint8_t battery_level; - - if (mvolts >= 3000) - { - battery_level = 100; - } - else if (mvolts > 2900) - { - battery_level = 100 - ((3000 - mvolts) * 58) / 100; - } - else if (mvolts > 2740) - { - battery_level = 42 - ((2900 - mvolts) * 24) / 160; - } - else if (mvolts > 2440) - { - battery_level = 18 - ((2740 - mvolts) * 12) / 300; - } - else if (mvolts > 2100) - { - battery_level = 6 - ((2440 - mvolts) * 6) / 340; - } - else - { - battery_level = 0; - } - - return battery_level; -} - -/**@brief Function for checking if a pointer value is aligned to a 4 byte boundary. - * - * @param[in] p Pointer value to be checked. - * - * @return TRUE if pointer is aligned to a 4 byte boundary, FALSE otherwise. - */ -static __INLINE bool is_word_aligned(void * p) -{ - return (((uint32_t)p & 0x00000003) == 0); -} - -#endif // APP_UTIL_H__ - -/** @} */ diff --git a/libraries/ble/nRF51822/nordic/nrf-sdk/app_common/crc16.h b/libraries/ble/nRF51822/nordic/nrf-sdk/app_common/crc16.h deleted file mode 100644 index 8aa779e4ab..0000000000 --- a/libraries/ble/nRF51822/nordic/nrf-sdk/app_common/crc16.h +++ /dev/null @@ -1,44 +0,0 @@ -/* Copyright (c) 2013 Nordic Semiconductor. All Rights Reserved. - * - * The information contained herein is property of Nordic Semiconductor ASA. - * Terms and conditions of usage are described in detail in NORDIC - * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. - * - * Licensees are granted free, non-transferable use of the information. NO - * WARRANTY of ANY KIND is provided. This heading must NOT be removed from - * the file. - * - */ - -/** @file - * - * @defgroup crc_compute CRC compute - * @{ - * @ingroup hci_transport - * - * @brief This module implements the CRC-16 calculation in the blocks. - */ - -#ifndef CRC16_H__ -#define CRC16_H__ - -#include -#include "nordic_global.h" - -/**@brief Function for calculating CRC-16 in blocks. - * - * Feed each consecutive data block into this function, along with the current value of p_crc as - * returned by the previous call of this function. The first call of this function should pass NULL - * as the initial value of the crc in p_crc. - * - * @param[in] p_data The input data block for computation. - * @param[in] size The size of the input data block in bytes. - * @param[in] p_crc The previous calculated CRC-16 value or NULL if first call. - * - * @return The updated CRC-16 value, based on the input supplied. - */ -uint16_t crc16_compute(const uint8_t * p_data, uint32_t size, const uint16_t * p_crc); - -#endif // CRC16_H__ - -/** @} */ diff --git a/libraries/ble/nRF51822/nordic/nrf-sdk/app_common/hci_mem_pool.h b/libraries/ble/nRF51822/nordic/nrf-sdk/app_common/hci_mem_pool.h deleted file mode 100644 index 6c5016fd72..0000000000 --- a/libraries/ble/nRF51822/nordic/nrf-sdk/app_common/hci_mem_pool.h +++ /dev/null @@ -1,133 +0,0 @@ -/* Copyright (c) 2013 Nordic Semiconductor. All Rights Reserved. - * - * The information contained herein is property of Nordic Semiconductor ASA. - * Terms and conditions of usage are described in detail in NORDIC - * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. - * - * Licensees are granted free, non-transferable use of the information. NO - * WARRANTY of ANY KIND is provided. This heading must NOT be removed from - * the file. - * - */ - -/** @file - * - * @defgroup memory_pool Memory pool - * @{ - * @ingroup app_common - * - * @brief Memory pool implementation - * - * Memory pool implementation, based on circular buffer data structure, which supports asynchronous - * processing of RX data. The current default implementation supports 1 TX buffer and 4 RX buffers. - * The memory managed by the pool is allocated from static storage instead of heap. The internal - * design of the circular buffer implementing the RX memory layout is illustrated in the picture - * below. - * - * @image html memory_pool.png "Circular buffer design" - * - * The expected call order for the RX APIs is as follows: - * - hci_mem_pool_rx_produce - * - hci_mem_pool_rx_data_size_set - * - hci_mem_pool_rx_extract - * - hci_mem_pool_rx_consume - * - * @warning If the above mentioned expected call order is violated the end result can be undefined. - * - * \par Component specific configuration options - * - * The following compile time configuration options are available to suit various implementations: - * - TX_BUF_SIZE TX buffer size in bytes. - * - RX_BUF_SIZE RX buffer size in bytes. - * - RX_BUF_QUEUE_SIZE RX buffer element size. - */ - -#ifndef HCI_MEM_POOL_H__ -#define HCI_MEM_POOL_H__ - -#include -#include "nordic_global.h" -#include "nrf_error.h" - -/**@brief Function for opening the module. - * - * @retval NRF_SUCCESS Operation success. - */ -uint32_t hci_mem_pool_open(void); - -/**@brief Function for closing the module. - * - * @retval NRF_SUCCESS Operation success. - */ -uint32_t hci_mem_pool_close(void); - -/**@brief Function for allocating requested amount of TX memory. - * - * @param[out] pp_buffer Pointer to the allocated memory. - * - * @retval NRF_SUCCESS Operation success. Memory was allocated. - * @retval NRF_ERROR_NO_MEM Operation failure. No memory available for allocation. - * @retval NRF_ERROR_NULL Operation failure. NULL pointer supplied. - */ -uint32_t hci_mem_pool_tx_alloc(void ** pp_buffer); - -/**@brief Function for freeing previously allocated TX memory. - * - * @note Memory management follows the FIFO principle meaning that free() order must match the - * alloc(...) order, which is the reason for omitting exact memory block identifier as an - * input parameter. - * - * @retval NRF_SUCCESS Operation success. Memory was freed. - */ -uint32_t hci_mem_pool_tx_free(void); - -/**@brief Function for producing a free RX memory block for usage. - * - * @note Upon produce request amount being 0, NRF_SUCCESS is returned. - * - * @param[in] length Amount, in bytes, of free memory to be produced. - * @param[out] pp_buffer Pointer to the allocated memory. - * - * @retval NRF_SUCCESS Operation success. Free RX memory block produced. - * @retval NRF_ERROR_NO_MEM Operation failure. No suitable memory available for allocation. - * @retval NRF_ERROR_DATA_SIZE Operation failure. Request size exceeds limit. - * @retval NRF_ERROR_NULL Operation failure. NULL pointer supplied. - */ -uint32_t hci_mem_pool_rx_produce(uint32_t length, void ** pp_buffer); - -/**@brief Function for setting the length of the last produced RX memory block. - * - * @warning If call to this API is omitted the end result is that the following call to - * mem_pool_rx_extract will return incorrect data in the p_length output parameter. - * - * @param[in] length Amount, in bytes, of actual memory used. - * - * @retval NRF_SUCCESS Operation success. Length was set. - */ -uint32_t hci_mem_pool_rx_data_size_set(uint32_t length); - -/**@brief Function for extracting a packet, which has been filled with read data, for further - * processing. - * - * @param[out] pp_buffer Pointer to the packet data. - * @param[out] p_length Length of packet data in bytes. - * - * @retval NRF_SUCCESS Operation success. - * @retval NRF_ERROR_NO_MEM Operation failure. No packet available to extract. - * @retval NRF_ERROR_NULL Operation failure. NULL pointer supplied. - */ -uint32_t hci_mem_pool_rx_extract(uint8_t ** pp_buffer, uint32_t * p_length); - -/**@brief Function for freeing previously extracted packet, which has been filled with read data. - * - * @param[in] p_buffer Pointer to consumed buffer. - * - * @retval NRF_SUCCESS Operation success. - * @retval NRF_ERROR_NO_MEM Operation failure. No packet available to free. - * @retval NRF_ERROR_INVALID_ADDR Operation failure. Not a valid pointer. - */ -uint32_t hci_mem_pool_rx_consume(uint8_t * p_buffer); - -#endif // HCI_MEM_POOL_H__ - -/** @} */ diff --git a/libraries/ble/nRF51822/nordic/nrf-sdk/app_common/hci_mem_pool_internal.h b/libraries/ble/nRF51822/nordic/nrf-sdk/app_common/hci_mem_pool_internal.h deleted file mode 100644 index f1fa77fea6..0000000000 --- a/libraries/ble/nRF51822/nordic/nrf-sdk/app_common/hci_mem_pool_internal.h +++ /dev/null @@ -1,32 +0,0 @@ -/* Copyright (c) 2013 Nordic Semiconductor. All Rights Reserved. - * - * The information contained herein is property of Nordic Semiconductor ASA. - * Terms and conditions of usage are described in detail in NORDIC - * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. - * - * Licensees are granted free, non-transferable use of the information. NO - * WARRANTY of ANY KIND is provided. This heading must NOT be removed from - * the file. - * - */ - -/** @file - * - * @defgroup memory_pool_internal Memory Pool Internal - * @{ - * @ingroup memory_pool - * - * @brief Memory pool internal definitions - */ - -#ifndef MEM_POOL_INTERNAL_H__ -#define MEM_POOL_INTERNAL_H__ - -#define TX_BUF_SIZE 600u /**< TX buffer size in bytes. */ -#define RX_BUF_SIZE TX_BUF_SIZE /**< RX buffer size in bytes. */ - -#define RX_BUF_QUEUE_SIZE 4u /**< RX buffer element size. */ - -#endif // MEM_POOL_INTERNAL_H__ - -/** @} */ diff --git a/libraries/ble/nRF51822/nordic/nrf-sdk/app_common/hci_slip.h b/libraries/ble/nRF51822/nordic/nrf-sdk/app_common/hci_slip.h deleted file mode 100644 index d6205f6cfd..0000000000 --- a/libraries/ble/nRF51822/nordic/nrf-sdk/app_common/hci_slip.h +++ /dev/null @@ -1,130 +0,0 @@ -/* Copyright (c) 2013 Nordic Semiconductor. All Rights Reserved. - * - * The information contained herein is property of Nordic Semiconductor ASA. - * Terms and conditions of usage are described in detail in NORDIC - * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. - * - * Licensees are granted free, non-transferable use of the information. NO - * WARRANTY of ANY KIND is provided. This heading must NOT be removed from - * the file. - * - */ - -/** @file - * - * @defgroup hci_slip SLIP module - * @{ - * @ingroup app_common - * - * @brief SLIP layer for supporting packet framing in HCI transport. - * - * @details This module implements SLIP packet framing as described in the Bluetooth Core - * Specification 4.0, Volume 4, Part D, Chapter 3 SLIP Layer. - * - * SLIP framing ensures that all packets sent on the UART are framed as: - * <0xC0> SLIP packet 1 <0xC0> <0xC0> SLIP packet 2 <0xC0>. - * - * The SLIP layer uses events to notify the upper layer when data transmission is complete - * and when a SLIP packet is received. - */ - -#ifndef HCI_SLIP_H__ -#define HCI_SLIP_H__ - -#include -#include "nordic_global.h" - -/**@brief Event types from the SLIP Layer. */ -typedef enum -{ - HCI_SLIP_RX_RDY, /**< An event indicating that an RX packet is ready to be read. */ - HCI_SLIP_TX_DONE, /**< An event indicating write completion of the TX packet provided in the function call \ref hci_slip_write . */ - HCI_SLIP_RX_OVERFLOW, /**< An event indicating that RX data has been discarded due to lack of free RX memory. */ - HCI_SLIP_ERROR, /**< An event indicating that an unrecoverable error has occurred. */ - HCI_SLIP_EVT_TYPE_MAX /**< Enumeration upper bound. */ -} hci_slip_evt_type_t; - -/**@brief Structure containing an event from the SLIP layer. - */ -typedef struct -{ - hci_slip_evt_type_t evt_type; /**< Type of event. */ - const uint8_t * packet; /**< This field contains a pointer to the packet for which the event relates, i.e. SLIP_TX_DONE: the packet transmitted, SLIP_RX_RDY: the packet received, SLIP_RX_OVERFLOW: The packet which overflow/or NULL if no receive buffer is available. */ - uint32_t packet_length; /**< Packet length, i.e. SLIP_TX_DONE: Bytes transmitted, SLIP_RX_RDY: Bytes received, SLIP_RX_OVERFLOW: index at which the packet overflowed. */ -} hci_slip_evt_t; - -/**@brief Function for the SLIP layer event callback. - */ -typedef void (*hci_slip_event_handler_t)(hci_slip_evt_t event); - -/**@brief Function for registering the event handler provided as parameter and this event handler - * will be used by SLIP layer to send events described in \ref hci_slip_evt_type_t. - * - * @note Multiple registration requests will overwrite any existing registration. - * - * @param[in] event_handler This function is called by the SLIP layer upon an event. - * - * @retval NRF_SUCCESS Operation success. - */ -uint32_t hci_slip_evt_handler_register(hci_slip_event_handler_t event_handler); - -/**@brief Function for opening the SLIP layer. This function must be called before - * \ref hci_slip_write and before any data can be received. - * - * @note Can be called multiple times. - * - * @retval NRF_SUCCESS Operation success. - * - * The SLIP layer module will propagate errors from underlying sub-modules. - * This implementation is using UART module as a physical transmission layer, and hci_slip_open - * executes \ref app_uart_init . For an extended error list, please refer to \ref app_uart_init . - */ -uint32_t hci_slip_open(void); - -/**@brief Function for closing the SLIP layer. After this function is called no data can be - * transmitted or received in this layer. - * - * @note This function can be called multiple times and also for an unopened channel. - * - * @retval NRF_SUCCESS Operation success. - */ -uint32_t hci_slip_close(void); - -/**@brief Function for writing a packet with SLIP encoding. Packet transmission is confirmed when - * the HCI_SLIP_TX_DONE event is received by the function caller. - * - * @param[in] p_buffer Pointer to the packet to transmit. - * @param[in] length Packet length, in bytes. - * - * @retval NRF_SUCCESS Operation success. Packet was encoded and added to the - * transmission queue and an event will be sent upon transmission - * completion. - * @retval NRF_ERROR_NO_MEM Operation failure. Transmission queue is full and packet was not - * added to the transmission queue. Application shall wait for - * the \ref HCI_SLIP_TX_DONE event. After HCI_SLIP_TX_DONE this - * function can be executed for transmission of next packet. - * @retval NRF_ERROR_INVALID_ADDR If a NULL pointer is provided. - * @retval NRF_ERROR_INVALID_STATE Operation failure. Module is not open. - */ -uint32_t hci_slip_write(const uint8_t * p_buffer, uint32_t length); - -/**@brief Function for registering a receive buffer. The receive buffer will be used for storage of - * received and SLIP decoded data. - * No data can be received by the SLIP layer until a receive buffer has been registered. - * - * @note The lifetime of the buffer must be valid during complete reception of data. A static - * buffer is recommended. - * - * @warning Multiple registration requests will overwrite any existing registration. - * - * @param[in] p_buffer Pointer to receive buffer. The received and SLIP decoded packet - * will be placed in this buffer. - * @param[in] length Buffer length, in bytes. - * - * @retval NRF_SUCCESS Operation success. - */ -uint32_t hci_slip_rx_buffer_register(uint8_t * p_buffer, uint32_t length); - -#endif // HCI_SLIP_H__ - -/** @} */ diff --git a/libraries/ble/nRF51822/nordic/nrf-sdk/app_common/hci_transport.h b/libraries/ble/nRF51822/nordic/nrf-sdk/app_common/hci_transport.h deleted file mode 100644 index d29fbe46c9..0000000000 --- a/libraries/ble/nRF51822/nordic/nrf-sdk/app_common/hci_transport.h +++ /dev/null @@ -1,221 +0,0 @@ -/* Copyright (c) 2013 Nordic Semiconductor. All Rights Reserved. - * - * The information contained herein is property of Nordic Semiconductor ASA. - * Terms and conditions of usage are described in detail in NORDIC - * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. - * - * Licensees are granted free, non-transferable use of the information. NO - * WARRANTY of ANY KIND is provided. This heading must NOT be removed from - * the file. - * - */ - -/**@file - * - * @defgroup hci_transport HCI Transport - * @{ - * @ingroup app_common - * - * @brief HCI transport module implementation. - * - * This module implements certain specific features from the three-wire UART transport layer, - * defined by the Bluetooth specification version 4.0 [Vol 4] part D. - * - * \par Features supported - * - Transmission and reception of Vendor Specific HCI packet type application packets. - * - Transmission and reception of reliable packets: defined by chapter 6 of the specification. - * - * \par Features not supported - * - Link establishment procedure: defined by chapter 8 of the specification. - * - Low power: defined by chapter 9 of the specification. - * - * \par Implementation specific behaviour - * - As Link establishment procedure is not supported following static link configuration parameters - * are used: - * + TX window size is 1. - * + 16 bit CCITT-CRC must be used. - * + Out of frame software flow control not supported. - * + Parameters specific for resending reliable packets are compile time configurable (clarifed - * later in this document). - * + Acknowledgement packet transmissions are not timeout driven , meaning they are delivered for - * transmission within same context which the corresponding application packet was received. - * - * \par Implementation specific limitations - * Current implementation has the following limitations which will have impact to system wide - * behaviour: - * - Delayed acknowledgement scheduling not implemented: - * There exists a possibility that acknowledgement TX packet and application TX packet will collide - * in the TX pipeline having the end result that acknowledgement packet will be excluded from the TX - * pipeline which will trigger the retransmission algorithm within the peer protocol entity. - * - Delayed retransmission scheduling not implemented: - * There exists a possibility that retransmitted application TX packet and acknowledgement TX packet - * will collide in the TX pipeline having the end result that retransmitted application TX packet - * will be excluded from the TX pipeline. - * - Processing of the acknowledgement number from RX application packets: - * Acknowledgement number is not processed from the RX application packets having the end result - * that unnecessary application packet retransmissions can occur. - * - * The application TX packet processing flow is illustrated by the statemachine below. - * - * @image html hci_transport_tx_sm.png "TX - application packet statemachine" - * - * \par Component specific configuration options - * - * The following compile time configuration options are available, and used to configure the - * application TX packet retransmission interval, in order to suite various application specific - * implementations: - * - MAC_PACKET_SIZE_IN_BITS Maximum size of a single application packet in bits. - * - USED_BAUD_RATE Used uart baudrate. - * - * The following compile time configuration option is available to configure module specific - * behaviour: - * - MAX_RETRY_COUNT Max retransmission retry count for applicaton packets. - */ - -#ifndef HCI_TRANSPORT_H__ -#define HCI_TRANSPORT_H__ - -#include -#include "nordic_global.h" -#include "nrf_error.h" - -/**@brief Generic event callback function events. */ -typedef enum -{ - HCI_TRANSPORT_RX_RDY, /**< An event indicating that RX packet is ready for read. */ - HCI_TRANSPORT_EVT_TYPE_MAX /**< Enumeration upper bound. */ -} hci_transport_evt_type_t; - -/**@brief Struct containing events from the Transport layer. - */ -typedef struct -{ - hci_transport_evt_type_t evt_type; /**< Type of event. */ -} hci_transport_evt_t; - -/**@brief Transport layer generic event callback function type. - * - * @param[in] event Transport layer event. - */ -typedef void (*hci_transport_event_handler_t)(hci_transport_evt_t event); - -/**@brief TX done event callback function result codes. */ -typedef enum -{ - HCI_TRANSPORT_TX_DONE_SUCCESS, /**< Transmission success, peer transport entity has acknowledged the transmission. */ - HCI_TRANSPORT_TX_DONE_FAILURE /**< Transmission failure. */ -} hci_transport_tx_done_result_t; - -/**@brief Transport layer TX done event callback function type. - * - * @param[in] result TX done event result code. - */ -typedef void (*hci_transport_tx_done_handler_t)(hci_transport_tx_done_result_t result); - -/**@brief Function for registering a generic event handler. - * - * @note Multiple registration requests will overwrite any possible existing registration. - * - * @param[in] event_handler The function to be called by the transport layer upon an event. - * - * @retval NRF_SUCCESS Operation success. - * @retval NRF_ERROR_NULL Operation failure. NULL pointer supplied. - */ -uint32_t hci_transport_evt_handler_reg(hci_transport_event_handler_t event_handler); - -/**@brief Function for registering a handler for TX done event. - * - * @note Multiple registration requests will overwrite any possible existing registration. - * - * @param[in] event_handler The function to be called by the transport layer upon TX done - * event. - * - * @retval NRF_SUCCESS Operation success. - * @retval NRF_ERROR_NULL Operation failure. NULL pointer supplied. - */ -uint32_t hci_transport_tx_done_register(hci_transport_tx_done_handler_t event_handler); - -/**@brief Function for opening the transport channel and initializing the transport layer. - * - * @warning Must not be called for a channel which has been allready opened. - * - * @retval NRF_SUCCESS Operation success. - * @retval NRF_ERROR_INTERNAL Operation failure. Internal error ocurred. - */ -uint32_t hci_transport_open(void); - -/**@brief Function for closing the transport channel. - * - * @note Can be called multiple times and also for not opened channel. - * - * @retval NRF_SUCCESS Operation success. - */ -uint32_t hci_transport_close(void); - -/**@brief Function for allocating tx packet memory. - * - * @param[out] pp_memory Pointer to the packet data. - * - * @retval NRF_SUCCESS Operation success. Memory was allocated. - * @retval NRF_ERROR_NO_MEM Operation failure. No memory available. - * @retval NRF_ERROR_NULL Operation failure. NULL pointer supplied. - */ -uint32_t hci_transport_tx_alloc(uint8_t ** pp_memory); - -/**@brief Function for freeing tx packet memory. - * - * @note Memory management works in FIFO principle meaning that free order must match the alloc - * order. - * - * @retval NRF_SUCCESS Operation success. Memory was freed. - */ -uint32_t hci_transport_tx_free(void); - -/**@brief Function for writing a packet. - * - * @note Completion of this method does not guarantee that actual peripheral transmission would - * have completed. - * - * @note In case of 0 byte packet length write request, message will consist of only transport - * module specific headers. - * - * @retval NRF_SUCCESS Operation success. Packet was added to the transmission queue - * and an event will be send upon transmission completion. - * @retval NRF_ERROR_NO_MEM Operation failure. Transmission queue is full and packet was not - * added to the transmission queue. User should wait for - * a appropriate event prior issuing this operation again. - * @retval NRF_ERROR_DATA_SIZE Operation failure. Packet size exceeds limit. - * @retval NRF_ERROR_NULL Operation failure. NULL pointer supplied. - * @retval NRF_ERROR_INVALID_STATE Operation failure. Channel is not open. - */ -uint32_t hci_transport_pkt_write(const uint8_t * p_buffer, uint32_t length); - -/**@brief Function for extracting received packet. - * - * @note Extracted memory can't be reused by the underlying transport layer untill freed by call to - * hci_transport_rx_pkt_consume(). - * - * @param[out] pp_buffer Pointer to the packet data. - * @param[out] p_length Length of packet data in bytes. - * - * @retval NRF_SUCCESS Operation success. Packet was extracted. - * @retval NRF_ERROR_NO_MEM Operation failure. No packet available to extract. - * @retval NRF_ERROR_NULL Operation failure. NULL pointer supplied. - */ -uint32_t hci_transport_rx_pkt_extract(uint8_t ** pp_buffer, uint32_t * p_length); - -/**@brief Function for consuming extracted packet described by p_buffer. - * - * RX memory pointed to by p_buffer is freed and can be reused by the underlying transport layer. - * - * @param[in] p_buffer Pointer to the buffer that has been consumed. - * - * @retval NRF_SUCCESS Operation success. - * @retval NRF_ERROR_NO_MEM Operation failure. No packet available to consume. - * @retval NRF_ERROR_INVALID_ADDR Operation failure. Not a valid pointer. - */ -uint32_t hci_transport_rx_pkt_consume(uint8_t * p_buffer); - -#endif // HCI_TRANSPORT_H__ - -/** @} */ diff --git a/libraries/ble/nRF51822/nordic/nrf-sdk/app_common/pstorage.h b/libraries/ble/nRF51822/nordic/nrf-sdk/app_common/pstorage.h deleted file mode 100644 index c76e59fd97..0000000000 --- a/libraries/ble/nRF51822/nordic/nrf-sdk/app_common/pstorage.h +++ /dev/null @@ -1,334 +0,0 @@ -/* Copyright (c) 2013 Nordic Semiconductor. All Rights Reserved. - * - * The information contained herein is property of Nordic Semiconductor ASA. - * Terms and conditions of usage are described in detail in NORDIC - * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. - * - * Licensees are granted free, non-transferable use of the information. NO - * WARRANTY of ANY KIND is provided. This heading must NOT be removed from - * the file. - * - */ - -/**@file - * - * @defgroup persistent_storage Persistent Storage Interface - * @{ - * @ingroup app_common - * @brief Abstracted flash interface. - * - * @details In order to ensure that the SDK and application be moved to alternate persistent storage - * options other than the default provided with NRF solution, an abstracted interface is provided - * by the module to ensure SDK modules and application can be ported to alternate option with ease. - */ - -#ifndef PSTORAGE_H__ -#define PSTORAGE_H__ - -#include "nordic_global.h" -#include "pstorage_platform.h" - - -/**@defgroup ps_opcode Persistent Storage Access Operation Codes - * @{ - * @brief Persistent Storage Access Operation Codes. These are used to report any error during - * a persistent storage access operation or any general error that may occur in the - * interface. - * - * @details Persistent Storage Access Operation Codes used in error notification callback - * registered with the interface to report any error during an persistent storage access - * operation or any general error that may occur in the interface. - */ - #define PSTORAGE_ERROR_OP_CODE 0x01 /**< General Error Code */ - #define PSTORAGE_STORE_OP_CODE 0x02 /**< Error when Store Operation was requested */ - #define PSTORAGE_LOAD_OP_CODE 0x03 /**< Error when Load Operation was requested */ - #define PSTORAGE_CLEAR_OP_CODE 0x04 /**< Error when Clear Operation was requested */ - -/**@} */ - -/**@defgroup pstorage_data_types Persistent Memory Interface Data Types - * @{ - * @brief Data Types needed for interfacing with persistent memory. - * - * @details Data Types needed for interfacing with persistent memory. - */ - -/**@brief Persistent Storage Error Reporting Callback - * - * @details Persistent Storage Error Reporting Callback that is used by the interface to report - * success or failure of a flash operation. Therefore, for store operation or clear - * operations, that take time, application can know when the procedure was complete. - * For store operation, since no data copy is made, receiving a success or failure - * notification, indicated by the reason parameter of callback is an indication that - * the resident memory could now be reused or freed, as the case may be. - * This callback is not received for load operation. - * - * @param handle Identifies module and block for which callback is received. - * @param op_code Identifies the operation for which the event is notified. - * @param result Identifies the result of flash access operation. - * NRF_SUCCESS implies, operation succeeded. - * @param p_data Identifies the application data pointer. In case of store operation, this points - * to the resident source of application memory that application can now free or - * reuse. In case of clear, this is NULL as no application pointer is needed for - * this operation. - * @param data_len Length data application had provided for the operation. - * - */ -typedef void (*pstorage_ntf_cb_t)(pstorage_handle_t * p_handle, - uint8_t op_code, - uint32_t result, - uint8_t * p_data, - uint32_t data_len); - - -typedef struct ps_module_param -{ - - pstorage_ntf_cb_t cb; /**< Callback registered with the module to be notified of any error occurring in persistent memory management */ - pstorage_size_t block_size; /**< Desired block size for persistent memory storage, for example, if a module has a table with 10 entries, each entry is size 64 bytes, - * it can request 10 blocks with block size 64 bytes. On the other hand, the module can also request one block of size 640 based on - * how it would like to access or alter memory in persistent memory. - * First option is preferred when single entries that need to be updated often when having no impact on the other entries. - * While second option is preferred when entries of table are not changed on individually but have common point of loading and storing - * data. - */ - pstorage_size_t block_count; /** Number of blocks requested by the module, minimum values is 1. */ - -} pstorage_module_param_t; - -/**@} */ - -/**@defgroup pstorage_routines Persistent Storage Access Routines - * @{ - * @brief Functions/Interface SDK modules use to persistently store data. - * - * @details Interface for Application & SDK module to load/store information persistently. - * Note: that while implementation of each of the persistent storage access function - * depends on the system and can specific to system/solution, the signature of the - * interface routines should not be altered. - */ - -/**@brief Module Initialization Routine. - * - * @details Initializes module. To be called once before any other APIs of the module are used. - * - * @retval NRF_SUCCESS on success, otherwise an appropriate error code. - */ -uint32_t pstorage_init(void); - - -/**@brief Register with persistent storage interface. - * - * @param[in] p_module_param Module registration param. - * @param[out] p_block_id Block identifier to identify persistent memory blocks in case registration - * succeeds. Application is expected to use the block ids for subsequent operations on - * requested persistent memory. Maximum registrations permitted is determined by - * configuration parameter PSTORAGE_MAX_APPLICATIONS. - * In case more than one memory blocks are requested, the identifier provided here is - * the base identifier for the first block and to identify subsequent block, - * application shall use \@ref pstorage_block_identifier_get with this base identifier - * and block number. Therefore if 10 blocks of size 64 are requested and application - * wishes to store memory in 6th block, it shall use - * \@ref pstorage_block_identifier_get with based id and provide a block number of 5. - * This way application is only expected to remember the base block identifier. - * - * @retval NRF_SUCCESS on success, otherwise an appropriate error code. - * @retval NRF_ERROR_INVALID_STATE is returned is API is called without module initialization. - * @retval NRF_ERROR_NULL if NULL parameter has been passed. - * @retval NRF_ERROR_INVALID_PARAM if invalid parameters are passed to the API. - * @retval NRF_ERROR_NO_MEM in case no more registrations can be supported. - */ -uint32_t pstorage_register(pstorage_module_param_t * p_module_param, - pstorage_handle_t* p_block_id); - - -/** - * @brief Function to get block id with reference to base block identifier provided at time of - * registration. - * - * @details Function to get block id with reference to base block identifier provided at time of - * registration. - * In case more than one memory blocks were requested when registering, the identifier - * provided here is the base identifier for the first block and to identify subsequent - * block, application shall use this routine to get block identifier providing input as - * base identifier and block number. Therefore if 10 blocks of size 64 are requested and - * application wishes to store memory in 6th block, it shall use - * \@ref pstorage_block_identifier_get with based id and provide a block number of 5. - * This way application is only expected to remember the base block identifier. - * - * @param[in] p_base_id Base block id received at the time of registration. - * @param[in] block_num Block Number, with first block numbered zero. - * @param[out] p_block_id Block identifier for the block number requested in case the API succeeds. - * - * @retval NRF_SUCCESS on success, else an error code indicating reason for failure. - * @retval NRF_ERROR_INVALID_STATE is returned is API is called without module initialization. - * @retval NRF_ERROR_NULL if NULL parameter has been passed. - * @retval NRF_ERROR_INVALID_PARAM if invalid parameters are passed to the API. - */ -uint32_t pstorage_block_identifier_get(pstorage_handle_t * p_base_id, - pstorage_size_t block_num, - pstorage_handle_t * p_block_id); - - -/**@brief Routine to persistently store data of length 'size' contained in 'p_src' address - * in storage module at 'p_dest' address; Equivalent to Storage Write. - * - * @param[in] p_dest Destination address where data is to be stored persistently. - * @param[in] p_src Source address containing data to be stored. API assumes this to be resident - * memory and no intermediate copy of data is made by the API. - * @param[in] size Size of data to be stored expressed in bytes. Should be word aligned. - * @param[in] offset Offset in bytes to be applied when writing to the block. - * For example, if within a block of 100 bytes, application wishes to - * write 20 bytes at offset of 12, then this field should be set to 12. - * Should be word aligned. - * - * @retval NRF_SUCCESS on success, otherwise an appropriate error code. - * @retval NRF_ERROR_INVALID_STATE is returned is API is called without module initialization. - * @retval NRF_ERROR_NULL if NULL parameter has been passed. - * @retval NRF_ERROR_INVALID_PARAM if invalid parameters are passed to the API. - * @retval NRF_ERROR_INVALID_ADDR in case data address 'p_src' is not aligned. - * @retval NRF_ERROR_NO_MEM in case request cannot be processed. - * - * @warning No copy of the data is made, and hence memory provided for data source to be written - * to flash cannot be freed or reused by the application until this procedure - * is complete. End of this procedure is notified to the application using the - * notification callback registered by the application. - */ -uint32_t pstorage_store(pstorage_handle_t * p_dest, - uint8_t * p_src, - pstorage_size_t size, - pstorage_size_t offset); - - -/**@brief Routine to load persistently stored data of length 'size' from 'p_src' address - * to 'p_dest' address; Equivalent to Storage Read. - * - * @param[in] p_dest Destination address where persistently stored data is to be loaded. - * @param[in] p_src Source from where data is to be loaded from persistent memory. - * @param[in] size Size of data to be loaded from persistent memory expressed in bytes. - * Should be word aligned. - * @param[in] offset Offset in bytes to be applied when loading from the block. - * For example, if within a block of 100 bytes, application wishes to - * load 20 bytes from offset of 12, then this field should be set to 12. - * Should be word aligned. - * - * - * @retval NRF_SUCCESS on success, otherwise an appropriate error code. - * @retval NRF_ERROR_INVALID_STATE is returned is API is called without module initialization. - * @retval NRF_ERROR_NULL if NULL parameter has been passed. - * @retval NRF_ERROR_INVALID_PARAM if invalid parameters are passed to the API. - * @retval NRF_ERROR_INVALID_ADDR in case data address 'p_dst' is not aligned. - */ -uint32_t pstorage_load(uint8_t * p_dest, - pstorage_handle_t * p_src, - pstorage_size_t size, - pstorage_size_t offset); - - -/**@brief Routine to clear data in persistent memory. - * - * @param[in] p_base_id Base block identifier in persistent memory that needs to cleared; - * Equivalent to an Erase Operation. - * - * @param[in] size Size of data to be cleared from persistent memory expressed in bytes. - * This is currently unused. And a clear would mean clearing all blocks, - * however, this parameter is to provision for clearing of certain blocks - * of memory only and not all if need be. - * - * @retval NRF_SUCCESS on success, otherwise an appropriate error code. - * @retval NRF_ERROR_INVALID_STATE is returned is API is called without module initialization. - * @retval NRF_ERROR_NULL if NULL parameter has been passed. - * @retval NRF_ERROR_INVALID_PARAM if invalid parameters are passed to the API. - * @retval NRF_ERROR_NO_MEM in case request cannot be processed. - * - * @note Clear operations may take time. This API however, does not block until the clear - * procedure is complete. Application is notified of procedure completion using - * notification callback registered by the application. 'result' parameter of the - * callback suggests if the procedure was successful or not. - */ -uint32_t pstorage_clear(pstorage_handle_t * p_base_id, pstorage_size_t size); - -#ifdef PSTORAGE_RAW_MODE_ENABLE - -/**@brief Function for registering with persistent storage interface. - * - * @param[in] p_module_param Module registration param. - * @param[out] p_block_id Block identifier to identify persistent memory blocks in case - * registration succeeds. Application is expected to use the block ids for subsequent - * operations on requested persistent memory. - * In case more than one memory blocks are requested, the identifier provided here is - * the base identifier for the first block and to identify subsequent block, - * application shall use \@ref pstorage_block_identifier_get with this base identifier - * and block number. Therefore if 10 blocks of size 64 are requested and application - * wishes to store memory in 6th block, it shall use - * \@ref pstorage_block_identifier_get with based id and provide a block number of 5. - * This way application is only expected to remember the base block identifier. - * - * @retval NRF_SUCCESS on success, otherwise an appropriate error code. - * @retval NRF_ERROR_INVALID_STATE is returned is API is called without module initialization. - * @retval NRF_ERROR_NULL if NULL parameter has been passed. - * @retval NRF_ERROR_INVALID_PARAM if invalid parameters are passed to the API. - * @retval NRF_ERROR_NO_MEM in case no more registrations can be supported. - */ -uint32_t pstorage_raw_register(pstorage_module_param_t * p_module_param, - pstorage_handle_t * p_block_id); - -/**@brief Raw mode function for persistently storing data of length 'size' contained in 'p_src' - * address in storage module at 'p_dest' address; Equivalent to Storage Write. - * - * @param[in] p_dest Destination address where data is to be stored persistently. - * @param[in] p_src Source address containing data to be stored. API assumes this to be resident - * memory and no intermediate copy of data is made by the API. - * @param[in] size Size of data to be stored expressed in bytes. Should be word aligned. - * @param[in] offset Offset in bytes to be applied when writing to the block. - * For example, if within a block of 100 bytes, application wishes to - * write 20 bytes at offset of 12, then this field should be set to 12. - * Should be word aligned. - * - * @retval NRF_SUCCESS on success, otherwise an appropriate error code. - * @retval NRF_ERROR_INVALID_STATE is returned is API is called without module initialization. - * @retval NRF_ERROR_NULL if NULL parameter has been passed. - * @retval NRF_ERROR_INVALID_PARAM if invalid parameters are passed to the API. - * @retval NRF_ERROR_INVALID_ADDR in case data address 'p_src' is not aligned. - * @retval NRF_ERROR_NO_MEM in case request cannot be processed. - * - * @warning No copy of the data is made, and hence memory provided for data source to be written - * to flash cannot be freed or reused by the application until this procedure - * is complete. End of this procedure is notified to the application using the - * notification callback registered by the application. - */ -uint32_t pstorage_raw_store(pstorage_handle_t * p_dest, - uint8_t * p_src, - pstorage_size_t size, - pstorage_size_t offset); - -/**@brief Function for clearing data in persistent memory in raw mode. - * - * @param[in] p_base_id Base block identifier in persistent memory that needs to cleared; - * Equivalent to an Erase Operation. - * - * @param[in] size Size of data to be cleared from persistent memory expressed in bytes. - * This is currently unused. And a clear would mean clearing all blocks, - * however, this parameter is to provision for clearing of certain blocks - * of memory only and not all if need be. - * - * @retval NRF_SUCCESS on success, otherwise an appropriate error code. - * @retval NRF_ERROR_INVALID_STATE is returned is API is called without module initialization. - * @retval NRF_ERROR_NULL if NULL parameter has been passed. - * @retval NRF_ERROR_INVALID_PARAM if invalid parameters are passed to the API. - * @retval NRF_ERROR_NO_MEM in case request cannot be processed. - * - * @note Clear operations may take time. This API however, does not block until the clear - * procedure is complete. Application is notified of procedure completion using - * notification callback registered by the application. 'result' parameter of the - * callback suggests if the procedure was successful or not. - */ -uint32_t pstorage_raw_clear(pstorage_handle_t * p_dest, pstorage_size_t size); - -#endif // PSTORAGE_RAW_MODE_ENABLE - -/**@} */ -/**@} */ - -#endif // PSTORAGE_H__ - diff --git a/libraries/ble/nRF51822/nordic/nrf-sdk/ble/ble_advdata.h b/libraries/ble/nRF51822/nordic/nrf-sdk/ble/ble_advdata.h deleted file mode 100644 index a906bae0d0..0000000000 --- a/libraries/ble/nRF51822/nordic/nrf-sdk/ble/ble_advdata.h +++ /dev/null @@ -1,114 +0,0 @@ -/* Copyright (c) 2012 Nordic Semiconductor. All Rights Reserved. - * - * The information contained herein is property of Nordic Semiconductor ASA. - * Terms and conditions of usage are described in detail in NORDIC - * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. - * - * Licensees are granted free, non-transferable use of the information. NO - * WARRANTY of ANY KIND is provided. This heading must NOT be removed from - * the file. - * - */ - -/** @file - * - * @defgroup ble_sdk_lib_advdata Advertising Data Encoder - * @{ - * @ingroup ble_sdk_lib - * @brief Function for encoding the advertising data and/or scan response data, and passing them to - * the stack. - */ - -#ifndef BLE_ADVDATA_H__ -#define BLE_ADVDATA_H__ - -#include -#include -#include -#include "nordic_global.h" -#include "ble.h" -#include "app_util.h" - -/**@brief Advertising data name type. This contains the options available for the device name inside - * the advertising data. */ -typedef enum -{ - BLE_ADVDATA_NO_NAME, /**< Include no device name in advertising data. */ - BLE_ADVDATA_SHORT_NAME, /**< Include short device name in advertising data. */ - BLE_ADVDATA_FULL_NAME /**< Include full device name in advertising data. */ -} ble_advdata_name_type_t; - -/**@brief UUID list type. */ -typedef struct -{ - uint16_t uuid_cnt; /**< Number of UUID entries. */ - ble_uuid_t * p_uuids; /**< Pointer to UUID array entries. */ -} ble_advdata_uuid_list_t; - -/**@brief Connection interval range structure. */ -typedef struct -{ - uint16_t min_conn_interval; /**< Minimum Connection Interval, in units of 1.25ms, range 6 to 3200 (i.e. 7.5ms to 4s). */ - uint16_t max_conn_interval; /**< Maximum Connection Interval, in units of 1.25ms, range 6 to 3200 (i.e. 7.5ms to 4s). Value of 0xFFFF indicates no specific maximum. */ -} ble_advdata_conn_int_t; - -/**@brief Manufacturer specific data structure. */ -typedef struct -{ - uint16_t company_identifier; /**< Company Identifier Code. */ - uint8_array_t data; /**< Additional manufacturer specific data. */ -} ble_advdata_manuf_data_t; - -/**@brief Service data structure. */ -typedef struct -{ - uint16_t service_uuid; /**< Service UUID. */ - uint8_array_t data; /**< Additional service data. */ -} ble_advdata_service_data_t; - -/**@brief Advertising data structure. This contains all options and data needed for encoding and - * setting the advertising data. */ -typedef struct -{ - ble_advdata_name_type_t name_type; /**< Type of device name. */ - uint8_t short_name_len; /**< Length of short device name (if short type is specified). */ - bool include_appearance; /**< Determines if Appearance shall be included. */ - uint8_array_t flags; /**< Advertising data Flags field. */ - int8_t * p_tx_power_level; /**< TX Power Level field. */ - ble_advdata_uuid_list_t uuids_more_available; /**< List of UUIDs in the 'More Available' list. */ - ble_advdata_uuid_list_t uuids_complete; /**< List of UUIDs in the 'Complete' list. */ - ble_advdata_uuid_list_t uuids_solicited; /**< List of solcited UUIDs. */ - ble_advdata_conn_int_t * p_slave_conn_int; /**< Slave Connection Interval Range. */ - ble_advdata_manuf_data_t * p_manuf_specific_data; /**< Manufacturer specific data. */ - ble_advdata_service_data_t * p_service_data_array; /**< Array of Service data structures. */ - uint8_t service_data_count; /**< Number of Service data structures. */ -} ble_advdata_t; - -/**@brief Function for encoding and setting the advertising data and/or scan response data. - * - * @details This function encodes advertising data and/or scan response data based on the selections - * in the supplied structures, and passes the encoded data to the stack. - * - * @param[in] p_advdata Structure for specifying the content of the advertising data. - * Set to NULL if advertising data is not to be set. - * @param[in] p_srdata Structure for specifying the content of the scan response data. - * Set to NULL if scan response data is not to be set. - * - * @return NRF_SUCCESS on success, NRF_ERROR_DATA_SIZE if not all the requested data could fit - * into the advertising packet. The maximum size of the advertisement packet is @ref - * BLE_GAP_ADV_MAX_SIZE. - * - * @warning This API may override application's request to use the long name and use a short name - * instead. This truncation will occur in case the long name does not fit advertisement data size. - * Application is permitted to specify a preferred short name length in case truncation is required. - * For example, if the complete device name is ABCD_HRMonitor, application can specify short name - * length to 8 such that short device name appears as ABCD_HRM instead of ABCD_HRMo or ABCD_HRMoni - * etc if available size for short name is 9 or 12 respectively to have more apporpriate short name. - * However, it should be noted that this is just a preference that application can specify and - * if the preference too large to fit in Advertisement Data, this can be further truncated. - */ -uint32_t ble_advdata_set(const ble_advdata_t * p_advdata, const ble_advdata_t * p_srdata); - -#endif // BLE_ADVDATA_H__ - -/** @} */ diff --git a/libraries/ble/nRF51822/nordic/nrf-sdk/ble/ble_advdata_parser.h b/libraries/ble/nRF51822/nordic/nrf-sdk/ble/ble_advdata_parser.h deleted file mode 100644 index b0f7bbc8f3..0000000000 --- a/libraries/ble/nRF51822/nordic/nrf-sdk/ble/ble_advdata_parser.h +++ /dev/null @@ -1,10 +0,0 @@ -#ifndef BLE_ADVDATA_PARSER_H_ -#define BLE_ADVDATA_PARSER_H_ - -#include "nordic_global.h" -#include "ble_advdata.h" - -uint32_t ble_advdata_parse(uint8_t * p_data, uint8_t len, ble_advdata_t * advdata); -uint32_t ble_advdata_parser_field_find(uint8_t type, uint8_t * p_advdata, uint8_t * len, uint8_t ** pp_field_data); - -#endif diff --git a/libraries/ble/nRF51822/nordic/nrf-sdk/ble/ble_bondmngr.h b/libraries/ble/nRF51822/nordic/nrf-sdk/ble/ble_bondmngr.h deleted file mode 100644 index 1416568107..0000000000 --- a/libraries/ble/nRF51822/nordic/nrf-sdk/ble/ble_bondmngr.h +++ /dev/null @@ -1,339 +0,0 @@ -/* Copyright (c) 2012 Nordic Semiconductor. All Rights Reserved. - * - * The information contained herein is property of Nordic Semiconductor ASA. - * Terms and conditions of usage are described in detail in NORDIC - * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. - * - * Licensees are granted free, non-transferable use of the information. NO - * WARRANTY of ANY KIND is provided. This heading must NOT be removed from - * the file. - * - */ - -/** @file - * - * @defgroup ble_sdk_lib_bond_manager Bonds and Persistent Data Manager - * @{ - * @ingroup ble_sdk_lib - * @brief This module handles multiple bonds and persistent attributes. - * - * @details When using Bluetooth low energy, a central device and a peripheral device can - * exchange identification information which they are capable of storing in memory (for - * example, in non-volatile memory). This information can be used for identity verification - * between the devices when they reconnect in the future. This relationship is known as a - * 'bond'. - * - * Bonding Information: - * - * The S110 SoftDevice handles the BLE on-air transactions necessary to establish a new - * bond or to use a previous bond when it reconnects to a bonded central. It is however up - * to the application layer to memorize the identification information between - * connections and to provide them back to the S110 stack when it detects a re-connection - * from a previously bonded central. This identification information is referred to as - * Bonding Information in code and the SDK. - * - * System Attributes: - * - * If the application is a GATT server, it stores a set of persistent attributes related - * to a connection when bonding with a central. On reconnection with the known bonded - * central, the application restores the related persistent attributes in the last known - * state back to the S110 SoftDevice. These persistent attributes mainly include the Client - * Characteristic Configuration Descriptor (or CCCD, see the Bluetooth - * Core Specification for more information) states and could include other attributes - * in the future. Persistent attributes are referred to as System Attributes in code and - * in the SDK documentation. - * - * An application can use the Bonds and Persistent Data Manager module (referred to as the - * bond manager) included in the nRF51 SDK to handle most of the operations related to - * the Bonding Information and System Attributes. The bond manager notifies the - * application when it's connected to a new bonded central or to a previously bonded central. - * The application can use the Bond Manager API to store or load (or restore) the - * Bonding Information and System Attributes. The bond manager identifies all the centrals - * the application is bonded to and restores their respective Bonding Information and - * System Attributes to the S110 stack. - * - * In addition, you can use the bond manager to set up your application to advertise: - * - * - To a given bonded central using directed advertisement. - * - To a list of bonded centrals - i.e. using whitelist. - * - * The bond manager automatically writes the Bonding Information to the flash memory when - * the bonding procedure to a new central is finished. Upon disconnection, the application - * should use the Bond Manager API @ref ble_bondmngr_bonded_centrals_store to write the - * latest Bonding Information and System Attributes to flash. - * - * The bond manager provides the API @ref ble_bondmngr_sys_attr_store to allow the - * application to write the System Attributes to flash while in a connection. Your - * application should call this API when it considers that all CCCDs and other persistent - * attributes are in a stable state. This API call will safely fail if System Attributes - * data for the current connected central is already present in the flash. The API does so - * because a flash write in such a situation would require an erase of flash, which takes a - * long time (21 milliseconds) to complete. This may disrupt the radio. - * - * Applications using the Bond Manager must have a configuration file named - * ble_bondmngr_cfg.h (see below for details). - * - * Refer to @ref ble_bond_mgr_msc to see the flow of events when connecting to a central - * using the Bond Manager - * - * - * @section ble_sdk_lib_bond_manager_cfg Configuration File - * Applications using the Bond Manager must have a configuration file named ble_bondmngr_cfg.h. - * Here is an example of this file: - * - * @code - * #ifndef BLE_BONDMNGR_CFG_H__ - * #define BLE_BONDMNGR_CFG_H__ - * - * #define BLE_BONDMNGR_CCCD_COUNT 1 - * #define BLE_BONDMNGR_MAX_BONDED_CENTRALS 4 - * - * #endif // BLE_BONDMNGR_CFG_H__ - * @endcode - * - * BLE_BONDMNGR_CCCD_COUNT is the number of CCCDs used in the application, and - * BLE_BONDMNGR_MAX_BONDED_CENTRALS is the maximum number of bonded centrals to be supported by the - * application. - */ - -#ifndef BLE_BONDMNGR_H__ -#define BLE_BONDMNGR_H__ - -#include -#include "nordic_global.h" -#include "ble.h" -#include "ble_srv_common.h" - - -/** @defgroup ble_bond_mgr_msc Message Sequence Charts - * @{ - * @brief Bond Manager interaction with S110 Stack - * @{ - * @defgroup UNBONDED_CENTRAL Connecting to an unbonded central - * @image html bond_manager_unbonded_master.jpg Connecting to an unbonded central - * @defgroup BONDED_CENTRAL Connecting to a bonded central - * @image html bond_manager_bonded_master.jpg Connecting to a bonded central - * @} - * @} - */ - -/** @defgroup DEFINES Defines - * @brief Macros defined by this module. - * @{ */ - -#define INVALID_CENTRAL_HANDLE (-1) /**< Invalid handle, used to indicate that the central is not a known bonded central. */ - -/** @} */ - -/** @defgroup ENUMS Enumerations - * @brief Enumerations defined by this module. - * @{ */ - -/**@brief Bond Manager Module event type. */ -typedef enum -{ - BLE_BONDMNGR_EVT_NEW_BOND, /**< New bond has been created. */ - BLE_BONDMNGR_EVT_CONN_TO_BONDED_CENTRAL, /**< Connected to a previously bonded central. */ - BLE_BONDMNGR_EVT_ENCRYPTED, /**< Current link is encrypted. */ - BLE_BONDMNGR_EVT_AUTH_STATUS_UPDATED, /**< Authentication status updated for current central. */ - BLE_BONDMNGR_EVT_BOND_FLASH_FULL /**< Flash block for storing Bonding Information is full. */ -} ble_bondmngr_evt_type_t; - -/** @} */ - - -/** @defgroup DATA_STRUCTURES Data Structures - * @brief Data Structures defined by this module. - * @{ */ - -/**@brief Bond Manager Module event. */ -typedef struct -{ - ble_bondmngr_evt_type_t evt_type; /**< Type of event. */ - int8_t central_handle; /**< Handle to the current central. This is an index to the central list maintained internally by the bond manager. */ - uint16_t central_id; /**< Identifier to the central. This will be the same as Encryption diversifier of the central (see @ref ble_gap_evt_sec_info_request_t). This value is constant for the duration of the bond. */ -} ble_bondmngr_evt_t; - -/** @} */ - -/** @defgroup TYPEDEFS Typedefs - * @brief Typedefs defined by this module. - * @{ */ - -/**@brief Bond Manager Module event handler type. */ -typedef void (*ble_bondmngr_evt_handler_t) (ble_bondmngr_evt_t * p_evt); - -/** @} */ - -/** @addtogroup DATA_STRUCTURES - * @{ */ - -/**@brief Bond Manager Module init structure. This contains all options and data needed for - * initialization of the Bond Manager module. */ -typedef struct -{ - uint8_t flash_page_num_bond; /**< Flash page number to use for storing Bonding Information. */ - uint8_t flash_page_num_sys_attr; /**< Flash page number to use for storing System Attributes. */ - bool bonds_delete; /**< TRUE if bonding and System Attributes for all centrals is to be deleted from flash during initialization, FALSE otherwise. */ - ble_bondmngr_evt_handler_t evt_handler; /**< Event handler to be called for handling events in bond manager. */ - ble_srv_error_handler_t error_handler; /**< Function to be called in case of an error. */ -} ble_bondmngr_init_t; - -/** @} */ - - -/** @defgroup FUNCTIONS Functions - * @brief Functions/APIs implemented and exposed by this module. - * @{ */ - -/**@brief Function for initializing the Bond Manager. - * - * @param[in] p_init This contains information needed to initialize this module. - * - * @return NRF_SUCCESS on successful initialization, otherwise an error code. - */ -uint32_t ble_bondmngr_init(ble_bondmngr_init_t * p_init); - -/**@brief Function for handling all events from the BLE stack that relate to this module. - * - * @param[in] p_ble_evt The event received from the BLE stack. - * - * @return NRF_SUCCESS if all operations went successfully, - * NRF_ERROR_NO_MEM if the maximum number of bonded centrals has been reached. - * Other error codes in other situations. - */ -void ble_bondmngr_on_ble_evt(ble_evt_t * p_ble_evt); - -/**@brief Function for storing the bonded centrals data including bonding info and System Attributes into - * flash memory. - * - * @details If the data to be written is different from the existing data, this function erases the - * flash pages before writing to flash. - * - * @warning This function could prevent the radio from running. Therefore it MUST be called ONLY - * when the application knows that the Bluetooth radio is not active. An example of - * such a state is when the application has received the Disconnected event and has not yet - * started advertising. If it is called in any other state, or if it is not called at - * all, the behavior is undefined. - * - * @return NRF_SUCCESS on success, an error_code otherwise. - */ -uint32_t ble_bondmngr_bonded_centrals_store(void); - -/**@brief Function for deleting the bonded central database from flash. - * - * @details After calling this function you should call ble_bondmngr_init() to re-initialize the - * RAM database. - * - * @return NRF_SUCCESS on success, an error_code otherwise. - */ -uint32_t ble_bondmngr_bonded_centrals_delete(void); - -/**@brief Function for getting the whitelist containing all currently bonded centrals. - * - * @details This function populates the whitelist with either the IRKs or the public adresses - * of all bonded centrals. - * - * @param[out] p_whitelist Whitelist structure with all bonded centrals. - * - * @return NRF_SUCCESS on success, an error_code otherwise. - */ -uint32_t ble_bondmngr_whitelist_get(ble_gap_whitelist_t * p_whitelist); - -/**@brief Function for getting the central's address corresponding to a given central_handle. - * - * @note This function returns NRF_ERROR_INVALID_PARAM if the given central has a private - * address. - * - * @param[in] central_handle Central's handle. - * @param[out] p_central_addr Pointer to the central's address which can be used for - * directed advertising. - */ -uint32_t ble_bondmngr_central_addr_get(int8_t central_handle, ble_gap_addr_t * p_central_addr); - -/**@brief Function for storing the System Attributes of a newly connected central. - * - * @details This function fetches the System Attributes of the current central from the stack, adds - * it to the database in memory, and also stores it in the flash (without erasing any - * flash page). - * This function is intended to facilitate the storage of System Attributes when connected - * to new central (whose System Attributes are NOT yet stored in flash) even in connected - * state without affecting radio link. This function can, for example, be called after the - * CCCD is written by a central. The function will succeed if the central is a new central. - * See @ref ble_sdk_app_hids_keyboard or @ref ble_sdk_app_hids_mouse for sample usage. - * - * @return NRF_SUCCESS on success, otherwise an error code. - * NRF_ERROR_INVALID_STATE is returned if the System Attributes of the current central is - * already present in the flash because it is a previously known central. - */ -uint32_t ble_bondmngr_sys_attr_store(void); - -/**@brief Function for fetching the identifiers of known centrals. - * - * @details This function fetches the identifiers of the centrals that are currently in the - * database, or in other words, known to the bond manager. - * - * @param[out] p_central_ids Pointer to the array of central identifiers. It is recommended - * that the length of this array be equal to - * MAX_NUMBER_OF_BONDED_CENTRALS * 2 bytes. If value of this pointer - * is NULL, only the number of centrals in the database will be - * filled in p_length. This can be used to find out the - * required size of the array pointed to by p_central_ids in - * a subsequent call. - * @param[in, out] p_length Pointer to the length of p_central_ids array provided as - * input. On return, this function will write the number of central - * identifiers found to p_length - * - * @return NRF_SUCCESS on success. - * NRF_ERROR_NULL if the input parameter p_length is NULL. - * NRF_ERROR_INVALID_STATE is returned if the bond manager was not initialized. - * NRF_ERROR_DATA_SIZE is returned if the length of the input parameter - * p_central_ids provided is not enough to fit in all the central identifiers in the - * database. - */ -uint32_t ble_bondmngr_central_ids_get(uint16_t * p_central_ids, uint16_t * p_length); - -/**@brief Function for deleting a single central from the database. - * @details This function deletes the Bonding Information and System Attributes of a single - * central from the flash. - * The application can use the @ref ble_bondmngr_central_ids_get function to fetch the - * identifiers of centrals present in the database and then call this function. - * - * @warning This function could prevent the radio from running. Therefore it MUST be called ONLY - * when the application knows that the Bluetooth radio is not active. An example - * of such a state could be when the application is not in a connected state AND is - * also not advertising. If it is called in any other state, the behavior is - * undefined. - * - * @param[in] central_id Identifier of the central to be deleted. - * - * @return NRF_SUCCESS on success. - * NRF_ERROR_INVALID_STATE is returned if the bond manager was not initialized. - * NRF_ERROR_NOT_FOUND if the central with the given identifier is not found in the - * database. - */ -uint32_t ble_bondmngr_bonded_central_delete(uint16_t central_id); - -/**@brief Function to verify encryption status link with bonded central is encrypted or not. - * @details This function provides status of encrption of the link with a bonded central. - * Its is recommended that the application can use the - * @ref ble_bondmngr_central_ids_get function to verify if the central is in the - * database and then call this function. - * - * @warning Currently the central id paramater is unused and is added only for future extension. - * As, today only one link is permitted for the peripheral device, status of current - * link is provided. In future, with more possibilities in the topology, central_id - * will be needed to identify the central. - * - * @param[out] status Status of encryption, true implies link encrypted. - * - * @return NRF_SUCCESS on success. - * NRF_ERROR_INVALID_STATE is returned if the bond manager was not initialized. - */ -uint32_t ble_bondmngr_is_link_encrypted(bool * status); - -/** @} */ - -#endif // BLE_BONDMNGR_H__ - -/** @} */ diff --git a/libraries/ble/nRF51822/nordic/nrf-sdk/ble/ble_central_bondmngr.h b/libraries/ble/nRF51822/nordic/nrf-sdk/ble/ble_central_bondmngr.h deleted file mode 100644 index 17cbf00a70..0000000000 --- a/libraries/ble/nRF51822/nordic/nrf-sdk/ble/ble_central_bondmngr.h +++ /dev/null @@ -1,26 +0,0 @@ -#ifndef __BLE_CENTRAL_BONDMNGR_H_ -#define __BLE_CENTRAL_BONDMNGR_H_ - -#include "nordic_global.h" -#include "ble.h" -#include "ble_gap.h" - -#include -#include - -typedef struct -{ - ble_gap_sec_params_t * p_sec_params; -} ble_central_bondmngr_t; - -typedef struct -{ - ble_gap_sec_params_t * p_sec_params; - bool delete_bonds; -} ble_central_bondmngr_init_t; - -uint32_t ble_central_bondmngr_init(ble_central_bondmngr_t * p_bm, ble_central_bondmngr_init_t * p_bm_init); -void ble_central_bondmngr_on_ble_evt(ble_central_bondmngr_t * p_bm, ble_evt_t * p_ble_evt); -uint32_t ble_central_bondmngr_store(ble_central_bondmngr_t * p_bm); - -#endif diff --git a/libraries/ble/nRF51822/nordic/nrf-sdk/ble/ble_conn_params.h b/libraries/ble/nRF51822/nordic/nrf-sdk/ble/ble_conn_params.h deleted file mode 100644 index d0c7463d8a..0000000000 --- a/libraries/ble/nRF51822/nordic/nrf-sdk/ble/ble_conn_params.h +++ /dev/null @@ -1,112 +0,0 @@ -/* Copyright (c) 2012 Nordic Semiconductor. All Rights Reserved. - * - * The information contained herein is property of Nordic Semiconductor ASA. - * Terms and conditions of usage are described in detail in NORDIC - * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. - * - * Licensees are granted free, non-transferable use of the information. NO - * WARRANTY of ANY KIND is provided. This heading must NOT be removed from - * the file. - * - */ - -/** @file - * - * @defgroup ble_sdk_lib_conn_params Connection Parameters Negotiation - * @{ - * @ingroup ble_sdk_lib - * @brief Module for initiating and executing a connection parameters negotiation procedure. - */ - -#ifndef BLE_CONN_PARAMS_H__ -#define BLE_CONN_PARAMS_H__ - -#include -#include "nordic_global.h" -#include "ble.h" -#include "ble_srv_common.h" - -/**@brief Connection Parameters Module event type. */ -typedef enum -{ - BLE_CONN_PARAMS_EVT_FAILED , /**< Negotiation procedure failed. */ - BLE_CONN_PARAMS_EVT_SUCCEEDED /**< Negotiation procedure succeeded. */ -} ble_conn_params_evt_type_t; - -/**@brief Connection Parameters Module event. */ -typedef struct -{ - ble_conn_params_evt_type_t evt_type; /**< Type of event. */ -} ble_conn_params_evt_t; - -/**@brief Connection Parameters Module event handler type. */ -typedef void (*ble_conn_params_evt_handler_t) (ble_conn_params_evt_t * p_evt); - -/**@brief Connection Parameters Module init structure. This contains all options and data needed for - * initialization of the connection parameters negotiation module. */ -typedef struct -{ - ble_gap_conn_params_t * p_conn_params; /**< Pointer to the connection parameters desired by the application. When calling ble_conn_params_init, if this parameter is set to NULL, the connection parameters will be fetched from host. */ - uint32_t first_conn_params_update_delay; /**< Time from initiating event (connect or start of notification) to first time sd_ble_gap_conn_param_update is called (in number of timer ticks). */ - uint32_t next_conn_params_update_delay; /**< Time between each call to sd_ble_gap_conn_param_update after the first (in number of timer ticks). Recommended value 30 seconds as per BLUETOOTH SPECIFICATION Version 4.0. */ - uint8_t max_conn_params_update_count; /**< Number of attempts before giving up the negotiation. */ - uint16_t start_on_notify_cccd_handle; /**< If procedure is to be started when notification is started, set this to the handle of the corresponding CCCD. Set to BLE_GATT_HANDLE_INVALID if procedure is to be started on connect event. */ - bool disconnect_on_fail; /**< Set to TRUE if a failed connection parameters update shall cause an automatic disconnection, set to FALSE otherwise. */ - ble_conn_params_evt_handler_t evt_handler; /**< Event handler to be called for handling events in the Battery Service. */ - ble_srv_error_handler_t error_handler; /**< Function to be called in case of an error. */ -} ble_conn_params_init_t; - - -/**@brief Function for initializing the Connection Parameters module. - * - * @note If the negotiation procedure should be triggered when notification/indication of - * any characteristic is enabled by the peer, then this function must be called after - * having initialized the services. - * - * @param[in] p_init This contains information needed to initialize this module. - * - * @return NRF_SUCCESS on successful initialization, otherwise an error code. - */ -uint32_t ble_conn_params_init(const ble_conn_params_init_t * p_init); - -/**@brief Function for stopping the Connection Parameters module. - * - * @details This function is intended to be used by the application to clean up the connection - * parameters update module. This will stop the connection parameters update timer if - * running, thereby preventing any impending connection parameters update procedure. This - * function must be called by the application when it needs to clean itself up (for - * example, before disabling the bluetooth SoftDevice) so that an unwanted timer expiry - * event can be avoided. - * - * @return NRF_SUCCESS on successful initialization, otherwise an error code. - */ -uint32_t ble_conn_params_stop(void); - -/**@brief Function for changing the current connection parameters to a new set. - * - * @details Use this function to change the connection parameters to a new set of parameter - * (ie different from the ones given at init of the module). - * This function is usefull for scenario where most of the time the application - * needs a relatively big connection interval, and just sometimes, for a temporary - * period requires shorter connection interval, for example to transfer a higher - * amount of data. - * If the given parameters does not match the current connection's parameters - * this function initiates a new negotiation. - * - * @param[in] new_params This contains the new connections parameters to setup. - * - * @return NRF_SUCCESS on successful initialization, otherwise an error code. - */ -uint32_t ble_conn_params_change_conn_params(ble_gap_conn_params_t *new_params); - -/**@brief Function for handling the Application's BLE Stack events. - * - * @details Handles all events from the BLE stack that are of interest to this module. - * - * @param[in] p_ble_evt The event received from the BLE stack. - */ -void ble_conn_params_on_ble_evt(ble_evt_t * p_ble_evt); - -#endif // BLE_CONN_PARAMS_H__ - -/** @} */ diff --git a/libraries/ble/nRF51822/nordic/nrf-sdk/ble/ble_date_time.h b/libraries/ble/nRF51822/nordic/nrf-sdk/ble/ble_date_time.h deleted file mode 100644 index 6e323004c1..0000000000 --- a/libraries/ble/nRF51822/nordic/nrf-sdk/ble/ble_date_time.h +++ /dev/null @@ -1,77 +0,0 @@ -/* Copyright (c) 2011 Nordic Semiconductor. All Rights Reserved. -* -* The information contained herein is property of Nordic Semiconductor ASA. -* Terms and conditions of usage are described in detail in NORDIC -* SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. -* -* Licensees are granted free, non-transferable use of the information. NO -* WARRANTY of ANY KIND is provided. This heading must NOT be removed from -* the file. -*/ - -/* Attention! -* To maintain compliance with Nordic Semiconductor ASA�s Bluetooth profile -* qualification listings, this section of source code must not be modified. -*/ - -/** @file - * @brief Contains definition of ble_date_time structure. - */ - -/** @file - * - * @defgroup ble_sdk_srv_date_time BLE Date Time characteristic type - * @{ - * @ingroup ble_sdk_srv - * @brief Definition of ble_date_time_t type. - */ - -#ifndef BLE_DATE_TIME_H__ -#define BLE_DATE_TIME_H__ - -#include -#include "nordic_global.h" - -/**@brief Date and Time structure. */ -typedef struct -{ - uint16_t year; - uint8_t month; - uint8_t day; - uint8_t hours; - uint8_t minutes; - uint8_t seconds; -} ble_date_time_t; - -static __INLINE uint8_t ble_date_time_encode(const ble_date_time_t * p_date_time, - uint8_t * p_encoded_data) -{ - uint8_t len = uint16_encode(p_date_time->year, p_encoded_data); - - p_encoded_data[len++] = p_date_time->month; - p_encoded_data[len++] = p_date_time->day; - p_encoded_data[len++] = p_date_time->hours; - p_encoded_data[len++] = p_date_time->minutes; - p_encoded_data[len++] = p_date_time->seconds; - - return len; -} - -static __INLINE uint8_t ble_date_time_decode(ble_date_time_t * p_date_time, - const uint8_t * p_encoded_data) -{ - uint8_t len = sizeof(uint16_t); - - p_date_time->year = uint16_decode(p_encoded_data); - p_date_time->month = p_encoded_data[len++]; - p_date_time->day = p_encoded_data[len++]; - p_date_time->hours = p_encoded_data[len++]; - p_date_time->minutes = p_encoded_data[len++]; - p_date_time->seconds = p_encoded_data[len++]; - - return len; -} - -#endif // BLE_DATE_TIME_H__ - -/** @} */ diff --git a/libraries/ble/nRF51822/nordic/nrf-sdk/ble/ble_debug_assert_handler.h b/libraries/ble/nRF51822/nordic/nrf-sdk/ble/ble_debug_assert_handler.h deleted file mode 100644 index eec0bbfcff..0000000000 --- a/libraries/ble/nRF51822/nordic/nrf-sdk/ble/ble_debug_assert_handler.h +++ /dev/null @@ -1,49 +0,0 @@ -/* Copyright (c) 2013 Nordic Semiconductor. All Rights Reserved. - * - * The information contained herein is property of Nordic Semiconductor ASA. - * Terms and conditions of usage are described in detail in NORDIC - * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. - * - * Licensees are granted free, non-transferable use of the information. NO - * WARRANTY of ANY KIND is provided. This heading must NOT be removed from - * the file. - * - */ - -/** @file - * - * @defgroup ble_debug_assert_handler Assert Handler for debug purposes. - * @{ - * @ingroup ble_sdk_lib - * @brief Module for handling of assert during application development when debugging. - * - * @details This module may be used during development of an application to facilitate debugging. - * It contains a function to write file name, line number and the Stack Memory to flash. - * This module is ONLY for debugging purposes and must never be used in final product. - * - */ - -#ifndef BLE_DEBUG_ASSERT_HANDLER_H__ -#define BLE_DEBUG_ASSERT_HANDLER_H__ - -#include -#include "nordic_global.h" - -/**@brief Function for handling the Debug assert, which can be called from an error handler. - * To be used only for debugging purposes. - * - *@details This code will copy the filename and line number into local variables for them to always - * be accessible in Keil debugger. The function will also write the ARM Cortex-M0 stack - * memory into flash where it can be retrieved and manually un-winded in order to - * back-trace the location where the error ocured.
- * @warning ALL INTERRUPTS WILL BE DISABLED. - * - * @note This function will never return but loop forever for debug purposes. - * - * @param[in] error_code Error code supplied to the handler. - * @param[in] line_num Line number where the original handler is called. - * @param[in] p_file_name Pointer to the file name. - */ -void ble_debug_assert_handler(uint32_t error_code, uint32_t line_num, const uint8_t * p_file_name); - -#endif /* BLE_DEBUG_ASSERT_HANDLER_H__ */ diff --git a/libraries/ble/nRF51822/nordic/nrf-sdk/ble/ble_dtm.h b/libraries/ble/nRF51822/nordic/nrf-sdk/ble/ble_dtm.h deleted file mode 100644 index 013e0b0f99..0000000000 --- a/libraries/ble/nRF51822/nordic/nrf-sdk/ble/ble_dtm.h +++ /dev/null @@ -1,142 +0,0 @@ -/* Copyright (c) 2012 Nordic Semiconductor. All Rights Reserved. - * - * The information contained herein is property of Nordic Semiconductor ASA. - * Terms and conditions of usage are described in detail in NORDIC - * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. - * - * Licensees are granted free, non-transferable use of the information. NO - * WARRANTY of ANY KIND is provided. This heading must NOT be removed from - * the file. - * - */ - -/** @file - * - * @defgroup ble_sdk_dtmlib_dtm DTM - Direct Test Mode - * @{ - * @ingroup ble_sdk_lib - * @brief Module for testing RF/PHY using DTM commands. - */ - -#ifndef BLE_DTM_H__ -#define BLE_DTM_H__ - -#include -#include -#include "nordic_global.h" - - -/**@brief Configuration parameters. */ -#define DEFAULT_TX_POWER RADIO_TXPOWER_TXPOWER_Pos4dBm /**< Default Transmission power using in the DTM module. */ -#define DEFAULT_TIMER NRF_TIMER0 /**< Default timer used for timing. */ -#define DEFAULT_TIMER_IRQn TIMER0_IRQn /**< IRQ used for timer. NOTE: MUST correspond to DEFAULT_TIMER. */ - -/**@brief BLE DTM command codes. */ -typedef uint32_t dtm_cmd_t; /**< DTM command type. */ - -#define LE_RESET 0 /**< DTM command: Reset device. */ -#define LE_RECEIVER_TEST 1 /**< DTM command: Start receive test. */ -#define LE_TRANSMITTER_TEST 2 /**< DTM command: Start transmission test. */ -#define LE_TEST_END 3 /**< DTM command: End test and send packet report. */ - -// Configuration options used as parameter 2 -// when cmd == LE_TRANSMITTER_TEST and payload == DTM_PKT_VENDORSPECIFIC -// Configuration value, if any, is supplied in parameter 3 - -#define CARRIER_TEST 0 /**< Length=0 indicates a constant, unmodulated carrier until LE_TEST_END or LE_RESET */ -#define CARRIER_TEST_STUDIO 1 /**< nRFgo Studio uses value 1 in length field, to indicate a constant, unmodulated carrier until LE_TEST_END or LE_RESET */ -#define SET_TX_POWER 2 /**< Set transmission power, value -40..+4 dBm in steps of 4 */ -#define SELECT_TIMER 3 /**< Select on of the 16 MHz timers 0, 1 or 2 */ - -#define LE_PACKET_REPORTING_EVENT 0x8000 /**< DTM Packet reporting event, returned by the device to the tester. */ -#define LE_TEST_STATUS_EVENT_SUCCESS 0x0000 /**< DTM Status event, indicating success. */ -#define LE_TEST_STATUS_EVENT_ERROR 0x0001 /**< DTM Status event, indicating an error. */ - -#define DTM_PKT_PRBS9 0x00 /**< Bit pattern PRBS9. */ -#define DTM_PKT_0X0F 0x01 /**< Bit pattern 11110000 (LSB is the leftmost bit). */ -#define DTM_PKT_0X55 0x02 /**< Bit pattern 10101010 (LSB is the leftmost bit). */ -#define DTM_PKT_VENDORSPECIFIC 0xFFFFFFFF /**< Vendor specific. Nordic: Continuous carrier test, or configuration. */ - -/**@brief Return codes from dtm_cmd(). */ -#define DTM_SUCCESS 0x00 /**< Indicate that the DTM function completed with success. */ -#define DTM_ERROR_ILLEGAL_CHANNEL 0x01 /**< Physical channel number must be in the range 0..39. */ -#define DTM_ERROR_INVALID_STATE 0x02 /**< Sequencing error: Command is not valid now. */ -#define DTM_ERROR_ILLEGAL_LENGTH 0x03 /**< Payload size must be in the range 0..37. */ -#define DTM_ERROR_ILLEGAL_CONFIGURATION 0x04 /**< Parameter out of range (legal range is function dependent). */ -#define DTM_ERROR_UNINITIALIZED 0x05 /**< DTM module has not been initialized by the application. */ - -// Note: DTM_PKT_VENDORSPECIFIC, is not a packet type -#define PACKET_TYPE_MAX DTM_PKT_0X55 /**< Highest value allowed as DTM Packet type. */ - -/** @brief BLE DTM event type. */ -typedef uint32_t dtm_event_t; /**< Type for handling DTM event. */ - -/** @brief BLE DTM frequency type. */ -typedef uint32_t dtm_freq_t; /**< Physical channel, valid range: 0..39. */ - -/**@brief BLE DTM packet types. */ -typedef uint32_t dtm_pkt_type_t; /**< Type for holding the requested DTM payload type.*/ - - -/**@brief Function for initializing or re-initializing DTM module - * - * @return DTM_SUCCESS on successful initialization of the DTM module. -*/ -uint32_t dtm_init(void); - - -/**@brief Function for giving control to dtmlib for handling timer and radio events. - * Will return to caller at 625us intervals or whenever another event than radio occurs - * (such as UART input). Function will put MCU to sleep between events. - * - * @return Time counter, incremented every 625 us. - */ -uint32_t dtm_wait(void); - - -/**@brief Function for calling when a complete command has been prepared by the Tester. - * - * @param[in] cmd One of the DTM_CMD values (bits 14:15 in the 16-bit UART format). - * @param[in] freq Phys. channel no - actual frequency = (2402 + freq * 2) MHz (bits 8:13 in - * the 16-bit UART format). - * @param[in] length Payload length, 0..37 (bits 2:7 in the 16-bit UART format). - * @param[in] payload One of the DTM_PKT values (bits 0:1 in the 16-bit UART format). - * - * @return DTM_SUCCESS or one of the DTM_ERROR_ values - */ -uint32_t dtm_cmd(dtm_cmd_t cmd, dtm_freq_t freq, uint32_t length, dtm_pkt_type_t payload); - - -/**@brief Function for reading the result of a DTM command - * - * @param[out] p_dtm_event Pointer to buffer for 16 bit event code according to DTM standard. - * - * @return true: new event, false: no event since last call, this event has been read earlier - */ -bool dtm_event_get(dtm_event_t * p_dtm_event); - - -/**@brief Function for configuring the timer to use. - * - * @note Must be called when no DTM test is running. - * - * @param[in] new_timer Index (0..2) of timer to be used by the DTM library - * - * @return true: success, new timer was selected, false: parameter error - */ -bool dtm_set_timer(uint32_t new_timer); - - -/**@brief Function for configuring the transmit power. - * - * @note Must be called when no DTM test is running. - * - * @param[in] new_tx_power New output level, +4..-40, in steps of 4. - * - * @return true: tx power setting changed, false: parameter error - */ -bool dtm_set_txpower(uint32_t new_tx_power); - -#endif // BLE_DTM_H__ - -/** @} */ diff --git a/libraries/ble/nRF51822/nordic/nrf-sdk/ble/ble_error_log.h b/libraries/ble/nRF51822/nordic/nrf-sdk/ble/ble_error_log.h deleted file mode 100644 index 6a4084f534..0000000000 --- a/libraries/ble/nRF51822/nordic/nrf-sdk/ble/ble_error_log.h +++ /dev/null @@ -1,70 +0,0 @@ -/* Copyright (c) 2012 Nordic Semiconductor. All Rights Reserved. - * - * The information contained herein is property of Nordic Semiconductor ASA. - * Terms and conditions of usage are described in detail in NORDIC - * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. - * - * Licensees are granted free, non-transferable use of the information. NO - * WARRANTY of ANY KIND is provided. This heading must NOT be removed from - * the file. - * - */ - -/** @file - * - * @defgroup ble_error_log_module Error Log Module - * @{ - * @ingroup ble_sdk_lib - * @brief Module for writing error and stack to flash memory. - * - * @details It contains functions for writing an error code, line number, filename/message and - * the stack to the flash during an error, e.g. in the assert handler. - * - */ -#ifndef BLE_ERROR_LOG_H__ -#define BLE_ERROR_LOG_H__ - -#include -#include -#include "ble_flash.h" -#include "nordic_global.h" - -#define ERROR_MESSAGE_LENGTH 128 /**< Length of error message to stored. */ -#define STACK_DUMP_LENGTH 256 /**< Length of stack to be stored at max: 64 entries of 4 bytes each. */ -#define FLASH_PAGE_ERROR_LOG (BLE_FLASH_PAGE_END - 2) /**< Address in flash where stack trace can be stored. */ - -/**@brief Error Log Data structure. - * - * @details The structure contains the error, message/filename, line number as well as the current - * stack, at the time where an error occured. - */ -typedef struct -{ - uint16_t failure; /**< Indication that a major failure has occurred during last execution of the application. */ - uint16_t line_number; /**< Line number indicating at which line the failure occurred. */ - uint32_t err_code; /**< Error code when failure occurred. */ - uint8_t message[ERROR_MESSAGE_LENGTH]; /**< Will just use the first 128 bytes of filename to store for debugging purposes. */ - uint32_t stack_info[STACK_DUMP_LENGTH / 4]; /**< Will contain stack information, can be manually unwinded for debug purposes. */ -} ble_error_log_data_t; - - -/**@brief Function for writing the file name/message, line number, and current program stack - * to flash. - * - * @note This function will force the writing to flash, and disregard any radio communication. - * USE THIS FUNCTION WITH CARE. - * - * @param[in] err_code Error code to be logged. - * @param[in] p_message Message to be written to the flash together with stack dump, usually - * the file name where the error occured. - * @param[in] line_number Line number where the error occured. - * - * @return NRF_SUCCESS on successful writing of the error log. - * - */ -uint32_t ble_error_log_write(uint32_t err_code, const uint8_t * p_message, uint16_t line_number); - - -#endif /* BLE_ERROR_LOG_H__ */ - -/** @} */ diff --git a/libraries/ble/nRF51822/nordic/nrf-sdk/ble/ble_flash.h b/libraries/ble/nRF51822/nordic/nrf-sdk/ble/ble_flash.h deleted file mode 100644 index 9670ec9276..0000000000 --- a/libraries/ble/nRF51822/nordic/nrf-sdk/ble/ble_flash.h +++ /dev/null @@ -1,143 +0,0 @@ -/* Copyright (c) 2012 Nordic Semiconductor. All Rights Reserved. - * - * The information contained herein is property of Nordic Semiconductor ASA. - * Terms and conditions of usage are described in detail in NORDIC - * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. - * - * Licensees are granted free, non-transferable use of the information. NO - * WARRANTY of ANY KIND is provided. This heading must NOT be removed from - * the file. - * - */ - -/** @file - * - * @defgroup ble_flash_module Flash Manager - * @{ - * @ingroup ble_sdk_lib - * @brief Module for accessing flash memory. - * - * @details It contains functions for reading, writing and erasing one page in flash. - * - * The module uses the first 32 bits of the flash page to write a magic number in order to - * determine if the page has been written or not. - * - * @note Be careful not to use a page number in the SoftDevice area (which currently occupies the - * range 0 to 127), or in your application space! In both cases, this would end up - * with a hard fault. - */ - -#ifndef BLE_FLASH_H__ -#define BLE_FLASH_H__ - -#include -#include -#include -#include "nordic_global.h" - -#define BLE_FLASH_PAGE_SIZE ((uint16_t)NRF_FICR->CODEPAGESIZE) /**< Size of one flash page. */ -#define BLE_FLASH_MAGIC_NUMBER 0x45DE0000 /**< Magic value to identify if flash contains valid data. */ -#define BLE_FLASH_EMPTY_MASK 0xFFFFFFFF /**< Bit mask that defines an empty address in flash. */ - - -/**@brief Macro for getting the end of the flash available for application. - * - * @details The result flash page number indicates the end boundary of the flash available - * to the application. If a bootloader is used, the end will be the start of the - * bootloader region. Otherwise, the end will be the size of the flash. - */ -#define BLE_FLASH_PAGE_END \ - ((NRF_UICR->BOOTLOADERADDR != BLE_FLASH_EMPTY_MASK) \ - ? (NRF_UICR->BOOTLOADERADDR / BLE_FLASH_PAGE_SIZE) \ - : NRF_FICR->CODESIZE) - -/**@brief Function for erasing the specified flash page, and then writes the given data to this page. - * - * @warning This operation blocks the CPU. DO NOT use while in a connection! - * - * @param[in] page_num Page number to update. - * @param[in] p_in_array Pointer to a RAM area containing the elements to write in flash. - * This area has to be 32 bits aligned. - * @param[in] word_count Number of 32 bits words to write in flash. - * - * @return NRF_SUCCESS on successful flash write, otherwise an error code. - */ -uint32_t ble_flash_page_write(uint8_t page_num, uint32_t * p_in_array, uint8_t word_count); - -/**@brief Function for reading data from flash to RAM. - * - * @param[in] page_num Page number to read. - * @param[out] p_out_array Pointer to a RAM area where the found data will be written. - * This area has to be 32 bits aligned. - * @param[out] p_word_count Number of 32 bits words read. - * - * @return NRF_SUCCESS on successful upload, NRF_ERROR_NOT_FOUND if no valid data has been found - * in flash (first 32 bits not equal to the MAGIC_NUMBER+CRC). - */ -uint32_t ble_flash_page_read(uint8_t page_num, uint32_t * p_out_array, uint8_t * p_word_count); - -/**@brief Function for erasing a flash page. - * - * @note This operation blocks the CPU, so it should not be done while the radio is running! - * - * @param[in] page_num Page number to erase. - * - * @return NRF_SUCCESS on success, an error_code otherwise. - */ -uint32_t ble_flash_page_erase(uint8_t page_num); - -/**@brief Function for writing one word to flash. - * - * @note Flash location to be written must have been erased previously. - * - * @param[in] p_address Pointer to flash location to be written. - * @param[in] value Value to write to flash. - * - * @return NRF_SUCCESS. - */ -uint32_t ble_flash_word_write(uint32_t * p_address, uint32_t value); - -/**@brief Function for writing a data block to flash. - * - * @note Flash locations to be written must have been erased previously. - * - * @param[in] p_address Pointer to start of flash location to be written. - * @param[in] p_in_array Pointer to start of flash block to be written. - * @param[in] word_count Number of words to be written. - * - * @return NRF_SUCCESS. - */ -uint32_t ble_flash_block_write(uint32_t * p_address, uint32_t * p_in_array, uint16_t word_count); - -/**@brief Function for computing pointer to start of specified flash page. - * - * @param[in] page_num Page number. - * @param[out] pp_page_addr Pointer to start of flash page. - * - * @return NRF_SUCCESS. - */ -uint32_t ble_flash_page_addr(uint8_t page_num, uint32_t ** pp_page_addr); - -/**@brief Function for calculating a 16 bit CRC using the CRC-16-CCITT scheme. - * - * @param[in] p_data Pointer to data on which the CRC is to be calulated. - * @param[in] size Number of bytes on which the CRC is to be calulated. - * @param[in] p_crc Initial CRC value (if NULL, a preset value is used as the initial value). - * - * @return Calculated CRC. - */ -uint16_t ble_flash_crc16_compute(uint8_t * p_data, uint16_t size, uint16_t * p_crc); - -/**@brief Function for handling flashing module Radio Notification event. - * - * @note For flash writing to work safely while in a connection or while advertising, this function - * MUST be called from the Radio Notification module's event handler (see - * @ref ble_radio_notification for details). - * - * @param[in] radio_active TRUE if radio is active (or about to become active), FALSE otherwise. - */ -void ble_flash_on_radio_active_evt(bool radio_active); - -#endif // BLE_FLASH_H__ - -/** @} */ diff --git a/libraries/ble/nRF51822/nordic/nrf-sdk/ble/ble_racp.h b/libraries/ble/nRF51822/nordic/nrf-sdk/ble/ble_racp.h deleted file mode 100644 index 9528fcbb5d..0000000000 --- a/libraries/ble/nRF51822/nordic/nrf-sdk/ble/ble_racp.h +++ /dev/null @@ -1,98 +0,0 @@ -/* Copyright (c) 2012 Nordic Semiconductor. All Rights Reserved. - * - * The information contained herein is property of Nordic Semiconductor ASA. - * Terms and conditions of usage are described in detail in NORDIC - * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. - * - * Licensees are granted free, non-transferable use of the information. NO - * WARRANTY of ANY KIND is provided. This heading must NOT be removed from - * the file. - */ - -/** @file - * - * @defgroup ble_sdk_lib_racp Record Access Control Point - * @{ - * @ingroup ble_sdk_lib - * @brief Record Access Control Point library. - */ - -#ifndef BLE_RACP_H__ -#define BLE_RACP_H__ - -#include -#include -#include "nordic_global.h" -#include "ble.h" -#include "ble_types.h" -#include "ble.h" - -/**@brief Record Access Control Point opcodes. */ -#define RACP_OPCODE_RESERVED 0 /**< Record Access Control Point opcode - Reserved for future use. */ -#define RACP_OPCODE_REPORT_RECS 1 /**< Record Access Control Point opcode - Report stored records. */ -#define RACP_OPCODE_DELETE_RECS 2 /**< Record Access Control Point opcode - Delete stored records. */ -#define RACP_OPCODE_ABORT_OPERATION 3 /**< Record Access Control Point opcode - Abort operation. */ -#define RACP_OPCODE_REPORT_NUM_RECS 4 /**< Record Access Control Point opcode - Report number of stored records. */ -#define RACP_OPCODE_NUM_RECS_RESPONSE 5 /**< Record Access Control Point opcode - Number of stored records response. */ -#define RACP_OPCODE_RESPONSE_CODE 6 /**< Record Access Control Point opcode - Response code. */ - -/**@brief Record Access Control Point operators. */ -#define RACP_OPERATOR_NULL 0 /**< Record Access Control Point operator - Null. */ -#define RACP_OPERATOR_ALL 1 /**< Record Access Control Point operator - All records. */ -#define RACP_OPERATOR_LESS_OR_EQUAL 2 /**< Record Access Control Point operator - Less than or equal to. */ -#define RACP_OPERATOR_GREATER_OR_EQUAL 3 /**< Record Access Control Point operator - Greater than or equal to. */ -#define RACP_OPERATOR_RANGE 4 /**< Record Access Control Point operator - Within range of (inclusive). */ -#define RACP_OPERATOR_FIRST 5 /**< Record Access Control Point operator - First record (i.e. oldest record). */ -#define RACP_OPERATOR_LAST 6 /**< Record Access Control Point operator - Last record (i.e. most recent record). */ -#define RACP_OPERATOR_RFU_START 7 /**< Record Access Control Point operator - Start of Reserved for Future Use area. */ - -/**@brief Record Access Control Point response codes. */ -#define RACP_RESPONSE_RESERVED 0 /**< Record Access Control Point response code - Reserved for future use. */ -#define RACP_RESPONSE_SUCCESS 1 /**< Record Access Control Point response code - Successful operation. */ -#define RACP_RESPONSE_OPCODE_UNSUPPORTED 2 /**< Record Access Control Point response code - Unsupported op code received. */ -#define RACP_RESPONSE_INVALID_OPERATOR 3 /**< Record Access Control Point response code - Operator not valid for service. */ -#define RACP_RESPONSE_OPERATOR_UNSUPPORTED 4 /**< Record Access Control Point response code - Unsupported operator. */ -#define RACP_RESPONSE_INVALID_OPERAND 5 /**< Record Access Control Point response code - Operand not valid for service. */ -#define RACP_RESPONSE_NO_RECORDS_FOUND 6 /**< Record Access Control Point response code - No matching records found. */ -#define RACP_RESPONSE_ABORT_FAILED 7 /**< Record Access Control Point response code - Abort could not be completed. */ -#define RACP_RESPONSE_PROCEDURE_NOT_DONE 8 /**< Record Access Control Point response code - Procedure could not be completed. */ -#define RACP_RESPONSE_OPERAND_UNSUPPORTED 9 /**< Record Access Control Point response code - Unsupported operand. */ - -/**@brief Record Access Control Point value structure. */ -typedef struct -{ - uint8_t opcode; /**< Op Code. */ - uint8_t operator; /**< Operator. */ - uint8_t operand_len; /**< Length of the operand. */ - uint8_t * p_operand; /**< Pointer to the operand. */ -} ble_racp_value_t; - -/**@brief Function for decoding a Record Access Control Point write. - * - * @details This call decodes a write to the Record Access Control Point. - * - * @param[in] data_len Length of data in received write. - * @param[in] p_data Pointer to received data. - * @param[out] p_racp_val Pointer to decoded Record Access Control Point write. - * @note This does not do a data copy. It assumes the data pointed to by - * p_data is persistant until no longer needed. - */ -void ble_racp_decode(uint8_t data_len, uint8_t * p_data, ble_racp_value_t * p_racp_val); - -/**@brief Function for encoding a Record Access Control Point response. - * - * @details This call encodes a response from the Record Access Control Point response. - * - * @param[in] p_racp_val Pointer to Record Access Control Point to encode. - * @param[out] p_data Pointer to where encoded data is written. - * NOTE! It is calling routines respsonsibility to make sure. - * - * @return Length of encoded data. - */ -uint8_t ble_racp_encode(const ble_racp_value_t * p_racp_val, uint8_t * p_data); - -#endif // BLE_RACP_H__ - -/** @} */ - -/** @endcond */ diff --git a/libraries/ble/nRF51822/nordic/nrf-sdk/ble/ble_radio_notification.h b/libraries/ble/nRF51822/nordic/nrf-sdk/ble/ble_radio_notification.h deleted file mode 100644 index 35e781d43c..0000000000 --- a/libraries/ble/nRF51822/nordic/nrf-sdk/ble/ble_radio_notification.h +++ /dev/null @@ -1,46 +0,0 @@ -/* Copyright (c) 2012 Nordic Semiconductor. All Rights Reserved. - * - * The information contained herein is property of Nordic Semiconductor ASA. - * Terms and conditions of usage are described in detail in NORDIC - * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. - * - * Licensees are granted free, non-transferable use of the information. NO - * WARRANTY of ANY KIND is provided. This heading must NOT be removed from - * the file. - */ - -/** @file - * - * @defgroup ble_radio_notification Radio Notification Event Handler - * @{ - * @ingroup ble_sdk_lib - * @brief Module for propagating Radio Notification events to the application. - */ - -#ifndef BLE_RADIO_NOTIFICATION_H__ -#define BLE_RADIO_NOTIFICATION_H__ - -#include -#include -#include "nordic_global.h" -#include "nrf_soc.h" - -/**@brief Application radio notification event handler type. */ -typedef void (*ble_radio_notification_evt_handler_t) (bool radio_active); - -/**@brief Function for initializing the Radio Notification module. - * - * @param[in] irq_priority Interrupt priority for the Radio Notification interrupt handler. - * @param[in] distance The time from an Active event until the radio is activated. - * @param[in] evt_handler Handler to be executed when a radio notification event has been - * received. - * - * @return NRF_SUCCESS on successful initialization, otherwise an error code. - */ -uint32_t ble_radio_notification_init(nrf_app_irq_priority_t irq_priority, - nrf_radio_notification_distance_t distance, - ble_radio_notification_evt_handler_t evt_handler); - -#endif // BLE_RADIO_NOTIFICATION_H__ - -/** @} */ diff --git a/libraries/ble/nRF51822/nordic/nrf-sdk/ble/ble_sensorsim.h b/libraries/ble/nRF51822/nordic/nrf-sdk/ble/ble_sensorsim.h deleted file mode 100644 index 02fb08e594..0000000000 --- a/libraries/ble/nRF51822/nordic/nrf-sdk/ble/ble_sensorsim.h +++ /dev/null @@ -1,66 +0,0 @@ -/* Copyright (c) 2012 Nordic Semiconductor. All Rights Reserved. - * - * The information contained herein is property of Nordic Semiconductor ASA. - * Terms and conditions of usage are described in detail in NORDIC - * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. - * - * Licensees are granted free, non-transferable use of the information. NO - * WARRANTY of ANY KIND is provided. This heading must NOT be removed from - * the file. - * - */ - -/** @file - * - * @defgroup ble_sdk_lib_sensorsim Sensor Data Simulator - * @{ - * @ingroup ble_sdk_lib - * @brief Functions for simulating sensor data. - * - * @details Currently only a triangular waveform simulator is implemented. - */ - -#ifndef BLE_SENSORSIM_H__ -#define BLE_SENSORSIM_H__ - -#include -#include -#include "nordic_global.h" - -/**@brief Triangular waveform sensor simulator configuration. */ -typedef struct -{ - uint32_t min; /**< Minimum simulated value. */ - uint32_t max; /**< Maximum simulated value. */ - uint32_t incr; /**< Increment between each measurement. */ - bool start_at_max; /**< TRUE is measurement is to start at the maximum value, FALSE if it is to start at the minimum. */ -} ble_sensorsim_cfg_t; - -/**@brief Triangular waveform sensor simulator state. */ -typedef struct -{ - uint32_t current_val; /**< Current sensor value. */ - bool is_increasing; /**< TRUE if the simulator is in increasing state, FALSE otherwise. */ -} ble_sensorsim_state_t; - -/**@brief Function for initializing a triangular waveform sensor simulator. - * - * @param[out] p_state Current state of simulator. - * @param[in] p_cfg Simulator configuration. - */ -void ble_sensorsim_init(ble_sensorsim_state_t * p_state, - const ble_sensorsim_cfg_t * p_cfg); - -/**@brief Function for generating a simulated sensor measurement using a triangular waveform generator. - * - * @param[in,out] p_state Current state of simulator. - * @param[in] p_cfg Simulator configuration. - * - * @return Simulator output. - */ -uint32_t ble_sensorsim_measure(ble_sensorsim_state_t * p_state, - const ble_sensorsim_cfg_t * p_cfg); - -#endif // BLE_SENSORSIM_H__ - -/** @} */ diff --git a/libraries/ble/nRF51822/nordic/nrf-sdk/ble/ble_services/ble_srv_common.h b/libraries/ble/nRF51822/nordic/nrf-sdk/ble/ble_services/ble_srv_common.h deleted file mode 100644 index f27d48021c..0000000000 --- a/libraries/ble/nRF51822/nordic/nrf-sdk/ble/ble_services/ble_srv_common.h +++ /dev/null @@ -1,235 +0,0 @@ -/* Copyright (c) 2012 Nordic Semiconductor. All Rights Reserved. - * - * The information contained herein is property of Nordic Semiconductor ASA. - * Terms and conditions of usage are described in detail in NORDIC - * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. - * - * Licensees are granted free, non-transferable use of the information. NO - * WARRANTY of ANY KIND is provided. This heading must NOT be removed from - * the file. - * - */ - -/** @file - * - * @defgroup ble_sdk_srv_common 'Common service definitions' - * @{ - * @ingroup ble_sdk_srv - * @brief Constants, type definitions and functions that are common to all services. - */ - -#ifndef BLE_SRV_COMMON_H__ -#define BLE_SRV_COMMON_H__ - -#include -#include -#include "nordic_global.h" -#include "ble_types.h" -#include "app_util.h" -#include "ble_gap.h" -#include "ble_gatt.h" - -/** @defgroup UUID_SERVICES Service UUID definitions - * @{ */ -#define BLE_UUID_ALERT_NOTIFICATION_SERVICE 0x1811 /**< Alert Notification service UUID. */ -#define BLE_UUID_BATTERY_SERVICE 0x180F /**< Battery service UUID. */ -#define BLE_UUID_BLOOD_PRESSURE_SERVICE 0x1810 /**< Blood Pressure service UUID. */ -#define BLE_UUID_CURRENT_TIME_SERVICE 0x1805 /**< Current Time service UUID. */ -#define BLE_UUID_CYCLING_SPEED_AND_CADENCE 0x1816 /**< Cycling Speed and Cadence service UUID. */ -#define BLE_UUID_DEVICE_INFORMATION_SERVICE 0x180A /**< Device Information service UUID. */ -#define BLE_UUID_GLUCOSE_SERVICE 0x1808 /**< Glucose service UUID. */ -#define BLE_UUID_HEALTH_THERMOMETER_SERVICE 0x1809 /**< Health Thermometer service UUID. */ -#define BLE_UUID_HEART_RATE_SERVICE 0x180D /**< Heart Rate service UUID. */ -#define BLE_UUID_HUMAN_INTERFACE_DEVICE_SERVICE 0x1812 /**< Human Interface Device service UUID. */ -#define BLE_UUID_IMMEDIATE_ALERT_SERVICE 0x1802 /**< Immediate Alert service UUID. */ -#define BLE_UUID_LINK_LOSS_SERVICE 0x1803 /**< Link Loss service UUID. */ -#define BLE_UUID_NEXT_DST_CHANGE_SERVICE 0x1807 /**< Next Dst Change service UUID. */ -#define BLE_UUID_PHONE_ALERT_STATUS_SERVICE 0x180E /**< Phone Alert Status service UUID. */ -#define BLE_UUID_REFERENCE_TIME_UPDATE_SERVICE 0x1806 /**< Reference Time Update service UUID. */ -#define BLE_UUID_RUNNING_SPEED_AND_CADENCE 0x1814 /**< Running Speed and Cadence service UUID. */ -#define BLE_UUID_SCAN_PARAMETERS_SERVICE 0x1813 /**< Scan Parameters service UUID. */ -#define BLE_UUID_TX_POWER_SERVICE 0x1804 /**< TX Power service UUID. */ -/** @} */ - -/** @defgroup UUID_CHARACTERISTICS Characteristic UUID definitions - * @{ */ -#define BLE_UUID_BATTERY_LEVEL_STATE_CHAR 0x2A1B /**< Battery Level State characteristic UUID. */ -#define BLE_UUID_BATTERY_POWER_STATE_CHAR 0x2A1A /**< Battery Power State characteristic UUID. */ -#define BLE_UUID_REMOVABLE_CHAR 0x2A3A /**< Removable characteristic UUID. */ -#define BLE_UUID_SERVICE_REQUIRED_CHAR 0x2A3B /**< Service Required characteristic UUID. */ -#define BLE_UUID_ALERT_CATEGORY_ID_CHAR 0x2A43 /**< Alert Category Id characteristic UUID. */ -#define BLE_UUID_ALERT_CATEGORY_ID_BIT_MASK_CHAR 0x2A42 /**< Alert Category Id Bit Mask characteristic UUID. */ -#define BLE_UUID_ALERT_LEVEL_CHAR 0x2A06 /**< Alert Level characteristic UUID. */ -#define BLE_UUID_ALERT_NOTIFICATION_CONTROL_POINT_CHAR 0x2A44 /**< Alert Notification Control Point characteristic UUID. */ -#define BLE_UUID_ALERT_STATUS_CHAR 0x2A3F /**< Alert Status characteristic UUID. */ -#define BLE_UUID_BATTERY_LEVEL_CHAR 0x2A19 /**< Battery Level characteristic UUID. */ -#define BLE_UUID_BLOOD_PRESSURE_FEATURE_CHAR 0x2A49 /**< Blood Pressure Feature characteristic UUID. */ -#define BLE_UUID_BLOOD_PRESSURE_MEASUREMENT_CHAR 0x2A35 /**< Blood Pressure Measurement characteristic UUID. */ -#define BLE_UUID_BODY_SENSOR_LOCATION_CHAR 0x2A38 /**< Body Sensor Location characteristic UUID. */ -#define BLE_UUID_BOOT_KEYBOARD_INPUT_REPORT_CHAR 0x2A22 /**< Boot Keyboard Input Report characteristic UUID. */ -#define BLE_UUID_BOOT_KEYBOARD_OUTPUT_REPORT_CHAR 0x2A32 /**< Boot Keyboard Output Report characteristic UUID. */ -#define BLE_UUID_BOOT_MOUSE_INPUT_REPORT_CHAR 0x2A33 /**< Boot Mouse Input Report characteristic UUID. */ -#define BLE_UUID_CURRENT_TIME_CHAR 0x2A2B /**< Current Time characteristic UUID. */ -#define BLE_UUID_DATE_TIME_CHAR 0x2A08 /**< Date Time characteristic UUID. */ -#define BLE_UUID_DAY_DATE_TIME_CHAR 0x2A0A /**< Day Date Time characteristic UUID. */ -#define BLE_UUID_DAY_OF_WEEK_CHAR 0x2A09 /**< Day Of Week characteristic UUID. */ -#define BLE_UUID_DST_OFFSET_CHAR 0x2A0D /**< Dst Offset characteristic UUID. */ -#define BLE_UUID_EXACT_TIME_256_CHAR 0x2A0C /**< Exact Time 256 characteristic UUID. */ -#define BLE_UUID_FIRMWARE_REVISION_STRING_CHAR 0x2A26 /**< Firmware Revision String characteristic UUID. */ -#define BLE_UUID_GLUCOSE_FEATURE_CHAR 0x2A51 /**< Glucose Feature characteristic UUID. */ -#define BLE_UUID_GLUCOSE_MEASUREMENT_CHAR 0x2A18 /**< Glucose Measurement characteristic UUID. */ -#define BLE_UUID_GLUCOSE_MEASUREMENT_CONTEXT_CHAR 0x2A34 /**< Glucose Measurement Context characteristic UUID. */ -#define BLE_UUID_HARDWARE_REVISION_STRING_CHAR 0x2A27 /**< Hardware Revision String characteristic UUID. */ -#define BLE_UUID_HEART_RATE_CONTROL_POINT_CHAR 0x2A39 /**< Heart Rate Control Point characteristic UUID. */ -#define BLE_UUID_HEART_RATE_MEASUREMENT_CHAR 0x2A37 /**< Heart Rate Measurement characteristic UUID. */ -#define BLE_UUID_HID_CONTROL_POINT_CHAR 0x2A4C /**< Hid Control Point characteristic UUID. */ -#define BLE_UUID_HID_INFORMATION_CHAR 0x2A4A /**< Hid Information characteristic UUID. */ -#define BLE_UUID_IEEE_REGULATORY_CERTIFICATION_DATA_LIST_CHAR 0x2A2A /**< IEEE Regulatory Certification Data List characteristic UUID. */ -#define BLE_UUID_INTERMEDIATE_CUFF_PRESSURE_CHAR 0x2A36 /**< Intermediate Cuff Pressure characteristic UUID. */ -#define BLE_UUID_INTERMEDIATE_TEMPERATURE_CHAR 0x2A1E /**< Intermediate Temperature characteristic UUID. */ -#define BLE_UUID_LOCAL_TIME_INFORMATION_CHAR 0x2A0F /**< Local Time Information characteristic UUID. */ -#define BLE_UUID_MANUFACTURER_NAME_STRING_CHAR 0x2A29 /**< Manufacturer Name String characteristic UUID. */ -#define BLE_UUID_MEASUREMENT_INTERVAL_CHAR 0x2A21 /**< Measurement Interval characteristic UUID. */ -#define BLE_UUID_MODEL_NUMBER_STRING_CHAR 0x2A24 /**< Model Number String characteristic UUID. */ -#define BLE_UUID_UNREAD_ALERT_CHAR 0x2A45 /**< Unread Alert characteristic UUID. */ -#define BLE_UUID_NEW_ALERT_CHAR 0x2A46 /**< New Alert characteristic UUID. */ -#define BLE_UUID_PNP_ID_CHAR 0x2A50 /**< PNP Id characteristic UUID. */ -#define BLE_UUID_PROTOCOL_MODE_CHAR 0x2A4E /**< Protocol Mode characteristic UUID. */ -#define BLE_UUID_RECORD_ACCESS_CONTROL_POINT_CHAR 0x2A52 /**< Record Access Control Point characteristic UUID. */ -#define BLE_UUID_REFERENCE_TIME_INFORMATION_CHAR 0x2A14 /**< Reference Time Information characteristic UUID. */ -#define BLE_UUID_REPORT_CHAR 0x2A4D /**< Report characteristic UUID. */ -#define BLE_UUID_REPORT_MAP_CHAR 0x2A4B /**< Report Map characteristic UUID. */ -#define BLE_UUID_RINGER_CONTROL_POINT_CHAR 0x2A40 /**< Ringer Control Point characteristic UUID. */ -#define BLE_UUID_RINGER_SETTING_CHAR 0x2A41 /**< Ringer Setting characteristic UUID. */ -#define BLE_UUID_SCAN_INTERVAL_WINDOW_CHAR 0x2A4F /**< Scan Interval Window characteristic UUID. */ -#define BLE_UUID_SCAN_REFRESH_CHAR 0x2A31 /**< Scan Refresh characteristic UUID. */ -#define BLE_UUID_SERIAL_NUMBER_STRING_CHAR 0x2A25 /**< Serial Number String characteristic UUID. */ -#define BLE_UUID_SOFTWARE_REVISION_STRING_CHAR 0x2A28 /**< Software Revision String characteristic UUID. */ -#define BLE_UUID_SUPPORTED_NEW_ALERT_CATEGORY_CHAR 0x2A47 /**< Supported New Alert Category characteristic UUID. */ -#define BLE_UUID_SUPPORTED_UNREAD_ALERT_CATEGORY_CHAR 0x2A48 /**< Supported Unread Alert Category characteristic UUID. */ -#define BLE_UUID_SYSTEM_ID_CHAR 0x2A23 /**< System Id characteristic UUID. */ -#define BLE_UUID_TEMPERATURE_MEASUREMENT_CHAR 0x2A1C /**< Temperature Measurement characteristic UUID. */ -#define BLE_UUID_TEMPERATURE_TYPE_CHAR 0x2A1D /**< Temperature Type characteristic UUID. */ -#define BLE_UUID_TIME_ACCURACY_CHAR 0x2A12 /**< Time Accuracy characteristic UUID. */ -#define BLE_UUID_TIME_SOURCE_CHAR 0x2A13 /**< Time Source characteristic UUID. */ -#define BLE_UUID_TIME_UPDATE_CONTROL_POINT_CHAR 0x2A16 /**< Time Update Control Point characteristic UUID. */ -#define BLE_UUID_TIME_UPDATE_STATE_CHAR 0x2A17 /**< Time Update State characteristic UUID. */ -#define BLE_UUID_TIME_WITH_DST_CHAR 0x2A11 /**< Time With Dst characteristic UUID. */ -#define BLE_UUID_TIME_ZONE_CHAR 0x2A0E /**< Time Zone characteristic UUID. */ -#define BLE_UUID_TX_POWER_LEVEL_CHAR 0x2A07 /**< TX Power Level characteristic UUID. */ -#define BLE_UUID_CSC_FEATURE_CHAR 0x2A5C /**< Cycling Speed and Cadence Feature characteristic UUID. */ -#define BLE_UUID_CSC_MEASUREMENT_CHAR 0x2A5B /**< Cycling Speed and Cadence Measurement characteristic UUID. */ -#define BLE_UUID_RSC_FEATURE_CHAR 0x2A54 /**< Running Speed and Cadence Feature characteristic UUID. */ -#define BLE_UUID_SC_CTRLPT_CHAR 0x2A55 /**< Speed and Cadence Control Point UUID. */ -#define BLE_UUID_RSC_MEASUREMENT_CHAR 0x2A53 /**< Running Speed and Cadence Measurement characteristic UUID. */ -#define BLE_UUID_SENSOR_LOCATION_CHAR 0x2A5D /**< Sensor Location characteristic UUID. */ -/** @} */ - -/** @defgroup UUID_CHARACTERISTICS descriptors UUID definitions - * @{ */ -#define BLE_UUID_EXTERNAL_REPORT_REF_DESCR 0x2907 /**< External Report Reference descriptor UUID. */ -#define BLE_UUID_REPORT_REF_DESCR 0x2908 /**< Report Reference descriptor UUID. */ -/** @} */ - -/** @defgroup ALERT_LEVEL_VALUES Definitions for the Alert Level characteristic values - * @{ */ -#define BLE_CHAR_ALERT_LEVEL_NO_ALERT 0x00 /**< No Alert. */ -#define BLE_CHAR_ALERT_LEVEL_MILD_ALERT 0x01 /**< Mild Alert. */ -#define BLE_CHAR_ALERT_LEVEL_HIGH_ALERT 0x02 /**< High Alert. */ -/** @} */ - -#define BLE_SRV_ENCODED_REPORT_REF_LEN 2 /**< The length of an encoded Report Reference Descriptor. */ -#define BLE_CCCD_VALUE_LEN 2 /**< The length of a CCCD value. */ - -/**@brief Type definition for error handler function which will be called in case of an error in - * a service or a service library module. */ -typedef void (*ble_srv_error_handler_t)(uint32_t nrf_error); - -/**@brief Value of a Report Reference descriptor. - * - * @details This is mapping information which maps the parent characteristic to the Report ID(s) and - * Report Type(s) defined within a Report Map characteristic. - */ -typedef struct -{ - uint8_t report_id; /**< Non-zero value if these is more than one instance of the same Report Type */ - uint8_t report_type; /**< Type of Report characteristic (see @ref BLE_SRV_HIDS_REPORT_TYPE) */ -} ble_srv_report_ref_t; - -/**@brief UTF-8 string data type. - * - * @note The type can only hold a pointer to the string data (i.e. not the actual data). - */ -typedef struct -{ - uint16_t length; /**< String length. */ - uint8_t * p_str; /**< String data. */ -} ble_srv_utf8_str_t; - -/**@brief Security settings structure. - * @details This structure contains the security options needed during initialization of the - * service. - */ -typedef struct -{ - ble_gap_conn_sec_mode_t read_perm; /**< Read permissions. */ - ble_gap_conn_sec_mode_t write_perm; /**< Write permissions. */ -} ble_srv_security_mode_t; - -/**@brief Security settings structure. - * @details This structure contains the security options needed during initialization of the - * service. It can be used when the charecteristics contains cccd. - */ -typedef struct -{ - ble_gap_conn_sec_mode_t cccd_write_perm; - ble_gap_conn_sec_mode_t read_perm; /**< Read permissions. */ - ble_gap_conn_sec_mode_t write_perm; /**< Write permissions. */ -} ble_srv_cccd_security_mode_t; - -/**@brief Function for decoding a CCCD value, and then testing if notification is - * enabled. - * - * @param[in] p_encoded_data Buffer where the encoded CCCD is stored. - * - * @return TRUE if notification is enabled, FALSE otherwise. - */ -static __INLINE bool ble_srv_is_notification_enabled(uint8_t * p_encoded_data) -{ - uint16_t cccd_value = uint16_decode(p_encoded_data); - return ((cccd_value & BLE_GATT_HVX_NOTIFICATION) != 0); -} - -/**@brief Function for decoding a CCCD value, and then testing if indication is - * enabled. - * - * @param[in] p_encoded_data Buffer where the encoded CCCD is stored. - * - * @return TRUE if indication is enabled, FALSE otherwise. - */ -static __INLINE bool ble_srv_is_indication_enabled(uint8_t * p_encoded_data) -{ - uint16_t cccd_value = uint16_decode(p_encoded_data); - return ((cccd_value & BLE_GATT_HVX_INDICATION) != 0); -} - -/**@brief Function for encoding a Report Reference Descriptor. - * - * @param[in] p_encoded_buffer The buffer of the encoded data. - * @param[in] p_report_ref Report Reference value to be encoded. - * - * @return Length of the encoded data. - */ -uint8_t ble_srv_report_ref_encode(uint8_t * p_encoded_buffer, - const ble_srv_report_ref_t * p_report_ref); - -/**@brief Function for making UTF-8 structure refer to an ASCII string. - * - * @param[out] p_utf8 UTF-8 structure to be set. - * @param[in] p_ascii ASCII string to be referred to. - */ -void ble_srv_ascii_to_utf8(ble_srv_utf8_str_t * p_utf8, char * p_ascii); - -#endif // BLE_SRV_COMMON_H__ - -/** @} */ diff --git a/libraries/ble/nRF51822/nordic/nrf-sdk/ble/rpc/ble_rpc_cmd_decoder.h b/libraries/ble/nRF51822/nordic/nrf-sdk/ble/rpc/ble_rpc_cmd_decoder.h deleted file mode 100644 index 8a744bea8a..0000000000 --- a/libraries/ble/nRF51822/nordic/nrf-sdk/ble/rpc/ble_rpc_cmd_decoder.h +++ /dev/null @@ -1,81 +0,0 @@ -/* Copyright (c) 2013 Nordic Semiconductor. All Rights Reserved. - * - * The information contained herein is property of Nordic Semiconductor ASA. - * Terms and conditions of usage are described in detail in NORDIC - * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. - * - * Licensees are granted free, non-transferable use of the information. NO - * WARRANTY of ANY KIND is provided. This heading must NOT be removed from - * the file. - * - */ - -/** @file - * - * @defgroup ble_rpc_cmd_decoder Command Decoder - * @{ - * @ingroup ble_sdk_lib_serialization - * - * @brief Decoder for serialized commands from Application Chip. - * - * @details This file contains declaration of common functions used for sending responses back to - * Application Chip after the command is processed, and function for processing commands - * received by the transport layer. - */ - -#ifndef BLE_RPC_CMD_DECODER_H__ -#define BLE_RPC_CMD_DECODER_H__ - -#include - -#define RPC_DECODER_LENGTH_CHECK(LEN, INDEX, CMD) if ( INDEX > LEN) \ - return ble_rpc_cmd_resp_send(CMD, NRF_ERROR_INVALID_LENGTH); - -/**@brief Function for sending a Command Response packet to the Application Chip through the transport - * layer. - * - * @param[in] op_code The op code of the command for which the Command Response is sent. - * @param[in] status The status field to be encoded into the Command Response. - * - * @retval NRF_SUCCESS On successful write of Command Response, otherwise an error code. - * If the transport layer returns an error code while sending - * the Command Response, the same error code will be returned by this - * function (see @ref hci_transport_pkt_write for the list of - * error codes). - */ -uint32_t ble_rpc_cmd_resp_send(uint8_t op_code, uint32_t status); - -/**@brief Function for sending a command response with additional data to the Application Chip through - * the transport layer. - * - * @param[in] op_code The op code of the command for which the Command Response is sent. - * @param[in] status The status field to be encoded into the Command Response. - * @param[in] p_data The data to be sent along with the status. - * @param[in] data_len The length of the additional data. - * - * @retval NRF_SUCCESS On successful write of Command Response, otherwise an error code. - * If the transport layer returns an error code while sending - * the Command Response, the same error code will be returned by this - * function (see @ref hci_transport_pkt_write for the list of - * error codes). - */ -uint32_t ble_rpc_cmd_resp_data_send(uint8_t op_code, - uint8_t status, - const uint8_t * const p_data, - uint16_t data_len); - -/**@brief Function for scheduling an RPC command event to be processed in main-thread. - * - * @details The function will read the arrived packet from the transport layer - * which is passed for decoding by the rpc_cmd_decoder module. - * - * @param[in] p_event_data Event data. This will be NULL as rpc_evt_schedule - * does not set any data. - * @param[in] event_size Event data size. This will be 0 as rpc_evt_schedule - * does not set any data. - */ -void ble_rpc_cmd_handle(void * p_event_data, uint16_t event_size); - -#endif // BLE_RPC_CMD_DECODER_H__ - -/** @} */ diff --git a/libraries/ble/nRF51822/nordic/nrf-sdk/ble/rpc/ble_rpc_cmd_decoder_gap.h b/libraries/ble/nRF51822/nordic/nrf-sdk/ble/rpc/ble_rpc_cmd_decoder_gap.h deleted file mode 100644 index 41edb3776d..0000000000 --- a/libraries/ble/nRF51822/nordic/nrf-sdk/ble/rpc/ble_rpc_cmd_decoder_gap.h +++ /dev/null @@ -1,53 +0,0 @@ -/* Copyright (c) 2013 Nordic Semiconductor. All Rights Reserved. - * - * The information contained herein is property of Nordic Semiconductor ASA. - * Terms and conditions of usage are described in detail in NORDIC - * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. - * - * Licensees are granted free, non-transferable use of the information. NO - * WARRANTY of ANY KIND is provided. This heading must NOT be removed from - * the file. - * - */ - -/** @file - * - * @defgroup ble_rpc_cmd_decoder_gap GAP Command Decoder - * @{ - * @ingroup ble_sdk_lib_serialization - * - * @brief Decoder for serialized GAP commands from Application Chip. - * - * @details This file contains the declaration of the function that decodes the serialized GAP - * commands from Application Chip and calls the appropriate BLE stack API. - */ - -#ifndef BLE_RPC_CMD_DECODER_GAP_H__ -#define BLE_RPC_CMD_DECODER_GAP_H__ - -#include - -/**@brief Function for processing the encoded GAP command from Application Chip. - * - * @details This function will decode the encoded command and call the appropriate BLE Stack - * API. It will then create a Command Response packet with the return value from the - * stack API encoded in it and will send it to the transport layer for transmission to - * the application controller chip. - - * @param[in] p_command The encoded command. - * @param[in] op_code Operation code of the command. - * @param[in] command_len Length of the encoded command. - * - * @retval NRF_SUCCESS If the decoding of the command was successful, the soft device API - * was called, and the command response was sent to peer, otherwise an - * error code. - * If the transport layer returns an error code while sending - * the Command Response, the same error code will be returned by this - * function (see @ref hci_transport_pkt_write for the list of - * error codes). - */ -uint32_t ble_rpc_cmd_gap_decode(uint8_t * p_command, uint8_t op_code, uint32_t command_len); - -#endif // BLE_RPC_CMD_DECODER_GAP_H__ - -/** @} */ diff --git a/libraries/ble/nRF51822/nordic/nrf-sdk/ble/rpc/ble_rpc_cmd_decoder_gatts.h b/libraries/ble/nRF51822/nordic/nrf-sdk/ble/rpc/ble_rpc_cmd_decoder_gatts.h deleted file mode 100644 index 048cf7a1fd..0000000000 --- a/libraries/ble/nRF51822/nordic/nrf-sdk/ble/rpc/ble_rpc_cmd_decoder_gatts.h +++ /dev/null @@ -1,53 +0,0 @@ -/* Copyright (c) 2013 Nordic Semiconductor. All Rights Reserved. - * - * The information contained herein is property of Nordic Semiconductor ASA. - * Terms and conditions of usage are described in detail in NORDIC - * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. - * - * Licensees are granted free, non-transferable use of the information. NO - * WARRANTY of ANY KIND is provided. This heading must NOT be removed from - * the file. - * - */ - -/** @file - * - * @defgroup ble_rpc_cmd_decoder_gatts GATTS Command Decoder - * @{ - * @ingroup ble_sdk_lib_serialization - * - * @brief Decoder for serialized GATTS commands from Application Chip. - * - * @details This file contains the declaration of the function that decodes the serialized GATTS - * commands from Application Chip and calls the appropriate BLE stack API. - */ - -#ifndef BLE_RPC_CMD_DECODER_GATTS_H__ -#define BLE_RPC_CMD_DECODER_GATTS_H__ - -#include - -/**@brief Function for processing the encoded GATTS command from application chip. - * - * @details This function will decode the encoded command and call the appropriate BLE Stack - * API. It will then create a Command Response packet with the return value from the - * stack API encoded in it and will send it to the transport layer for transmission to - * the application controller chip. - - * @param[in] p_command The encoded command. - * @param[in] op_code Operation code of the command. - * @param[in] command_len Length of the encoded command. - * - * @retval NRF_SUCCESS If the decoding of the command was successful, the soft device API - * was called, and the command response was sent to peer, otherwise an - * error code. - * If the transport layer returns an error code while sending - * the Command Response, the same error code will be returned by this - * function (see @ref hci_transport_pkt_write for the list of - * error codes). - */ -uint32_t ble_rpc_cmd_gatts_decode(uint8_t * p_command, uint8_t op_code, uint32_t command_len); - -#endif // BLE_RPC_CMD_DECODER_GATTS_H__ - -/** @} */ diff --git a/libraries/ble/nRF51822/nordic/nrf-sdk/ble/rpc/ble_rpc_cmd_encoder.h b/libraries/ble/nRF51822/nordic/nrf-sdk/ble/rpc/ble_rpc_cmd_encoder.h deleted file mode 100644 index 633589e267..0000000000 --- a/libraries/ble/nRF51822/nordic/nrf-sdk/ble/rpc/ble_rpc_cmd_encoder.h +++ /dev/null @@ -1,70 +0,0 @@ -/* Copyright (c) 2013 Nordic Semiconductor. All Rights Reserved. - * - * The information contained herein is property of Nordic Semiconductor ASA. - * Terms and conditions of usage are described in detail in NORDIC - * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. - * - * Licensees are granted free, non-transferable use of the information. NO - * WARRANTY of ANY KIND is provided. This heading must NOT be removed from - * the file. - * - */ - -/** @file - * - * @defgroup ble_rpc_cmd_encoder Command Encoder - * @{ - * @ingroup ble_sdk_lib_serialization - * - * @brief Encoder for serialized commands from Application Chip. - * - * @details This file contains the declaration of the functions that encode serialized commands - * from Application Chip. - */ - -#ifndef BLE_RPC_CMD_ENCODER_H__ -#define BLE_RPC_CMD_ENCODER_H__ - -#include -#include "ble_rpc_defines.h" - -/**@brief Command response type. */ -typedef struct -{ - uint8_t op_code; /**< Operation code for which this response applies. */ - uint32_t err_code; /**< Error code received for this response applies. */ -} cmd_response_t; - -/**@brief Function for initializing the BLE S110 RPC Command Encoder module. - * - * @details This function uses the HCI Transport module, \ref hci_transport and executes - * \ref hci_transport_tx_done_register and \ref hci_transport_tx_alloc . All errors - * returned by those functions are passed on by this function. - * - * @retval NRF_SUCCESS Upon success - * @return Errors from \ref hci_transport and \ref hci_transport_tx_alloc . - */ -uint32_t ble_rpc_cmd_encoder_init(void); - -/**@brief Function for blocking in a loop, using WFE to allow low power mode, while awaiting a - * response from the connectivity chip. - * - * @param[in] op_code The Operation Code for which a response message is expected. - * - * @return The decoded error code received from the connectivity chip. - */ -uint32_t ble_rpc_cmd_resp_wait(uint8_t op_code); - -/**@brief Function for handling the command response packet. - * - * @details This function will be called when a command response is received in the transport - * layer. The response is decoded and returned to the waiting caller. - * - * @param[in] p_packet The packet from the transport layer. - * @param[in] packet_length The length of the packet. - */ -void ble_rpc_cmd_rsp_pkt_received(uint8_t * p_packet, uint16_t packet_length); - -#endif // BLE_RPC_CMD_ENCODER_H__ - -/**@} */ diff --git a/libraries/ble/nRF51822/nordic/nrf-sdk/ble/rpc/ble_rpc_defines.h b/libraries/ble/nRF51822/nordic/nrf-sdk/ble/rpc/ble_rpc_defines.h deleted file mode 100644 index 9e4eac1e58..0000000000 --- a/libraries/ble/nRF51822/nordic/nrf-sdk/ble/rpc/ble_rpc_defines.h +++ /dev/null @@ -1,55 +0,0 @@ -/* Copyright (c) 2013 Nordic Semiconductor. All Rights Reserved. - * - * The information contained herein is property of Nordic Semiconductor ASA. - * Terms and conditions of usage are described in detail in NORDIC - * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. - * - * Licensees are granted free, non-transferable use of the information. NO - * WARRANTY of ANY KIND is provided. This heading must NOT be removed from - * the file. - * - */ - -/** @file - * - * @defgroup rpc_cmd_defines Defines related to serialized BLE commands. - * @{ - * @ingroup ble_sdk_lib - * - * @brief Defines for serialized BLE commands. - * - */ - -#ifndef BLE_RPC_DEFINES_H__ -#define BLE_RPC_DEFINES_H__ - -#define RPC_CMD_OP_CODE_POS 0 /**< Position of the Op Code in the command buffer.*/ -#define RPC_CMD_DATA_POS 1 /**< Position of the data in the command buffer.*/ - -#define RPC_CMD_RESP_PKT_TYPE_POS 0 /**< Position of Packet type in the command response buffer.*/ -#define RPC_CMD_RESP_OP_CODE_POS 1 /**< Position of the Op Code in the command response buffer.*/ -#define RPC_CMD_RESP_STATUS_POS 2 /**< Position of the status field in the command response buffer.*/ - -#define RPC_BLE_FIELD_LEN 1 /**< Optional field length size in bytes. */ -#define RPC_BLE_FIELD_PRESENT 0x01 /**< Value to indicate that an optional field is encoded in the serialized packet, e.g. white list. */ -#define RPC_BLE_FIELD_NOT_PRESENT 0x00 /**< Value to indicate that an optional field is not encoded in the serialized packet. */ - -#define RPC_ERR_CODE_SIZE 4 /**< BLE API err_code size in bytes. */ -#define BLE_PKT_TYPE_SIZE 1 /**< Packet type (@ref ble_rpc_pkt_type_t) field size in bytes. */ -#define BLE_OP_CODE_SIZE 1 /**< Operation code field size in bytes. */ - -#define RPC_BLE_CMD_RESP_PKT_MIN_SIZE 6 /**< Minimum length of a command response. */ -#define RPC_BLE_PKT_MAX_SIZE 596 /**< Maximum size for a BLE packet on the HCI Transport layer. This value is the hci_mem_pool buffer size minus the HCI Transport size. @note This value must be aligned with TX_BUF_SIZE in hci_mem_pool_internal.h. */ - -/**@brief The types of packets. */ -typedef enum -{ - BLE_RPC_PKT_CMD, /**< Command packet type. */ - BLE_RPC_PKT_RESP, /**< Command Response packet type. */ - BLE_RPC_PKT_EVT, /**< Event packet type. */ - BLE_RPC_PKT_TYPE_MAX /**< Upper bound. */ -} ble_rpc_pkt_type_t; - -#endif // BLE_RPC_DEFINES_H__ - -/** @} */ diff --git a/libraries/ble/nRF51822/nordic/nrf-sdk/ble/rpc/ble_rpc_event_decoder.h b/libraries/ble/nRF51822/nordic/nrf-sdk/ble/rpc/ble_rpc_event_decoder.h deleted file mode 100644 index 2091af72de..0000000000 --- a/libraries/ble/nRF51822/nordic/nrf-sdk/ble/rpc/ble_rpc_event_decoder.h +++ /dev/null @@ -1,50 +0,0 @@ -/* Copyright (c) 2013 Nordic Semiconductor. All Rights Reserved. - * - * The information contained herein is property of Nordic Semiconductor ASA. - * Terms and conditions of usage are described in detail in NORDIC - * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. - * - * Licensees are granted free, non-transferable use of the information. NO - * WARRANTY of ANY KIND is provided. This heading must NOT be removed from - * the file. - * - */ - -/** @file - * - * @defgroup ble_rpc_evt_decoder Event Decoder - * @{ - * @ingroup ble_sdk_lib_serialization - * - * @brief Decoder for serialized events from nRF51822. - * - * @details This file contains the declaration of the function that initializes the event decoder - * module and processes received events. - */ - -#ifndef BLE_RPC_EVT_DECODER_H__ -#define BLE_RPC_EVT_DECODER_H__ - -#include - -#ifndef SVCALL_AS_NORMAL_FUNCTION -#error "The compiler define SVCALL_AS_NORMAL_FUNCTION is not defined." -#endif - - -/**@brief Function for pushing an encoded packet in the event decoder. - * - * @warning This function is not reentrant safe and should always be called from the same interrupt - * context. - * - * @param[in] p_event_packet Pointer to the encoded event received. - * @param[in] event_packet_length Length of received packet. - * - * @retval NRF_SUCCESS Upon success. - * @retval NRF_ERROR_NO_MEM Upon receive queue full. - */ -uint32_t ble_rpc_event_pkt_received(uint8_t * p_event_packet, uint16_t event_packet_length); - -#endif // BLE_RPC_EVT_DECODER_H__ - -/** @} **/ diff --git a/libraries/ble/nRF51822/nordic/nrf-sdk/ble/rpc/ble_rpc_event_decoder_gap.h b/libraries/ble/nRF51822/nordic/nrf-sdk/ble/rpc/ble_rpc_event_decoder_gap.h deleted file mode 100644 index 2879fd6d5b..0000000000 --- a/libraries/ble/nRF51822/nordic/nrf-sdk/ble/rpc/ble_rpc_event_decoder_gap.h +++ /dev/null @@ -1,49 +0,0 @@ -/* Copyright (c) 2013 Nordic Semiconductor. All Rights Reserved. - * - * The information contained herein is property of Nordic Semiconductor ASA. - * Terms and conditions of usage are described in detail in NORDIC - * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. - * - * Licensees are granted free, non-transferable use of the information. NO - * WARRANTY of ANY KIND is provided. This heading must NOT be removed from - * the file. - * - */ - -/** @file - * - * @defgroup ble_rpc_evt_decoder_gap GAP Event Decoder - * @{ - * @ingroup ble_sdk_lib_serialization - * - * @brief Decoder for serialized GAP events from nRF51822. - * - * @details This file contains declarations of functions used for decoding GAP event packets - * received from the Connectivity Chip. - * - */ - -#ifndef BLE_RPC_EVENT_DECODER_GAP_H__ -#define BLE_RPC_EVENT_DECODER_GAP_H__ - -#include -#include "ble.h" - -/** @brief Function for decoding the length of a BLE GAP event. - * - * @param[in] event_id Event Id for the event to length decode. - * @param[out] p_event_length The pointer for storing the decoded event length. - */ -void ble_rpc_gap_evt_length_decode(uint8_t event_id, uint16_t * p_event_length); - -/** @brief Function for decoding a BLE GAP event. - * - * @param[out] p_ble_evt The pointer for storing the decoded event. - * @param[in] p_packet The pointer to the encoded event. - */ -void ble_rpc_gap_evt_packet_decode(ble_evt_t * p_ble_evt, - uint8_t const * const p_packet); - -#endif // BLE_RPC_EVENT_DECODER_GAP_H__ - -/** @} **/ diff --git a/libraries/ble/nRF51822/nordic/nrf-sdk/ble/rpc/ble_rpc_event_decoder_gatts.h b/libraries/ble/nRF51822/nordic/nrf-sdk/ble/rpc/ble_rpc_event_decoder_gatts.h deleted file mode 100644 index dd2554c984..0000000000 --- a/libraries/ble/nRF51822/nordic/nrf-sdk/ble/rpc/ble_rpc_event_decoder_gatts.h +++ /dev/null @@ -1,55 +0,0 @@ -/* Copyright (c) 2013 Nordic Semiconductor. All Rights Reserved. - * - * The information contained herein is property of Nordic Semiconductor ASA. - * Terms and conditions of usage are described in detail in NORDIC - * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. - * - * Licensees are granted free, non-transferable use of the information. NO - * WARRANTY of ANY KIND is provided. This heading must NOT be removed from - * the file. - * - */ - -/** @file - * - * @defgroup ble_rpc_evt_decoder_gatts GATTS Event Decoder - * @{ - * @ingroup ble_sdk_lib_serialization - * - * @brief Decoder for serialized GATT Server events from nRF51822. - * - * @details This file contains declarations of functions used for decoding GATTS event packets - * received from the Connectivity Chip. - * - */ - -#ifndef BLE_RPC_EVENT_DECODER_GATTS_H__ -#define BLE_RPC_EVENT_DECODER_GATTS_H__ - -#include -#include "ble.h" -#include "ble_gatts.h" - -/** @brief Function for decoding the length of a BLE GATTS event. The decoded BLE GATTS event - * length will be returned in p_event_length. - * - * @param[in] event_id Event Id of the event, whose length is to be decoded. - * @param[out] p_event_length The pointer for storing the decoded event length. - * @param[in] p_packet The pointer to the encoded event. - */ -void ble_rpc_gatts_evt_length_decode(uint8_t event_id, - uint16_t * p_event_length, - uint8_t const * const p_packet); - -/** @brief Function for decoding a BLE GATTS event. The decoded BLE GATTS event will be returned in - * the memory pointed to by p_ble_evt. - * - * @param[out] p_ble_evt The pointer for storing the decoded event. - * @param[in] p_packet The pointer to the encoded event. - */ -void ble_rpc_gatts_evt_packet_decode(ble_evt_t * p_ble_evt, - uint8_t const * const p_packet); - -#endif // BLE_RPC_EVENT_DECODER_GATTS_H__ - -/** @} **/ diff --git a/libraries/ble/nRF51822/nordic/nrf-sdk/ble/rpc/ble_rpc_event_encoder.h b/libraries/ble/nRF51822/nordic/nrf-sdk/ble/rpc/ble_rpc_event_encoder.h deleted file mode 100644 index 7095ff88c4..0000000000 --- a/libraries/ble/nRF51822/nordic/nrf-sdk/ble/rpc/ble_rpc_event_encoder.h +++ /dev/null @@ -1,38 +0,0 @@ -/* Copyright (c) 2013 Nordic Semiconductor. All Rights Reserved. - * - * The information contained herein is property of Nordic Semiconductor ASA. - * Terms and conditions of usage are described in detail in NORDIC - * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. - * - * Licensees are granted free, non-transferable use of the information. NO - * WARRANTY of ANY KIND is provided. This heading must NOT be removed from - * the file. - * - */ - -/** @file - * - * @defgroup ble_rpc_event_encoder Events Encoder - * @{ - * @ingroup ble_sdk_lib_serialization - * - * @brief Event encoder for S110 SoftDevice serialization. - * - * @details This module provides a function for serializing S110 SoftDevice events. - * - */ -#ifndef BLE_RPC_EVENT_ENCODER_H__ -#define BLE_RPC_EVENT_ENCODER_H__ - -#include "ble.h" - -/**@brief Function for encoding a @ref ble_evt_t. The function will pass the serialized byte stream to the - * transport layer after encoding. - * - * @param[in] p_ble_evt S110 SoftDevice event to serialize. - */ -void ble_rpc_event_handle(ble_evt_t * p_ble_evt); - -#endif // BLE_RPC_EVENT_ENCODER_H__ - -/** @} */ diff --git a/libraries/ble/nRF51822/nordic/nrf-sdk/ble/rpc/ble_rpc_event_encoder_gap.h b/libraries/ble/nRF51822/nordic/nrf-sdk/ble/rpc/ble_rpc_event_encoder_gap.h deleted file mode 100644 index ab183480c4..0000000000 --- a/libraries/ble/nRF51822/nordic/nrf-sdk/ble/rpc/ble_rpc_event_encoder_gap.h +++ /dev/null @@ -1,41 +0,0 @@ -/* Copyright (c) 2013 Nordic Semiconductor. All Rights Reserved. - * - * The information contained herein is property of Nordic Semiconductor ASA. - * Terms and conditions of usage are described in detail in NORDIC - * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. - * - * Licensees are granted free, non-transferable use of the information. NO - * WARRANTY of ANY KIND is provided. This heading must NOT be removed from - * the file. - * - */ - -/** @file - * - * @defgroup ble_rpc_event_encoder_gap GAP Event Encoder - * @{ - * @ingroup ble_sdk_lib_serialization - * - * @brief Event encoder for S110 SoftDevice serialization. - * - * @details This module provides functions for serializing S110 SoftDevice events. - * - */ -#ifndef BLE_RPC_EVENT_ENCODER_GAP_H__ -#define BLE_RPC_EVENT_ENCODER_GAP_H__ - -#include -#include - -/**@brief Function for encoding a @ref ble_evt_t GAP event. - * - * @param[in] p_ble_evt S110 SoftDevice event to serialize. - * @param[out] p_buffer Pointer to a buffer for the encoded event. - * - * @return Number of bytes encoded. - */ -uint32_t ble_rpc_evt_gap_encode(ble_evt_t * p_ble_evt, uint8_t * p_buffer); - -#endif // BLE_RPC_EVENT_ENCODER_GAP_H__ - -/** @} */ diff --git a/libraries/ble/nRF51822/nordic/nrf-sdk/ble/rpc/ble_rpc_event_encoder_gatts.h b/libraries/ble/nRF51822/nordic/nrf-sdk/ble/rpc/ble_rpc_event_encoder_gatts.h deleted file mode 100644 index 2b42aa174f..0000000000 --- a/libraries/ble/nRF51822/nordic/nrf-sdk/ble/rpc/ble_rpc_event_encoder_gatts.h +++ /dev/null @@ -1,41 +0,0 @@ -/* Copyright (c) 2013 Nordic Semiconductor. All Rights Reserved. - * - * The information contained herein is property of Nordic Semiconductor ASA. - * Terms and conditions of usage are described in detail in NORDIC - * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. - * - * Licensees are granted free, non-transferable use of the information. NO - * WARRANTY of ANY KIND is provided. This heading must NOT be removed from - * the file. - * - */ - -/** @file - * - * @defgroup ble_rpc_event_encoder_gatts GATTS Events Encoder - * @{ - * @ingroup ble_sdk_lib_serialization - * - * @brief Event encoder for S110 SoftDevice serialization. - * - * @details This module provides functions for serializing S110 SoftDevice events. - * - */ -#ifndef BLE_RPC_EVENT_ENCODER_GATTS_H__ -#define BLE_RPC_EVENT_ENCODER_GATTS_H__ - -#include -#include - -/**@brief Function for encoding a @ref ble_evt_t GATTS event. - * - * @param[in] p_ble_evt S110 SoftDevice event to serialize. - * @param[out] p_buffer Pointer to a buffer for the encoded event. - * - * @return Number of bytes encoded. - */ -uint32_t ble_rpc_evt_gatts_encode(ble_evt_t * p_ble_evt, uint8_t * p_buffer); - -#endif // BLE_RPC_EVENT_ENCODER_GATTS_H__ - -/** @} */ diff --git a/libraries/ble/nRF51822/nordic/nrf-sdk/ble/rpc/ble_rpc_pkt_receiver.h b/libraries/ble/nRF51822/nordic/nrf-sdk/ble/rpc/ble_rpc_pkt_receiver.h deleted file mode 100644 index 6048b66301..0000000000 --- a/libraries/ble/nRF51822/nordic/nrf-sdk/ble/rpc/ble_rpc_pkt_receiver.h +++ /dev/null @@ -1,35 +0,0 @@ -/* Copyright (c) 2013 Nordic Semiconductor. All Rights Reserved. - * - * The information contained herein is property of Nordic Semiconductor ASA. - * Terms and conditions of usage are described in detail in NORDIC - * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. - * - * Licensees are granted free, non-transferable use of the information. NO - * WARRANTY of ANY KIND is provided. This heading must NOT be removed from - * the file. - * - */ - -/** @file - * - * @defgroup rpc_pkt_receiver Packet Receiver - * @{ - * @ingroup ble_sdk_lib_serialization - * - * @brief This module is used for processing the Command Response packets and Event packets. - */ - -#ifndef BLE_RPC_PKT_RECEIVER_H__ -#define BLE_RPC_PKT_RECEIVER_H__ - -#include - -/**@brief Function for initializing the BLE S110 RPC Packet Receiver module. - * - * @return NRF_SUCCESS upon success, any other upon failure. - */ -uint32_t ble_rpc_pkt_receiver_init(void); - -#endif - -/** @} **/ diff --git a/libraries/ble/nRF51822/nordic/nrf-sdk/nordic_common.h b/libraries/ble/nRF51822/nordic/nrf-sdk/nordic_common.h deleted file mode 100644 index 620c31a681..0000000000 --- a/libraries/ble/nRF51822/nordic/nrf-sdk/nordic_common.h +++ /dev/null @@ -1,73 +0,0 @@ -/* Copyright (c) 2008 Nordic Semiconductor. All Rights Reserved. - * - * The information contained herein is property of Nordic Semiconductor ASA. - * Terms and conditions of usage are described in detail in NORDIC - * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. - * - * Licensees are granted free, non-transferable use of the information. NO - * WARRANTY of ANY KIND is provided. This heading must NOT be removed from - * the file. - */ - -/** @file - * @brief Common defines and macros for firmware developed by Nordic Semiconductor. - */ - -#ifndef NORDIC_COMMON_H__ -#define NORDIC_COMMON_H__ - -#include "nordic_global.h" - -/** Swaps the upper byte with the lower byte in a 16 bit variable */ -//lint -emacro((572),SWAP) // Suppress warning 572 "Excessive shift value" -#define SWAP(x) ((((x)&0xFF)<<8)|(((x)>>8)&0xFF)) - -/** The upper 8 bits of a 16 bit value */ -#define MSB(a) (((a) & 0xFF00) >> 8) -/** The lower 8 bits (of a 16 bit value) */ -#define LSB(a) ((a) & 0xFF) - -/** Leaves the minimum of the two arguments */ -/*lint -emacro(506, MIN) */ /* Suppress "Constant value Boolean */ -#define MIN(a, b) ((a) < (b) ? (a) : (b)) -/** Leaves the maximum of the two arguments */ -/*lint -emacro(506, MAX) */ /* Suppress "Constant value Boolean */ -#define MAX(a, b) ((a) < (b) ? (b) : (a)) - -#define BIT_0 0x01 /**< The value of bit 0 */ -#define BIT_1 0x02 /**< The value of bit 1 */ -#define BIT_2 0x04 /**< The value of bit 2 */ -#define BIT_3 0x08 /**< The value of bit 3 */ -#define BIT_4 0x10 /**< The value of bit 4 */ -#define BIT_5 0x20 /**< The value of bit 5 */ -#define BIT_6 0x40 /**< The value of bit 6 */ -#define BIT_7 0x80 /**< The value of bit 7 */ -#define BIT_8 0x0100 /**< The value of bit 8 */ -#define BIT_9 0x0200 /**< The value of bit 9 */ -#define BIT_10 0x0400 /**< The value of bit 10 */ -#define BIT_11 0x0800 /**< The value of bit 11 */ -#define BIT_12 0x1000 /**< The value of bit 12 */ -#define BIT_13 0x2000 /**< The value of bit 13 */ -#define BIT_14 0x4000 /**< The value of bit 14 */ -#define BIT_15 0x8000 /**< The value of bit 15 */ -#define BIT_16 0x00010000 /**< The value of bit 16 */ -#define BIT_17 0x00020000 /**< The value of bit 17 */ -#define BIT_18 0x00040000 /**< The value of bit 18 */ -#define BIT_19 0x00080000 /**< The value of bit 19 */ -#define BIT_20 0x00100000 /**< The value of bit 20 */ -#define BIT_21 0x00200000 /**< The value of bit 21 */ -#define BIT_22 0x00400000 /**< The value of bit 22 */ -#define BIT_23 0x00800000 /**< The value of bit 23 */ -#define BIT_24 0x01000000 /**< The value of bit 24 */ -#define BIT_25 0x02000000 /**< The value of bit 25 */ -#define BIT_26 0x04000000 /**< The value of bit 26 */ -#define BIT_27 0x08000000 /**< The value of bit 27 */ -#define BIT_28 0x10000000 /**< The value of bit 28 */ -#define BIT_29 0x20000000 /**< The value of bit 29 */ -#define BIT_30 0x40000000 /**< The value of bit 30 */ -#define BIT_31 0x80000000 /**< The value of bit 31 */ - -#define UNUSED_VARIABLE(X) ((void)(X)) -#define UNUSED_PARAMETER(X) UNUSED_VARIABLE(X) - -#endif // NORDIC_COMMON_H__ diff --git a/libraries/ble/nRF51822/nordic/nrf-sdk/nrf_assert.h b/libraries/ble/nRF51822/nordic/nrf-sdk/nrf_assert.h deleted file mode 100644 index 62fef5987d..0000000000 --- a/libraries/ble/nRF51822/nordic/nrf-sdk/nrf_assert.h +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (c) 2006 Nordic Semiconductor. All Rights Reserved. - * - * The information contained herein is confidential property of Nordic Semiconductor. The use, - * copying, transfer or disclosure of such information is prohibited except by express written - * agreement with Nordic Semiconductor. - * - */ - -/** @file - * @brief Utilities for verifying program logic - */ - -#ifndef NRF_ASSERT_H_ -#define NRF_ASSERT_H_ - -#include -#include "nordic_global.h" - -#if defined(DEBUG_NRF) || defined(DEBUG_NRF_USER) - -/** @brief Function for handling assertions. - * - * - * @note - * This function is called when an assertion has triggered. - * - * - * @post - * All hardware is put into an idle non-emitting state (in particular the radio is highly - * important to switch off since the radio might be in a state that makes it send - * packets continiously while a typical final infinit ASSERT loop is executing). - * - * - * @param line_num The line number where the assertion is called - * @param file_name Pointer to the file name - */ -void assert_nrf_callback(uint16_t line_num, const uint8_t *file_name); - -/*lint -emacro(506, ASSERT) */ /* Suppress "Constant value Boolean */ -/*lint -emacro(774, ASSERT) */ /* Suppress "Boolean within 'if' always evaluates to True" */ \ - -/** @brief Function for checking intended for production code. - * - * Check passes if "expr" evaluates to true. */ -#define ASSERT(expr) \ -if (expr) \ -{ \ -} \ -else \ -{ \ - assert_nrf_callback((uint16_t)__LINE__, (uint8_t *)__FILE__); \ -} -#else -#define ASSERT(expr) //!< Assert empty when disabled -void assert_nrf_callback(uint16_t line_num, const uint8_t *file_name); -#endif /* defined(DEBUG_NRF) || defined(DEBUG_NRF_USER) */ - -#endif /* NRF_ASSERT_H_ */ diff --git a/libraries/ble/nRF51822/nordic/nrf-sdk/nrf_ecb.h b/libraries/ble/nRF51822/nordic/nrf-sdk/nrf_ecb.h deleted file mode 100644 index c36103a550..0000000000 --- a/libraries/ble/nRF51822/nordic/nrf-sdk/nrf_ecb.h +++ /dev/null @@ -1,67 +0,0 @@ -/* Copyright (c) 2012 Nordic Semiconductor. All Rights Reserved. - * - * The information contained herein is confidential property of Nordic - * Semiconductor ASA.Terms and conditions of usage are described in detail - * in NORDIC SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. - * - * Licensees are granted free, non-transferable use of the information. NO - * WARRANTY of ANY KIND is provided. This heading must NOT be removed from - * the file. - * - * $LastChangedRevision: 13999 $ - */ - -/** - * @file - * @brief ECB driver API. - */ - -#ifndef NRF_ECB_H__ -#define NRF_ECB_H__ - -/** - * @defgroup nrf_ecb AES ECB encryption - * @{ - * @ingroup nrf_drivers - * @brief Driver for the nRF51 AES Electronic Code Book (ECB) peripheral. - * - * In order to encrypt and decrypt data the peripheral must be powered on - * using nrf_ecb_init() and then the key set using nrf_ecb_set_key. - */ - -#include -#include "nordic_global.h" - -/** - * Initialize and power on the ECB peripheral. - * - * Allocates memory for the ECBDATAPTR. - * @retval true Initialization was successful. - * @retval false Powering up failed. - */ -bool nrf_ecb_init(void); - -/** - * Encrypt/decrypt 16-byte data using current key. - * - * The function avoids unnecessary copying of data if the point to the - * correct locations in the ECB data structure. - * - * @param dst Result of encryption/decryption. 16 bytes will be written. - * @param src Source with 16-byte data to be encrypted/decrypted. - * - * @retval true If the encryption operation completed. - * @retval false If the encryption operation did not complete. - */ -bool nrf_ecb_crypt(uint8_t * dst, const uint8_t * src); - -/** - * Set the key to be used for encryption/decryption. - * - * @param key Pointer to key. 16 bytes will be read. - */ -void nrf_ecb_set_key(const uint8_t * key); - -#endif // NRF_ECB_H__ - -/** @} */ diff --git a/libraries/ble/nRF51822/nordic/nrf-sdk/nrf_gpio.h b/libraries/ble/nRF51822/nordic/nrf-sdk/nrf_gpio.h deleted file mode 100644 index 50c6c0f8b2..0000000000 --- a/libraries/ble/nRF51822/nordic/nrf-sdk/nrf_gpio.h +++ /dev/null @@ -1,411 +0,0 @@ -#ifndef NRF_GPIO_H__ -#define NRF_GPIO_H__ - -#include "nordic_global.h" -#include "nrf51.h" -#include "nrf51_bitfields.h" - -/** - * @defgroup nrf_gpio GPIO abstraction - * @{ - * @ingroup nrf_drivers - * @brief GPIO pin abstraction and port abstraction for reading and writing byte-wise to GPIO ports. - * - * Here, the GPIO ports are defined as follows: - * - Port 0 -> pin 0-7 - * - Port 1 -> pin 8-15 - * - Port 2 -> pin 16-23 - * - Port 3 -> pin 24-31 - */ - -/** - * @enum nrf_gpio_port_dir_t - * @brief Enumerator used for setting the direction of a GPIO port. - */ -typedef enum -{ - NRF_GPIO_PORT_DIR_OUTPUT, ///< Output - NRF_GPIO_PORT_DIR_INPUT ///< Input -} nrf_gpio_port_dir_t; - -/** - * @enum nrf_gpio_pin_dir_t - * Pin direction definitions. - */ -typedef enum -{ - NRF_GPIO_PIN_DIR_INPUT, ///< Input - NRF_GPIO_PIN_DIR_OUTPUT ///< Output -} nrf_gpio_pin_dir_t; - -/** - * @enum nrf_gpio_port_select_t - * @brief Enumerator used for selecting between port 0 - 3. - */ -typedef enum -{ - NRF_GPIO_PORT_SELECT_PORT0 = 0, ///< Port 0 (GPIO pin 0-7) - NRF_GPIO_PORT_SELECT_PORT1, ///< Port 1 (GPIO pin 8-15) - NRF_GPIO_PORT_SELECT_PORT2, ///< Port 2 (GPIO pin 16-23) - NRF_GPIO_PORT_SELECT_PORT3, ///< Port 3 (GPIO pin 24-31) -} nrf_gpio_port_select_t; - -/** - * @enum nrf_gpio_pin_pull_t - * @brief Enumerator used for selecting the pin to be pulled down or up at the time of pin configuration - */ -typedef enum -{ - NRF_GPIO_PIN_NOPULL = GPIO_PIN_CNF_PULL_Disabled, ///< Pin pullup resistor disabled - NRF_GPIO_PIN_PULLDOWN = GPIO_PIN_CNF_PULL_Pulldown, ///< Pin pulldown resistor enabled - NRF_GPIO_PIN_PULLUP = GPIO_PIN_CNF_PULL_Pullup, ///< Pin pullup resistor enabled -} nrf_gpio_pin_pull_t; - -/** - * @enum nrf_gpio_pin_sense_t - * @brief Enumerator used for selecting the pin to sense high or low level on the pin input. - */ -typedef enum -{ - NRF_GPIO_PIN_NOSENSE = GPIO_PIN_CNF_SENSE_Disabled, ///< Pin sense level disabled. - NRF_GPIO_PIN_SENSE_LOW = GPIO_PIN_CNF_SENSE_Low, ///< Pin sense low level. - NRF_GPIO_PIN_SENSE_HIGH = GPIO_PIN_CNF_SENSE_High, ///< Pin sense high level. -} nrf_gpio_pin_sense_t; - -/** - * @brief Function for configuring the GPIO pin range as outputs with normal drive strength. - * This function can be used to configure pin range as simple output with gate driving GPIO_PIN_CNF_DRIVE_S0S1 (normal cases). - * - * @param pin_range_start specifies the start number (inclusive) in the range of pin numbers to be configured (allowed values 0-30) - * - * @param pin_range_end specifies the end number (inclusive) in the range of pin numbers to be configured (allowed values 0-30) - * - * @note For configuring only one pin as output use @ref nrf_gpio_cfg_output - * Sense capability on the pin is disabled, and input is disconnected from the buffer as the pins are configured as output. - */ -static __INLINE void nrf_gpio_range_cfg_output(uint32_t pin_range_start, uint32_t pin_range_end) -{ - /*lint -e{845} // A zero has been given as right argument to operator '|'" */ - for (; pin_range_start <= pin_range_end; pin_range_start++) - { - NRF_GPIO->PIN_CNF[pin_range_start] = (GPIO_PIN_CNF_SENSE_Disabled << GPIO_PIN_CNF_SENSE_Pos) - | (GPIO_PIN_CNF_DRIVE_S0S1 << GPIO_PIN_CNF_DRIVE_Pos) - | (GPIO_PIN_CNF_PULL_Disabled << GPIO_PIN_CNF_PULL_Pos) - | (GPIO_PIN_CNF_INPUT_Connect << GPIO_PIN_CNF_INPUT_Pos) - | (GPIO_PIN_CNF_DIR_Output << GPIO_PIN_CNF_DIR_Pos); - } -} - -/** - * @brief Function for configuring the GPIO pin range as inputs with given initial value set, hiding inner details. - * This function can be used to configure pin range as simple input. - * - * @param pin_range_start specifies the start number (inclusive) in the range of pin numbers to be configured (allowed values 0-30) - * - * @param pin_range_end specifies the end number (inclusive) in the range of pin numbers to be configured (allowed values 0-30) - * - * @param pull_config State of the pin range pull resistor (no pull, pulled down or pulled high) - * - * @note For configuring only one pin as input use @ref nrf_gpio_cfg_input - * Sense capability on the pin is disabled, and input is connected to buffer so that the GPIO->IN register is readable - */ -static __INLINE void nrf_gpio_range_cfg_input(uint32_t pin_range_start, uint32_t pin_range_end, nrf_gpio_pin_pull_t pull_config) -{ - /*lint -e{845} // A zero has been given as right argument to operator '|'" */ - for (; pin_range_start <= pin_range_end; pin_range_start++) - { - NRF_GPIO->PIN_CNF[pin_range_start] = (GPIO_PIN_CNF_SENSE_Disabled << GPIO_PIN_CNF_SENSE_Pos) - | (GPIO_PIN_CNF_DRIVE_S0S1 << GPIO_PIN_CNF_DRIVE_Pos) - | (pull_config << GPIO_PIN_CNF_PULL_Pos) - | (GPIO_PIN_CNF_INPUT_Connect << GPIO_PIN_CNF_INPUT_Pos) - | (GPIO_PIN_CNF_DIR_Input << GPIO_PIN_CNF_DIR_Pos); - } -} - -/** - * @brief Function for configuring the given GPIO pin number as output with given initial value set, hiding inner details. - * This function can be used to configure pin range as simple input with gate driving GPIO_PIN_CNF_DRIVE_S0S1 (normal cases). - * - * @param pin_number specifies the pin number of gpio pin numbers to be configured (allowed values 0-30) - * - * @note Sense capability on the pin is disabled, and input is disconnected from the buffer as the pins are configured as output. - */ -static __INLINE void nrf_gpio_cfg_output(uint32_t pin_number) -{ - /*lint -e{845} // A zero has been given as right argument to operator '|'" */ - NRF_GPIO->PIN_CNF[pin_number] = (GPIO_PIN_CNF_SENSE_Disabled << GPIO_PIN_CNF_SENSE_Pos) - | (GPIO_PIN_CNF_DRIVE_S0S1 << GPIO_PIN_CNF_DRIVE_Pos) - | (GPIO_PIN_CNF_PULL_Disabled << GPIO_PIN_CNF_PULL_Pos) - | (GPIO_PIN_CNF_INPUT_Connect << GPIO_PIN_CNF_INPUT_Pos) - | (GPIO_PIN_CNF_DIR_Output << GPIO_PIN_CNF_DIR_Pos); -} - -/** - * @brief Function for configuring the given GPIO pin number as input with given initial value set, hiding inner details. - * This function can be used to configure pin range as simple input with gate driving GPIO_PIN_CNF_DRIVE_S0S1 (normal cases). - * - * @param pin_number specifies the pin number of gpio pin numbers to be configured (allowed values 0-30) - * - * @param pull_config State of the pin range pull resistor (no pull, pulled down or pulled high) - * - * @note Sense capability on the pin is disabled, and input is connected to buffer so that the GPIO->IN register is readable - */ -static __INLINE void nrf_gpio_cfg_input(uint32_t pin_number, nrf_gpio_pin_pull_t pull_config) -{ - /*lint -e{845} // A zero has been given as right argument to operator '|'" */ - NRF_GPIO->PIN_CNF[pin_number] = (GPIO_PIN_CNF_SENSE_Disabled << GPIO_PIN_CNF_SENSE_Pos) - | (GPIO_PIN_CNF_DRIVE_S0S1 << GPIO_PIN_CNF_DRIVE_Pos) - | (pull_config << GPIO_PIN_CNF_PULL_Pos) - | (GPIO_PIN_CNF_INPUT_Connect << GPIO_PIN_CNF_INPUT_Pos) - | (GPIO_PIN_CNF_DIR_Input << GPIO_PIN_CNF_DIR_Pos); -} - -/** - * @brief Function for configuring the given GPIO pin number as input with given initial value set, hiding inner details. - * This function can be used to configure pin range as simple input with gate driving GPIO_PIN_CNF_DRIVE_S0S1 (normal cases). - * Sense capability on the pin is configurable, and input is connected to buffer so that the GPIO->IN register is readable. - * - * @param pin_number specifies the pin number of gpio pin numbers to be configured (allowed values 0-30). - * - * @param pull_config state of the pin pull resistor (no pull, pulled down or pulled high). - * - * @param sense_config sense level of the pin (no sense, sense low or sense high). - */ -static __INLINE void nrf_gpio_cfg_sense_input(uint32_t pin_number, nrf_gpio_pin_pull_t pull_config, nrf_gpio_pin_sense_t sense_config) -{ - /*lint -e{845} // A zero has been given as right argument to operator '|'" */ - NRF_GPIO->PIN_CNF[pin_number] = (sense_config << GPIO_PIN_CNF_SENSE_Pos) - | (GPIO_PIN_CNF_DRIVE_S0S1 << GPIO_PIN_CNF_DRIVE_Pos) - | (pull_config << GPIO_PIN_CNF_PULL_Pos) - | (GPIO_PIN_CNF_INPUT_Connect << GPIO_PIN_CNF_INPUT_Pos) - | (GPIO_PIN_CNF_DIR_Input << GPIO_PIN_CNF_DIR_Pos); -} - -/** - * @brief Function for setting the direction for a GPIO pin. - * - * @param pin_number specifies the pin number [0:31] for which to - * set the direction. - * - * @param direction specifies the direction - */ -static __INLINE void nrf_gpio_pin_dir_set(uint32_t pin_number, nrf_gpio_pin_dir_t direction) -{ - if(direction == NRF_GPIO_PIN_DIR_INPUT) - { - NRF_GPIO->PIN_CNF[pin_number] = - (GPIO_PIN_CNF_SENSE_Disabled << GPIO_PIN_CNF_SENSE_Pos) - | (GPIO_PIN_CNF_DRIVE_S0S1 << GPIO_PIN_CNF_DRIVE_Pos) - | (GPIO_PIN_CNF_PULL_Disabled << GPIO_PIN_CNF_PULL_Pos) - | (GPIO_PIN_CNF_INPUT_Connect << GPIO_PIN_CNF_INPUT_Pos) - | (GPIO_PIN_CNF_DIR_Input << GPIO_PIN_CNF_DIR_Pos); - } - else - { - NRF_GPIO->DIRSET = (1UL << pin_number); - } -} - -/** - * @brief Function for setting a GPIO pin. - * - * Note that the pin must be configured as an output for this - * function to have any effect. - * - * @param pin_number specifies the pin number [0:31] to - * set. - */ -static __INLINE void nrf_gpio_pin_set(uint32_t pin_number) -{ - NRF_GPIO->OUTSET = (1UL << pin_number); -} - -/** - * @brief Function for clearing a GPIO pin. - * - * Note that the pin must be configured as an output for this - * function to have any effect. - * - * @param pin_number specifies the pin number [0:31] to - * clear. - */ -static __INLINE void nrf_gpio_pin_clear(uint32_t pin_number) -{ - NRF_GPIO->OUTCLR = (1UL << pin_number); -} - -/** - * @brief Function for toggling a GPIO pin. - * - * Note that the pin must be configured as an output for this - * function to have any effect. - * - * @param pin_number specifies the pin number [0:31] to - * toggle. - */ -static __INLINE void nrf_gpio_pin_toggle(uint32_t pin_number) -{ - NRF_GPIO->OUT ^= (1UL << pin_number); -} - -/** - * @brief Function for writing a value to a GPIO pin. - * - * Note that the pin must be configured as an output for this - * function to have any effect. - * - * @param pin_number specifies the pin number [0:31] to - * write. - * - * @param value specifies the value to be written to the pin. - * @arg 0 clears the pin - * @arg >=1 sets the pin. - */ -static __INLINE void nrf_gpio_pin_write(uint32_t pin_number, uint32_t value) -{ - if (value == 0) - { - nrf_gpio_pin_clear(pin_number); - } - else - { - nrf_gpio_pin_set(pin_number); - } -} - -/** - * @brief Function for reading the input level of a GPIO pin. - * - * Note that the pin must have input connected for the value - * returned from this function to be valid. - * - * @param pin_number specifies the pin number [0:31] to - * read. - * - * @return - * @retval 0 if the pin input level is low. - * @retval 1 if the pin input level is high. - * @retval > 1 should never occur. - */ -static __INLINE uint32_t nrf_gpio_pin_read(uint32_t pin_number) -{ - return ((NRF_GPIO->IN >> pin_number) & 1UL); -} - -/** - * @brief Generic function for writing a single byte of a 32 bit word at a given - * address. - * - * This function should not be called from outside the nrf_gpio - * abstraction layer. - * - * @param word_address is the address of the word to be written. - * - * @param byte_no is the the word byte number (0-3) to be written. - * - * @param value is the value to be written to byte "byte_no" of word - * at address "word_address" - */ -static __INLINE void nrf_gpio_word_byte_write(volatile uint32_t * word_address, uint8_t byte_no, uint8_t value) -{ - *((volatile uint8_t*)(word_address) + byte_no) = value; -} - -/** - * @brief Generic function for reading a single byte of a 32 bit word at a given - * address. - * - * This function should not be called from outside the nrf_gpio - * abstraction layer. - * - * @param word_address is the address of the word to be read. - * - * @param byte_no is the the byte number (0-3) of the word to be read. - * - * @return byte "byte_no" of word at address "word_address". - */ -static __INLINE uint8_t nrf_gpio_word_byte_read(const volatile uint32_t* word_address, uint8_t byte_no) -{ - return (*((const volatile uint8_t*)(word_address) + byte_no)); -} - -/** - * @brief Function for setting the direction of a port. - * - * @param port is the port for which to set the direction. - * - * @param dir direction to be set for this port. - */ -static __INLINE void nrf_gpio_port_dir_set(nrf_gpio_port_select_t port, nrf_gpio_port_dir_t dir) -{ - if (dir == NRF_GPIO_PORT_DIR_OUTPUT) - { - nrf_gpio_word_byte_write(&NRF_GPIO->DIRSET, port, 0xFF); - } - else - { - nrf_gpio_range_cfg_input(port*8, (port+1)*8-1, NRF_GPIO_PIN_NOPULL); - } -} - -/** - * @brief Function for reading a GPIO port. - * - * @param port is the port to read. - * - * @return the input value on this port. - */ -static __INLINE uint8_t nrf_gpio_port_read(nrf_gpio_port_select_t port) -{ - return nrf_gpio_word_byte_read(&NRF_GPIO->IN, port); -} - -/** - * @brief Function for writing to a GPIO port. - * - * @param port is the port to write. - * - * @param value is the value to write to this port. - * - * @sa nrf_gpio_port_dir_set() - */ -static __INLINE void nrf_gpio_port_write(nrf_gpio_port_select_t port, uint8_t value) -{ - nrf_gpio_word_byte_write(&NRF_GPIO->OUT, port, value); -} - -/** - * @brief Function for setting individual pins on GPIO port. - * - * @param port is the port for which to set the pins. - * - * @param set_mask is a mask specifying which pins to set. A bit - * set to 1 indicates that the corresponding port pin shall be - * set. - * - * @sa nrf_gpio_port_dir_set() - */ -static __INLINE void nrf_gpio_port_set(nrf_gpio_port_select_t port, uint8_t set_mask) -{ - nrf_gpio_word_byte_write(&NRF_GPIO->OUTSET, port, set_mask); -} - -/** - * @brief Function for clearing individual pins on GPIO port. - * - * @param port is the port for which to clear the pins. - * - * @param clr_mask is a mask specifying which pins to clear. A bit - * set to 1 indicates that the corresponding port pin shall be - * cleared. - * - * @sa nrf_gpio_port_dir_set() - */ -static __INLINE void nrf_gpio_port_clear(nrf_gpio_port_select_t port, uint8_t clr_mask) -{ - nrf_gpio_word_byte_write(&NRF_GPIO->OUTCLR, port, clr_mask); -} - -/** @} */ - -#endif diff --git a/libraries/ble/nRF51822/nordic/nrf-sdk/nrf_nvmc.h b/libraries/ble/nRF51822/nordic/nrf-sdk/nrf_nvmc.h deleted file mode 100644 index 7c68c0d541..0000000000 --- a/libraries/ble/nRF51822/nordic/nrf-sdk/nrf_nvmc.h +++ /dev/null @@ -1,91 +0,0 @@ -/* Copyright (c) 2012 Nordic Semiconductor. All Rights Reserved. - * - * The information contained herein is confidential property of Nordic - * Semiconductor ASA.Terms and conditions of usage are described in detail - * in NORDIC SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. - * - * Licensees are granted free, non-transferable use of the information. NO - * WARRANTY of ANY KIND is provided. This heading must NOT be removed from - * the file. - * - * $LastChangedRevision: 17685 $ - */ - -/** - * @file - * @brief NMVC driver API. - */ - -#ifndef NRF_NVMC_H__ -#define NRF_NVMC_H__ - -#include -#include "nordic_global.h" - - -/** - * @defgroup nrf_nvmc Non-volatile memory controller - * @{ - * @ingroup nrf_drivers - * @brief Driver for the nRF51 NVMC peripheral. - * - * This driver allows writing to the non-volatile memory (NVM) regions - * of the nRF51. In order to write to NVM the controller must be powered - * on and the relevant page must be erased. - * - */ - - -/** - * @brief Erase a page in flash. This is required before writing to any - * address in the page. - * - * @param address Start address of the page. - */ -void nrf_nvmc_page_erase(uint32_t address); - - -/** - * @brief Write a single byte to flash. - * - * The function reads the word containing the byte, and then - * rewrites the entire word. - * - * @param address Address to write to. - * @param value Value to write. - */ -void nrf_nvmc_write_byte(uint32_t address , uint8_t value); - - -/** - * @brief Write a 32-bit word to flash. - * @param address Address to write to. - * @param value Value to write. - */ -void nrf_nvmc_write_word(uint32_t address, uint32_t value); - - -/** - * @brief Write consecutive bytes to flash. - * - * @param address Address to write to. - * @param src Pointer to data to copy from. - * @param num_bytes Number of bytes in src to write. - */ -void nrf_nvmc_write_bytes(uint32_t address, const uint8_t * src, uint32_t num_bytes); - - -/** - @ @brief Write consecutive words to flash. - * - * @param address Address to write to. - * @param src Pointer to data to copy from. - * @param num_words Number of bytes in src to write. - */ -void nrf_nvmc_write_words(uint32_t address, const uint32_t * src, uint32_t num_words); - - -#endif // NRF_NVMC_H__ -/** @} */ - - diff --git a/libraries/ble/nRF51822/nordic/nrf-sdk/nrf_temp.h b/libraries/ble/nRF51822/nordic/nrf-sdk/nrf_temp.h deleted file mode 100644 index 74a3df368b..0000000000 --- a/libraries/ble/nRF51822/nordic/nrf-sdk/nrf_temp.h +++ /dev/null @@ -1,62 +0,0 @@ -/* Copyright (c) 2012 Nordic Semiconductor. All Rights Reserved. - * - * The information contained herein is property of Nordic Semiconductor ASA. - * Terms and conditions of usage are described in detail in NORDIC - * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. - * - * Licensees are granted free, non-transferable use of the information. NO - * WARRANTY of ANY KIND is provided. This heading must NOT be removed from - * the file. - * - */ - -#ifndef NRF_TEMP_H__ -#define NRF_TEMP_H__ - -#include "nordic_global.h" -#include "nrf51.h" - -/** -* @defgroup nrf_temperature TEMP (temperature) abstraction -* @{ -* @ingroup nrf_drivers temperature_example -* @brief Temperature module init and read functions. -* -*/ - - - -/** - * @brief Function for preparing the temp module for temperature measurement. - * - * This function initializes the TEMP module and writes to the hidden configuration register. - * - * @param none - */ -static __INLINE void nrf_temp_init(void) -{ - /**@note Workaround for PAN_028 rev2.0A anomaly 31 - TEMP: Temperature offset value has to be manually loaded to the TEMP module */ - *(uint32_t *) 0x4000C504 = 0; -} - - - -#define MASK_SIGN (0x00000200UL) -#define MASK_SIGN_EXTENSION (0xFFFFFC00UL) - -/** - * @brief Function for reading temperature measurement. - * - * The function reads the 10 bit 2's complement value and transforms it to a 32 bit 2's complement value. - * - * @param none - */ -static __INLINE int32_t nrf_temp_read(void) -{ - /**@note Workaround for PAN_028 rev2.0A anomaly 28 - TEMP: Negative measured values are not represented correctly */ - return ((NRF_TEMP->TEMP & MASK_SIGN) != 0) ? (NRF_TEMP->TEMP | MASK_SIGN_EXTENSION) : (NRF_TEMP->TEMP); -} - -/** @} */ - -#endif diff --git a/libraries/ble/nRF51822/nordic/nrf-sdk/s110/ble.h b/libraries/ble/nRF51822/nordic/nrf-sdk/s110/ble.h deleted file mode 100644 index 4f2ab86089..0000000000 --- a/libraries/ble/nRF51822/nordic/nrf-sdk/s110/ble.h +++ /dev/null @@ -1,303 +0,0 @@ -/* Copyright (c) 2011 Nordic Semiconductor. All Rights Reserved. - * - * The information contained herein is confidential property of Nordic Semiconductor. The use, - * copying, transfer or disclosure of such information is prohibited except by express written - * agreement with Nordic Semiconductor. - * - */ -/** - @addtogroup BLE_COMMON BLE SoftDevice Common - @{ - @defgroup ble_api Events, type definitions and API calls - @{ - - @brief Module independent events, type definitions and API calls for the S110 SoftDevice. - - */ - -#ifndef BLE_H__ -#define BLE_H__ - -#include "nordic_global.h" -#include "ble_ranges.h" -#include "ble_types.h" -#include "ble_gap.h" -#include "ble_l2cap.h" -#include "ble_gatt.h" -#include "ble_gattc.h" -#include "ble_gatts.h" - -/** - * @brief Common API SVC numbers. - */ -enum BLE_COMMON_SVCS -{ - SD_BLE_EVT_GET = BLE_SVC_BASE, /**< Get an event from the pending events queue. */ - SD_BLE_TX_BUFFER_COUNT_GET, /**< Get the total number of available application transmission buffers from the stack. */ - SD_BLE_UUID_VS_ADD, /**< Add a Vendor Specific UUID. */ - SD_BLE_UUID_DECODE, /**< Decode UUID bytes. */ - SD_BLE_UUID_ENCODE, /**< Encode UUID bytes. */ - SD_BLE_VERSION_GET, /**< Get the local version information (company id, LMP Version, LMP Subversion). */ - SD_BLE_USER_MEM_REPLY, /**< User Memory Reply. */ -}; - -/** @brief Required pointer alignment for BLE Events. -*/ -#define BLE_EVTS_PTR_ALIGNMENT 4 - -/** @defgroup BLE_USER_MEM_TYPES User Memory Types - * @{ */ -#define BLE_USER_MEM_TYPE_INVALID 0x00 /**< Invalid User Memory Types. */ -#define BLE_USER_MEM_TYPE_GATTS_QUEUED_WRITES 0x01 /**< User Memory for GATTS queued writes. */ -/** @} */ - -/** @brief Maximum number of Vendor Specific UUIDs. -*/ -#define BLE_UUID_VS_MAX_COUNT 10 - -/** - * @brief BLE Module Independent Event IDs. - */ -enum BLE_COMMON_EVTS -{ - BLE_EVT_TX_COMPLETE = BLE_EVT_BASE, /**< Transmission Complete. */ - BLE_EVT_USER_MEM_REQUEST, /**< User Memory request. */ - BLE_EVT_USER_MEM_RELEASE /**< User Memory release. */ -}; - -/**@brief User Memory Block. */ -typedef struct -{ - uint8_t* p_mem; /**< Pointer to the start of the user memory block. */ - uint16_t len; /**< Length in bytes of the user memory block. */ -} ble_user_mem_block_t; - -/** - * @brief TX complete event. - */ -typedef struct -{ - uint8_t count; /**< Number of packets transmitted. */ -} ble_evt_tx_complete_t; - -/**@brief Event structure for BLE_EVT_USER_MEM_REQUEST. */ -typedef struct -{ - uint8_t type; /**< User memory type, see @ref BLE_USER_MEM_TYPES. */ -} ble_evt_user_mem_request_t; - -/**@brief Event structure for BLE_EVT_USER_MEM_RELEASE. */ -typedef struct -{ - uint8_t type; /**< User memory type, see @ref BLE_USER_MEM_TYPES. */ - ble_user_mem_block_t mem_block; /**< User memory block */ -} ble_evt_user_mem_release_t; - - -/**@brief Event structure for events not associated with a specific function module. */ -typedef struct -{ - uint16_t conn_handle; /**< Connection Handle on which this event occured. */ - union - { - ble_evt_tx_complete_t tx_complete; /**< Transmission Complete. */ - ble_evt_user_mem_request_t user_mem_request; /**< User Memory Request Event Parameters. */ - ble_evt_user_mem_release_t user_mem_release; /**< User Memory Release Event Parameters. */ - } params; -} ble_common_evt_t; - -/**@brief BLE Event header. */ -typedef struct -{ - uint16_t evt_id; /**< Value from a BLE__EVT series. */ - uint16_t evt_len; /**< Length in octets excluding this header. */ -} ble_evt_hdr_t; - -/**@brief Common BLE Event type, wrapping the module specific event reports. */ -typedef struct -{ - ble_evt_hdr_t header; /**< Event header. */ - union - { - ble_common_evt_t common_evt; /**< Common Event, evt_id in BLE_EVT_* series. */ - ble_gap_evt_t gap_evt; /**< GAP originated event, evt_id in BLE_GAP_EVT_* series. */ - ble_l2cap_evt_t l2cap_evt; /**< L2CAP originated event, evt_id in BLE_L2CAP_EVT* series. */ - ble_gattc_evt_t gattc_evt; /**< GATT client originated event, evt_id in BLE_GATTC_EVT* series. */ - ble_gatts_evt_t gatts_evt; /**< GATT server originated event, evt_id in BLE_GATTS_EVT* series. */ - } evt; -} ble_evt_t; - - -/** - * @brief Version Information. - */ -typedef struct -{ - uint8_t version_number; /**< LMP Version number for BT 4.0 spec is 6 (https://www.bluetooth.org/technical/assignednumbers/link_layer.htm). */ - uint16_t company_id; /**< Company ID, Nordic Semiconductor's company ID is 89 (0x0059) (https://www.bluetooth.org/apps/content/Default.aspx?doc_id=49708). */ - uint16_t subversion_number; /**< LMP Sub Version number corresponds to the SoftDevice Config ID. */ -} ble_version_t; - - -/**@brief Get an event from the pending events queue. - * - * @param[in] p_dest Pointer to buffer to be filled in with an event, or NULL to retrieve the event length. This buffer must be 4-byte aligned in memory. - * @param[in, out] p_len Pointer the length of the buffer, on return it is filled with the event length. - * - * @details This call allows the application to pull a BLE event from the BLE stack. The application is signalled that an event is - * available from the BLE Stack by the triggering of the SD_EVT_IRQn interrupt (mapped to IRQ 22). - * The application is free to choose whether to call this function from thread mode (main context) or directly from the Interrupt Service Routine - * that maps to SD_EVT_IRQn. In any case however, and because the BLE stack runs at a higher priority than the application, this function should be called - * in a loop (until @ref NRF_ERROR_NOT_FOUND is returned) every time SD_EVT_IRQn is raised to ensure that all available events are pulled from the stack. - * Failure to do so could potentially leave events in the internal queue without the application being aware of this fact. - * Sizing the p_dest buffer is equally important, since the application needs to provide all the memory necessary for the event to be copied into - * application memory. If the buffer provided is not large enough to fit the entire contents of the event, @ref NRF_ERROR_DATA_SIZE will be returned - * and the application can then call again with a larger buffer size. - * Please note that because of the variable length nature of some events, sizeof(ble_evt_t) will not always be large enough to fit certain events, - * and so it is the application's responsability to provide an amount of memory large enough so that the relevant event is copied in full. - * The application may "peek" the event length by providing p_dest as a NULL pointer and inspecting the value of *p_len upon return. - * - * @note The pointer supplied must be aligned to the extend defined by @ref BLE_EVTS_PTR_ALIGNMENT - * - * @return @ref NRF_SUCCESS Event pulled and stored into the supplied buffer. - * @return @ref NRF_ERROR_INVALID_ADDR Invalid or not sufficiently aligned pointer supplied. - * @return @ref NRF_ERROR_NOT_FOUND No events ready to be pulled. - * @return @ref NRF_ERROR_DATA_SIZE Event ready but could not fit into the supplied buffer. - */ -SVCALL(SD_BLE_EVT_GET, uint32_t, sd_ble_evt_get(uint8_t* p_dest, uint16_t *p_len)); - - -/**@brief Get the total number of available application transmission buffers in the BLE stack. - * - * @details This call allows the application to obtain the total number of - * transmission buffers available for application data. Please note that - * this does not give the number of free buffers, but rather the total amount of them. - * The application has two options to handle its own application transmission buffers: - * - Use a simple arithmetic calculation: at boot time the application should use this function - * to find out the total amount of buffers available to it and store it in a variable. - * Every time a packet that consumes an application buffer is sent using any of the - * exposed functions in this BLE API, the application should decrement that variable. - * Conversely, whenever a @ref BLE_EVT_TX_COMPLETE event is received by the application - * it should retrieve the count field in such event and add that number to the same - * variable storing the number of available packets. - * This mechanism allows the application to be aware at any time of the number of - * application packets available in the BLE stack's internal buffers, and therefore - * it can know with certainty whether it is possible to send more data or it has to - * wait for a @ref BLE_EVT_TX_COMPLETE event before it proceeds. - * - Choose to simply not keep track of available buffers at all, and instead handle the - * @ref BLE_ERROR_NO_TX_BUFFERS error by queueing the packet to be transmitted and - * try again as soon as a @ref BLE_EVT_TX_COMPLETE event arrives. - * - * The API functions that may consume an application buffer depending on - * the parameters supplied to them can be found below: - * - * - @ref sd_ble_gattc_write (write witout response only) - * - @ref sd_ble_gatts_hvx (notifications only) - * - @ref sd_ble_l2cap_tx (all packets) - * - * @param[out] p_count Pointer to a uint8_t which will contain the number of application transmission buffers upon - * successful return. - * - * @return @ref NRF_SUCCESS Number of application transmission buffers retrieved successfully. - * @return @ref NRF_ERROR_INVALID_ADDR Invalid pointer supplied. - */ -SVCALL(SD_BLE_TX_BUFFER_COUNT_GET, uint32_t, sd_ble_tx_buffer_count_get(uint8_t* p_count)); - - -/**@brief Add a Vendor Specific UUID. - * - * @details This call enables the application to add a vendor specific UUID to the BLE stack's table, - * for later use all other modules and APIs. This then allows the application to use the shorter, - * 24-bit @ref ble_uuid_t format when dealing with both 16-bit and 128-bit UUIDs without having to - * check for lengths and having split code paths. The way that this is accomplished is by extending the - * grouping mechanism that the Bluetooth SIG standard base UUID uses for all other 128-bit UUIDs. The - * type field in the @ref ble_uuid_t structure is an index (relative to @ref BLE_UUID_TYPE_VENDOR_BEGIN) - * to the table populated by multiple calls to this function, and the uuid field in the same structure - * contains the 2 bytes at indices 12 and 13. The number of possible 128-bit UUIDs available to the - * application is therefore the number of Vendor Specific UUIDs added with the help of this function times 65536, - * although restricted to modifying bytes 12 and 13 for each of the entries in the supplied array. - * - * @note Bytes 12 and 13 of the provided UUID will not be used internally, since those are always replaced by - * the 16-bit uuid field in @ref ble_uuid_t. - * - * - * @param[in] p_vs_uuid Pointer to a 16-octet (128-bit) little endian Vendor Specific UUID disregarding - * bytes 12 and 13. - * @param[out] p_uuid_type Pointer where the type field in @ref ble_uuid_t corresponding to this UUID will be stored. - * - * @return @ref NRF_SUCCESS Successfully added the Vendor Specific UUID. - * @return @ref NRF_ERROR_INVALID_ADDR If p_vs_uuid or p_uuid_type is NULL or invalid. - * @return @ref NRF_ERROR_NO_MEM If there are no more free slots for VS UUIDs. - * @return @ref NRF_ERROR_FORBIDDEN If p_vs_uuid has already been added to the VS UUID table. - */ -SVCALL(SD_BLE_UUID_VS_ADD, uint32_t, sd_ble_uuid_vs_add(ble_uuid128_t const * const p_vs_uuid, uint8_t * const p_uuid_type)); - - -/** @brief Decode little endian raw UUID bytes (16-bit or 128-bit) into a 24 bit @ref ble_uuid_t structure. - * - * @details The raw UUID bytes excluding bytes 12 and 13 (i.e. bytes 0-11 and 14-15) of p_uuid_le are compared - * to the corresponding ones in each entry of the table of vendor specific UUIDs pouplated with @ref sd_ble_uuid_vs_add - * to look for a match. If there is such a match, bytes 12 and 13 are returned as p_uuid->uuid and the index - * relative to @ref BLE_UUID_TYPE_VENDOR_BEGIN as p_uuid->type. - * - * @note If the UUID length supplied is 2, then the type set by this call will always be @ref BLE_UUID_TYPE_BLE. - * - * @param[in] uuid_le_len Length in bytes of the buffer pointed to by p_uuid_le (must be 2 or 16 bytes). - * @param[in] p_uuid_le Pointer pointing to little endian raw UUID bytes. - * @param[in,out] p_uuid Pointer to a @ref ble_uuid_t structure to be filled in. - * - * @return @ref NRF_SUCCESS Successfully decoded into the @ref ble_uuid_t structure. - * @return @ref NRF_ERROR_INVALID_ADDR Invalid pointer supplied. - * @return @ref NRF_ERROR_INVALID_LENGTH Invalid UUID length. - * @return @ref NRF_ERROR_NOT_FOUND For a 128-bit UUID, no match in the populated table of UUIDs. - */ -SVCALL(SD_BLE_UUID_DECODE, uint32_t, sd_ble_uuid_decode(uint8_t uuid_le_len, uint8_t const * const p_uuid_le, ble_uuid_t * const p_uuid)); - - -/** @brief Encode a @ref ble_uuid_t structure into little endian raw UUID bytes (16-bit or 128-bit). - * - * @note The pointer to the destination buffer p_uuid_le may be NULL, in which case only the validitiy and size of p_uuid is computed. - * - * @param[in] p_uuid Pointer to a @ref ble_uuid_t structure that will be encoded into bytes. - * @param[out] p_uuid_le_len Pointer to a uint8_t that will be filled with the encoded length (2 or 16 bytes). - * @param[out] p_uuid_le Pointer to a buffer where the little endian raw UUID bytes (2 or 16) will be stored. - * - * @return @ref NRF_SUCCESS Successfully encoded into the buffer. - * @return @ref NRF_ERROR_INVALID_ADDR Invalid pointer supplied. - * @return @ref NRF_ERROR_INVALID_PARAM Invalid UUID type. - */ -SVCALL(SD_BLE_UUID_ENCODE, uint32_t, sd_ble_uuid_encode(ble_uuid_t const * const p_uuid, uint8_t * const p_uuid_le_len, uint8_t * const p_uuid_le)); - - -/**@brief Get Version Information. - * - * @details This call allows the application to get the BLE stack version information. - * - * @param[in] p_version Pointer to ble_version_t structure to be filled in. - * - * @return @ref NRF_SUCCESS Version information stored successfully. - * @return @ref NRF_ERROR_INVALID_ADDR Invalid pointer supplied. - * @return @ref NRF_ERROR_BUSY The stack is busy (typically doing a locally-initiated disconnection procedure). - */ -SVCALL(SD_BLE_VERSION_GET, uint32_t, sd_ble_version_get(ble_version_t * p_version)); - - -/**@brief Provide a user memory block. - * - * @note This call can only be used as a response to a @ref BLE_EVT_USER_MEM_REQUEST event issued to the application. - * - * @param[in] conn_handle Connection handle. - * @param[in] p_block Pointer to a user memory block structure. - * - * @return @ref NRF_SUCCESS Successfully queued a response to the peer. - * @return @ref BLE_ERROR_INVALID_CONN_HANDLE Invalid Connection Handle. - * @return @ref NRF_ERROR_INVALID_STATE No execute write request pending. - */ -SVCALL(SD_BLE_USER_MEM_REPLY, uint32_t, sd_ble_user_mem_reply(uint16_t conn_handle, ble_user_mem_block_t *p_block)); - -#endif /* BLE_H__ */ - -/** - @} - @} -*/ diff --git a/libraries/ble/nRF51822/nordic/nrf-sdk/s110/ble_err.h b/libraries/ble/nRF51822/nordic/nrf-sdk/s110/ble_err.h deleted file mode 100644 index 20eb843ad3..0000000000 --- a/libraries/ble/nRF51822/nordic/nrf-sdk/s110/ble_err.h +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (c) 2012 Nordic Semiconductor. All Rights Reserved. - * - * The information contained herein is confidential property of Nordic Semiconductor. The use, - * copying, transfer or disclosure of such information is prohibited except by express written - * agreement with Nordic Semiconductor. - * - */ - /** - @addtogroup BLE_COMMON - @{ - @addtogroup nrf_error - @{ - @ingroup BLE_COMMON - @} - - @defgroup ble_err General error codes - @{ - - @brief General error code definitions for the BLE API. - - @ingroup BLE_COMMON -*/ -#ifndef NRF_BLE_ERR_H__ -#define NRF_BLE_ERR_H__ - -#include "nordic_global.h" -#include "nrf_error.h" - -/* @defgroup BLE_ERRORS Error Codes - * @{ */ -#define BLE_ERROR_INVALID_CONN_HANDLE (NRF_ERROR_STK_BASE_NUM+0x001) /**< Invalid connection handle. */ -#define BLE_ERROR_INVALID_ATTR_HANDLE (NRF_ERROR_STK_BASE_NUM+0x002) /**< Invalid attribute handle. */ -#define BLE_ERROR_NO_TX_BUFFERS (NRF_ERROR_STK_BASE_NUM+0x003) /**< Buffer capacity exceeded. */ -/** @} */ - - -/** @defgroup BLE_ERROR_SUBRANGES Module specific error code subranges - * @brief Assignment of subranges for module specific error codes. - * @note For specific error codes, see ble_.h or ble_error_.h. - * @{ */ -#define NRF_L2CAP_ERR_BASE (NRF_ERROR_STK_BASE_NUM+0x100) /**< L2CAP specific errors. */ -#define NRF_GAP_ERR_BASE (NRF_ERROR_STK_BASE_NUM+0x200) /**< GAP specific errors. */ -#define NRF_GATTC_ERR_BASE (NRF_ERROR_STK_BASE_NUM+0x300) /**< GATT client specific errors. */ -#define NRF_GATTS_ERR_BASE (NRF_ERROR_STK_BASE_NUM+0x400) /**< GATT server specific errors. */ -/** @} */ - -#endif - - -/** - @} - @} -*/ diff --git a/libraries/ble/nRF51822/nordic/nrf-sdk/s110/ble_gap.h b/libraries/ble/nRF51822/nordic/nrf-sdk/s110/ble_gap.h deleted file mode 100644 index 1d70885156..0000000000 --- a/libraries/ble/nRF51822/nordic/nrf-sdk/s110/ble_gap.h +++ /dev/null @@ -1,896 +0,0 @@ -/* Copyright (c) 2011 Nordic Semiconductor. All Rights Reserved. - * - * The information contained herein is confidential property of Nordic Semiconductor. The use, - * copying, transfer or disclosure of such information is prohibited except by express written - * agreement with Nordic Semiconductor. - * - */ -/** - @addtogroup BLE_GAP Generic Access Profile (GAP) - @{ - @brief Definitions and prototypes for the GAP interface. - */ - -#ifndef BLE_GAP_H__ -#define BLE_GAP_H__ - -#include "nordic_global.h" -#include "ble_types.h" -#include "ble_ranges.h" -#include "nrf_svc.h" - -/** - * @brief GAP API SVC numbers. - */ -enum BLE_GAP_SVCS -{ - SD_BLE_GAP_ADDRESS_SET = BLE_GAP_SVC_BASE, /**< Set own Bluetooth Address. */ - SD_BLE_GAP_ADDRESS_GET, /**< Get own Bluetooth Address. */ - SD_BLE_GAP_ADV_DATA_SET, /**< Set Advertisement Data. */ - SD_BLE_GAP_ADV_START, /**< Start Advertising. */ - SD_BLE_GAP_ADV_STOP, /**< Stop Advertising. */ - SD_BLE_GAP_CONN_PARAM_UPDATE, /**< Connection Parameter Update. */ - SD_BLE_GAP_DISCONNECT, /**< Disconnect. */ - SD_BLE_GAP_TX_POWER_SET, /**< Set TX Power. */ - SD_BLE_GAP_APPEARANCE_SET, /**< Set Appearance. */ - SD_BLE_GAP_APPEARANCE_GET, /**< Get Appearance. */ - SD_BLE_GAP_PPCP_SET, /**< Set PPCP. */ - SD_BLE_GAP_PPCP_GET, /**< Get PPCP. */ - SD_BLE_GAP_DEVICE_NAME_SET, /**< Set Device Name. */ - SD_BLE_GAP_DEVICE_NAME_GET, /**< Get Device Name. */ - SD_BLE_GAP_AUTHENTICATE, /**< Initiate Pairing/Bonding. */ - SD_BLE_GAP_SEC_PARAMS_REPLY, /**< Reply with Security Parameters. */ - SD_BLE_GAP_AUTH_KEY_REPLY, /**< Reply with an authentication key. */ - SD_BLE_GAP_SEC_INFO_REPLY, /**< Reply with Security Information. */ - SD_BLE_GAP_CONN_SEC_GET, /**< Obtain connection security level. */ - SD_BLE_GAP_RSSI_START, /**< Start reporting of changes in RSSI. */ - SD_BLE_GAP_RSSI_STOP, /**< Stop reporting of changes in RSSI. */ -}; - - -/** @addtogroup BLE_GAP_DEFINES Defines - * @{ */ - -/** @defgroup BLE_ERRORS_GAP SVC return values specific to GAP - * @{ */ -#define BLE_ERROR_GAP_UUID_LIST_MISMATCH (NRF_GAP_ERR_BASE + 0x000) /**< UUID list does not contain an integral number of UUIDs. */ -#define BLE_ERROR_GAP_DISCOVERABLE_WITH_WHITELIST (NRF_GAP_ERR_BASE + 0x001) /**< Use of Whitelist not permitted with discoverable advertising. */ -#define BLE_ERROR_GAP_INVALID_BLE_ADDR (NRF_GAP_ERR_BASE + 0x002) /**< The upper two bits of the address do not correspond to the specified address type. */ -/** @} */ - - -/** @defgroup BLE_GAP_ROLES GAP Roles - * @note Not explicitly used in peripheral API, but will be relevant for central API. - * @{ */ -#define BLE_GAP_ROLE_INVALID 0x0 /**< Invalid Role. */ -#define BLE_GAP_ROLE_PERIPH 0x1 /**< Peripheral Role. */ -#define BLE_GAP_ROLE_CENTRAL 0x2 /**< Central Role. */ -/** @} */ - - -/** @defgroup BLE_GAP_TIMEOUT_SOURCES GAP Timeout sources - * @{ */ -#define BLE_GAP_TIMEOUT_SRC_ADVERTISEMENT 0x00 /**< Advertisement timeout. */ -#define BLE_GAP_TIMEOUT_SRC_SECURITY_REQUEST 0x01 /**< Security request timeout. */ -/** @} */ - - -/** @defgroup BLE_GAP_ADDR_TYPES GAP Address types - * @{ */ -#define BLE_GAP_ADDR_TYPE_PUBLIC 0x00 /**< Public address. */ -#define BLE_GAP_ADDR_TYPE_RANDOM_STATIC 0x01 /**< Random Static address. */ -#define BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_RESOLVABLE 0x02 /**< Private Resolvable address. */ -#define BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_NON_RESOLVABLE 0x03 /**< Private Non-Resolvable address. */ -/** @} */ - - -/** @brief BLE address length. */ -#define BLE_GAP_ADDR_LEN 6 - - -/** @defgroup BLE_GAP_AD_TYPE_DEFINITIONS GAP Advertising and Scan Response Data format - * @note Found at https://www.bluetooth.org/Technical/AssignedNumbers/generic_access_profile.htm - * @{ */ -#define BLE_GAP_AD_TYPE_FLAGS 0x01 /**< Flags for discoverability. */ -#define BLE_GAP_AD_TYPE_16BIT_SERVICE_UUID_MORE_AVAILABLE 0x02 /**< Partial list of 16 bit service UUIDs. */ -#define BLE_GAP_AD_TYPE_16BIT_SERVICE_UUID_COMPLETE 0x03 /**< Complete list of 16 bit service UUIDs. */ -#define BLE_GAP_AD_TYPE_32BIT_SERVICE_UUID_MORE_AVAILABLE 0x04 /**< Partial list of 32 bit service UUIDs. */ -#define BLE_GAP_AD_TYPE_32BIT_SERVICE_UUID_COMPLETE 0x05 /**< Complete list of 32 bit service UUIDs. */ -#define BLE_GAP_AD_TYPE_128BIT_SERVICE_UUID_MORE_AVAILABLE 0x06 /**< Partial list of 128 bit service UUIDs. */ -#define BLE_GAP_AD_TYPE_128BIT_SERVICE_UUID_COMPLETE 0x07 /**< Complete list of 128 bit service UUIDs. */ -#define BLE_GAP_AD_TYPE_SHORT_LOCAL_NAME 0x08 /**< Short local device name. */ -#define BLE_GAP_AD_TYPE_COMPLETE_LOCAL_NAME 0x09 /**< Complete local device name. */ -#define BLE_GAP_AD_TYPE_TX_POWER_LEVEL 0x0A /**< Transmit power level. */ -#define BLE_GAP_AD_TYPE_CLASS_OF_DEVICE 0x0D /**< Class of device. */ -#define BLE_GAP_AD_TYPE_SIMPLE_PAIRING_HASH_C 0x0E /**< Simple Pairing Hash C. */ -#define BLE_GAP_AD_TYPE_SIMPLE_PAIRING_RANDOMIZER_R 0x0F /**< Simple Pairing Randomizer R. */ -#define BLE_GAP_AD_TYPE_SECURITY_MANAGER_TK_VALUE 0x10 /**< Security Manager TK Value. */ -#define BLE_GAP_AD_TYPE_SECURITY_MANAGER_OOB_FLAGS 0x11 /**< Security Manager Out Of Band Flags. */ -#define BLE_GAP_AD_TYPE_SLAVE_CONNECTION_INTERVAL_RANGE 0x12 /**< Slave Connection Interval Range. */ -#define BLE_GAP_AD_TYPE_SOLICITED_SERVICE_UUIDS_16BIT 0x14 /**< List of 16-bit Service Solicitation UUIDs. */ -#define BLE_GAP_AD_TYPE_SOLICITED_SERVICE_UUIDS_128BIT 0x15 /**< List of 128-bit Service Solicitation UUIDs. */ -#define BLE_GAP_AD_TYPE_SERVICE_DATA 0x16 /**< Service Data. */ -#define BLE_GAP_AD_TYPE_PUBLIC_TARGET_ADDRESS 0x17 /**< Public Target Address. */ -#define BLE_GAP_AD_TYPE_RANDOM_TARGET_ADDRESS 0x18 /**< Random Target Address. */ -#define BLE_GAP_AD_TYPE_APPEARANCE 0x19 /**< Appearance. */ -#define BLE_GAP_AD_TYPE_MANUFACTURER_SPECIFIC_DATA 0xFF /**< Manufacturer Specific Data. */ -/** @} */ - - -/** @defgroup BLE_GAP_ADV_FLAGS GAP Advertisement Flags - * @{ */ -#define BLE_GAP_ADV_FLAG_LE_LIMITED_DISC_MODE (0x01) /**< LE Limited Discoverable Mode. */ -#define BLE_GAP_ADV_FLAG_LE_GENERAL_DISC_MODE (0x02) /**< LE General Discoverable Mode. */ -#define BLE_GAP_ADV_FLAG_BR_EDR_NOT_SUPPORTED (0x04) /**< BR/EDR not supported. */ -#define BLE_GAP_ADV_FLAG_LE_BR_EDR_CONTROLLER (0x08) /**< Simultaneous LE and BR/EDR, Controller. */ -#define BLE_GAP_ADV_FLAG_LE_BR_EDR_HOST (0x10) /**< Simultaneous LE and BR/EDR, Host. */ -#define BLE_GAP_ADV_FLAGS_LE_ONLY_LIMITED_DISC_MODE (BLE_GAP_ADV_FLAG_LE_LIMITED_DISC_MODE | BLE_GAP_ADV_FLAG_BR_EDR_NOT_SUPPORTED) /**< LE Limited Discoverable Mode, BR/EDR not supported. */ -#define BLE_GAP_ADV_FLAGS_LE_ONLY_GENERAL_DISC_MODE (BLE_GAP_ADV_FLAG_LE_GENERAL_DISC_MODE | BLE_GAP_ADV_FLAG_BR_EDR_NOT_SUPPORTED) /**< LE General Discoverable Mode, BR/EDR not supported. */ -/** @} */ - - -/** @defgroup BLE_GAP_ADV_INTERVALS GAP Advertising interval max and min - * @{ */ -#define BLE_GAP_ADV_INTERVAL_MIN 0x0020 /**< Minimum Advertising interval in 625 us units, i.e. 20 ms. */ -#define BLE_GAP_ADV_NONCON_INTERVAL_MIN 0x00A0 /**< Minimum Advertising interval in 625 us units for non connectable mode, i.e. 100 ms. */ -#define BLE_GAP_ADV_INTERVAL_MAX 0x4000 /**< Maximum Advertising interval in 625 us units, i.e. 10.24 s. */ - /** @} */ - - -/** @brief Maximum size of advertising data in octets. */ -#define BLE_GAP_ADV_MAX_SIZE 31 - - -/** @defgroup BLE_GAP_ADV_TYPES GAP Advertising types - * @{ */ -#define BLE_GAP_ADV_TYPE_ADV_IND 0x00 /**< Connectable undirected. */ -#define BLE_GAP_ADV_TYPE_ADV_DIRECT_IND 0x01 /**< Connectable directed. */ -#define BLE_GAP_ADV_TYPE_ADV_SCAN_IND 0x02 /**< Scannable undirected. */ -#define BLE_GAP_ADV_TYPE_ADV_NONCONN_IND 0x03 /**< Non connectable undirected. */ -/** @} */ - - -/** @defgroup BLE_GAP_ADV_FILTER_POLICIES GAP Advertising filter policies - * @{ */ -#define BLE_GAP_ADV_FP_ANY 0x00 /**< Allow scan requests and connect requests from any device. */ -#define BLE_GAP_ADV_FP_FILTER_SCANREQ 0x01 /**< Filter scan requests with whitelist. */ -#define BLE_GAP_ADV_FP_FILTER_CONNREQ 0x02 /**< Filter connect requests with whitelist. */ -#define BLE_GAP_ADV_FP_FILTER_BOTH 0x03 /**< Filter both scan and connect requests with whitelist. */ -/** @} */ - - -/** @defgroup BLE_GAP_ADV_TIMEOUT_VALUES GAP Advertising timeout values - * @{ */ -#define BLE_GAP_ADV_TIMEOUT_LIMITED_MAX 180 /**< Maximum advertising time in limited discoverable mode (TGAP(lim_adv_timeout) = 180s in spec (Addendum 2)). */ -#define BLE_GAP_ADV_TIMEOUT_GENERAL_UNLIMITED 0 /**< Unlimited advertising in general discoverable mode. */ -/** @} */ - - -/** @defgroup BLE_GAP_DISC_MODES GAP Discovery modes - * @{ */ -#define BLE_GAP_DISC_MODE_NOT_DISCOVERABLE 0x00 /**< Not discoverable discovery Mode. */ -#define BLE_GAP_DISC_MODE_LIMITED 0x01 /**< Limited Discovery Mode. */ -#define BLE_GAP_DISC_MODE_GENERAL 0x02 /**< General Discovery Mode. */ -/** @} */ - -/** @defgroup BLE_GAP_IO_CAPS GAP IO Capabilities - * @{ */ -#define BLE_GAP_IO_CAPS_DISPLAY_ONLY 0x00 /**< Display Only. */ -#define BLE_GAP_IO_CAPS_DISPLAY_YESNO 0x01 /**< Display and Yes/No entry. */ -#define BLE_GAP_IO_CAPS_KEYBOARD_ONLY 0x02 /**< Keyboard Only. */ -#define BLE_GAP_IO_CAPS_NONE 0x03 /**< No I/O capabilities. */ -#define BLE_GAP_IO_CAPS_KEYBOARD_DISPLAY 0x04 /**< Keyboard and Display. */ -/** @} */ - - -/** @defgroup BLE_GAP_AUTH_KEY_TYPES GAP Authentication Key Types - * @{ */ -#define BLE_GAP_AUTH_KEY_TYPE_NONE 0x00 /**< No key (may be used to reject). */ -#define BLE_GAP_AUTH_KEY_TYPE_PASSKEY 0x01 /**< 6-digit Passkey. */ -#define BLE_GAP_AUTH_KEY_TYPE_OOB 0x02 /**< Out Of Band data. */ -/** @} */ - -/** @defgroup BLE_GAP_SEC_STATUS GAP Security status - * @{ */ -#define BLE_GAP_SEC_STATUS_SUCCESS 0x00 /**< Successful parameters. */ -#define BLE_GAP_SEC_STATUS_TIMEOUT 0x01 /**< Procedure timed out. */ -#define BLE_GAP_SEC_STATUS_PDU_INVALID 0x02 /**< Invalid PDU received. */ -#define BLE_GAP_SEC_STATUS_PASSKEY_ENTRY_FAILED 0x81 /**< Passkey entry failed (user cancelled or other). */ -#define BLE_GAP_SEC_STATUS_OOB_NOT_AVAILABLE 0x82 /**< Out of Band Key not available. */ -#define BLE_GAP_SEC_STATUS_AUTH_REQ 0x83 /**< Authentication requirements not met. */ -#define BLE_GAP_SEC_STATUS_CONFIRM_VALUE 0x84 /**< Confirm value failed. */ -#define BLE_GAP_SEC_STATUS_PAIRING_NOT_SUPP 0x85 /**< Pairing not supported. */ -#define BLE_GAP_SEC_STATUS_ENC_KEY_SIZE 0x86 /**< Encryption key size. */ -#define BLE_GAP_SEC_STATUS_SMP_CMD_UNSUPPORTED 0x87 /**< Unsupported SMP command. */ -#define BLE_GAP_SEC_STATUS_UNSPECIFIED 0x88 /**< Unspecified reason. */ -#define BLE_GAP_SEC_STATUS_REPEATED_ATTEMPTS 0x89 /**< Too little time elapsed since last attempt. */ -#define BLE_GAP_SEC_STATUS_INVALID_PARAMS 0x8A /**< Invalid parameters. */ -/** @} */ - -/** @defgroup BLE_GAP_SEC_STATUS_SOURCES GAP Security status sources - * @{ */ -#define BLE_GAP_SEC_STATUS_SOURCE_LOCAL 0x00 /**< Local failure. */ -#define BLE_GAP_SEC_STATUS_SOURCE_REMOTE 0x01 /**< Remote failure. */ -/** @} */ - -/** @defgroup BLE_GAP_CP_LIMITS GAP Connection Parameters Limits - * @{ */ -#define BLE_GAP_CP_MIN_CONN_INTVL_NONE 0xFFFF /**< No new minimum connction interval specified in connect parameters. */ -#define BLE_GAP_CP_MIN_CONN_INTVL_MIN 0x0006 /**< Lowest mimimum connection interval permitted, in units of 1.25 ms, i.e. 7.5 ms. */ -#define BLE_GAP_CP_MIN_CONN_INTVL_MAX 0x0C80 /**< Highest minimum connection interval permitted, in units of 1.25 ms, i.e. 4 s. */ -#define BLE_GAP_CP_MAX_CONN_INTVL_NONE 0xFFFF /**< No new maximum connction interval specified in connect parameters. */ -#define BLE_GAP_CP_MAX_CONN_INTVL_MIN 0x0006 /**< Lowest maximum connection interval permitted, in units of 1.25 ms, i.e. 7.5 ms. */ -#define BLE_GAP_CP_MAX_CONN_INTVL_MAX 0x0C80 /**< Highest maximum connection interval permitted, in units of 1.25 ms, i.e. 4 s. */ -#define BLE_GAP_CP_SLAVE_LATENCY_MAX 0x03E8 /**< Highest slave latency permitted, in connection events. */ -#define BLE_GAP_CP_CONN_SUP_TIMEOUT_NONE 0xFFFF /**< No new supervision timeout specified in connect parameters. */ -#define BLE_GAP_CP_CONN_SUP_TIMEOUT_MIN 0x000A /**< Lowest supervision timeout permitted, in units of 10 ms, i.e. 100 ms. */ -#define BLE_GAP_CP_CONN_SUP_TIMEOUT_MAX 0x0C80 /**< Highest supervision timeout permitted, in units of 10 ms, i.e. 32 s. */ -/** @} */ - - -/**@brief GAP device name maximum length. */ -#define BLE_GAP_DEVNAME_MAX_LEN 31 - - -/** @defgroup BLE_GAP_CONN_SEC_MODE_SET_MACROS GAP attribute security requirement setters - * - * See @ref ble_gap_conn_sec_mode_t. - * @{ */ -/** @brief Set sec_mode pointed to by ptr to have no access rights.*/ -#define BLE_GAP_CONN_SEC_MODE_SET_NO_ACCESS(ptr) do {(ptr)->sm = 0; (ptr)->lv = 0;} while(0) -/** @brief Set sec_mode pointed to by ptr to require no protection, open link.*/ -#define BLE_GAP_CONN_SEC_MODE_SET_OPEN(ptr) do {(ptr)->sm = 1; (ptr)->lv = 1;} while(0) -/** @brief Set sec_mode pointed to by ptr to require encryption, but no MITM protection.*/ -#define BLE_GAP_CONN_SEC_MODE_SET_ENC_NO_MITM(ptr) do {(ptr)->sm = 1; (ptr)->lv = 2;} while(0) -/** @brief Set sec_mode pointed to by ptr to require encryption and MITM protection.*/ -#define BLE_GAP_CONN_SEC_MODE_SET_ENC_WITH_MITM(ptr) do {(ptr)->sm = 1; (ptr)->lv = 3;} while(0) -/** @brief Set sec_mode pointed to by ptr to require signing or encryption, no MITM protection needed.*/ -#define BLE_GAP_CONN_SEC_MODE_SET_SIGNED_NO_MITM(ptr) do {(ptr)->sm = 2; (ptr)->lv = 1;} while(0) -/** @brief Set sec_mode pointed to by ptr to require signing or encryption with MITM protection.*/ -#define BLE_GAP_CONN_SEC_MODE_SET_SIGNED_WITH_MITM(ptr) do {(ptr)->sm = 2; (ptr)->lv = 2;} while(0) -/** @} */ - - -/**@brief GAP Security Key Length. */ -#define BLE_GAP_SEC_KEY_LEN 16 - -/**@brief Maximum amount of addresses in a whitelist. */ -#define BLE_GAP_WHITELIST_ADDR_MAX_COUNT (8) - -/**@brief Maximum amount of IRKs in a whitelist. - * @note The number of IRKs is limited to 8, even if the hardware supports more. - */ -#define BLE_GAP_WHITELIST_IRK_MAX_COUNT (8) - -/** @defgroup GAP_SEC_MODES GAP Security Modes - * @{ */ -#define BLE_GAP_SEC_MODE 0x00 /**< No key (may be used to reject). */ - -/** @} */ - - -/** @} */ - -/**@brief Bluetooth Low Energy address. */ -typedef struct -{ - uint8_t addr_type; /**< See @ref BLE_GAP_ADDR_TYPES. */ - uint8_t addr[BLE_GAP_ADDR_LEN]; /**< 48-bit address, LSB format. */ -} ble_gap_addr_t; - - -/**@brief GAP connection parameters. - * - * @note When ble_conn_params_t is received in an event, both min_conn_interval and - * max_conn_interval will be equal to the connection interval set by the central. - */ -typedef struct -{ - uint16_t min_conn_interval; /**< Minimum Connection Interval in 1.25 ms units, see @ref BLE_GAP_CP_LIMITS.*/ - uint16_t max_conn_interval; /**< Maximum Connection Interval in 1.25 ms units, see @ref BLE_GAP_CP_LIMITS.*/ - uint16_t slave_latency; /**< Slave Latency in number of connection events, see @ref BLE_GAP_CP_LIMITS.*/ - uint16_t conn_sup_timeout; /**< Connection Supervision Timeout in 10 ms units, see @ref BLE_GAP_CP_LIMITS.*/ -} ble_gap_conn_params_t; - - -/**@brief GAP link requirements. - * - * See Bluetooth Core specification, Volume 3 Part C 10.2 for details. - * - * Security Mode 0 Level 0: No access permissions at all (this level is not defined by the Bluetooth Core specification).\n - * Security Mode 1 Level 1: No security is needed (aka open link).\n - * Security Mode 1 Level 2: Encrypted link required, MITM protection not necessary.\n - * Security Mode 1 Level 3: MITM protected encrypted link required.\n - * Security Mode 2 Level 1: Signing or encryption required, MITM protection not necessary.\n - * Security Mode 2 Level 2: MITM protected signing required, unless link is MITM protected encrypted.\n - */ -typedef struct -{ - uint8_t sm : 4; /**< Security Mode (1 or 2), 0 for no permissions at all. */ - uint8_t lv : 4; /**< Level (1, 2 or 3), 0 for no permissions at all. */ - -} ble_gap_conn_sec_mode_t; - - - -/**@brief GAP connection security status.*/ -typedef struct -{ - ble_gap_conn_sec_mode_t sec_mode; /**< Currently active security mode for this connection.*/ - uint8_t encr_key_size; /**< Length of currently active encryption key, 7 to 16 octets.*/ -} ble_gap_conn_sec_t; - - - -/**@brief Identity Resolving Key. */ -typedef struct -{ - uint8_t irk[BLE_GAP_SEC_KEY_LEN]; /**< Array containing IRK. */ -} ble_gap_irk_t; - - -/**@brief Whitelist structure. */ -typedef struct -{ - ble_gap_addr_t ** pp_addrs; /**< Pointer to array of device address pointers, pointing to addresses to be used in whitelist. NULL if none are given. */ - uint8_t addr_count; /**< Count of device addresses in array, up to @ref BLE_GAP_WHITELIST_ADDR_MAX_COUNT. */ - ble_gap_irk_t ** pp_irks; /**< Pointer to array of Identity Resolving Key (IRK) pointers, each pointing to an IRK in the whitelist. NULL if none are given. */ - uint8_t irk_count; /**< Count of IRKs in array, up to @ref BLE_GAP_WHITELIST_IRK_MAX_COUNT. */ -} ble_gap_whitelist_t; - - -/**@brief GAP advertising parameters.*/ -typedef struct -{ - uint8_t type; /**< See @ref BLE_GAP_ADV_TYPES. */ - ble_gap_addr_t* p_peer_addr; /**< For BLE_GAP_CONN_MODE_DIRECTED mode only, known peer address. */ - uint8_t fp; /**< Filter Policy, see @ref BLE_GAP_ADV_FILTER_POLICIES. */ - ble_gap_whitelist_t * p_whitelist; /**< Pointer to whitelist, NULL if none is given. */ - uint16_t interval; /**< Advertising interval between 0x0020 and 0x4000 in 0.625 ms units (20ms to 10.24s), see @ref BLE_GAP_ADV_INTERVALS. This parameter must be set to 0 if type equals @ref BLE_GAP_ADV_TYPE_ADV_DIRECT_IND. */ - uint16_t timeout; /**< Advertising timeout between 0x0001 and 0x3FFF in seconds, 0x0000 disables timeout. See also @ref BLE_GAP_ADV_TIMEOUT_VALUES. This parameter must be set to 0 if type equals @ref BLE_GAP_ADV_TYPE_ADV_DIRECT_IND. */ -} ble_gap_adv_params_t; - - -/**@brief GAP scanning parameters. */ -typedef struct -{ - uint8_t filter; /**< Filter based on discovery mode, see @ref BLE_GAP_DISC_MODES. */ - uint8_t active : 1; /**< If 1, perform active scanning (scan requests). */ - uint8_t selective : 1; /**< If 1, ignore unknown devices (non whitelisted). */ - uint16_t interval; /**< Scan interval between 0x0020 and 0x4000 in 0.625ms units (20ms to 10.24s). */ - uint16_t window; /**< Scan window between 0x0004 and 0x4000 in 0.625ms units (2.5ms to 10.24s). */ - uint16_t timeout; /**< Scan timeout between 0x0001 and 0x3FFF in seconds, 0x0000 disables timeout. */ -} ble_gap_scan_params_t; - - -/**@brief GAP security parameters. */ -typedef struct -{ - uint16_t timeout; /**< Timeout for SMP transactions or Security Request in seconds, see @ref sd_ble_gap_authenticate and @ref sd_ble_gap_sec_params_reply for more information. */ - uint8_t bond : 1; /**< Perform bonding. */ - uint8_t mitm : 1; /**< Man In The Middle protection required. */ - uint8_t io_caps : 3; /**< IO capabilities, see @ref BLE_GAP_IO_CAPS. */ - uint8_t oob : 1; /**< Out Of Band data available. */ - uint8_t min_key_size; /**< Minimum encryption key size in octets between 7 and 16. */ - uint8_t max_key_size; /**< Maximum encryption key size in octets between min_key_size and 16. */ -} ble_gap_sec_params_t; - - -/**@brief GAP Encryption Information. */ -typedef struct -{ - uint16_t div; /**< Encryption Diversifier. */ - uint8_t ltk[BLE_GAP_SEC_KEY_LEN]; /**< Long Term Key. */ - uint8_t auth : 1; /**< Authenticated Key. */ - uint8_t ltk_len : 7; /**< LTK length in octets. */ -} ble_gap_enc_info_t; - - -/**@brief GAP Master Identification. */ -typedef struct -{ - uint16_t ediv; /**< Encrypted Diversifier. */ - uint8_t rand[8]; /**< Random Number. */ -} ble_gap_master_id_t; - - -/**@brief GAP Identity Information. */ -typedef struct -{ - ble_gap_addr_t addr; /**< Bluetooth address to which this key applies. */ - uint8_t irk[BLE_GAP_SEC_KEY_LEN]; /**< Identity Resolution Key. */ -} ble_gap_id_info_t; - - -/**@brief GAP Signing Information. */ -typedef struct -{ - uint8_t csrk[BLE_GAP_SEC_KEY_LEN]; /* Connection Signature Resolving Key. */ -} ble_gap_sign_info_t; - - - -/** - * @brief GAP Event IDs. - * Those IDs uniquely identify an event coming from the stack to the application. - */ -enum BLE_GAP_EVTS -{ - BLE_GAP_EVT_CONNECTED = BLE_GAP_EVT_BASE, /**< Connection established. */ - BLE_GAP_EVT_DISCONNECTED, /**< Disconnected from peer. */ - BLE_GAP_EVT_CONN_PARAM_UPDATE, /**< Connection Parameters updated. */ - BLE_GAP_EVT_SEC_PARAMS_REQUEST, /**< Request to provide security parameters. */ - BLE_GAP_EVT_SEC_INFO_REQUEST, /**< Request to provide security information. */ - BLE_GAP_EVT_PASSKEY_DISPLAY, /**< Request to display a passkey to the user. */ - BLE_GAP_EVT_AUTH_KEY_REQUEST, /**< Request to provide an authentication key. */ - BLE_GAP_EVT_AUTH_STATUS, /**< Authentication procedure completed with status. */ - BLE_GAP_EVT_CONN_SEC_UPDATE, /**< Connection security updated. */ - BLE_GAP_EVT_TIMEOUT, /**< Timeout expired. */ - BLE_GAP_EVT_RSSI_CHANGED, /**< Signal strength measurement report. */ -}; - - -/** @brief Event data for connected event. */ -typedef struct -{ - ble_gap_addr_t peer_addr; /**< Bluetooth address of the peer device. */ - uint8_t irk_match :1; /**< If 1, peer device's address resolved using an IRK. */ - uint8_t irk_match_idx :7; /**< Index in IRK list where the address was matched. */ - ble_gap_conn_params_t conn_params; /**< GAP Connection Parameters. */ -} ble_gap_evt_connected_t; - - -/** @brief Event data for disconnected event. */ -typedef struct -{ - uint8_t reason; /**< HCI error code. */ -} ble_gap_evt_disconnected_t; - - -/** @brief Event data for connection parameter update event. */ -typedef struct -{ - ble_gap_conn_params_t conn_params; /**< GAP Connection Parameters. */ -} ble_gap_evt_conn_param_update_t; - - -/** @brief Event data for security parameters request event. */ -typedef struct -{ - ble_gap_sec_params_t peer_params; /**< Initiator Security Parameters. */ -} ble_gap_evt_sec_params_request_t; - - -/** @brief Event data for securito info request event. */ -typedef struct -{ - ble_gap_addr_t peer_addr; /**< Bluetooth address of the peer device. */ - uint16_t div; /**< Encryption diversifier for LTK lookup. */ - uint8_t enc_info : 1; /**< If 1, Encryption Information required. */ - uint8_t id_info : 1; /**< If 1, Identity Information required. */ - uint8_t sign_info : 1; /**< If 1, Signing Information required. */ -} ble_gap_evt_sec_info_request_t; - - -/** @brief Event data for passkey display event. */ -typedef struct -{ - uint8_t passkey[6]; /**< 6-digit passkey in ASCII ('0'-'9' digits only). */ -} ble_gap_evt_passkey_display_t; - - -/** @brief Event data for authentication key request event. */ -typedef struct -{ - uint8_t key_type; /**< See @ref BLE_GAP_AUTH_KEY_TYPES. */ -} ble_gap_evt_auth_key_request_t; - - -/** @brief Security levels supported. - * @note See Bluetooth Specification Version 4.0 Volume 3, Chapter 10. -*/ -typedef struct -{ - uint8_t lv1 : 1; /**< If 1: Level 1 is supported. */ - uint8_t lv2 : 1; /**< If 1: Level 2 is supported. */ - uint8_t lv3 : 1; /**< If 1: Level 3 is supported. */ -} ble_gap_sec_levels_t; - - -/** @brief Keys that have been exchanged. */ -typedef struct -{ - uint8_t ltk : 1; /**< Long Term Key. */ - uint8_t ediv_rand : 1; /**< Encrypted Diversifier and Random value. */ - uint8_t irk : 1; /**< Identity Resolving Key. */ - uint8_t address : 1; /**< Public or static random address. */ - uint8_t csrk : 1; /**< Connection Signature Resolving Key. */ -} ble_gap_sec_keys_t; - - -/** @brief Event data for authentication status event. */ -typedef struct -{ - uint8_t auth_status; /**< Authentication status, see @ref BLE_GAP_SEC_STATUS. */ - uint8_t error_src; /**< On error, source that caused the failure, see @ref BLE_GAP_SEC_STATUS_SOURCES. */ - ble_gap_sec_levels_t sm1_levels; /**< Levels supported in Security Mode 1. */ - ble_gap_sec_levels_t sm2_levels; /**< Levels supported in Security Mode 2. */ - ble_gap_sec_keys_t periph_kex; /**< Bitmap stating which keys were exchanged (distributed) by the peripheral. */ - ble_gap_sec_keys_t central_kex; /**< Bitmap stating which keys were exchanged (distributed) by the central. */ - struct periph_keys_t - { - ble_gap_enc_info_t enc_info; /**< Peripheral's Encryption information. */ - } periph_keys; /**< Actual keys distributed from the Peripheral to the Central. */ - struct central_keys_t - { - ble_gap_irk_t irk; /**< Central's IRK. */ - ble_gap_addr_t id_info; /**< Central's Identity Info. */ - } central_keys; /**< Actual keys distributed from the Central to the Peripheral. */ -} ble_gap_evt_auth_status_t; - - -/** @brief Event data for connection security update event. */ -typedef struct -{ - ble_gap_conn_sec_t conn_sec; /**< Connection security level. */ -} ble_gap_evt_conn_sec_update_t; - - -/** @brief Event data for timeout event. */ -typedef struct -{ - uint8_t src; /**< Source of timeout event, see @ref BLE_GAP_TIMEOUT_SOURCES. */ -} ble_gap_evt_timeout_t; - - -/** @brief Event data for advertisement report event. */ -typedef struct -{ - int8_t rssi; /**< Received Signal Strength Indication in dBm. */ -} ble_gap_evt_rssi_changed_t; - - - -/**@brief GAP event callback event structure. */ -typedef struct -{ - uint16_t conn_handle; /**< Connection Handle on which event occured. */ - union /**< union alternative identified by evt_id in enclosing struct. */ - { - ble_gap_evt_connected_t connected; /**< Connected Event Parameters. */ - ble_gap_evt_disconnected_t disconnected; /**< Disconnected Event Parameters. */ - ble_gap_evt_conn_param_update_t conn_param_update; /**< Connection Parameter Update Parameters. */ - ble_gap_evt_sec_params_request_t sec_params_request; /**< Security Parameters Request Event Parameters. */ - ble_gap_evt_sec_info_request_t sec_info_request; /**< Security Information Request Event Parameters. */ - ble_gap_evt_passkey_display_t passkey_display; /**< Passkey Display Event Parameters. */ - ble_gap_evt_auth_key_request_t auth_key_request; /**< Authentication Key Request Event Parameters. */ - ble_gap_evt_auth_status_t auth_status; /**< Authentication Status Event Parameters. */ - ble_gap_evt_conn_sec_update_t conn_sec_update; /**< Connection Security Update Event Parameters. */ - ble_gap_evt_timeout_t timeout; /**< Timeout Event Parameters. */ - ble_gap_evt_rssi_changed_t rssi_changed; /**< RSSI Event parameters. */ - } params; - -} ble_gap_evt_t; - - -/**@brief Set local Bluetooth address. - * - * @param[in] p_addr Pointer to address structure. - * - * @return @ref NRF_SUCCESS Address successfully set. - * @return @ref NRF_ERROR_INVALID_ADDR Invalid pointer supplied. - * @return @ref BLE_ERROR_GAP_INVALID_BLE_ADDR Invalid address. - * @return @ref NRF_ERROR_BUSY The stack is busy, process pending events and retry. - */ -SVCALL(SD_BLE_GAP_ADDRESS_SET, uint32_t, sd_ble_gap_address_set(ble_gap_addr_t const * const p_addr)); - - -/**@brief Get local Bluetooth address. - * - * @param[out] p_addr Pointer to address structure. - * - * @return @ref NRF_SUCCESS Address successfully retrieved. - * @return @ref NRF_ERROR_INVALID_ADDR Invalid pointer supplied. - */ -SVCALL(SD_BLE_GAP_ADDRESS_GET, uint32_t, sd_ble_gap_address_get(ble_gap_addr_t * const p_addr)); - - -/**@brief Set, clear or update advertisement and scan response data. - * - * @note The format of the advertisement data will be checked by this call to ensure interoperability. - * Limitations imposed by this API call to the data provided include having a flags data type in the scan response data and - * duplicating the local name in the advertisement data and scan response data. - * - * @note: To clear the advertisement data and set it to a 0-length packet, simply provide a valid pointer (p_data/p_sr_data) with its corresponding - * length (dlen/srdlen) set to 0. - * - * @note: The call will fail if p_data and p_sr_data are both NULL since this would have no effect. - * - * @param[in] p_data Raw data to be placed in advertisement packet. If NULL, no changes are made to the current advertisement packet data. - * @param[in] dlen Data length for p_data. Max size: @ref BLE_GAP_ADV_MAX_SIZE octets. Should be 0 if p_data is NULL, can be 0 if p_data is not NULL. - * @param[in] p_sr_data Raw data to be placed in scan response packet. If NULL, no changes are made to the current scan response packet data. - * @param[in] srdlen Data length for p_sr_data. Max size: @ref BLE_GAP_ADV_MAX_SIZE octets. Should be 0 if p_sr_data is NULL, can be 0 if p_data is not NULL. - * - * @return @ref NRF_SUCCESS Advertisement data successfully updated or cleared. - * @return @ref NRF_ERROR_INVALID_ADDR Invalid pointer supplied. - * @return @ref NRF_ERROR_INVALID_FLAGS Invalid combination of advertising flags supplied. - * @return @ref NRF_ERROR_INVALID_DATA Invalid data type(s) supplied, check the advertising data format specification. - * @return @ref NRF_ERROR_INVALID_LENGTH Invalid data length(s) supplied. - * @return @ref BLE_ERROR_GAP_UUID_LIST_MISMATCH Invalid UUID list supplied. - * @return @ref NRF_ERROR_BUSY The stack is busy, process pending events and retry. - */ -SVCALL(SD_BLE_GAP_ADV_DATA_SET, uint32_t, sd_ble_gap_adv_data_set(uint8_t const * const p_data, uint8_t dlen, uint8_t const * const p_sr_data, uint8_t srdlen)); - - -/**@brief Start advertising (GAP Discoverable, Connectable modes, Broadcast Procedure). - * - * @param[in] p_adv_params Pointer to advertising parameters structure. - * - * @return @ref NRF_SUCCESS The BLE stack has started advertising. - * @return @ref NRF_ERROR_INVALID_ADDR Invalid pointer supplied. - * @return @ref NRF_ERROR_INVALID_STATE Invalid state to perform operation. - * @return @ref NRF_ERROR_INVALID_PARAM Invalid parameter(s) supplied, check the accepted ranges and limits. - * @return @ref BLE_ERROR_GAP_INVALID_BLE_ADDR Invalid Bluetooth address supplied. - * @return @ref BLE_ERROR_GAP_DISCOVERABLE_WITH_WHITELIST Discoverable mode and whitelist incompatible. - */ -SVCALL(SD_BLE_GAP_ADV_START, uint32_t, sd_ble_gap_adv_start(ble_gap_adv_params_t const * const p_adv_params)); - - -/**@brief Stop advertising (GAP Discoverable, Connectable modes, Broadcast Procedure). - * - * @return @ref NRF_SUCCESS The BLE stack has stopped advertising. - * @return @ref NRF_ERROR_INVALID_STATE Invalid state to perform operation (most probably not in advertising state). - */ -SVCALL(SD_BLE_GAP_ADV_STOP, uint32_t, sd_ble_gap_adv_stop(void)); - - -/**@brief Update connection parameters. - * - * @details In the central role this will initiate a Link Layer connection parameter update procedure, - * otherwise in the peripheral role, this will send the corresponding L2CAP request and wait for - * the central to perform the procedure. In both cases, and regardless of success or failure, the application - * will be informed of the result with a @ref BLE_GAP_EVT_CONN_PARAM_UPDATE event. - * - * @note If both a connection supervision timeout and a maximum connection interval are specified, then the following constraint - * applies: (conn_sup_timeout * 8) >= (max_conn_interval * (slave_latency + 1)) - * - * @param[in] conn_handle Connection handle. - * @param[in] p_conn_params Pointer to desired connection parameters. If NULL is provided on a peripheral role, - * the parameters in the PPCP characteristic of the GAP service will be used instead. - * - * @return @ref NRF_SUCCESS The Connection Update procedure has been started successfully. - * @return @ref NRF_ERROR_INVALID_ADDR Invalid pointer supplied. - * @return @ref NRF_ERROR_INVALID_PARAM Invalid parameter(s) supplied, check parameter limits and constraints. - * @return @ref NRF_ERROR_BUSY Procedure already in progress or not allowed at this time, process pending events and retry. - * @return @ref BLE_ERROR_INVALID_CONN_HANDLE Invalid connection handle supplied. - * @return @ref NRF_ERROR_NO_MEM Not enough memory to complete operation. - */ -SVCALL(SD_BLE_GAP_CONN_PARAM_UPDATE, uint32_t, sd_ble_gap_conn_param_update(uint16_t conn_handle, ble_gap_conn_params_t const * const p_conn_params)); - - -/**@brief Disconnect (GAP Link Termination). - * - * @details This call initiates the disconnection procedure, and its completion will be communicated to the application - * with a BLE_GAP_EVT_DISCONNECTED event. - * - * @param[in] conn_handle Connection handle. - * @param[in] hci_status_code HCI status code, see @ref BLE_HCI_STATUS_CODES (accepted values are BTLE_REMOTE_USER_TERMINATED_CONNECTION and BTLE_CONN_INTERVAL_UNACCEPTABLE). - * - * @return @ref NRF_SUCCESS The disconnection procedure has been started successfully. - * @return @ref NRF_ERROR_INVALID_PARAM Invalid parameter(s) supplied. - * @return @ref BLE_ERROR_INVALID_CONN_HANDLE Invalid connection handle supplied. - * @return @ref NRF_ERROR_INVALID_STATE Invalid state to perform operation (disconnection is already in progress or not connected at all). - */ -SVCALL(SD_BLE_GAP_DISCONNECT, uint32_t, sd_ble_gap_disconnect(uint16_t conn_handle, uint8_t hci_status_code)); - - -/**@brief Set the radio's transmit power. - * - * @param[in] tx_power Radio transmit power in dBm (accepted values are -40, -30, -20, -16, -12, -8, -4, 0, and 4 dBm). - * - * @note -40 dBm will not actually give -40 dBm, but will instead be remapped to -30 dBm. - * - * @return @ref NRF_SUCCESS Successfully changed the transmit power. - * @return @ref NRF_ERROR_INVALID_PARAM Invalid parameter(s) supplied. - * @return @ref NRF_ERROR_BUSY The stack is busy, process pending events and retry. - */ -SVCALL(SD_BLE_GAP_TX_POWER_SET, uint32_t, sd_ble_gap_tx_power_set(int8_t tx_power)); - - -/**@brief Set GAP Appearance value. - * - * @param[in] appearance Appearance (16-bit), see @ref BLE_APPEARANCES. - * - * @return @ref NRF_SUCCESS Appearance value set successfully. - * @return @ref NRF_ERROR_INVALID_PARAM Invalid parameter(s) supplied. - */ -SVCALL(SD_BLE_GAP_APPEARANCE_SET, uint32_t, sd_ble_gap_appearance_set(uint16_t appearance)); - - -/**@brief Get GAP Appearance value. - * - * @param[out] p_appearance Appearance (16-bit), see @ref BLE_APPEARANCES. - * - * @return @ref NRF_SUCCESS Appearance value retrieved successfully. - * @return @ref NRF_ERROR_INVALID_ADDR Invalid pointer supplied. - */ -SVCALL(SD_BLE_GAP_APPEARANCE_GET, uint32_t, sd_ble_gap_appearance_get(uint16_t * const p_appearance)); - - -/**@brief Set GAP Peripheral Preferred Connection Parameters. - * - * @param[in] p_conn_params Pointer to a @ref ble_gap_conn_params_t structure with the desired parameters. - * - * @return @ref NRF_SUCCESS Peripheral Preferred Connection Parameters set successfully. - * @return @ref NRF_ERROR_INVALID_ADDR Invalid pointer supplied. - * @return @ref NRF_ERROR_INVALID_PARAM Invalid parameter(s) supplied. - */ -SVCALL(SD_BLE_GAP_PPCP_SET, uint32_t, sd_ble_gap_ppcp_set(ble_gap_conn_params_t const * const p_conn_params)); - - -/**@brief Get GAP Peripheral Preferred Connection Parameters. - * - * @param[out] p_conn_params Pointer to a @ref ble_gap_conn_params_t structure where the parameters will be stored. - * - * @return @ref NRF_SUCCESS Peripheral Preferred Connection Parameters retrieved successfully. - * @return @ref NRF_ERROR_INVALID_ADDR Invalid pointer supplied. - */ -SVCALL(SD_BLE_GAP_PPCP_GET, uint32_t, sd_ble_gap_ppcp_get(ble_gap_conn_params_t * const p_conn_params)); - - -/**@brief Set GAP device name. - * - * @param[in] p_write_perm Write permissions for the Device Name characteristic see @ref ble_gap_conn_sec_mode_t. - * @param[in] p_dev_name Pointer to a UTF-8 encoded, non NULL-terminated string. - * @param[in] len Length of the UTF-8, non NULL-terminated string pointed to by p_dev_name in octets (must be smaller or equal than @ref BLE_GAP_DEVNAME_MAX_LEN). - * - * @return @ref NRF_SUCCESS GAP device name and permissions set successfully. - * @return @ref NRF_ERROR_INVALID_ADDR Invalid pointer supplied. - * @return @ref NRF_ERROR_INVALID_PARAM Invalid parameter(s) supplied. - * @return @ref NRF_ERROR_DATA_SIZE Invalid data size(s) supplied. - */ -SVCALL(SD_BLE_GAP_DEVICE_NAME_SET, uint32_t, sd_ble_gap_device_name_set(ble_gap_conn_sec_mode_t const * const p_write_perm, uint8_t const * const p_dev_name, uint16_t len)); - - -/**@brief Get GAP device name. - * - * @param[in] p_dev_name Pointer to an empty buffer where the UTF-8 non NULL-terminated string will be placed. Set to NULL to obtain the complete device name length. - * @param[in,out] p_len Length of the buffer pointed by p_dev_name, complete device name length on output. - * - * @note If the device name is longer than the size of the supplied buffer, - * p_len will return the complete device name length, - * and not the number of bytes actually returned in p_dev_name. - * The application may use this information to allocate a suitable buffer size. - * - * @return @ref NRF_SUCCESS GAP device name retrieved successfully. - * @return @ref NRF_ERROR_INVALID_ADDR Invalid pointer supplied. - * @return @ref NRF_ERROR_DATA_SIZE Invalid data size(s) supplied. - */ -SVCALL(SD_BLE_GAP_DEVICE_NAME_GET, uint32_t, sd_ble_gap_device_name_get(uint8_t * const p_dev_name, uint16_t * const p_len)); - - -/**@brief Initiate GAP Authentication procedure. - * - * @param[in] conn_handle Connection handle. - * @param[in] p_sec_params Pointer to the @ref ble_gap_sec_params_t structure with the security parameters to be used during the pairing procedure. - * - * @details In the central role, this function will send an SMP Pairing Request, otherwise in the peripheral role, an SMP Security Request will be sent. - * In the peripheral role, only the timeout, bond and mitm fields of @ref ble_gap_sec_params_t are used. - * - * @note The GAP Authentication procedure may be triggered by the central without calling this function when accessing a secure service. - * @note Calling this function may result in the following events depending on the outcome and parameters: @ref BLE_GAP_EVT_SEC_PARAMS_REQUEST, - * @ref BLE_GAP_EVT_SEC_INFO_REQUEST, @ref BLE_GAP_EVT_AUTH_KEY_REQUEST, @ref BLE_GAP_EVT_AUTH_STATUS. - * @note The timeout parameter in @ref ble_gap_sec_params_t is interpreted here as the Security Request timeout - * - * - * @return @ref NRF_SUCCESS Successfully initiated authentication procedure. - * @return @ref NRF_ERROR_INVALID_ADDR Invalid pointer supplied. - * @return @ref NRF_ERROR_INVALID_PARAM Invalid parameter(s) supplied. - * @return @ref NRF_ERROR_INVALID_STATE Invalid state to perform operation. - * @return @ref BLE_ERROR_INVALID_CONN_HANDLE Invalid connection handle supplied. - */ -SVCALL(SD_BLE_GAP_AUTHENTICATE, uint32_t, sd_ble_gap_authenticate(uint16_t conn_handle, ble_gap_sec_params_t const * const p_sec_params)); - - -/**@brief Reply with GAP security parameters. - * - * @param[in] conn_handle Connection handle. - * @param[in] sec_status Security status, see @ref BLE_GAP_SEC_STATUS. - * @param[in] p_sec_params Pointer to a @ref ble_gap_sec_params_t security parameters structure. - * - * @details This function is only used to reply to a @ref BLE_GAP_EVT_SEC_PARAMS_REQUEST, calling it at other times will result in an NRF_ERROR_INVALID_STATE. - * @note If the call returns an error code, the request is still pending, and the reply call may be repeated with corrected parameters. - * @note The timeout parameter in @ref ble_gap_sec_params_t is interpreted here as the SMP procedure timeout, and must be 30 seconds. The function will fail - * if the application supplies a different value. - * - * @return @ref NRF_SUCCESS Successfully accepted security parameter from the application. - * @return @ref NRF_ERROR_INVALID_ADDR Invalid pointer supplied. - * @return @ref NRF_ERROR_INVALID_PARAM Invalid parameter(s) supplied. - * @return @ref NRF_ERROR_INVALID_STATE Invalid state to perform operation. - * @return @ref BLE_ERROR_INVALID_CONN_HANDLE Invalid connection handle supplied. - */ -SVCALL(SD_BLE_GAP_SEC_PARAMS_REPLY, uint32_t, sd_ble_gap_sec_params_reply(uint16_t conn_handle, uint8_t sec_status, ble_gap_sec_params_t const * const p_sec_params)); - - -/**@brief Reply with an authentication key. - * - * @param[in] conn_handle Connection handle. - * @param[in] key_type See @ref BLE_GAP_AUTH_KEY_TYPES. - * @param[in] key If key type is BLE_GAP_AUTH_KEY_TYPE_NONE, then NULL. - * If key type is BLE_GAP_AUTH_KEY_TYPE_PASSKEY, then a 6-byte ASCII string (digit 0..9 only, no NULL termination). - * If key type is BLE_GAP_AUTH_KEY_TYPE_OOB, then a 16-byte OOB key value in Little Endian format. - * - * @details This function is only used to reply to a @ref BLE_GAP_EVT_AUTH_KEY_REQUEST, calling it at other times will result in an NRF_ERROR_INVALID_STATE. - * @note If the call returns an error code, the request is still pending, and the reply call may be repeated with corrected parameters. - * - * @return @ref NRF_SUCCESS Authentication key successfully set. - * @return @ref NRF_ERROR_INVALID_ADDR Invalid pointer supplied. - * @return @ref NRF_ERROR_INVALID_PARAM Invalid parameter(s) supplied. - * @return @ref NRF_ERROR_INVALID_STATE Invalid state to perform operation. - * @return @ref BLE_ERROR_INVALID_CONN_HANDLE Invalid connection handle supplied. - */ -SVCALL(SD_BLE_GAP_AUTH_KEY_REPLY, uint32_t, sd_ble_gap_auth_key_reply(uint16_t conn_handle, uint8_t key_type, uint8_t const * const key)); - - -/**@brief Reply with GAP security information. - * - * @param[in] conn_handle Connection handle. - * @param[in] p_enc_info Pointer to a @ref ble_gap_enc_info_t encryption information structure. May be NULL to signal none is available. - * @param[in] p_sign_info Pointer to a @ref ble_gap_sign_info_t signing information structure. May be NULL to signal none is available. - * - * @details This function is only used to reply to a @ref BLE_GAP_EVT_SEC_INFO_REQUEST, calling it at other times will result in NRF_ERROR_INVALID_STATE. - * @note If the call returns an error code, the request is still pending, and the reply call may be repeated with corrected parameters. - * @note Data signing is not implemented yet. p_sign_info must therefore be NULL. - * - * @return @ref NRF_SUCCESS Successfully accepted security information. - * @return @ref NRF_ERROR_INVALID_PARAM Invalid parameter(s) supplied. - * @return @ref NRF_ERROR_INVALID_STATE Invalid state to perform operation. - * @return @ref BLE_ERROR_INVALID_CONN_HANDLE Invalid connection handle supplied. - * @return @ref NRF_ERROR_BUSY The stack is busy, process pending events and retry. - */ -SVCALL(SD_BLE_GAP_SEC_INFO_REPLY, uint32_t, sd_ble_gap_sec_info_reply(uint16_t conn_handle, ble_gap_enc_info_t const * const p_enc_info, ble_gap_sign_info_t const * const p_sign_info)); - - -/**@brief Get the current connection security. - * - * @param[in] conn_handle Connection handle. - * @param[out] p_conn_sec Pointer to a @ref ble_gap_conn_sec_t structure to be filled in. - * - * @return @ref NRF_SUCCESS Current connection security successfully retrieved. - * @return @ref NRF_ERROR_INVALID_ADDR Invalid pointer supplied. - * @return @ref BLE_ERROR_INVALID_CONN_HANDLE Invalid connection handle supplied. - */ -SVCALL(SD_BLE_GAP_CONN_SEC_GET, uint32_t, sd_ble_gap_conn_sec_get(uint16_t conn_handle, ble_gap_conn_sec_t * const p_conn_sec)); - - -/**@brief Start reporting the received signal strength to the application. - * - * A new event is reported whenever the RSSI value changes, until @ref sd_ble_gap_rssi_stop is called. - * - * @param[in] conn_handle Connection handle. - * - * @return @ref NRF_SUCCESS Successfully activated RSSI reporting. - * @return @ref NRF_ERROR_INVALID_STATE Invalid state to perform operation. - * @return @ref BLE_ERROR_INVALID_CONN_HANDLE Invalid connection handle supplied. - */ -SVCALL(SD_BLE_GAP_RSSI_START, uint32_t, sd_ble_gap_rssi_start(uint16_t conn_handle)); - - -/**@brief Stop reporting the received singnal strength. - * - * An RSSI change detected before the call but not yet received by the application - * may be reported after @ref sd_ble_gap_rssi_stop has been called. - * - * @param[in] conn_handle Connection handle. - * - * @return @ref NRF_SUCCESS Successfully deactivated RSSI reporting. - * @return @ref NRF_ERROR_INVALID_STATE Invalid state to perform operation. - * @return @ref BLE_ERROR_INVALID_CONN_HANDLE Invalid connection handle supplied. - */ -SVCALL(SD_BLE_GAP_RSSI_STOP, uint32_t, sd_ble_gap_rssi_stop(uint16_t conn_handle)); - -#endif // BLE_GAP_H__ - -/** - @} -*/ diff --git a/libraries/ble/nRF51822/nordic/nrf-sdk/s110/ble_gatt.h b/libraries/ble/nRF51822/nordic/nrf-sdk/s110/ble_gatt.h deleted file mode 100644 index 8a64b520b5..0000000000 --- a/libraries/ble/nRF51822/nordic/nrf-sdk/s110/ble_gatt.h +++ /dev/null @@ -1,167 +0,0 @@ -/* Copyright (c) 2012 Nordic Semiconductor. All Rights Reserved. - * - * The information contained herein is confidential property of Nordic Semiconductor. The use, - * copying, transfer or disclosure of such information is prohibited except by express written - * agreement with Nordic Semiconductor. - * - */ - /** - @addtogroup BLE_GATT Generic Attribute Profile (GATT) Common - @{ - @brief Common definitions and prototypes for the GATT interfaces. - */ - -#ifndef BLE_GATT_H__ -#define BLE_GATT_H__ - -#include "nordic_global.h" -#include "ble_types.h" -#include "ble_ranges.h" - - -/** @addtogroup BLE_GATT_DEFINES Defines - * @{ */ - -/** @brief Default MTU size. */ -#define GATT_MTU_SIZE_DEFAULT 23 - -/** @brief Only the default MTU size of 23 is currently supported. */ -#define GATT_RX_MTU 23 - - -/**@brief Invalid Attribute Handle. */ -#define BLE_GATT_HANDLE_INVALID 0x0000 - -/** @defgroup BLE_GATT_TIMEOUT_SOURCES GATT Timeout sources - * @{ */ -#define BLE_GATT_TIMEOUT_SRC_PROTOCOL 0x00 /**< ATT Protocol timeout. */ -/** @} */ - -/** @defgroup BLE_GATT_WRITE_OPS GATT Write operations - * @{ */ -#define BLE_GATT_OP_INVALID 0x00 /**< Invalid Operation. */ -#define BLE_GATT_OP_WRITE_REQ 0x01 /**< Write Request. */ -#define BLE_GATT_OP_WRITE_CMD 0x02 /**< Write Command. */ -#define BLE_GATT_OP_SIGN_WRITE_CMD 0x03 /**< Signed Write Command. */ -#define BLE_GATT_OP_PREP_WRITE_REQ 0x04 /**< Prepare Write Request. */ -#define BLE_GATT_OP_EXEC_WRITE_REQ 0x05 /**< Execute Write Request. */ -/** @} */ - -/** @defgroup BLE_GATT_EXEC_WRITE_FLAGS GATT Execute Write flags - * @{ */ -#define BLE_GATT_EXEC_WRITE_FLAG_PREPARED_CANCEL 0x00 -#define BLE_GATT_EXEC_WRITE_FLAG_PREPARED_WRITE 0x01 -/** @} */ - -/** @defgroup BLE_GATT_HVX_TYPES GATT Handle Value operations - * @{ */ -#define BLE_GATT_HVX_INVALID 0x00 /**< Invalid Operation. */ -#define BLE_GATT_HVX_NOTIFICATION 0x01 /**< Handle Value Notification. */ -#define BLE_GATT_HVX_INDICATION 0x02 /**< Handle Value Indication. */ -/** @} */ - -/** @defgroup BLE_GATT_STATUS_CODES GATT Status Codes - * @{ */ -#define BLE_GATT_STATUS_SUCCESS 0x0000 /**< Success. */ -#define BLE_GATT_STATUS_UNKNOWN 0x0001 /**< Unknown or not applicable status. */ -#define BLE_GATT_STATUS_ATTERR_INVALID 0x0100 /**< ATT Error: Invalid Error Code. */ -#define BLE_GATT_STATUS_ATTERR_INVALID_HANDLE 0x0101 /**< ATT Error: Invalid Attribute Handle. */ -#define BLE_GATT_STATUS_ATTERR_READ_NOT_PERMITTED 0x0102 /**< ATT Error: Read not permitted. */ -#define BLE_GATT_STATUS_ATTERR_WRITE_NOT_PERMITTED 0x0103 /**< ATT Error: Write not permitted. */ -#define BLE_GATT_STATUS_ATTERR_INVALID_PDU 0x0104 /**< ATT Error: Used in ATT as Invalid PDU. */ -#define BLE_GATT_STATUS_ATTERR_INSUF_AUTHENTICATION 0x0105 /**< ATT Error: Authenticated link required. */ -#define BLE_GATT_STATUS_ATTERR_REQUEST_NOT_SUPPORTED 0x0106 /**< ATT Error: Used in ATT as Request Not Supported. */ -#define BLE_GATT_STATUS_ATTERR_INVALID_OFFSET 0x0107 /**< ATT Error: Offset specified was past the end of the attribute. */ -#define BLE_GATT_STATUS_ATTERR_INSUF_AUTHORIZATION 0x0108 /**< ATT Error: Used in ATT as Insufficient Authorisation. */ -#define BLE_GATT_STATUS_ATTERR_PREPARE_QUEUE_FULL 0x0109 /**< ATT Error: Used in ATT as Prepare Queue Full. */ -#define BLE_GATT_STATUS_ATTERR_ATTRIBUTE_NOT_FOUND 0x010A /**< ATT Error: Used in ATT as Attribute not found. */ -#define BLE_GATT_STATUS_ATTERR_ATTRIBUTE_NOT_LONG 0x010B /**< ATT Error: Attribute cannot be read or written using read/write blob requests. */ -#define BLE_GATT_STATUS_ATTERR_INSUF_ENC_KEY_SIZE 0x010C /**< ATT Error: Encryption key size used is insufficient. */ -#define BLE_GATT_STATUS_ATTERR_INVALID_ATT_VAL_LENGTH 0x010D /**< ATT Error: Invalid value size. */ -#define BLE_GATT_STATUS_ATTERR_UNLIKELY_ERROR 0x010E /**< ATT Error: Very unlikely error. */ -#define BLE_GATT_STATUS_ATTERR_INSUF_ENCRYPTION 0x010F /**< ATT Error: Encrypted link required. */ -#define BLE_GATT_STATUS_ATTERR_UNSUPPORTED_GROUP_TYPE 0x0110 /**< ATT Error: Attribute type is not a supported grouping attribute. */ -#define BLE_GATT_STATUS_ATTERR_INSUF_RESOURCES 0x0111 /**< ATT Error: Encrypted link required. */ -#define BLE_GATT_STATUS_ATTERR_RFU_RANGE1_BEGIN 0x0112 /**< ATT Error: Reserved for Future Use range #1 begin. */ -#define BLE_GATT_STATUS_ATTERR_RFU_RANGE1_END 0x017F /**< ATT Error: Reserved for Future Use range #1 end. */ -#define BLE_GATT_STATUS_ATTERR_APP_BEGIN 0x0180 /**< ATT Error: Application range begin. */ -#define BLE_GATT_STATUS_ATTERR_APP_END 0x019F /**< ATT Error: Application range end. */ -#define BLE_GATT_STATUS_ATTERR_RFU_RANGE2_BEGIN 0x01A0 /**< ATT Error: Reserved for Future Use range #2 begin. */ -#define BLE_GATT_STATUS_ATTERR_RFU_RANGE2_END 0x01DF /**< ATT Error: Reserved for Future Use range #2 end. */ -#define BLE_GATT_STATUS_ATTERR_RFU_RANGE3_BEGIN 0x01E0 /**< ATT Error: Reserved for Future Use range #3 begin. */ -#define BLE_GATT_STATUS_ATTERR_RFU_RANGE3_END 0x01FC /**< ATT Error: Reserved for Future Use range #3 end. */ -#define BLE_GATT_STATUS_ATTERR_CPS_CCCD_CONFIG_ERROR 0x01FD /**< ATT Common Profile and Service Error: Client Characteristic Configuration Descriptor improperly configured. */ -#define BLE_GATT_STATUS_ATTERR_CPS_PROC_ALR_IN_PROG 0x01FE /**< ATT Common Profile and Service Error: Procedure Already in Progress. */ -#define BLE_GATT_STATUS_ATTERR_CPS_OUT_OF_RANGE 0x01FF /**< ATT Common Profile and Service Error: Out Of Range. */ -/** @} */ - - -/** @defgroup BLE_GATT_CPF_FORMATS Characteristic Presentation Formats - * @note Found at http://developer.bluetooth.org/gatt/descriptors/Pages/DescriptorViewer.aspx?u=org.bluetooth.descriptor.gatt.characteristic_presentation_format.xml - * @{ */ -#define BLE_GATT_CPF_FORMAT_RFU 0x00 /**< Reserved For Future Use. */ -#define BLE_GATT_CPF_FORMAT_BOOLEAN 0x01 /**< Boolean. */ -#define BLE_GATT_CPF_FORMAT_2BIT 0x02 /**< Unsigned 2-bit integer. */ -#define BLE_GATT_CPF_FORMAT_NIBBLE 0x03 /**< Unsigned 4-bit integer. */ -#define BLE_GATT_CPF_FORMAT_UINT8 0x04 /**< Unsigned 8-bit integer. */ -#define BLE_GATT_CPF_FORMAT_UINT12 0x05 /**< Unsigned 12-bit integer. */ -#define BLE_GATT_CPF_FORMAT_UINT16 0x06 /**< Unsigned 16-bit integer. */ -#define BLE_GATT_CPF_FORMAT_UINT24 0x07 /**< Unsigned 24-bit integer. */ -#define BLE_GATT_CPF_FORMAT_UINT32 0x08 /**< Unsigned 32-bit integer. */ -#define BLE_GATT_CPF_FORMAT_UINT48 0x09 /**< Unsigned 48-bit integer. */ -#define BLE_GATT_CPF_FORMAT_UINT64 0x0A /**< Unsigned 64-bit integer. */ -#define BLE_GATT_CPF_FORMAT_UINT128 0x0B /**< Unsigned 128-bit integer. */ -#define BLE_GATT_CPF_FORMAT_SINT8 0x0C /**< Signed 2-bit integer. */ -#define BLE_GATT_CPF_FORMAT_SINT12 0x0D /**< Signed 12-bit integer. */ -#define BLE_GATT_CPF_FORMAT_SINT16 0x0E /**< Signed 16-bit integer. */ -#define BLE_GATT_CPF_FORMAT_SINT24 0x0F /**< Signed 24-bit integer. */ -#define BLE_GATT_CPF_FORMAT_SINT32 0x10 /**< Signed 32-bit integer. */ -#define BLE_GATT_CPF_FORMAT_SINT48 0x11 /**< Signed 48-bit integer. */ -#define BLE_GATT_CPF_FORMAT_SINT64 0x12 /**< Signed 64-bit integer. */ -#define BLE_GATT_CPF_FORMAT_SINT128 0x13 /**< Signed 128-bit integer. */ -#define BLE_GATT_CPF_FORMAT_FLOAT32 0x14 /**< IEEE-754 32-bit floating point. */ -#define BLE_GATT_CPF_FORMAT_FLOAT64 0x15 /**< IEEE-754 64-bit floating point. */ -#define BLE_GATT_CPF_FORMAT_SFLOAT 0x16 /**< IEEE-11073 16-bit SFLOAT. */ -#define BLE_GATT_CPF_FORMAT_FLOAT 0x17 /**< IEEE-11073 32-bit FLOAT. */ -#define BLE_GATT_CPF_FORMAT_DUINT16 0x18 /**< IEEE-20601 format. */ -#define BLE_GATT_CPF_FORMAT_UTF8S 0x19 /**< UTF-8 string. */ -#define BLE_GATT_CPF_FORMAT_UTF16S 0x1A /**< UTF-16 string. */ -#define BLE_GATT_CPF_FORMAT_STRUCT 0x1B /**< Opaque Structure. */ -/** @} */ - -/** @defgroup BLE_GATT_CPF_NAMESPACES GATT Bluetooth Namespaces - * @{ - */ -#define BLE_GATT_CPF_NAMESPACE_BTSIG 0x01 -#define BLE_GATT_CPF_NAMESPACE_DESCRIPTION_UNKNOWN 0x0000 -/** @} */ - -/** @} */ - -/**@brief GATT Characteristic Properties. */ -typedef struct -{ - /* Standard properties */ - uint8_t broadcast :1; /**< Broadcasting of value permitted. */ - uint8_t read :1; /**< Reading value permitted. */ - uint8_t write_wo_resp :1; /**< Writing value with Write Command permitted. */ - uint8_t write :1; /**< Writing value with Write Request permitted. */ - uint8_t notify :1; /**< Notications of value permitted. */ - uint8_t indicate :1; /**< Indications of value permitted. */ - uint8_t auth_signed_wr :1; /**< Writing value with Signed Write Command permitted. */ -} ble_gatt_char_props_t; - -/**@brief GATT Characteristic Extended Properties. */ -typedef struct -{ - /* Extended properties */ - uint8_t reliable_wr :1; /**< Writing value with Queued Write Request permitted. */ - uint8_t wr_aux :1; /**< Writing the Characteristic User Description permitted. */ -} ble_gatt_char_ext_props_t; - -#endif // BLE_GATT_H__ - -/** - @} - @} -*/ diff --git a/libraries/ble/nRF51822/nordic/nrf-sdk/s110/ble_gattc.h b/libraries/ble/nRF51822/nordic/nrf-sdk/s110/ble_gattc.h deleted file mode 100644 index 9a49031df7..0000000000 --- a/libraries/ble/nRF51822/nordic/nrf-sdk/s110/ble_gattc.h +++ /dev/null @@ -1,396 +0,0 @@ -/* Copyright (c) 2012 Nordic Semiconductor. All Rights Reserved. - * - * The information contained herein is confidential property of Nordic Semiconductor. The use, - * copying, transfer or disclosure of such information is prohibited except by express written - * agreement with Nordic Semiconductor. - * - */ -/** - @addtogroup BLE_GATTC Generic Attribute Profile (GATT) Client - @{ - @brief Definitions and prototypes for the GATT Client interface. - */ - -#ifndef BLE_GATTC_H__ -#define BLE_GATTC_H__ - -#include "nordic_global.h" -#include "ble_gatt.h" -#include "ble_types.h" -#include "ble_ranges.h" -#include "nrf_svc.h" - - -/**@brief GATTC API SVC numbers. */ -enum BLE_GATTC_SVCS -{ - SD_BLE_GATTC_PRIMARY_SERVICES_DISCOVER = BLE_GATTC_SVC_BASE, /**< Primary Service Discovery. */ - SD_BLE_GATTC_RELATIONSHIPS_DISCOVER, /**< Relationship Discovery. */ - SD_BLE_GATTC_CHARACTERISTICS_DISCOVER, /**< Characteristic Discovery. */ - SD_BLE_GATTC_DESCRIPTORS_DISCOVER, /**< Characteristic Descriptor Discovery. */ - SD_BLE_GATTC_CHAR_VALUE_BY_UUID_READ, /**< Read Characteristic Value by UUID. */ - SD_BLE_GATTC_READ, /**< Generic read. */ - SD_BLE_GATTC_CHAR_VALUES_READ, /**< Read multiple Characteristic Values. */ - SD_BLE_GATTC_WRITE, /**< Generic write. */ - SD_BLE_GATTC_HV_CONFIRM /**< Handle Value Confirmation. */ -}; - -/** @addtogroup BLE_GATTC_DEFINES Defines - * @{ */ - -/** @defgroup BLE_ERRORS_GATTC SVC return values specific to GATTC - * @{ */ -#define BLE_ERROR_GATTC_PROC_NOT_PERMITTED (NRF_GATTC_ERR_BASE + 0x000) -/** @} */ - -/**@brief Last Attribute Handle. */ -#define BLE_GATTC_HANDLE_END 0xFFFF - -/** @} */ - -/**@brief Operation Handle Range. */ -typedef struct -{ - uint16_t start_handle; /**< Start Handle. */ - uint16_t end_handle; /**< End Handle. */ -} ble_gattc_handle_range_t; - - -/**@brief GATT service. */ -typedef struct -{ - ble_uuid_t uuid; /**< Service UUID. */ - ble_gattc_handle_range_t handle_range; /**< Service Handle Range. */ -} ble_gattc_service_t; - - -/**@brief GATT include. */ -typedef struct -{ - uint16_t handle; /**< Include Handle. */ - ble_gattc_service_t included_srvc; /**< Handle of the included service. */ -} ble_gattc_include_t; - - -/**@brief GATT characteristic. */ -typedef struct -{ - ble_uuid_t uuid; /**< Characteristic UUID. */ - ble_gatt_char_props_t char_props; /**< Characteristic Properties. */ - uint8_t char_ext_props : 1; /**< Extended properties present. */ - uint16_t handle_decl; /**< Handle of the Characteristic Declaration. */ - uint16_t handle_value; /**< Handle of the Characteristic Value. */ -} ble_gattc_char_t; - - -/**@brief GATT descriptor. */ -typedef struct -{ - uint16_t handle; /**< Descriptor Handle. */ - ble_uuid_t uuid; /**< Descriptor UUID. */ -} ble_gattc_desc_t; - - -/**@brief Write Parameters. */ -typedef struct -{ - uint8_t write_op; /**< Write Operation to be performed, see BLE_GATT_WRITE_OPS. */ - uint16_t handle; /**< Handle to the attribute to be written. */ - uint16_t offset; /**< Offset in bytes. */ - uint16_t len; /**< Length of data in bytes. */ - uint8_t* p_value; /**< Pointer to the value data. */ - uint8_t flags; /**< Flags, see @ref BLE_GATT_EXEC_WRITE_FLAGS. */ -} ble_gattc_write_params_t; - - -/** - * @brief GATT Client Event IDs. - */ -enum BLE_GATTC_EVTS -{ - BLE_GATTC_EVT_PRIM_SRVC_DISC_RSP = BLE_GATTC_EVT_BASE, /**< Primary Service Discovery Response event. */ - BLE_GATTC_EVT_REL_DISC_RSP, /**< Relationship Discovery Response event. */ - BLE_GATTC_EVT_CHAR_DISC_RSP, /**< Characteristic Discovery Response event. */ - BLE_GATTC_EVT_DESC_DISC_RSP, /**< Descriptor Discovery Response event. */ - BLE_GATTC_EVT_CHAR_VAL_BY_UUID_READ_RSP, /**< Read By UUID Response event. */ - BLE_GATTC_EVT_READ_RSP, /**< Read Response event. */ - BLE_GATTC_EVT_CHAR_VALS_READ_RSP, /**< Read multiple Response event. */ - BLE_GATTC_EVT_WRITE_RSP, /**< Write Response event. */ - BLE_GATTC_EVT_HVX, /**< Handle Value Notification or Indication event. */ - BLE_GATTC_EVT_TIMEOUT /**< Timeout event. */ -}; - -/**@brief Event structure for BLE_GATTC_EVT_PRIM_SRVC_DISC_RSP. */ -typedef struct -{ - uint16_t count; /**< Service count. */ - ble_gattc_service_t services[1]; /**< Service data, variable length. */ -} ble_gattc_evt_prim_srvc_disc_rsp_t; - -/**@brief Event structure for BLE_GATTC_EVT_REL_DISC_RSP. */ -typedef struct -{ - uint16_t count; /**< Include count. */ - ble_gattc_include_t includes[1]; /**< Include data, variable length. */ -} ble_gattc_evt_rel_disc_rsp_t; - -/**@brief Event structure for BLE_GATTC_EVT_CHAR_DISC_RSP. */ -typedef struct -{ - uint16_t count; /**< Characteristic count. */ - ble_gattc_char_t chars[1]; /**< Characteristic data, variable length. */ -} ble_gattc_evt_char_disc_rsp_t; - -/**@brief Event structure for BLE_GATTC_EVT_DESC_DISC_RSP. */ -typedef struct -{ - uint16_t count; /**< Descriptor count. */ - ble_gattc_desc_t descs[1]; /**< Descriptor data, variable length. */ -} ble_gattc_evt_desc_disc_rsp_t; - -/**@brief GATT read by UUID handle value pair. */ -typedef struct -{ - uint16_t handle; /**< Attribute Handle. */ - uint8_t *p_value; /**< Pointer to value, variable length (length available as value_len in ble_gattc_evt_read_by_uuid_rsp_t). - Please note that this pointer is absolute to the memory provided by the user when retrieving the event, - so it will effectively point to a location inside the handle_value array. */ -} ble_gattc_handle_value_t; - -/**@brief Event structure for BLE_GATTC_EVT_CHAR_VAL_BY_UUID_READ_RSP. */ -typedef struct -{ - uint16_t count; /**< Handle-Value Pair Count. */ - uint16_t value_len; /**< Length of the value in Handle-Value(s) list. */ - ble_gattc_handle_value_t handle_value[1]; /**< Handle-Value(s) list, variable length. */ -} ble_gattc_evt_char_val_by_uuid_read_rsp_t; - -/**@brief Event structure for BLE_GATTC_EVT_READ_RSP. */ -typedef struct -{ - uint16_t handle; /**< Attribute Handle. */ - uint16_t offset; /**< Offset of the attribute data. */ - uint16_t len; /**< Attribute data length. */ - uint8_t data[1]; /**< Attribute data, variable length. */ -} ble_gattc_evt_read_rsp_t; - -/**@brief Event structure for BLE_GATTC_EVT_CHAR_VALS_READ_RSP. */ -typedef struct -{ - uint16_t len; /**< Concatenated Attribute values length. */ - uint8_t values[1]; /**< Attribute values, variable length. */ -} ble_gattc_evt_char_vals_read_rsp_t; - -/**@brief Event structure for BLE_GATTC_EVT_WRITE_RSP. */ -typedef struct -{ - uint16_t handle; /**< Attribute Handle. */ - uint8_t write_op; /**< Type of write operation, see @ref BLE_GATT_WRITE_OPS. */ - uint16_t offset; /**< Data Offset. */ - uint16_t len; /**< Data length. */ - uint8_t data[1]; /**< Data, variable length. */ -} ble_gattc_evt_write_rsp_t; - -/**@brief Event structure for BLE_GATTC_EVT_HVX. */ -typedef struct -{ - uint16_t handle; /**< Handle to which the HVx operation applies. */ - uint8_t type; /**< Indication or Notification, see @ref BLE_GATT_HVX_TYPES. */ - uint16_t len; /**< Attribute data length. */ - uint8_t data[1]; /**< Attribute data, variable length. */ -} ble_gattc_evt_hvx_t; - -/**@brief Event structure for BLE_GATTC_EVT_TIMEOUT. */ -typedef struct -{ - uint8_t src; /**< Timeout source, see @ref BLE_GATT_TIMEOUT_SOURCES. */ -} ble_gattc_evt_timeout_t; - -/**@brief GATTC event type. */ -typedef struct -{ - uint16_t conn_handle; /**< Connection Handle on which event occured. */ - uint16_t gatt_status; /**< GATT status code for the operation, see @ref BLE_GATT_STATUS_CODES. */ - uint16_t error_handle; /**< In case of error: The handle causing the error. In all other cases BLE_GATT_HANDLE_INVALID. */ - union - { - ble_gattc_evt_prim_srvc_disc_rsp_t prim_srvc_disc_rsp; /**< Primary Service Discovery Response Event Parameters. */ - ble_gattc_evt_rel_disc_rsp_t rel_disc_rsp; /**< Relationship Discovery Response Event Parameters. */ - ble_gattc_evt_char_disc_rsp_t char_disc_rsp; /**< Characteristic Discovery Response Event Parameters. */ - ble_gattc_evt_desc_disc_rsp_t desc_disc_rsp; /**< Descriptor Discovery Response Event Parameters. */ - ble_gattc_evt_char_val_by_uuid_read_rsp_t char_val_by_uuid_read_rsp; /**< Characteristic Value Read by UUID Response Event Parameters. */ - ble_gattc_evt_read_rsp_t read_rsp; /**< Read Response Event Parameters. */ - ble_gattc_evt_char_vals_read_rsp_t char_vals_read_rsp; /**< Characteristic Values Read Response Event Parameters. */ - ble_gattc_evt_write_rsp_t write_rsp; /**< Write Response Event Parameters. */ - ble_gattc_evt_hvx_t hvx; /**< Handle Value Notification/Indication Event Parameters. */ - ble_gattc_evt_timeout_t timeout; /**< Timeout Event Parameters. */ - } params; /**< Event Parameters. @note Only valid if @ref gatt_status == BLE_GATT_STATUS_SUCCESS. */ -} ble_gattc_evt_t; - - -/**@brief Initiate or continue a GATT Primary Service Discovery procedure. - * - * @details This function initiates a Primary Service discovery, starting from the supplied handle. - * If the last service has not been reached, this must be called again with an updated start handle value to continue the search. - * - * @note If any of the discovered services have 128-bit UUIDs which are not present in the table provided to ble_vs_uuids_assign, a UUID structure with - * type BLE_UUID_TYPE_UNKNOWN will be received in the corresponding event. - * - * @param[in] conn_handle The connection handle identifying the connection to perform this procedure on. - * @param[in] start_handle Handle to start searching from. - * @param[in] p_srvc_uuid Pointer to the service UUID to be found. If it is NULL, all primary services will be returned. - * - * @return @ref NRF_SUCCESS Successfully started or resumed the Primary Service Discovery procedure. - * @return @ref BLE_ERROR_INVALID_CONN_HANDLE Invalid Connection Handle. - * @return @ref NRF_ERROR_INVALID_PARAM Invalid parameter(s) supplied. - * @return @ref NRF_ERROR_BUSY Client procedure already in progress. - */ -SVCALL(SD_BLE_GATTC_PRIMARY_SERVICES_DISCOVER, uint32_t, sd_ble_gattc_primary_services_discover(uint16_t conn_handle, uint16_t start_handle, ble_uuid_t const * const p_srvc_uuid)); - - -/**@brief Initiate or continue a GATT Relationship Discovery procedure. - * - * @details This function initiates the Find Included Services sub-procedure. If the last included service has not been reached, - * this must be called again with an updated handle range to continue the search. - * - * @param[in] conn_handle The connection handle identifying the connection to perform this procedure on. - * @param[in] p_handle_range A pointer to the range of handles of the Service to perform this procedure on. - * - * @return @ref NRF_SUCCESS Successfully started or resumed the Relationship Discovery procedure. - * @return @ref BLE_ERROR_INVALID_CONN_HANDLE Invalid Connection Handle. - * @return @ref NRF_ERROR_INVALID_ADDR Invalid pointer supplied. - * @return @ref NRF_ERROR_INVALID_PARAM Invalid parameter(s) supplied. - * @return @ref NRF_ERROR_BUSY Client procedure already in progress. - */ -SVCALL(SD_BLE_GATTC_RELATIONSHIPS_DISCOVER, uint32_t, sd_ble_gattc_relationships_discover(uint16_t conn_handle, ble_gattc_handle_range_t const * const p_handle_range)); - - -/**@brief Initiate or continue a GATT Characteristic Discovery procedure. - * - * @details This function initiates a Characteristic discovery procedure. If the last Characteristic has not been reached, - * this must be called again with an updated handle range to continue the discovery. - * - * @note If any of the discovered characteristics have 128-bit UUIDs which are not present in the table provided to ble_vs_uuids_assign, a UUID structure with - * type BLE_UUID_TYPE_UNKNOWN will be received in the corresponding event. - * - * @param[in] conn_handle The connection handle identifying the connection to perform this procedure on. - * @param[in] p_handle_range A pointer to the range of handles of the Service to perform this procedure on. - * - * @return @ref NRF_SUCCESS Successfully started or resumed the Characteristic Discovery procedure. - * @return @ref BLE_ERROR_INVALID_CONN_HANDLE Invalid Connection Handle. - * @return @ref NRF_ERROR_INVALID_ADDR Invalid pointer supplied. - * @return @ref NRF_ERROR_BUSY Client procedure already in progress. - */ -SVCALL(SD_BLE_GATTC_CHARACTERISTICS_DISCOVER, uint32_t, sd_ble_gattc_characteristics_discover(uint16_t conn_handle, ble_gattc_handle_range_t const * const p_handle_range)); - - -/**@brief Initiate or continue a GATT Characteristic Descriptor Discovery procedure. - * - * @details This function initiates the Characteristic Descriptor discovery procedure. If the last Descriptor has not been reached, - * this must be called again with an updated handle range to continue the discovery. - * - * @param[in] conn_handle The connection handle identifying the connection to perform this procedure on. - * @param[in] p_handle_range A pointer to the range of handles of the Characteristic to perform this procedure on. - * - * @return @ref NRF_SUCCESS Successfully started or resumed the Descriptor Discovery procedure. - * @return @ref BLE_ERROR_INVALID_CONN_HANDLE Invalid Connection Handle. - * @return @ref NRF_ERROR_INVALID_ADDR Invalid pointer supplied. - * @return @ref NRF_ERROR_BUSY Client procedure already in progress. - */ -SVCALL(SD_BLE_GATTC_DESCRIPTORS_DISCOVER, uint32_t, sd_ble_gattc_descriptors_discover(uint16_t conn_handle, ble_gattc_handle_range_t const * const p_handle_range)); - - -/**@brief Initiate or continue a GATT Read using Characteristic UUID procedure. - * - * @details This function initiates the Read using Characteristic UUID procedure. If the last Characteristic has not been reached, - * this must be called again with an updated handle range to continue the discovery. - * - * @param[in] conn_handle The connection handle identifying the connection to perform this procedure on. - * @param[in] p_uuid Pointer to a Characteristic value UUID to read. - * @param[in] p_handle_range A pointer to the range of handles to perform this procedure on. - * - * @return @ref NRF_SUCCESS Successfully started or resumed the Read using Characteristic UUID procedure. - * @return @ref BLE_ERROR_INVALID_CONN_HANDLE Invalid Connection Handle. - * @return @ref NRF_ERROR_INVALID_ADDR Invalid pointer supplied. - * @return @ref NRF_ERROR_BUSY Client procedure already in progress. - */ -SVCALL(SD_BLE_GATTC_CHAR_VALUE_BY_UUID_READ, uint32_t, sd_ble_gattc_char_value_by_uuid_read(uint16_t conn_handle, ble_uuid_t const * const p_uuid, ble_gattc_handle_range_t const * const p_handle_range)); - - -/**@brief Initiate or continue a GATT Read (Long) Characteristic or Descriptor procedure. - * - * @details This function initiates a GATT Read (Long) Characteristic or Descriptor procedure. If the Characteristic or Descriptor - * to be read is longer than GATT_MTU - 1, this function must be called multiple times with appropriate offset to read the - * complete value. - * - * @param[in] conn_handle The connection handle identifying the connection to perform this procedure on. - * @param[in] handle The handle of the attribute to be read. - * @param[in] offset Offset into the attribute value to be read. - * - * @return @ref NRF_SUCCESS Successfully started or resumed the Read (Long) procedure. - * @return @ref BLE_ERROR_INVALID_CONN_HANDLE Invalid Connection Handle. - * @return @ref NRF_ERROR_INVALID_ADDR Invalid pointer supplied. - * @return @ref NRF_ERROR_BUSY Client procedure already in progress. - */ -SVCALL(SD_BLE_GATTC_READ, uint32_t, sd_ble_gattc_read(uint16_t conn_handle, uint16_t handle, uint16_t offset)); - - -/**@brief Initiate a GATT Read Multiple Characteristic Values procedure. - * - * @details This function initiates a GATT Read Multiple Characteristic Values procedure. - * - * @param[in] conn_handle The connection handle identifying the connection to perform this procedure on. - * @param[in] p_handles A pointer to the handle(s) of the attribute(s) to be read. - * @param[in] handle_count The number of handles in p_handles. - * - * @return @ref NRF_SUCCESS Successfully started the Read Multiple Characteristic Values procedure. - * @return @ref BLE_ERROR_INVALID_CONN_HANDLE Invalid Connection Handle. - * @return @ref NRF_ERROR_INVALID_ADDR Invalid pointer supplied. - * @return @ref NRF_ERROR_BUSY Client procedure already in progress. - */ -SVCALL(SD_BLE_GATTC_CHAR_VALUES_READ, uint32_t, sd_ble_gattc_char_values_read(uint16_t conn_handle, uint16_t const * const p_handles, uint16_t handle_count)); - - -/**@brief Perform a Write (Characteristic Value or Descriptor, with or without response, signed or not, long or reliable) procedure. - * - * @details This function can perform all write procedures described in GATT. - * - * @note It is important to note that a write without response will consume an application buffer, and will therefore - * generate a @ref BLE_EVT_TX_COMPLETE event when the packet has been transmitted. A write on the other hand will use the - * standard client internal buffer and thus will only generate a @ref BLE_GATTC_EVT_WRITE_RSP event as soon as the write response - * has been received from the peer. Please see the documentation of @ref sd_ble_tx_buffer_count_get for more details. - * - * @param[in] conn_handle The connection handle identifying the connection to perform this procedure on. - * @param[in] p_write_params A pointer to a write parameters structure. - * - * @return @ref NRF_SUCCESS Successfully started the Write procedure. - * @return @ref BLE_ERROR_INVALID_CONN_HANDLE Invalid Connection Handle. - * @return @ref NRF_ERROR_INVALID_ADDR Invalid pointer supplied. - * @return @ref NRF_ERROR_INVALID_PARAM Invalid parameter(s) supplied. - * @return @ref NRF_ERROR_DATA_SIZE Invalid data size(s) supplied. - * @return @ref NRF_ERROR_BUSY Procedure already in progress. - * @return @ref BLE_ERROR_NO_TX_BUFFERS There are no available buffers left. - */ -SVCALL(SD_BLE_GATTC_WRITE, uint32_t, sd_ble_gattc_write(uint16_t conn_handle, ble_gattc_write_params_t const * const p_write_params)); - - -/**@brief Send a Handle Value Confirmation to the GATT Server. - * - * @param[in] conn_handle The connection handle identifying the connection to perform this procedure on. - * @param[in] handle The handle of the attribute in the indication. - * - * @return @ref NRF_SUCCESS Successfully queued the Handle Value Confirmation for transmission. - * @return @ref BLE_ERROR_INVALID_CONN_HANDLE Invalid Connection Handle. - * @return @ref NRF_ERROR_INVALID_STATE No Indication pending to be confirmed. - * @return @ref BLE_ERROR_INVALID_ATTR_HANDLE Invalid attribute handle. - * @return @ref BLE_ERROR_NO_TX_BUFFERS There are no available buffers left. - */ -SVCALL(SD_BLE_GATTC_HV_CONFIRM, uint32_t, sd_ble_gattc_hv_confirm(uint16_t conn_handle, uint16_t handle)); - - -#endif /* BLE_GATTC_H__ */ - -/** - @} - @} -*/ diff --git a/libraries/ble/nRF51822/nordic/nrf-sdk/s110/ble_gatts.h b/libraries/ble/nRF51822/nordic/nrf-sdk/s110/ble_gatts.h deleted file mode 100644 index 8b54d750b7..0000000000 --- a/libraries/ble/nRF51822/nordic/nrf-sdk/s110/ble_gatts.h +++ /dev/null @@ -1,548 +0,0 @@ -/* Copyright (c) 2011 Nordic Semiconductor. All Rights Reserved. - * - * The information contained herein is confidential property of Nordic Semiconductor. The use, - * copying, transfer or disclosure of such information is prohibited except by express written - * agreement with Nordic Semiconductor. - * - */ -/** - @addtogroup BLE_GATTS Generic Attribute Profile (GATT) Server - @{ - @brief Definitions and prototypes for the GATTS interface. - */ - -#ifndef BLE_GATTS_H__ -#define BLE_GATTS_H__ - -#include "nordic_global.h" -#include "ble_types.h" -#include "ble_ranges.h" -#include "ble_l2cap.h" -#include "ble_gap.h" -#include "ble_gatt.h" -#include "nrf_svc.h" - - -/** - * @brief GATTS API SVC numbers. - */ -enum BLE_GATTS_SVCS -{ - SD_BLE_GATTS_SERVICE_ADD = BLE_GATTS_SVC_BASE, /**< Add a service. */ - SD_BLE_GATTS_INCLUDE_ADD, /**< Add an included service. */ - SD_BLE_GATTS_CHARACTERISTIC_ADD, /**< Add a characteristic. */ - SD_BLE_GATTS_DESCRIPTOR_ADD, /**< Add a generic attribute. */ - SD_BLE_GATTS_VALUE_SET, /**< Set an attribute value. */ - SD_BLE_GATTS_VALUE_GET, /**< Get an attribute value. */ - SD_BLE_GATTS_HVX, /**< Handle Value Notification or Indication. */ - SD_BLE_GATTS_SERVICE_CHANGED, /**< Perform a Service Changed Indication to one or more peers. */ - SD_BLE_GATTS_RW_AUTHORIZE_REPLY, /**< Reply to an authorization request for a read or write operation on one or more attributes. */ - SD_BLE_GATTS_SYS_ATTR_SET, /**< Set the persistent system attributes for a connection. */ - SD_BLE_GATTS_SYS_ATTR_GET, /**< Get updated persistent system attributes after terminating a connection. */ -}; - - -/** @addtogroup BLE_GATTS_DEFINES Defines - * @{ */ - -/** @brief Only the default MTU size of 23 is currently supported. */ -#define GATT_RX_MTU 23 - -/** @defgroup BLE_ERRORS_GATTS SVC return values specific to GATTS - * @{ */ -#define BLE_ERROR_GATTS_INVALID_ATTR_TYPE (NRF_GATTS_ERR_BASE + 0x000) /**< Invalid attribute type. */ -#define BLE_ERROR_GATTS_SYS_ATTR_MISSING (NRF_GATTS_ERR_BASE + 0x001) /**< System Attributes missing. */ -/** @} */ - -/** @defgroup BLE_GATTS_ATTR_LENS_MAX Maximum attribute lengths - * @{ */ -#define BLE_GATTS_FIX_ATTR_LEN_MAX (510) /**< Maximum length for fixed length Attribute Values. */ -#define BLE_GATTS_VAR_ATTR_LEN_MAX (512) /**< Maximum length for variable length Attribute Values. */ -/** @} */ - -/** @defgroup BLE_GATTS_SRVC_TYPES GATT Server Service Types - * @{ */ -#define BLE_GATTS_SRVC_TYPE_INVALID 0x00 /**< Invalid Service Type. */ -#define BLE_GATTS_SRVC_TYPE_PRIMARY 0x01 /**< Primary Service. */ -#define BLE_GATTS_SRVC_TYPE_SECONDARY 0x02 /**< Secondary Type. */ -/** @} */ - - -/** @defgroup BLE_GATTS_ATTR_TYPES GATT Server Attribute Types - * @{ */ -#define BLE_GATTS_ATTR_TYPE_INVALID 0x00 /**< Invalid Attribute Type. */ -#define BLE_GATTS_ATTR_TYPE_PRIM_SRVC_DECL 0x01 /**< Primary Service Declaration. */ -#define BLE_GATTS_ATTR_TYPE_SEC_SRVC_DECL 0x02 /**< Secondary Service Declaration. */ -#define BLE_GATTS_ATTR_TYPE_INC_DECL 0x03 /**< Include Declaration. */ -#define BLE_GATTS_ATTR_TYPE_CHAR_DECL 0x04 /**< Characteristic Declaration. */ -#define BLE_GATTS_ATTR_TYPE_CHAR_VAL 0x05 /**< Characteristic Value. */ -#define BLE_GATTS_ATTR_TYPE_DESC 0x06 /**< Descriptor. */ -#define BLE_GATTS_ATTR_TYPE_OTHER 0x07 /**< Other, non-GATT specific type. */ -/** @} */ - - -/** @defgroup BLE_GATTS_OPS GATT Server Operations - * @{ */ -#define BLE_GATTS_OP_INVALID 0x00 /**< Invalid Operation. */ -#define BLE_GATTS_OP_WRITE_REQ 0x01 /**< Write Request. */ -#define BLE_GATTS_OP_WRITE_CMD 0x02 /**< Write Command. */ -#define BLE_GATTS_OP_SIGN_WRITE_CMD 0x03 /**< Signed Write Command. */ -#define BLE_GATTS_OP_PREP_WRITE_REQ 0x04 /**< Prepare Write Request. */ -#define BLE_GATTS_OP_EXEC_WRITE_REQ_CANCEL 0x05 /**< Execute Write Request: Cancel all prepared writes. */ -#define BLE_GATTS_OP_EXEC_WRITE_REQ_NOW 0x06 /**< Execute Write Request: Immediately execute all prepared writes. */ -/** @} */ - -/** @defgroup BLE_GATTS_VLOCS GATT Value Locations - * @{ */ -#define BLE_GATTS_VLOC_INVALID 0x00 /**< Invalid Location. */ -#define BLE_GATTS_VLOC_STACK 0x01 /**< Attribute Value is located in stack memory, no user memory is required. */ -#define BLE_GATTS_VLOC_USER 0x02 /**< Attribute Value is located in user memory. This requires the user to maintain a valid buffer through the lifetime of the attribute, since the stack - will read and write directly to the memory using the pointer provided in the APIs. There are no alignment requirements for the buffer. */ -/** @} */ - -/** @defgroup BLE_GATTS_AUTHORIZE_TYPES GATT Server Authorization Types - * @{ */ -#define BLE_GATTS_AUTHORIZE_TYPE_INVALID 0x00 /**< Invalid Type. */ -#define BLE_GATTS_AUTHORIZE_TYPE_READ 0x01 /**< Authorize a Read Operation. */ -#define BLE_GATTS_AUTHORIZE_TYPE_WRITE 0x02 /**< Authorize a Write Request Operation. */ -/** @} */ - - -/** @} */ - -/**@brief Attribute metadata. */ -typedef struct -{ - ble_gap_conn_sec_mode_t read_perm; /**< Read permissions. */ - ble_gap_conn_sec_mode_t write_perm; /**< Write permissions. */ - uint8_t vlen :1; /**< Variable length attribute. */ - uint8_t vloc :2; /**< Value location, see @ref BLE_GATTS_VLOCS.*/ - uint8_t rd_auth :1; /**< Read Authorization and value will be requested from the application on every read operation. */ - uint8_t wr_auth :1; /**< Write Authorization will be requested from the application on every Write Request operation (but not Write Command). */ -} ble_gatts_attr_md_t; - - -/**@brief GATT Attribute. */ -typedef struct -{ - ble_uuid_t* p_uuid; /**< Pointer to the attribute UUID. */ - ble_gatts_attr_md_t* p_attr_md; /**< Pointer to the attribute metadata structure. */ - uint16_t init_len; /**< Initial attribute value length in bytes. */ - uint16_t init_offs; /**< Initial attribute value offset in bytes. If different from zero, the first init_offs bytes of the attribute value will be left uninitialized. */ - uint16_t max_len; /**< Maximum attribute value length in bytes, see @ref BLE_GATTS_ATTR_LENS_MAX for maximum values. */ - uint8_t* p_value; /**< Pointer to the attribute data. Please note that if the @ref BLE_GATTS_VLOC_USER value location is selected in the attribute metadata, this will have to point to a buffer - that remains valid through the lifetime of the attribute. This excludes usage of automatic variables that may go out of scope or any other temporary location. - The stack may access that memory directly without the application's knowledge. */ -} ble_gatts_attr_t; - - -/**@brief GATT Attribute Context. */ -typedef struct -{ - ble_uuid_t srvc_uuid; /**< Service UUID. */ - ble_uuid_t char_uuid; /**< Characteristic UUID if applicable (BLE_UUID_TYPE_UNKNOWN if N/A). */ - ble_uuid_t desc_uuid; /**< Descriptor UUID if applicable (BLE_UUID_TYPE_UNKNOWN if N/A). */ - uint16_t srvc_handle; /**< Service Handle. */ - uint16_t value_handle; /**< Characteristic Handle if applicable (BLE_GATT_HANDLE_INVALID if N/A). */ - uint8_t type; /**< Attribute Type, see @ref BLE_GATTS_ATTR_TYPES. */ -} ble_gatts_attr_context_t; - - -/**@brief GATT Characteristic Presentation Format. */ -typedef struct -{ - uint8_t format; /**< Format of the value, see @ref BLE_GATT_CPF_FORMATS. */ - int8_t exponent; /**< Exponent for integer data types. */ - uint16_t unit; /**< UUID from Bluetooth Assigned Numbers. */ - uint8_t name_space; /**< Namespace from Bluetooth Assigned Numbers, see @ref BLE_GATT_CPF_NAMESPACES. */ - uint16_t desc; /**< Namespace description from Bluetooth Assigned Numbers, see @ref BLE_GATT_CPF_NAMESPACES. */ -} ble_gatts_char_pf_t; - - -/**@brief GATT Characteristic metadata. */ -typedef struct -{ - ble_gatt_char_props_t char_props; /**< Characteristic Properties. */ - ble_gatt_char_ext_props_t char_ext_props; /**< Characteristic Extended Properties. */ - uint8_t* p_char_user_desc; /**< Pointer to a UTF-8, NULL if the descriptor is not required. */ - uint16_t char_user_desc_max_size; /**< The maximum size in bytes of the user description descriptor. */ - uint16_t char_user_desc_size; /**< The size of the user description, must be smaller or equal to char_user_desc_max_size. */ - ble_gatts_char_pf_t* p_char_pf; /**< Pointer to a presentation format structure or NULL if the descriptor is not required. */ - ble_gatts_attr_md_t* p_user_desc_md; /**< Attribute metadata for the User Description descriptor, or NULL for default values. */ - ble_gatts_attr_md_t* p_cccd_md; /**< Attribute metadata for the Client Characteristic Configuration Descriptor, or NULL for default values. */ - ble_gatts_attr_md_t* p_sccd_md; /**< Attribute metadata for the Server Characteristic Configuration Descriptor, or NULL for default values. */ -} ble_gatts_char_md_t; - - -/**@brief GATT Characteristic Definition Handles. */ -typedef struct -{ - uint16_t value_handle; /**< Handle to the characteristic value. */ - uint16_t user_desc_handle; /**< Handle to the User Description descriptor, or BLE_GATT_HANDLE_INVALID if not present. */ - uint16_t cccd_handle; /**< Handle to the Client Characteristic Configuration Descriptor, or BLE_GATT_HANDLE_INVALID if not present. */ - uint16_t sccd_handle; /**< Handle to the Server Characteristic Configuration Descriptor, or BLE_GATT_HANDLE_INVALID if not present. */ -} ble_gatts_char_handles_t; - - -/**@brief GATT HVx parameters. */ -typedef struct -{ - uint16_t handle; /**< Characteristic Value Handle. */ - uint8_t type; /**< Indication or Notification, see @ref BLE_GATT_HVX_TYPES. */ - uint16_t offset; /**< Offset within the attribute value. */ - uint16_t* p_len; /**< Length in bytes to be written, length in bytes written after successful return. */ - uint8_t* p_data; /**< Actual data content, use NULL to use the current attribute value. */ -} ble_gatts_hvx_params_t; - -/**@brief GATT Read Authorization parameters. */ -typedef struct -{ - uint16_t gatt_status; /**< GATT status code for the operation, see @ref BLE_GATT_STATUS_CODES. */ - uint8_t update : 1; /**< If set, data supplied in p_data will be used in the ATT response. */ - uint16_t offset; /**< Offset of the attribute value being updated. */ - uint16_t len; /**< Length in bytes of the value in p_data pointer, see @ref BLE_GATTS_ATTR_LENS_MAX. */ - uint8_t* p_data; /**< Pointer to new value used to update the attribute value. */ -} ble_gatts_read_authorize_params_t; - -/**@brief GATT Write Authorisation parameters. */ -typedef struct -{ - uint16_t gatt_status; /**< GATT status code for the operation, see @ref BLE_GATT_STATUS_CODES. */ -} ble_gatts_write_authorize_params_t; - -/**@brief GATT Read or Write Authorize Reply parameters. */ -typedef struct -{ - uint8_t type; /**< Type of authorize operation, see @ref BLE_GATTS_AUTHORIZE_TYPES. */ - union { - ble_gatts_read_authorize_params_t read; /**< Read authorization parameters. */ - ble_gatts_write_authorize_params_t write; /**< Write authorization parameters. */ - } params; -} ble_gatts_rw_authorize_reply_params_t; - - -/** - * @brief GATT Server Event IDs. - */ -enum BLE_GATTS_EVTS -{ - BLE_GATTS_EVT_WRITE = BLE_GATTS_EVT_BASE, /**< Write operation performed. */ - BLE_GATTS_EVT_RW_AUTHORIZE_REQUEST, /**< Read/Write Authorization request. */ - BLE_GATTS_EVT_SYS_ATTR_MISSING, /**< A persistent system attribute access is pending, awaiting a sd_ble_gatts_sys_attr_set(). */ - BLE_GATTS_EVT_HVC, /**< Handle Value Confirmation. */ - BLE_GATTS_EVT_SC_CONFIRM, /**< Service Changed Confirmation. */ - BLE_GATTS_EVT_TIMEOUT /**< Timeout. */ -}; - - -/**@brief Event structure for BLE_GATTS_EVT_WRITE. */ -typedef struct -{ - uint16_t handle; /**< Attribute Handle. */ - uint8_t op; /**< Type of write operation, see @ref BLE_GATTS_OPS. */ - ble_gatts_attr_context_t context; /**< Attribute Context. */ - uint16_t offset; /**< Offset for the write operation. */ - uint16_t len; /**< Length of the incoming data. */ - uint8_t data[1]; /**< Incoming data, variable length. */ -} ble_gatts_evt_write_t; - -/**@brief Event structure for authorize read request. */ -typedef struct -{ - uint16_t handle; /**< Attribute Handle. */ - ble_gatts_attr_context_t context; /**< Attribute Context. */ - uint16_t offset; /**< Offset for the read operation. */ -} ble_gatts_evt_read_t; - -/**@brief Event structure for BLE_GATTS_EVT_RW_AUTHORIZE_REQUEST. */ -typedef struct -{ - uint8_t type; /**< Type of authorize operation, see @ref BLE_GATTS_AUTHORIZE_TYPES. */ - union { - ble_gatts_evt_read_t read; /**< Attribute Read Parameters. */ - ble_gatts_evt_write_t write; /**< Attribute Write Parameters. */ - } request; -} ble_gatts_evt_rw_authorize_request_t; - -/**@brief Event structure for BLE_GATTS_EVT_SYS_ATTR_MISSING. */ -typedef struct -{ - uint8_t hint; -} ble_gatts_evt_sys_attr_missing_t; - - -/**@brief Event structure for BLE_GATTS_EVT_HVC. */ -typedef struct -{ - uint16_t handle; /**< Attribute Handle. */ -} ble_gatts_evt_hvc_t; - -/**@brief Event structure for BLE_GATTS_EVT_TIMEOUT. */ -typedef struct -{ - uint8_t src; /**< Timeout source, see @ref BLE_GATT_TIMEOUT_SOURCES. */ -} ble_gatts_evt_timeout_t; - - -/**@brief GATT Server event callback event structure. */ -typedef struct -{ - uint16_t conn_handle; /**< Connection Handle on which event occurred. */ - union - { - ble_gatts_evt_write_t write; /**< Write Event Parameters. */ - ble_gatts_evt_rw_authorize_request_t authorize_request; /**< Read or Write Authorize Request Parameters. */ - ble_gatts_evt_sys_attr_missing_t sys_attr_missing; /**< System attributes missing. */ - ble_gatts_evt_hvc_t hvc; /**< Handle Value Confirmation Event Parameters. */ - ble_gatts_evt_timeout_t timeout; /**< Timeout Event. */ - } params; -} ble_gatts_evt_t; - - -/**@brief Add a service declaration to the local server ATT table. - * - * @param[in] type Toggles between primary and secondary services, see @ref BLE_GATTS_SRVC_TYPES. - * @param[in] p_uuid Pointer to service UUID. - * @param[out] p_handle Pointer to a 16-bit word where the assigned handle will be stored. - * - * @note Secondary Services are only relevant in the context of the entity that references them, it is therefore forbidden to - * add a secondary service declaration that is not referenced by another service later in the ATT table. - * - * @return @ref NRF_SUCCESS Successfully added a service declaration. - * @return @ref NRF_ERROR_INVALID_ADDR Invalid pointer supplied. - * @return @ref NRF_ERROR_INVALID_PARAM Invalid parameter(s) supplied, Vendor Specific UUIDs need to be present in the table. - * @return @ref NRF_ERROR_FORBIDDEN Forbidden value supplied, certain UUIDs are reserved for the stack. - * @return @ref NRF_ERROR_NO_MEM Not enough memory to complete operation. - */ -SVCALL(SD_BLE_GATTS_SERVICE_ADD, uint32_t, sd_ble_gatts_service_add(uint8_t type, ble_uuid_t const*const p_uuid, uint16_t *const p_handle)); - - -/**@brief Add an include declaration to the local server ATT table. - * - * @note It is currently only possible to add an include declaration to the last added service (i.e. only sequential addition is supported at this time). - * - * @note The included service must already be present in the ATT table prior to this call. - * - * @param[in] service_handle Handle of the service where the included service is to be placed, if BLE_GATT_HANDLE_INVALID is used, it will be placed sequentially. - * @param[in] inc_srvc_handle Handle of the included service. - * @param[out] p_include_handle Pointer to a 16-bit word where the assigned handle will be stored. - * - * @return @ref NRF_SUCCESS Successfully added an include declaration. - * @return @ref NRF_ERROR_INVALID_ADDR Invalid pointer supplied. - * @return @ref NRF_ERROR_INVALID_PARAM Invalid parameter(s) supplied, handle values need to match previously added services. - * @return @ref NRF_ERROR_INVALID_STATE Invalid state to perform operation. - * @return @ref NRF_ERROR_FORBIDDEN Forbidden value supplied, self inclusions are not allowed. - * @return @ref NRF_ERROR_NO_MEM Not enough memory to complete operation. - * @return @ref NRF_ERROR_NOT_FOUND Attribute not found. - */ -SVCALL(SD_BLE_GATTS_INCLUDE_ADD, uint32_t, sd_ble_gatts_include_add(uint16_t service_handle, uint16_t inc_srvc_handle, uint16_t *const p_include_handle)); - - -/**@brief Add a characteristic declaration, a characteristic value declaration and optional characteristic descriptor declarations to the local server ATT table. - * - * @note It is currently only possible to add a characteristic to the last added service (i.e. only sequential addition is supported at this time). - * - * @note Several restrictions apply to the parameters, such as matching permissions between the user description descriptor and the writeable auxiliaries bits, - * readable (no security) and writeable (selectable) CCCDs and SCCDs and valid presentation format values. - * - * @note If no metadata is provided for the optional descriptors, their permissions will be derived from the characteristic permissions. - * - * @param[in] service_handle Handle of the service where the characteristic is to be placed, if BLE_GATT_HANDLE_INVALID is used, it will be placed sequentially. - * @param[in] p_char_md Characteristic metadata. - * @param[in] p_attr_char_value Pointer to the attribute structure corresponding to the characteristic value. - * @param[out] p_handles Pointer to the structure where the assigned handles will be stored. - * - * @return @ref NRF_SUCCESS Successfully added a characteristic. - * @return @ref NRF_ERROR_INVALID_ADDR Invalid pointer supplied. - * @return @ref NRF_ERROR_INVALID_PARAM Invalid parameter(s) supplied, service handle, Vendor Specific UUIDs, lengths, and permissions need to adhere to the constraints. - * @return @ref NRF_ERROR_INVALID_STATE Invalid state to perform operation, a service context is required. - * @return @ref NRF_ERROR_FORBIDDEN Forbidden value supplied, certain UUIDs are reserved for the stack. - * @return @ref NRF_ERROR_NO_MEM Not enough memory to complete operation. - * @return @ref NRF_ERROR_DATA_SIZE Invalid data size(s) supplied, attribute lengths are restricted by @ref BLE_GATTS_ATTR_LENS_MAX. - */ -SVCALL(SD_BLE_GATTS_CHARACTERISTIC_ADD, uint32_t, sd_ble_gatts_characteristic_add(uint16_t service_handle, ble_gatts_char_md_t const*const p_char_md, ble_gatts_attr_t const*const p_attr_char_value, ble_gatts_char_handles_t *const p_handles)); - - -/**@brief Add a descriptor to the local server ATT table. - * - * @note It is currently only possible to add a descriptor to the last added characteristic (i.e. only sequential addition is supported at this time). - * - * @param[in] char_handle Handle of the characteristic where the descriptor is to be placed, if BLE_GATT_HANDLE_INVALID is used, it will be placed sequentially. - * @param[in] p_attr Pointer to the attribute structure. - * @param[out] p_handle Pointer to a 16-bit word where the assigned handle will be stored. - * - * @return @ref NRF_SUCCESS Successfully added a descriptor. - * @return @ref NRF_ERROR_INVALID_ADDR Invalid pointer supplied. - * @return @ref NRF_ERROR_INVALID_PARAM Invalid parameter(s) supplied, characteristic handle, Vendor Specific UUIDs, lengths, and permissions need to adhere to the constraints. - * @return @ref NRF_ERROR_INVALID_STATE Invalid state to perform operation, a characteristic context is required. - * @return @ref NRF_ERROR_FORBIDDEN Forbidden value supplied, certain UUIDs are reserved for the stack. - * @return @ref NRF_ERROR_NO_MEM Not enough memory to complete operation. - * @return @ref NRF_ERROR_DATA_SIZE Invalid data size(s) supplied, attribute lengths are restricted by @ref BLE_GATTS_ATTR_LENS_MAX. - */ -SVCALL(SD_BLE_GATTS_DESCRIPTOR_ADD, uint32_t, sd_ble_gatts_descriptor_add(uint16_t char_handle, ble_gatts_attr_t const * const p_attr, uint16_t* const p_handle)); - -/**@brief Set the value of a given attribute. - * - * @param[in] handle Attribute handle. - * @param[in] offset Offset in bytes to write from. - * @param[in,out] p_len Length in bytes to be written, length in bytes written after successful return. - * @param[in] p_value Pointer to a buffer (at least len bytes long) containing the desired attribute value. - * - * @return @ref NRF_SUCCESS Successfully set the value of the attribute. - * @return @ref NRF_ERROR_INVALID_ADDR Invalid pointer supplied. - * @return @ref NRF_ERROR_INVALID_PARAM Invalid parameter(s) supplied. - * @return @ref NRF_ERROR_NOT_FOUND Attribute not found. - * @return @ref NRF_ERROR_FORBIDDEN Forbidden handle supplied, certain attributes are not modifiable by the application. - * @return @ref NRF_ERROR_DATA_SIZE Invalid data size(s) supplied, attribute lengths are restricted by @ref BLE_GATTS_ATTR_LENS_MAX. - */ -SVCALL(SD_BLE_GATTS_VALUE_SET, uint32_t, sd_ble_gatts_value_set(uint16_t handle, uint16_t offset, uint16_t* const p_len, uint8_t const * const p_value)); - -/**@brief Get the value of a given attribute. - * - * @param[in] handle Attribute handle. - * @param[in] offset Offset in bytes to read from. - * @param[in,out] p_len Length in bytes to be read, total length of attribute value (in bytes, starting from offset) after successful return. - * @param[in,out] p_data Pointer to a buffer (at least len bytes long) where to store the attribute value. Set to NULL to obtain the complete length of attribute value. - * - * @note If the attribute value is longer than the size of the supplied buffer, - * p_len will return the total attribute value length (excluding offset), - * and not the number of bytes actually returned in p_data. - * The application may use this information to allocate a suitable buffer size. - * - * @return @ref NRF_SUCCESS Successfully retrieved the value of the attribute. - * @return @ref NRF_ERROR_INVALID_ADDR Invalid pointer supplied. - * @return @ref NRF_ERROR_NOT_FOUND Attribute not found. - */ -SVCALL(SD_BLE_GATTS_VALUE_GET, uint32_t, sd_ble_gatts_value_get(uint16_t handle, uint16_t offset, uint16_t *const p_len, uint8_t* const p_data)); - -/**@brief Notify or Indicate an attribute value. - * - * @details This function checks for the relevant Client Characteristic Configuration descriptor value to verify that the relevant operation - * (notification or indication) has been enabled by the client. It is also able to update the attribute value before issuing the PDU, so that - * the application can atomically perform a value update and a server initiated transaction with a single API call. - * If the application chooses to indicate an attribute value, a @ref BLE_GATTS_EVT_HVC will be sent up as soon as the confirmation arrives from - * the peer. - * - * @note The local attribute value may be updated even if an outgoing packet is not sent to the peer due to an error during execution. - * When receiveing the error codes @ref NRF_ERROR_INVALID_STATE, @ref NRF_ERROR_BUSY, @ref BLE_ERROR_GATTS_SYS_ATTR_MISSING and - * @ref BLE_ERROR_NO_TX_BUFFERS the ATT table has been updated. - * The caller can check whether the value has been updated by looking at the contents of *(p_hvx_params->p_len). - * - * @note It is important to note that a notification will consume an application buffer, and will therefore - * generate a @ref BLE_EVT_TX_COMPLETE event when the packet has been transmitted. An indication on the other hand will use the - * standard server internal buffer and thus will only generate a @ref BLE_GATTS_EVT_HVC event as soon as the confirmation - * has been received from the peer. Please see the documentation of @ref sd_ble_tx_buffer_count_get for more details. - * - * @param[in] conn_handle Connection handle. - * @param[in] p_hvx_params Pointer to an HVx parameters structure. If the p_data member contains a non-NULL pointer the attribute value will be updated with - * the contents pointed by it before sending the notification or indication. - * - * @return @ref NRF_SUCCESS Successfully queued a notification or indication for transmission, and optionally updated the attribute value. - * @return @ref BLE_ERROR_INVALID_CONN_HANDLE Invalid Connection Handle. - * @return @ref NRF_ERROR_INVALID_ADDR Invalid pointer supplied. - * @return @ref NRF_ERROR_INVALID_PARAM Invalid parameter(s) supplied. - * @return @ref BLE_ERROR_INVALID_ATTR_HANDLE Invalid attribute handle(s) supplied. Only attributes added directly by the application are available to notify and indicate. - * @return @ref BLE_ERROR_GATTS_INVALID_ATTR_TYPE Invalid attribute type(s) supplied, only characteristic values may be notified and indicated. - * @return @ref NRF_ERROR_NOT_FOUND Attribute not found. - * @return @ref NRF_ERROR_DATA_SIZE Invalid data size(s) supplied. - * @return @ref NRF_ERROR_INVALID_STATE Invalid state to perform operation, notifications or indications must be enabled in the CCCD. - * @return @ref NRF_ERROR_BUSY Procedure already in progress. - * @return @ref BLE_ERROR_GATTS_SYS_ATTR_MISSING System attributes missing, use @ref sd_ble_gatts_sys_attr_set to set them to a known value. - * @return @ref BLE_ERROR_NO_TX_BUFFERS There are no available buffers to send the data, applies only to notifications. - */ -SVCALL(SD_BLE_GATTS_HVX, uint32_t, sd_ble_gatts_hvx(uint16_t conn_handle, ble_gatts_hvx_params_t const*const p_hvx_params)); - -/**@brief Indicate the Service Changed attribute value. - * - * @details This call will send a Handle Value Indication to one or more peers connected to inform them that the attribute - * table layout has changed. As soon as the peer has confirmed the indication, a @ref BLE_GATTS_EVT_SC_CONFIRM event will - * be issued. - * - * @note Some of the restrictions and limitations that apply to @ref sd_ble_gatts_hvx also apply here. - * - * @param[in] conn_handle Connection handle. - * @param[in] start_handle Start of affected attribute handle range. - * @param[in] end_handle End of affected attribute handle range. - * - * @return @ref NRF_SUCCESS Successfully queued the Service Changed indication for transmission. - * @return @ref BLE_ERROR_INVALID_CONN_HANDLE Invalid Connection Handle. - * @return @ref NRF_ERROR_INVALID_PARAM Invalid parameter(s) supplied. - * @return @ref BLE_ERROR_INVALID_ATTR_HANDLE Invalid attribute handle(s) supplied, handles must be in the range populated by the application. - * @return @ref NRF_ERROR_INVALID_STATE Invalid state to perform operation, notifications or indications must be enabled in the CCCD. - * @return @ref NRF_ERROR_BUSY Procedure already in progress. - * @return @ref BLE_ERROR_GATTS_SYS_ATTR_MISSING System attributes missing, use @ref sd_ble_gatts_sys_attr_set to set them to a known value. - */ -SVCALL(SD_BLE_GATTS_SERVICE_CHANGED, uint32_t, sd_ble_gatts_service_changed(uint16_t conn_handle, uint16_t start_handle, uint16_t end_handle)); - -/**@brief Respond to a Read/Write authorization request. - * - * @note This call should only be used as a response to a @ref BLE_GATTS_EVT_RW_AUTHORIZE_REQUEST event issued to the application. - * - * @param[in] conn_handle Connection handle. - * @param[in] p_rw_authorize_reply_params Pointer to a structure with the attribute provided by the application. - * - * @return @ref NRF_SUCCESS Successfully queued a response to the peer, and in the case of a write operation, ATT table updated. - * @return @ref BLE_ERROR_INVALID_CONN_HANDLE Invalid Connection Handle. - * @return @ref NRF_ERROR_INVALID_STATE No authorization request pending. - * @return @ref NRF_ERROR_INVALID_PARAM Authorization op invalid, - * or for Read Authorization reply: requested handles not replied with, - * or for Write Authorization reply: handle supplied does not match requested handle. - */ -SVCALL(SD_BLE_GATTS_RW_AUTHORIZE_REPLY, uint32_t, sd_ble_gatts_rw_authorize_reply(uint16_t conn_handle, ble_gatts_rw_authorize_reply_params_t const*const p_rw_authorize_reply_params)); - - -/**@brief Update persistent system attribute information. - * - * @details Supply to the stack information about persistent system attributes. - * This call is legal in the connected state only, and is usually - * made immediately after a connection is established and the bond identified. - * usually as a response to a BLE_GATTS_EVT_SYS_ATTR_MISSING. - * - * p_sysattrs may point directly to the application's stored copy of the struct. - * If the pointer is NULL, the system attribute info is initialized, assuming that - * the application does not have any previously saved data for this bond. - * - * @note The state of persistent system attributes is reset upon connection and then remembered for its duration. - * - * @note If this call returns with an error code different from @ref NRF_SUCCESS, the storage of persistent system attributes may have been completed only partially. - * This means that the state of the attribute table is undefined, and the application should either provide a new set of attributes using this same call or - * reset the SoftDevice to return to a known state. - * - * @param[in] conn_handle Connection handle. - * @param[in] p_sys_attr_data Pointer to a saved copy of system attributes supplied to the stack, or NULL. - * @param[in] len Size of data pointed by p_sys_attr_data, in octets. - * - * @return @ref NRF_SUCCESS Successfully set the system attribute information. - * @return @ref BLE_ERROR_INVALID_CONN_HANDLE Invalid Connection Handle. - * @return @ref NRF_ERROR_INVALID_DATA Invalid data supplied, the data should be exactly the same as retrieved with @ref sd_ble_gatts_sys_attr_get. - * @return @ref NRF_ERROR_NO_MEM Not enough memory to complete operation. - */ -SVCALL(SD_BLE_GATTS_SYS_ATTR_SET, uint32_t, sd_ble_gatts_sys_attr_set(uint16_t conn_handle, uint8_t const*const p_sys_attr_data, uint16_t len)); - - -/**@brief Retrieve persistent system attribute information from the stack. - * - * @details This call is used to retrieve information about values to be stored perisistently by the application - * after a connection has been terminated. When a new connection is made to the same bond, the values - * should be restored using @ref sd_ble_gatts_sys_attr_set. - * The data should be read before any new advertising is started, or any new connection established. The connection handle for - * the previous now defunct connection will remain valid until a new one is created to allow this API call to refer to it. - * - * @param[in] conn_handle Connection handle of the recently terminated connection. - * @param[in] p_sys_attr_data Pointer to a buffer where updated information about system attributes will be filled in. NULL can be provided to - * obtain the length of the data - * @param[in,out] p_len Size of application buffer if p_sys_attr_data is not NULL. Unconditially updated to actual length of system attribute data. - * - * @return @ref NRF_SUCCESS Successfully retrieved the system attribute information. - * @return @ref BLE_ERROR_INVALID_CONN_HANDLE Invalid Connection Handle. - * @return @ref NRF_ERROR_INVALID_ADDR Invalid pointer supplied. - * @return @ref NRF_ERROR_DATA_SIZE The system attribute information did not fit into the provided buffer. - */ -SVCALL(SD_BLE_GATTS_SYS_ATTR_GET, uint32_t, sd_ble_gatts_sys_attr_get(uint16_t conn_handle, uint8_t * const p_sys_attr_data, uint16_t* const p_len)); - - -#endif // BLE_GATTS_H__ - -/** - @} -*/ diff --git a/libraries/ble/nRF51822/nordic/nrf-sdk/s110/ble_hci.h b/libraries/ble/nRF51822/nordic/nrf-sdk/s110/ble_hci.h deleted file mode 100644 index 925776bd7d..0000000000 --- a/libraries/ble/nRF51822/nordic/nrf-sdk/s110/ble_hci.h +++ /dev/null @@ -1,96 +0,0 @@ -/* - Copyright (c) 2012 Nordic Semiconductor. All Rights Reserved. - - The information contained herein is confidential property of Nordic Semiconductor. The use, - copying, transfer or disclosure of such information is prohibited except by express written - agreement with Nordic Semiconductor. - */ -/** - @addtogroup BLE_COMMON - @{ -*/ - - -#ifndef BLE_HCI_H__ -#define BLE_HCI_H__ - -/** @defgroup BLE_HCI_STATUS_CODES Bluetooth status codes - * @{ */ - -#define BLE_HCI_STATUS_CODE_SUCCESS 0x00 -#define BLE_HCI_STATUS_CODE_UNKNOWN_BTLE_COMMAND 0x01 -#define BLE_HCI_STATUS_CODE_UNKNOWN_CONNECTION_IDENTIFIER 0x02 -/*0x03 Hardware Failure -0x04 Page Timeout -*/ -#define BLE_HCI_AUTHENTICATION_FAILURE 0x05 -#define BLE_HCI_STATUS_CODE_PIN_OR_KEY_MISSING 0x06 -#define BLE_HCI_MEMORY_CAPACITY_EXCEEDED 0x07 -#define BLE_HCI_CONNECTION_TIMEOUT 0x08 -/*0x09 Connection Limit Exceeded -0x0A Synchronous Connection Limit To A Device Exceeded -0x0B ACL Connection Already Exists*/ -#define BLE_HCI_STATUS_CODE_COMMAND_DISALLOWED 0x0C -/*0x0D Connection Rejected due to Limited Resources -0x0E Connection Rejected Due To Security Reasons -0x0F Connection Rejected due to Unacceptable BD_ADDR -0x10 Connection Accept Timeout Exceeded -0x11 Unsupported Feature or Parameter Value*/ -#define BLE_HCI_STATUS_CODE_INVALID_BTLE_COMMAND_PARAMETERS 0x12 -#define BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION 0x13 -#define BLE_HCI_REMOTE_DEV_TERMINATION_DUE_TO_LOW_RESOURCES 0x14 -#define BLE_HCI_REMOTE_DEV_TERMINATION_DUE_TO_POWER_OFF 0x15 -#define BLE_HCI_LOCAL_HOST_TERMINATED_CONNECTION 0x16 -/* -0x17 Repeated Attempts -0x18 Pairing Not Allowed -0x19 Unknown LMP PDU -*/ -#define BLE_HCI_UNSUPPORTED_REMOTE_FEATURE 0x1A -/* -0x1B SCO Offset Rejected -0x1C SCO Interval Rejected -0x1D SCO Air Mode Rejected*/ -#define BLE_HCI_STATUS_CODE_INVALID_LMP_PARAMETERS 0x1E -#define BLE_HCI_STATUS_CODE_UNSPECIFIED_ERROR 0x1F -/*0x20 Unsupported LMP Parameter Value -0x21 Role Change Not Allowed -*/ -#define BLE_HCI_STATUS_CODE_LMP_RESPONSE_TIMEOUT 0x22 -/*0x23 LMP Error Transaction Collision*/ -#define BLE_HCI_STATUS_CODE_LMP_PDU_NOT_ALLOWED 0x24 -/*0x25 Encryption Mode Not Acceptable -0x26 Link Key Can Not be Changed -0x27 Requested QoS Not Supported -*/ -#define BLE_HCI_INSTANT_PASSED 0x28 -#define BLE_HCI_PAIRING_WITH_UNIT_KEY_UNSUPPORTED 0x29 -#define BLE_HCI_DIFFERENT_TRANSACTION_COLLISION 0x2A -/* -0x2B Reserved -0x2C QoS Unacceptable Parameter -0x2D QoS Rejected -0x2E Channel Classification Not Supported -0x2F Insufficient Security -0x30 Parameter Out Of Mandatory Range -0x31 Reserved -0x32 Role Switch Pending -0x33 Reserved -0x34 Reserved Slot Violation -0x35 Role Switch Failed -0x36 Extended Inquiry Response Too Large -0x37 Secure Simple Pairing Not Supported By Host. -0x38 Host Busy - Pairing -0x39 Connection Rejected due to No Suitable Channel Found*/ -#define BLE_HCI_CONTROLLER_BUSY 0x3A -#define BLE_HCI_CONN_INTERVAL_UNACCEPTABLE 0x3B -#define BLE_HCI_DIRECTED_ADVERTISER_TIMEOUT 0x3C -#define BLE_HCI_CONN_TERMINATED_DUE_TO_MIC_FAILURE 0x3D -#define BLE_HCI_CONN_FAILED_TO_BE_ESTABLISHED 0x3E - -/** @} */ - - -#endif // BLE_HCI_H__ - -/** @} */ diff --git a/libraries/ble/nRF51822/nordic/nrf-sdk/s110/ble_l2cap.h b/libraries/ble/nRF51822/nordic/nrf-sdk/s110/ble_l2cap.h deleted file mode 100644 index d4dd1eaa3d..0000000000 --- a/libraries/ble/nRF51822/nordic/nrf-sdk/s110/ble_l2cap.h +++ /dev/null @@ -1,136 +0,0 @@ -/* Copyright (c) 2011 Nordic Semiconductor. All Rights Reserved. - * - * The information contained herein is confidential property of Nordic Semiconductor. The use, - * copying, transfer or disclosure of such information is prohibited except by express written - * agreement with Nordic Semiconductor. - * - */ -/** - @addtogroup BLE_L2CAP Logical Link Control and Adaptation Protocol (L2CAP) - @{ - @brief Definitions and prototypes for the L2CAP interface. - */ - -#ifndef BLE_L2CAP_H__ -#define BLE_L2CAP_H__ - -#include "nordic_global.h" -#include "ble_types.h" -#include "ble_ranges.h" -#include "ble_err.h" -#include "nrf_svc.h" - -/**@brief L2CAP API SVC numbers. */ -enum BLE_L2CAP_SVCS -{ - SD_BLE_L2CAP_CID_REGISTER = BLE_L2CAP_SVC_BASE, /**< Register a CID. */ - SD_BLE_L2CAP_CID_UNREGISTER, /**< Unregister a CID. */ - SD_BLE_L2CAP_TX /**< Transmit a packet. */ -}; - -/**@addtogroup BLE_L2CAP_DEFINES Defines - * @{ */ - -/**@defgroup BLE_ERRORS_L2CAP SVC return values specific to L2CAP - * @{ */ -#define BLE_ERROR_L2CAP_CID_IN_USE (NRF_L2CAP_ERR_BASE + 0x000) /**< CID already in use. */ -/** @} */ - -/**@brief Default L2CAP MTU. */ -#define BLE_L2CAP_MTU_DEF (23) - -/**@brief Invalid Channel Identifier. */ -#define BLE_L2CAP_CID_INVALID (0x0000) - -/**@brief Dynamic Channel Identifier base. */ -#define BLE_L2CAP_CID_DYN_BASE (0x0040) - -/**@brief Maximum amount of dynamic CIDs. */ -#define BLE_L2CAP_CID_DYN_MAX (8) - -/** @} */ - -/**@brief Packet header format for L2CAP transmission. */ -typedef struct -{ - uint16_t len; /**< Length of valid info in data member. */ - uint16_t cid; /**< Channel ID on which packet is transmitted. */ -} ble_l2cap_header_t; - -/**@brief L2CAP Event IDs. */ -enum BLE_L2CAP_EVTS -{ - BLE_L2CAP_EVT_RX = BLE_L2CAP_EVT_BASE /**< L2CAP packet received. */ -}; - - -/**@brief L2CAP Received packet event report. */ -typedef struct -{ - ble_l2cap_header_t header; /** L2CAP packet header. */ - uint8_t data[1]; /**< Packet data, variable length. */ -} ble_l2cap_evt_rx_t; - - -/**@brief L2CAP event callback event structure. */ -typedef struct -{ - uint16_t conn_handle; /**< Connection Handle on which event occured. */ - union - { - ble_l2cap_evt_rx_t rx; /**< RX Event parameters. */ - } params; -} ble_l2cap_evt_t; - - -/**@brief Register a CID with L2CAP. - * - * @details This registers a higher protocol layer with the L2CAP multiplexer, and is requried prior to all operations on the CID. - * - * @param[in] cid L2CAP CID. - * - * @return @ref NRF_SUCCESS Successfully registered a CID with the L2CAP layer. - * @return @ref NRF_ERROR_INVALID_PARAM Invalid parameter(s) supplied, CID must be above @ref BLE_L2CAP_CID_DYN_BASE. - * @return @ref BLE_ERROR_L2CAP_CID_IN_USE L2CAP CID already in use. - * @return @ref NRF_ERROR_NO_MEM Not enough memory to complete operation. - */ -SVCALL(SD_BLE_L2CAP_CID_REGISTER, uint32_t, sd_ble_l2cap_cid_register(uint16_t cid)); - -/**@brief Unregister a CID with L2CAP. - * - * @details This unregisters a previously registerd higher protocol layer with the L2CAP multiplexer. - * - * @param[in] cid L2CAP CID. - * - * @return @ref NRF_SUCCESS Successfully unregistered the CID. - * @return @ref NRF_ERROR_INVALID_PARAM Invalid parameter(s) supplied. - * @return @ref NRF_ERROR_NOT_FOUND CID not previously registered. - */ -SVCALL(SD_BLE_L2CAP_CID_UNREGISTER, uint32_t, sd_ble_l2cap_cid_unregister(uint16_t cid)); - -/**@brief Transmit an L2CAP packet. - * - * @note It is important to note that a call to this function will consume an application buffer, and will therefore - * generate a @ref BLE_EVT_TX_COMPLETE event when the packet has been transmitted. - * Please see the documentation of @ref sd_ble_tx_buffer_count_get for more details. - * - * @param[in] conn_handle Connection Handle. - * @param[in] p_header Pointer to a packet header containing length and CID. - * @param[in] p_data Pointer to the data to be transmitted. - * - * @return @ref NRF_SUCCESS Successfully queued an L2CAP packet for transmission. - * @return @ref NRF_ERROR_INVALID_ADDR Invalid pointer supplied. - * @return @ref NRF_ERROR_INVALID_PARAM Invalid parameter(s) supplied, CIDs must be registered beforehand with @ref sd_ble_l2cap_cid_register. - * @return @ref NRF_ERROR_NOT_FOUND CID not found. - * @return @ref NRF_ERROR_NO_MEM Not enough memory to complete operation. - * @return @ref BLE_ERROR_NO_TX_BUFFERS Not enough application buffers available. - * @return @ref NRF_ERROR_DATA_SIZE Invalid data size(s) supplied, see @ref BLE_L2CAP_MTU_DEF. - */ -SVCALL(SD_BLE_L2CAP_TX, uint32_t, sd_ble_l2cap_tx(uint16_t conn_handle, ble_l2cap_header_t const * const p_header, uint8_t const * const p_data)); - - -#endif // BLE_L2CAP_H__ - -/** - @} -*/ diff --git a/libraries/ble/nRF51822/nordic/nrf-sdk/s110/ble_ranges.h b/libraries/ble/nRF51822/nordic/nrf-sdk/s110/ble_ranges.h deleted file mode 100644 index c99e3556c4..0000000000 --- a/libraries/ble/nRF51822/nordic/nrf-sdk/s110/ble_ranges.h +++ /dev/null @@ -1,72 +0,0 @@ -/* - Copyright (c) 2012 Nordic Semiconductor. All Rights Reserved. - - The information contained herein is confidential property of Nordic Semiconductor. The use, - copying, transfer or disclosure of such information is prohibited except by express written - agreement with Nordic Semiconductor. - */ -/** - @addtogroup BLE_COMMON - @{ - @defgroup ble_ranges Module specific SVC and event number subranges - @{ - - @brief Definition of SVC and event number subranges for each API module. - - @note - SVCs and event numbers are split into subranges for each API module. - Each module receives its entire allocated range of SVC calls, whether implemented or not, - but return BLE_ERROR_NOT_SUPPORTED for unimplemented or undefined calls in its range. - - Note that the symbols BLE__SVC_LAST is the end of the allocated SVC range, - rather than the last SVC function call actually defined and implemented. - - Specific SVC and event values are defined in each module's ble_.h file, - which defines names of each individual SVC code based on the range start value. -*/ - -#ifndef BLE_RANGES_H__ -#define BLE_RANGES_H__ - -#define BLE_SVC_BASE 0x60 -#define BLE_SVC_LAST 0x6B /* Total: 12. */ - -#define BLE_RESERVED_SVC_BASE 0x6C -#define BLE_RESERVED_SVC_LAST 0x6F /* Total: 4. */ - -#define BLE_GAP_SVC_BASE 0x70 -#define BLE_GAP_SVC_LAST 0x8F /* Total: 32. */ - -#define BLE_GATTC_SVC_BASE 0x90 -#define BLE_GATTC_SVC_LAST 0x9F /* Total: 16. */ - -#define BLE_GATTS_SVC_BASE 0xA0 -#define BLE_GATTS_SVC_LAST 0xAF /* Total: 16. */ - -#define BLE_L2CAP_SVC_BASE 0xB0 -#define BLE_L2CAP_SVC_LAST 0xBF /* Total: 16. */ - - -#define BLE_EVT_INVALID 0x00 - -#define BLE_EVT_BASE 0x01 -#define BLE_EVT_LAST 0x0F /* Total: 15. */ - -#define BLE_GAP_EVT_BASE 0x10 -#define BLE_GAP_EVT_LAST 0x2F /* Total: 32. */ - -#define BLE_GATTC_EVT_BASE 0x30 -#define BLE_GATTC_EVT_LAST 0x4F /* Total: 32. */ - -#define BLE_GATTS_EVT_BASE 0x50 -#define BLE_GATTS_EVT_LAST 0x6F /* Total: 32. */ - -#define BLE_L2CAP_EVT_BASE 0x70 -#define BLE_L2CAP_EVT_LAST 0x8F /* Total: 32. */ - -#endif /* BLE_RANGES_H__ */ - -/** - @} - @} -*/ diff --git a/libraries/ble/nRF51822/nordic/nrf-sdk/s110/ble_types.h b/libraries/ble/nRF51822/nordic/nrf-sdk/s110/ble_types.h deleted file mode 100644 index 6f5ab22d6a..0000000000 --- a/libraries/ble/nRF51822/nordic/nrf-sdk/s110/ble_types.h +++ /dev/null @@ -1,158 +0,0 @@ -/* Copyright (c) 2011 Nordic Semiconductor. All Rights Reserved. - * - * The information contained herein is confidential property of Nordic Semiconductor. The use, - * copying, transfer or disclosure of such information is prohibited except by express written - * agreement with Nordic Semiconductor. - * - */ -/** - @addtogroup BLE_COMMON - @{ - @defgroup ble_types Common types and macro definitions - @{ - - @brief Common types and macro definitions for the S110 SoftDevice. - */ - -#ifndef BLE_TYPES_H__ -#define BLE_TYPES_H__ - -#include -#include "nordic_global.h" - -/** @addtogroup BLE_COMMON_DEFINES Defines - * @{ */ - -/** @defgroup BLE_CONN_HANDLES BLE Connection Handles - * @{ */ -#define BLE_CONN_HANDLE_INVALID 0xFFFF /**< Invalid Connection Handle. */ -#define BLE_CONN_HANDLE_ALL 0xFFFE /**< Applies to all Connection Handles. */ -/** @} */ - - -/** @defgroup BLE_UUID_VALUES Assigned Values for BLE UUIDs - * @{ */ -/* Generic UUIDs, applicable to all services */ -#define BLE_UUID_UNKNOWN 0x0000 /**< Reserved UUID. */ -#define BLE_UUID_SERVICE_PRIMARY 0x2800 /**< Primary Service. */ -#define BLE_UUID_SERVICE_SECONDARY 0x2801 /**< Secondary Service. */ -#define BLE_UUID_SERVICE_INCLUDE 0x2802 /**< Include. */ -#define BLE_UUID_CHARACTERISTIC 0x2803 /**< Characteristic. */ -#define BLE_UUID_DESCRIPTOR_CHAR_EXT_PROP 0x2900 /**< Characteristic Extended Properties Descriptor. */ -#define BLE_UUID_DESCRIPTOR_CHAR_USER_DESC 0x2901 /**< Characteristic User Description Descriptor. */ -#define BLE_UUID_DESCRIPTOR_CLIENT_CHAR_CONFIG 0x2902 /**< Client Characteristic Configuration Descriptor. */ -#define BLE_UUID_DESCRIPTOR_SERVER_CHAR_CONFIG 0x2903 /**< Server Characteristic Configuration Descriptor. */ -#define BLE_UUID_DESCRIPTOR_CHAR_PRESENTATION_FORMAT 0x2904 /**< Characteristic Presentation Format Descriptor. */ -#define BLE_UUID_DESCRIPTOR_CHAR_AGGREGATE_FORMAT 0x2905 /**< Characteristic Aggregate Format Descriptor. */ -/* GATT specific UUIDs */ -#define BLE_UUID_GATT 0x1801 /**< Generic Attribute Profile. */ -#define BLE_UUID_GATT_CHARACTERISTIC_SERVICE_CHANGED 0x2A05 /**< Service Changed Characteristic. */ -/* GAP specific UUIDs */ -#define BLE_UUID_GAP 0x1800 /**< Generic Access Profile. */ -#define BLE_UUID_GAP_CHARACTERISTIC_DEVICE_NAME 0x2A00 /**< Device Name Characteristic. */ -#define BLE_UUID_GAP_CHARACTERISTIC_APPEARANCE 0x2A01 /**< Appearance Characteristic. */ -#define BLE_UUID_GAP_CHARACTERISTIC_PPF 0x2A02 /**< Peripheral Privacy Flag Characteristic. */ -#define BLE_UUID_GAP_CHARACTERISTIC_RECONN_ADDR 0x2A03 /**< Reconnection Address Characteristic. */ -#define BLE_UUID_GAP_CHARACTERISTIC_PPCP 0x2A04 /**< Peripheral Preferred Connection Parameters Characteristic. */ -/** @} */ - - -/** @defgroup BLE_UUID_TYPES Types of UUID - * @{ */ -#define BLE_UUID_TYPE_UNKNOWN 0x00 /**< Invalid UUID type. */ -#define BLE_UUID_TYPE_BLE 0x01 /**< Bluetooth SIG UUID (16-bit). */ -#define BLE_UUID_TYPE_VENDOR_BEGIN 0x02 /**< Vendor UUID types start at this index (128-bit). */ -/** @} */ - - -/** @defgroup BLE_APPEARANCES Bluetooth Appearance values - * @note Retrieved from http://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.gap.appearance.xml - * @{ */ -#define BLE_APPEARANCE_UNKNOWN 0 /**< Unknown. */ -#define BLE_APPEARANCE_GENERIC_PHONE 64 /**< Generic Phone. */ -#define BLE_APPEARANCE_GENERIC_COMPUTER 128 /**< Generic Computer. */ -#define BLE_APPEARANCE_GENERIC_WATCH 192 /**< Generic Watch. */ -#define BLE_APPEARANCE_WATCH_SPORTS_WATCH 193 /**< Watch: Sports Watch. */ -#define BLE_APPEARANCE_GENERIC_CLOCK 256 /**< Generic Clock. */ -#define BLE_APPEARANCE_GENERIC_DISPLAY 320 /**< Generic Display. */ -#define BLE_APPEARANCE_GENERIC_REMOTE_CONTROL 384 /**< Generic Remote Control. */ -#define BLE_APPEARANCE_GENERIC_EYE_GLASSES 448 /**< Generic Eye-glasses. */ -#define BLE_APPEARANCE_GENERIC_TAG 512 /**< Generic Tag. */ -#define BLE_APPEARANCE_GENERIC_KEYRING 576 /**< Generic Keyring. */ -#define BLE_APPEARANCE_GENERIC_MEDIA_PLAYER 640 /**< Generic Media Player. */ -#define BLE_APPEARANCE_GENERIC_BARCODE_SCANNER 704 /**< Generic Barcode Scanner. */ -#define BLE_APPEARANCE_GENERIC_THERMOMETER 768 /**< Generic Thermometer. */ -#define BLE_APPEARANCE_THERMOMETER_EAR 769 /**< Thermometer: Ear. */ -#define BLE_APPEARANCE_GENERIC_HEART_RATE_SENSOR 832 /**< Generic Heart rate Sensor. */ -#define BLE_APPEARANCE_HEART_RATE_SENSOR_HEART_RATE_BELT 833 /**< Heart Rate Sensor: Heart Rate Belt. */ -#define BLE_APPEARANCE_GENERIC_BLOOD_PRESSURE 896 /**< Generic Blood Pressure. */ -#define BLE_APPEARANCE_BLOOD_PRESSURE_ARM 897 /**< Blood Pressure: Arm. */ -#define BLE_APPEARANCE_BLOOD_PRESSURE_WRIST 898 /**< Blood Pressure: Wrist. */ -#define BLE_APPEARANCE_GENERIC_HID 960 /**< Human Interface Device (HID). */ -#define BLE_APPEARANCE_HID_KEYBOARD 961 /**< Keyboard (HID Subtype). */ -#define BLE_APPEARANCE_HID_MOUSE 962 /**< Mouse (HID Subtype). */ -#define BLE_APPEARANCE_HID_JOYSTICK 963 /**< Joystiq (HID Subtype). */ -#define BLE_APPEARANCE_HID_GAMEPAD 964 /**< Gamepad (HID Subtype). */ -#define BLE_APPEARANCE_HID_DIGITIZERSUBTYPE 965 /**< Digitizer Tablet (HID Subtype). */ -#define BLE_APPEARANCE_HID_CARD_READER 966 /**< Card Reader (HID Subtype). */ -#define BLE_APPEARANCE_HID_DIGITAL_PEN 967 /**< Digital Pen (HID Subtype). */ -#define BLE_APPEARANCE_HID_BARCODE 968 /**< Barcode Scanner (HID Subtype). */ -#define BLE_APPEARANCE_GENERIC_GLUCOSE_METER 1024 /**< Generic Glucose Meter. */ -#define BLE_APPEARANCE_GENERIC_RUNNING_WALKING_SENSOR 1088 /**< Generic Running Walking Sensor. */ -#define BLE_APPEARANCE_RUNNING_WALKING_SENSOR_IN_SHOE 1089 /**< Running Walking Sensor: In-Shoe. */ -#define BLE_APPEARANCE_RUNNING_WALKING_SENSOR_ON_SHOE 1090 /**< Running Walking Sensor: On-Shoe. */ -#define BLE_APPEARANCE_RUNNING_WALKING_SENSOR_ON_HIP 1091 /**< Running Walking Sensor: On-Hip. */ -#define BLE_APPEARANCE_GENERIC_CYCLING 1152 /**< Generic Cycling. */ -#define BLE_APPEARANCE_CYCLING_CYCLING_COMPUTER 1153 /**< Cycling: Cycling Computer. */ -#define BLE_APPEARANCE_CYCLING_SPEED_SENSOR 1154 /**< Cycling: Speed Sensor. */ -#define BLE_APPEARANCE_CYCLING_CADENCE_SENSOR 1155 /**< Cycling: Cadence Sensor. */ -#define BLE_APPEARANCE_CYCLING_POWER_SENSOR 1156 /**< Cycling: Power Sensor. */ -#define BLE_APPEARANCE_CYCLING_SPEED_CADENCE_SENSOR 1157 /**< Cycling: Speed and Cadence Sensor. */ -/** @} */ - -/** @brief Set .type and .uuid fields of ble_uuid_struct to specified uuid value. */ -#define BLE_UUID_BLE_ASSIGN(instance, value) do {\ - instance.type = BLE_UUID_TYPE_BLE; \ - instance.uuid = value;} while(0) - -/** @brief Copy type and uuid members from src to dst ble_uuid_t pointer. Both pointers must be valid/non-null. */ -#define BLE_UUID_COPY_PTR(dst, src) do {\ - (dst)->type = (src)->type; \ - (dst)->uuid = (src)->uuid;} while(0) - -/** @brief Copy type and uuid members from src to dst ble_uuid_t struct. */ -#define BLE_UUID_COPY_INST(dst, src) do {\ - (dst).type = (src).type; \ - (dst).uuid = (src).uuid;} while(0) - -/** @brief Compare for equality both type and uuid members of two (valid, non-null) ble_uuid_t pointers. */ -#define BLE_UUID_EQ(p_uuid1, p_uuid2) \ - (((p_uuid1)->type == (p_uuid2)->type) && ((p_uuid1)->uuid == (p_uuid2)->uuid)) - -/** @brief Compare for difference both type and uuid members of two (valid, non-null) ble_uuid_t pointers. */ -#define BLE_UUID_NEQ(p_uuid1, p_uuid2) \ - (((p_uuid1)->type != (p_uuid2)->type) || ((p_uuid1)->uuid != (p_uuid2)->uuid)) - -/** @} */ - -/** @brief 128 bit UUID values. */ -typedef struct -{ - unsigned char uuid128[16]; -} ble_uuid128_t; - -/** @brief Bluetooth Low Energy UUID type, encapsulates both 16-bit and 128-bit UUIDs. */ -typedef struct -{ - uint16_t uuid; /**< 16-bit UUID value or octets 12-13 of 128-bit UUID. */ - uint8_t type; /**< UUID type, see @ref BLE_UUID_TYPES. If type is BLE_UUID_TYPE_UNKNOWN, the value of uuid is undefined. */ -} ble_uuid_t; - - - -#endif /* BLE_TYPES_H__ */ - -/** - @} - @} -*/ diff --git a/libraries/ble/nRF51822/nordic/nrf-sdk/s110/nrf_error.h b/libraries/ble/nRF51822/nordic/nrf-sdk/s110/nrf_error.h deleted file mode 100644 index 518ef82b8f..0000000000 --- a/libraries/ble/nRF51822/nordic/nrf-sdk/s110/nrf_error.h +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (c) 2012 Nordic Semiconductor. All Rights Reserved. - * - * The information contained herein is confidential property of Nordic Semiconductor. The use, - * copying, transfer or disclosure of such information is prohibited except by express written - * agreement with Nordic Semiconductor. - * - */ - /** - @defgroup nrf_error SoftDevice Global Error Codes - @{ - - @brief Global Error definitions -*/ - -/* Header guard */ -#ifndef NRF_ERROR_H__ -#define NRF_ERROR_H__ - -/** @defgroup NRF_ERRORS_BASE Error Codes Base number definitions - * @{ */ -#define NRF_ERROR_BASE_NUM (0x0) ///< Global error base -#define NRF_ERROR_SDM_BASE_NUM (0x1000) ///< SDM error base -#define NRF_ERROR_SOC_BASE_NUM (0x2000) ///< SoC error base -#define NRF_ERROR_STK_BASE_NUM (0x3000) ///< STK error base -/** @} */ - -#define NRF_SUCCESS (NRF_ERROR_BASE_NUM + 0) ///< Successful command -#define NRF_ERROR_SVC_HANDLER_MISSING (NRF_ERROR_BASE_NUM + 1) ///< SVC handler is missing -#define NRF_ERROR_SOFTDEVICE_NOT_ENABLED (NRF_ERROR_BASE_NUM + 2) ///< SoftDevice has not been enabled -#define NRF_ERROR_INTERNAL (NRF_ERROR_BASE_NUM + 3) ///< Internal Error -#define NRF_ERROR_NO_MEM (NRF_ERROR_BASE_NUM + 4) ///< No Memory for operation -#define NRF_ERROR_NOT_FOUND (NRF_ERROR_BASE_NUM + 5) ///< Not found -#define NRF_ERROR_NOT_SUPPORTED (NRF_ERROR_BASE_NUM + 6) ///< Not supported -#define NRF_ERROR_INVALID_PARAM (NRF_ERROR_BASE_NUM + 7) ///< Invalid Parameter -#define NRF_ERROR_INVALID_STATE (NRF_ERROR_BASE_NUM + 8) ///< Invalid state, operation disallowed in this state -#define NRF_ERROR_INVALID_LENGTH (NRF_ERROR_BASE_NUM + 9) ///< Invalid Length -#define NRF_ERROR_INVALID_FLAGS (NRF_ERROR_BASE_NUM + 10) ///< Invalid Flags -#define NRF_ERROR_INVALID_DATA (NRF_ERROR_BASE_NUM + 11) ///< Invalid Data -#define NRF_ERROR_DATA_SIZE (NRF_ERROR_BASE_NUM + 12) ///< Data size exceeds limit -#define NRF_ERROR_TIMEOUT (NRF_ERROR_BASE_NUM + 13) ///< Operation timed out -#define NRF_ERROR_NULL (NRF_ERROR_BASE_NUM + 14) ///< Null Pointer -#define NRF_ERROR_FORBIDDEN (NRF_ERROR_BASE_NUM + 15) ///< Forbidden Operation -#define NRF_ERROR_INVALID_ADDR (NRF_ERROR_BASE_NUM + 16) ///< Bad Memory Address -#define NRF_ERROR_BUSY (NRF_ERROR_BASE_NUM + 17) ///< Busy - -#endif // NRF_ERROR_H__ - -/** - @} -*/ diff --git a/libraries/ble/nRF51822/nordic/nrf-sdk/s110/nrf_error_sdm.h b/libraries/ble/nRF51822/nordic/nrf-sdk/s110/nrf_error_sdm.h deleted file mode 100644 index ea5413ff3f..0000000000 --- a/libraries/ble/nRF51822/nordic/nrf-sdk/s110/nrf_error_sdm.h +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) 2012 Nordic Semiconductor. All Rights Reserved. - * - * The information contained herein is confidential property of Nordic Semiconductor. The use, - * copying, transfer or disclosure of such information is prohibited except by express written - * agreement with Nordic Semiconductor. - * - */ - /** - @addtogroup nrf_sdm_api - @{ - @defgroup nrf_sdm_error SoftDevice Manager Error Codes - @{ - - @brief Error definitions for the SDM API -*/ - -/* Header guard */ -#ifndef NRF_ERROR_SDM_H__ -#define NRF_ERROR_SDM_H__ - -#include "nrf_error.h" - -#define NRF_ERROR_SDM_LFCLK_SOURCE_UNKNOWN (NRF_ERROR_SDM_BASE_NUM + 0) ///< Unknown lfclk source -#define NRF_ERROR_SDM_INCORRECT_INTERRUPT_CONFIGURATION (NRF_ERROR_SDM_BASE_NUM + 1) ///< Incorrect interrupt configuration (can be caused by using illegal priority levels, or having enabled SoftDevice interrupts) -#define NRF_ERROR_SDM_INCORRECT_CLENR0 (NRF_ERROR_SDM_BASE_NUM + 2) ///< Incorrect CLENR0 (can be caused by erronous SoftDevice flashing) - -#endif // NRF_ERROR_SDM_H__ - -/** - @} - @} -*/ diff --git a/libraries/ble/nRF51822/nordic/nrf-sdk/s110/nrf_error_soc.h b/libraries/ble/nRF51822/nordic/nrf-sdk/s110/nrf_error_soc.h deleted file mode 100644 index 08dc13c3e7..0000000000 --- a/libraries/ble/nRF51822/nordic/nrf-sdk/s110/nrf_error_soc.h +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (c) 2012 Nordic Semiconductor. All Rights Reserved. - * - * The information contained herein is confidential property of Nordic Semiconductor. The use, - * copying, transfer or disclosure of such information is prohibited except by express written - * agreement with Nordic Semiconductor. - * - */ - /** - @addtogroup nrf_soc_api - @{ - @defgroup nrf_soc_error SoC Library Error Codes - @{ - - @brief Error definitions for the SoC library - -*/ - -/* Header guard */ -#ifndef NRF_ERROR_SOC_H__ -#define NRF_ERROR_SOC_H__ - -#include "nrf_error.h" - -/* Mutex Errors */ -#define NRF_ERROR_SOC_MUTEX_ALREADY_TAKEN (NRF_ERROR_SOC_BASE_NUM + 0) ///< Mutex already taken - -/* NVIC errors */ -#define NRF_ERROR_SOC_NVIC_INTERRUPT_NOT_AVAILABLE (NRF_ERROR_SOC_BASE_NUM + 1) ///< NVIC interrupt not available -#define NRF_ERROR_SOC_NVIC_INTERRUPT_PRIORITY_NOT_ALLOWED (NRF_ERROR_SOC_BASE_NUM + 2) ///< NVIC interrupt priority not allowed -#define NRF_ERROR_SOC_NVIC_SHOULD_NOT_RETURN (NRF_ERROR_SOC_BASE_NUM + 3) ///< NVIC should not return - -/* Power errors */ -#define NRF_ERROR_SOC_POWER_MODE_UNKNOWN (NRF_ERROR_SOC_BASE_NUM + 4) ///< Power mode unknown -#define NRF_ERROR_SOC_POWER_POF_THRESHOLD_UNKNOWN (NRF_ERROR_SOC_BASE_NUM + 5) ///< Power POF threshold unknown -#define NRF_ERROR_SOC_POWER_OFF_SHOULD_NOT_RETURN (NRF_ERROR_SOC_BASE_NUM + 6) ///< Power off should not return - -/* Rand errors */ -#define NRF_ERROR_SOC_RAND_NOT_ENOUGH_VALUES (NRF_ERROR_SOC_BASE_NUM + 7) ///< RAND not enough values - -/* PPI errors */ -#define NRF_ERROR_SOC_PPI_INVALID_CHANNEL (NRF_ERROR_SOC_BASE_NUM + 8) ///< Invalid PPI Channel -#define NRF_ERROR_SOC_PPI_INVALID_GROUP (NRF_ERROR_SOC_BASE_NUM + 9) ///< Invalid PPI Group - -#endif // NRF_ERROR_SOC_H__ -/** - @} - @} -*/ diff --git a/libraries/ble/nRF51822/nordic/nrf-sdk/s110/nrf_sdm.h b/libraries/ble/nRF51822/nordic/nrf-sdk/s110/nrf_sdm.h deleted file mode 100644 index 6a46aba61e..0000000000 --- a/libraries/ble/nRF51822/nordic/nrf-sdk/s110/nrf_sdm.h +++ /dev/null @@ -1,164 +0,0 @@ -/* - * Copyright (c) 2011 Nordic Semiconductor. All Rights Reserved. - * - * The information contained herein is confidential property of Nordic Semiconductor. The use, - * copying, transfer or disclosure of such information is prohibited except by express written - * agreement with Nordic Semiconductor. - * - */ -/** - @defgroup nrf_sdm_api SoftDevice Manager API - @{ - - @brief APIs for SoftDevice management. - -*/ - -/* Header guard */ -#ifndef NRF_SDM_H__ -#define NRF_SDM_H__ - -#include "nordic_global.h" -#include "nrf_svc.h" -#include "nrf51.h" -#include "nrf_soc.h" -#include "nrf_error_sdm.h" - -/** @addtogroup NRF_SDM_DEFINES Defines - * @{ */ - -/**@brief SoftDevice Manager SVC Base number. */ -#define SDM_SVC_BASE 0x10 - -/** @} */ - -/** @addtogroup NRF_SDM_ENUMS Enumerations - * @{ */ - -/**@brief nRF SoftDevice Manager API SVC numbers. */ -enum NRF_SD_SVCS -{ - SD_SOFTDEVICE_ENABLE = SDM_SVC_BASE, /**< ::sd_softdevice_enable */ - SD_SOFTDEVICE_DISABLE, /**< ::sd_softdevice_disable */ - SD_SOFTDEVICE_IS_ENABLED, /**< ::sd_softdevice_is_enabled */ - SD_SOFTDEVICE_FORWARD_TO_APPLICATION,/**< ::sd_softdevice_forward_to_application */ - SVC_SDM_LAST /**< Placeholder for last SDM SVC */ -}; - -/**@brief Possible lfclk oscillator sources. */ -enum NRF_CLOCK_LFCLKSRCS -{ - NRF_CLOCK_LFCLKSRC_SYNTH_250_PPM, /**< LFCLK Synthesized from HFCLK. */ - NRF_CLOCK_LFCLKSRC_XTAL_500_PPM, /**< LFCLK crystal oscillator 500 PPM accuracy. */ - NRF_CLOCK_LFCLKSRC_XTAL_250_PPM, /**< LFCLK crystal oscillator 250 PPM accuracy. */ - NRF_CLOCK_LFCLKSRC_XTAL_150_PPM, /**< LFCLK crystal oscillator 150 PPM accuracy. */ - NRF_CLOCK_LFCLKSRC_XTAL_100_PPM, /**< LFCLK crystal oscillator 100 PPM accuracy. */ - NRF_CLOCK_LFCLKSRC_XTAL_75_PPM, /**< LFCLK crystal oscillator 75 PPM accuracy. */ - NRF_CLOCK_LFCLKSRC_XTAL_50_PPM, /**< LFCLK crystal oscillator 50 PPM accuracy. */ - NRF_CLOCK_LFCLKSRC_XTAL_30_PPM, /**< LFCLK crystal oscillator 30 PPM accuracy. */ - NRF_CLOCK_LFCLKSRC_XTAL_20_PPM, /**< LFCLK crystal oscillator 20 PPM accuracy. */ - NRF_CLOCK_LFCLKSRC_RC_250_PPM_250MS_CALIBRATION, /**< LFCLK RC oscillator, 250ms calibration interval.*/ - NRF_CLOCK_LFCLKSRC_RC_250_PPM_500MS_CALIBRATION, /**< LFCLK RC oscillator, 500ms calibration interval.*/ - NRF_CLOCK_LFCLKSRC_RC_250_PPM_1000MS_CALIBRATION, /**< LFCLK RC oscillator, 1000ms calibration interval.*/ - NRF_CLOCK_LFCLKSRC_RC_250_PPM_2000MS_CALIBRATION, /**< LFCLK RC oscillator, 2000ms calibration interval.*/ - NRF_CLOCK_LFCLKSRC_RC_250_PPM_4000MS_CALIBRATION, /**< LFCLK RC oscillator, 4000ms calibration interval.*/ - NRF_CLOCK_LFCLKSRC_RC_250_PPM_8000MS_CALIBRATION, /**< LFCLK RC oscillator, 8000ms calibration interval.*/ -}; - -/** @} */ - -/** @addtogroup NRF_SDM_TYPES Types - * @{ */ - -/**@brief Type representing lfclk oscillator source. */ -typedef uint32_t nrf_clock_lfclksrc_t; - - -/**@brief SoftDevice Assertion Handler type. - * - * When an unexpected error occurs within the SoftDevice it will call the SoftDevice assertion handler callback. - * The protocol stack will be in an undefined state when this happens and the only way to recover will be to - * perform a reset, using e.g. CMSIS NVIC_SystemReset(). - * - * @note This callback is executed in HardFault context, thus SVC functions cannot be called from the SoftDevice assert callback. - * - * @param[in] pc The program counter of the failed assert. - * @param[in] line_number Line number where the assert failed. - * @param[in] file_name File name where the assert failed. - */ -typedef void (*softdevice_assertion_handler_t)(uint32_t pc, uint16_t line_number, const uint8_t * p_file_name); - -/** @} */ - -/** @addtogroup NRF_SDM_FUNCTIONS Functions - * @{ */ - -/**@brief Enables the SoftDevice and by extension the protocol stack. - * - * Idempotent function to enable the SoftDevice. - * - * @note Some care must be taken if a low frequency clock source is already running when calling this function: - * If the LF clock has a different source then the one currently running, it will be stopped. Then, the new - * clock source will be started. - * - * @note This function has no effect when returning with an error. - * - * @post If return code is ::NRF_SUCCESS - * - SoC library and protocol stack APIs are made available - * - A portion of RAM will be unavailable (see relevant SDS documentation) - * - Some peripherals will be unavailable or available only through the SoC API (see relevant SDS documentation) - * - Interrupts will not arrive from protected peripherals or interrupts - * - nrf_nvic_ functions must be used instead of CMSIS NVIC_ functions for reliable usage of the softdevice. - * - Interrupt latency may be affected by the SoftDevice (see relevant SDS documentation) - * - Chosen low frequency clock source will be running - * - * @param clock_source Low frequency clock source and accuracy. (Note: In the case of XTAL source, the PPM accuracy of the chosen clock source must be greater than or equal to the actual characteristics of your XTAL clock). - * @param assertion_handler Callback for SoftDevice assertions. - * - * @retval ::NRF_SUCCESS - * @retval ::NRF_ERROR_SDM_INCORRECT_INTERRUPT_CONFIGURATION SoftDeviceinterrupt is already enabled, or an enabled interrupt has an illegal priority level - * @retval ::NRF_ERROR_SDM_LFCLK_SOURCE_UNKNOWN Unknown low frequency clock source selected - */ -SVCALL(SD_SOFTDEVICE_ENABLE, uint32_t, sd_softdevice_enable(nrf_clock_lfclksrc_t clock_source, softdevice_assertion_handler_t assertion_handler)); - -/**@brief Disables the SoftDevice and by extension the protocol stack. - * - * Idempotent function to disable the SoftDevice. - * - * @post SoC library and protocol stack APIs are made unavailable. - * @post All interrupts that was protected by the SoftDevice will be disabled and initialized to priority 0 (highest). - * @post All peripherals used by the SoftDevice will be reset to default values. - * @post All of RAM become available. - * @post All interrupts are forwarded to the application. - * @post LFCLK source chosen in ::sd_softdevice_enable will be left running. - * - * @retval ::NRF_SUCCESS - */ -SVCALL(SD_SOFTDEVICE_DISABLE, uint32_t, sd_softdevice_disable(void)); - -/**@brief Check if the SoftDevice is enabled. - * - * @param[out] p_softdevice_enabled If the SoftDevice is enabled: 1 else 0. - * - * @retval ::NRF_SUCCESS - */ -SVCALL(SD_SOFTDEVICE_IS_ENABLED, uint32_t, sd_softdevice_is_enabled(uint8_t * p_softdevice_enabled)); - -/**@brief Start forwarding interrupts to application. - * - * This function is only intended to be called when a bootloader is enabled is used. - * The bootloader should call this right before it starts the application. - * It is recommended that all interrupt sources are off when this is called, - * or you could end up having interrupts in the application being executed before main() of the application. - * - * @retval ::NRF_SUCCESS - */ -SVCALL(SD_SOFTDEVICE_FORWARD_TO_APPLICATION, uint32_t, sd_softdevice_forward_to_application(void)); - -/** @} */ - -#endif // NRF_SDM_H__ - -/** - @} -*/ diff --git a/libraries/ble/nRF51822/nordic/nrf-sdk/s110/nrf_soc.h b/libraries/ble/nRF51822/nordic/nrf-sdk/s110/nrf_soc.h deleted file mode 100644 index 8b7c137dd6..0000000000 --- a/libraries/ble/nRF51822/nordic/nrf-sdk/s110/nrf_soc.h +++ /dev/null @@ -1,778 +0,0 @@ -/* Copyright (c) 2011 Nordic Semiconductor. All Rights Reserved. - * - * The information contained herein is confidential property of Nordic Semiconductor. The use, - * copying, transfer or disclosure of such information is prohibited except by express written - * agreement with Nordic Semiconductor. - * - */ - -/** - @defgroup nrf_soc_api SoC Library API - @{ - - @brief APIs for the SoC library. - -*/ - -#ifndef NRF_SOC_H__ -#define NRF_SOC_H__ - -#include -#include -#include "nordic_global.h" -#include "nrf_svc.h" -#include "nrf51.h" -#include "nrf51_bitfields.h" -#include "nrf_error_soc.h" - -/** @addtogroup NRF_SOC_DEFINES Defines - * @{ */ - -/**@brief The number of the lowest SVC number reserved for the SoC library. */ -#define SOC_SVC_BASE 0x20 - -/**@brief Guranteed time for application to process radio inactive notification. */ -#define NRF_RADIO_NOTIFICATION_INACTIVE_GUARANTEED_TIME_US (62) - -#define SOC_ECB_KEY_LENGTH (16) /**< ECB key length. */ -#define SOC_ECB_CLEARTEXT_LENGTH (16) /**< ECB cleartext length. */ -#define SOC_ECB_CIPHERTEXT_LENGTH (SOC_ECB_CLEARTEXT_LENGTH) /**< ECB ciphertext length. */ - -#define SD_EVT_IRQn (SWI2_IRQn) /**< SoftDevice Event IRQ number. Used for both protocol events and SoC events. */ -#define SD_EVT_IRQHandler (SWI2_IRQHandler) /**< SoftDevice Event IRQ handler. Used for both protocol events and SoC events. */ -#define RADIO_NOTIFICATION_IRQn (SWI1_IRQn) /**< The radio notification IRQ number. */ -#define RADIO_NOTIFICATION_IRQHandler (SWI1_IRQHandler) /**< The radio notification IRQ handler. */ - -/** @} */ - -/** @addtogroup NRF_SOC_TYPES Types - * @{ */ - -/**@brief The SVC numbers used by the SVC functions in the SoC library. */ -enum NRF_SOC_SVCS -{ - SD_MUTEX_NEW = SOC_SVC_BASE, - SD_MUTEX_ACQUIRE, - SD_MUTEX_RELEASE, - SD_NVIC_ENABLEIRQ, - SD_NVIC_DISABLEIRQ, - SD_NVIC_GETPENDINGIRQ, - SD_NVIC_SETPENDINGIRQ, - SD_NVIC_CLEARPENDINGIRQ, - SD_NVIC_SETPRIORITY, - SD_NVIC_GETPRIORITY, - SD_NVIC_SYSTEMRESET, - SD_NVIC_CRITICAL_REGION_ENTER, - SD_NVIC_CRITICAL_REGION_EXIT, - SD_RAND_APPLICATION_POOL_CAPACITY, - SD_RAND_APPLICATION_BYTES_AVAILABLE, - SD_RAND_APPLICATION_GET_VECTOR, - SD_POWER_MODE_SET, - SD_POWER_SYSTEM_OFF, - SD_POWER_RESET_REASON_GET, - SD_POWER_RESET_REASON_CLR, - SD_POWER_POF_ENABLE, - SD_POWER_POF_THRESHOLD_SET, - SD_POWER_RAMON_SET, - SD_POWER_RAMON_CLR, - SD_POWER_RAMON_GET, - SD_POWER_GPREGRET_SET, - SD_POWER_GPREGRET_CLR, - SD_POWER_GPREGRET_GET, - SD_POWER_DCDC_MODE_SET, - SD_APP_EVT_WAIT, - SD_CLOCK_HFCLK_REQUEST, - SD_CLOCK_HFCLK_RELEASE, - SD_CLOCK_HFCLK_IS_RUNNING, - SD_PPI_CHANNEL_ENABLE_GET, - SD_PPI_CHANNEL_ENABLE_SET, - SD_PPI_CHANNEL_ENABLE_CLR, - SD_PPI_CHANNEL_ASSIGN, - SD_PPI_GROUP_TASK_ENABLE, - SD_PPI_GROUP_TASK_DISABLE, - SD_PPI_GROUP_ASSIGN, - SD_PPI_GROUP_GET, - SD_RADIO_NOTIFICATION_CFG_SET, - SD_ECB_BLOCK_ENCRYPT, - SD_RESERVED1, - SD_RESERVED2, - SD_RESERVED3, - SD_EVT_GET, - SD_TEMP_GET, - SD_FLASH_ERASE_PAGE, - SD_FLASH_WRITE, - SD_FLASH_PROTECT, - SVC_SOC_LAST -}; - -/**@brief Possible values of a ::nrf_mutex_t. */ -enum NRF_MUTEX_VALUES -{ - NRF_MUTEX_FREE, - NRF_MUTEX_TAKEN -}; - -/**@brief Possible values of ::nrf_app_irq_priority_t. */ -enum NRF_APP_PRIORITIES -{ - NRF_APP_PRIORITY_HIGH = 1, - NRF_APP_PRIORITY_LOW = 3 -}; - -/**@brief Possible values of ::nrf_power_mode_t. */ -enum NRF_POWER_MODES -{ - NRF_POWER_MODE_CONSTLAT, /**< Constant latency mode. See power management in the reference manual. */ - NRF_POWER_MODE_LOWPWR /**< Low power mode. See power management in the reference manual. */ -}; - - -/**@brief Possible values of ::nrf_power_failure_threshold_t */ -enum NRF_POWER_THRESHOLDS -{ - NRF_POWER_THRESHOLD_V21, /**< 2.1 Volts power failure threshold. */ - NRF_POWER_THRESHOLD_V23, /**< 2.3 Volts power failure threshold. */ - NRF_POWER_THRESHOLD_V25, /**< 2.5 Volts power failure threshold. */ - NRF_POWER_THRESHOLD_V27 /**< 2.7 Volts power failure threshold. */ -}; - - -/**@brief Possible values of ::nrf_power_dcdc_mode_t. */ -enum NRF_POWER_DCDC_MODES -{ - NRF_POWER_DCDC_MODE_OFF, /**< The DCDC is always off. */ - NRF_POWER_DCDC_MODE_ON, /**< The DCDC is always on. */ - NRF_POWER_DCDC_MODE_AUTOMATIC /**< The DCDC is automatically managed. */ -}; - -/**@brief Possible values of ::nrf_radio_notification_distance_t. */ -enum NRF_RADIO_NOTIFICATION_DISTANCES -{ - NRF_RADIO_NOTIFICATION_DISTANCE_NONE = 0, /**< The event does not have a notification. */ - NRF_RADIO_NOTIFICATION_DISTANCE_800US, /**< The distance from the active notification to start of radio activity. */ - NRF_RADIO_NOTIFICATION_DISTANCE_1740US, /**< The distance from the active notification to start of radio activity. */ - NRF_RADIO_NOTIFICATION_DISTANCE_2680US, /**< The distance from the active notification to start of radio activity. */ - NRF_RADIO_NOTIFICATION_DISTANCE_3620US, /**< The distance from the active notification to start of radio activity. */ - NRF_RADIO_NOTIFICATION_DISTANCE_4560US, /**< The distance from the active notification to start of radio activity. */ - NRF_RADIO_NOTIFICATION_DISTANCE_5500US /**< The distance from the active notification to start of radio activity. */ -}; - - -/**@brief Possible values of ::nrf_radio_notification_type_t. */ -enum NRF_RADIO_NOTIFICATION_TYPES -{ - NRF_RADIO_NOTIFICATION_TYPE_NONE = 0, /**< The event does not have a radio notification signal. */ - NRF_RADIO_NOTIFICATION_TYPE_INT_ON_ACTIVE, /**< Using interrupt for notification when the radio will be enabled. */ - NRF_RADIO_NOTIFICATION_TYPE_INT_ON_INACTIVE, /**< Using interrupt for notification when the radio has been disabled. */ - NRF_RADIO_NOTIFICATION_TYPE_INT_ON_BOTH, /**< Using interrupt for notification both when the radio will be enabled and disabled. */ -}; - -/**@brief SoC Events. */ -enum NRF_SOC_EVTS -{ - NRF_EVT_HFCLKSTARTED, /**< Event indicating that the HFCLK has started. */ - NRF_EVT_POWER_FAILURE_WARNING, /**< Event indicating that a power failure warning has occurred. */ - NRF_EVT_FLASH_OPERATION_SUCCESS, /**< Event indicating that the ongoing flash operation has completed successfully. */ - NRF_EVT_FLASH_OPERATION_ERROR, /**< Event indicating that the ongoing flash operation has timed out with an error. */ - NRF_EVT_RESERVED1, - NRF_EVT_RESERVED2, - NRF_EVT_RESERVED3, - NRF_EVT_RESERVED4, - NRF_EVT_RESERVED5, - NRF_EVT_NUMBER_OF_EVTS -}; - -/** @} */ - -/** @addtogroup NRF_SOC_TYPES Types - * @{ */ - -/**@brief Represents a mutex for use with the nrf_mutex functions. - * @note Accessing the value directly is not safe, use the mutex functions! - */ -typedef volatile uint8_t nrf_mutex_t; - -/**@brief The interrupt priorities available to the application while the softdevice is active. */ -typedef uint8_t nrf_app_irq_priority_t; - -/**@brief Represents a power mode, used in power mode functions */ -typedef uint8_t nrf_power_mode_t; - -/**@brief Represents a power failure threshold value. */ -typedef uint8_t nrf_power_failure_threshold_t; - -/**@brief Represents a DCDC mode value. */ -typedef uint32_t nrf_power_dcdc_mode_t; - -/**@brief Radio notification distances. */ -typedef uint8_t nrf_radio_notification_distance_t; - -/**@brief Radio notification types. */ -typedef uint8_t nrf_radio_notification_type_t; - - -/**@brief AES ECB data structure */ -typedef struct -{ - uint8_t key[SOC_ECB_KEY_LENGTH]; /**< Encryption key. */ - uint8_t cleartext[SOC_ECB_CLEARTEXT_LENGTH]; /**< Clear Text data. */ - uint8_t ciphertext[SOC_ECB_CIPHERTEXT_LENGTH]; /**< Cipher Text data. */ -} nrf_ecb_hal_data_t; - -/** @} */ - -/** @addtogroup NRF_SOC_FUNCTIONS Functions - * @{ */ - -/**@brief Initialize a mutex. - * - * @param[in] p_mutex Pointer to the mutex to initialize. - * - * @retval ::NRF_SUCCESS - */ -SVCALL(SD_MUTEX_NEW, uint32_t, sd_mutex_new(nrf_mutex_t * p_mutex)); - -/**@brief Attempt to acquire a mutex. - * - * @param[in] p_mutex Pointer to the mutex to acquire. - * - * @retval ::NRF_SUCCESS The mutex was successfully acquired. - * @retval ::NRF_ERROR_SOC_MUTEX_ALREADY_TAKEN The mutex could not be acquired. - */ -SVCALL(SD_MUTEX_ACQUIRE, uint32_t, sd_mutex_acquire(nrf_mutex_t * p_mutex)); - -/**@brief Release a mutex. - * - * @param[in] p_mutex Pointer to the mutex to release. - * - * @retval ::NRF_SUCCESS - */ -SVCALL(SD_MUTEX_RELEASE, uint32_t, sd_mutex_release(nrf_mutex_t * p_mutex)); - -/**@brief Enable External Interrupt. - * @note Corresponds to NVIC_EnableIRQ in CMSIS. - * - * @pre{IRQn is valid and not reserved by the stack} - * - * @param[in] IRQn See the NVIC_EnableIRQ documentation in CMSIS. - * - * @retval ::NRF_SUCCESS The interrupt was enabled. - * @retval ::NRF_ERROR_SOC_NVIC_INTERRUPT_NOT_AVAILABLE The interrupt is not available for the application. - * @retval ::NRF_ERROR_SOC_NVIC_INTERRUPT_PRIORITY_NOT_ALLOWED The interrupt has a priority not available for the application. - */ -SVCALL(SD_NVIC_ENABLEIRQ, uint32_t, sd_nvic_EnableIRQ(IRQn_Type IRQn)); - -/**@brief Disable External Interrupt. - * @note Corresponds to NVIC_DisableIRQ in CMSIS. - * - * @pre{IRQn is valid and not reserved by the stack} - * - * @param[in] IRQn See the NVIC_DisableIRQ documentation in CMSIS - * - * @retval ::NRF_SUCCESS The interrupt was disabled. - * @retval ::NRF_ERROR_SOC_NVIC_INTERRUPT_NOT_AVAILABLE The interrupt is not available for the application. - */ -SVCALL(SD_NVIC_DISABLEIRQ, uint32_t, sd_nvic_DisableIRQ(IRQn_Type IRQn)); - -/**@brief Get Pending Interrupt. - * @note Corresponds to NVIC_GetPendingIRQ in CMSIS. - * - * @pre{IRQn is valid and not reserved by the stack} - * - * @param[in] IRQn See the NVIC_GetPendingIRQ documentation in CMSIS. - * @param[out] p_pending_irq Return value from NVIC_GetPendingIRQ. - * - * @retval ::NRF_SUCCESS The interrupt is available for the application. - * @retval ::NRF_ERROR_SOC_NVIC_INTERRUPT_NOT_AVAILABLE IRQn is not available for the application. - */ -SVCALL(SD_NVIC_GETPENDINGIRQ, uint32_t, sd_nvic_GetPendingIRQ(IRQn_Type IRQn, uint32_t * p_pending_irq)); - -/**@brief Set Pending Interrupt. - * @note Corresponds to NVIC_SetPendingIRQ in CMSIS. - * - * @pre{IRQn is valid and not reserved by the stack} - * - * @param[in] IRQn See the NVIC_SetPendingIRQ documentation in CMSIS. - * - * @retval ::NRF_SUCCESS The interrupt is set pending. - * @retval ::NRF_ERROR_SOC_NVIC_INTERRUPT_NOT_AVAILABLE IRQn is not available for the application. - */ -SVCALL(SD_NVIC_SETPENDINGIRQ, uint32_t, sd_nvic_SetPendingIRQ(IRQn_Type IRQn)); - -/**@brief Clear Pending Interrupt. - * @note Corresponds to NVIC_ClearPendingIRQ in CMSIS. - * - * @pre{IRQn is valid and not reserved by the stack} - * - * @param[in] IRQn See the NVIC_ClearPendingIRQ documentation in CMSIS. - * - * @retval ::NRF_SUCCESS The interrupt pending flag is cleared. - * @retval ::NRF_ERROR_SOC_NVIC_INTERRUPT_NOT_AVAILABLE IRQn is not available for the application. - */ -SVCALL(SD_NVIC_CLEARPENDINGIRQ, uint32_t, sd_nvic_ClearPendingIRQ(IRQn_Type IRQn)); - -/**@brief Set Interrupt Priority. - * @note Corresponds to NVIC_SetPriority in CMSIS. - * - * @pre{IRQn is valid and not reserved by the stack} - * @pre{priority is valid and not reserved by the stack} - * - * @param[in] IRQn See the NVIC_SetPriority documentation in CMSIS. - * @param[in] priority A valid IRQ priority for use by the application. - * - * @retval ::NRF_SUCCESS The interrupt and priority level is available for the application. - * @retval ::NRF_ERROR_SOC_NVIC_INTERRUPT_NOT_AVAILABLE IRQn is not available for the application. - * @retval ::NRF_ERROR_SOC_NVIC_INTERRUPT_PRIORITY_NOT_ALLOWED The interrupt priority is not available for the application. - */ -SVCALL(SD_NVIC_SETPRIORITY, uint32_t, sd_nvic_SetPriority(IRQn_Type IRQn, nrf_app_irq_priority_t priority)); - -/**@brief Get Interrupt Priority. - * @note Corresponds to NVIC_GetPriority in CMSIS. - * - * @pre{IRQn is valid and not reserved by the stack} - * - * @param[in] IRQn See the NVIC_GetPriority documentation in CMSIS. - * @param[out] p_priority Return value from NVIC_GetPriority. - * - * @retval ::NRF_SUCCESS The interrupt priority is returned in p_priority. - * @retval ::NRF_ERROR_SOC_NVIC_INTERRUPT_NOT_AVAILABLE - IRQn is not available for the application. - */ -SVCALL(SD_NVIC_GETPRIORITY, uint32_t, sd_nvic_GetPriority(IRQn_Type IRQn, nrf_app_irq_priority_t * p_priority)); - -/**@brief System Reset. - * @note Corresponds to NVIC_SystemReset in CMSIS. - * - * @retval ::NRF_ERROR_SOC_NVIC_SHOULD_NOT_RETURN - */ -SVCALL(SD_NVIC_SYSTEMRESET, uint32_t, sd_nvic_SystemReset(void)); - -/**@brief Enters critical region. - * - * @post Application interrupts will be disabled. - * @sa sd_nvic_critical_region_exit - * - * @param[out] p_is_nested_critical_region 1: If in a nested critical region. - * 0: Otherwise. - * - * @retval ::NRF_SUCCESS - */ -SVCALL(SD_NVIC_CRITICAL_REGION_ENTER, uint32_t, sd_nvic_critical_region_enter(uint8_t * p_is_nested_critical_region)); - -/**@brief Exit critical region. - * - * @pre Application has entered a critical region using ::sd_nvic_critical_region_enter. - * @post If not in a nested critical region, the application interrupts will restored to the state before ::sd_nvic_critical_region_enter was called. - * - * @param[in] is_nested_critical_region If this is set to 1, the critical region won't be exited. @sa sd_nvic_critical_region_enter. - * - * @retval ::NRF_SUCCESS - */ -SVCALL(SD_NVIC_CRITICAL_REGION_EXIT, uint32_t, sd_nvic_critical_region_exit(uint8_t is_nested_critical_region)); - -/**@brief Query the capacity of the application random pool. - * - * @param[out] p_pool_capacity The capacity of the pool. - * - * @retval ::NRF_SUCCESS - */ -SVCALL(SD_RAND_APPLICATION_POOL_CAPACITY, uint32_t, sd_rand_application_pool_capacity_get(uint8_t * p_pool_capacity)); - -/**@brief Get number of random bytes available to the application. - * - * @param[out] p_bytes_available The number of bytes currently available in the pool. - * - * @retval ::NRF_SUCCESS - */ -SVCALL(SD_RAND_APPLICATION_BYTES_AVAILABLE, uint32_t, sd_rand_application_bytes_available_get(uint8_t * p_bytes_available)); - -/**@brief Get random bytes from the application pool. - - @param[out] p_buff Pointer to unit8_t buffer for storing the bytes. - @param[in] length Number of bytes to take from pool and place in p_buff. - - @retval ::NRF_SUCCESS The requested bytes were written to p_buff. - @retval ::NRF_ERROR_SOC_RAND_NOT_ENOUGH_VALUES No bytes were written to the buffer, because there were not enough bytes available. -*/ -SVCALL(SD_RAND_APPLICATION_GET_VECTOR, uint32_t, sd_rand_application_vector_get(uint8_t * p_buff, uint8_t length)); - -/**@brief Gets the reset reason register. - * - * @param[out] p_reset_reason Contents of the NRF_POWER->RESETREAS register. - * - * @retval ::NRF_SUCCESS - */ -SVCALL(SD_POWER_RESET_REASON_GET, uint32_t, sd_power_reset_reason_get(uint32_t * p_reset_reason)); - -/**@brief Clears the bits of the reset reason register. - * - * @param[in] reset_reason_clr_msk Contains the bits to clear from the reset reason register. - * - * @retval ::NRF_SUCCESS - */ -SVCALL(SD_POWER_RESET_REASON_CLR, uint32_t, sd_power_reset_reason_clr(uint32_t reset_reason_clr_msk)); - -/**@brief Sets the power mode when in CPU sleep. - * - * @param[in] power_mode The power mode to use when in CPU sleep. @sa sd_app_evt_wait - * - * @retval ::NRF_SUCCESS The power mode was set. - * @retval ::NRF_ERROR_SOC_POWER_MODE_UNKNOWN The power mode was unknown. - */ -SVCALL(SD_POWER_MODE_SET, uint32_t, sd_power_mode_set(nrf_power_mode_t power_mode)); - -/**@brief Puts the chip in System OFF mode. - * - * @retval ::NRF_ERROR_SOC_POWER_OFF_SHOULD_NOT_RETURN - */ -SVCALL(SD_POWER_SYSTEM_OFF, uint32_t, sd_power_system_off(void)); - -/**@brief Enables or disables the power-fail comparator. - * - * Enabling this will give a softdevice event (NRF_EVT_POWER_FAILURE_WARNING) when the power failure warning occurs. - * The event can be retrieved with sd_evt_get(); - * - * @param[in] pof_enable True if the power-fail comparator should be enabled, false if it should be disabled. - * - * @retval ::NRF_SUCCESS - */ -SVCALL(SD_POWER_POF_ENABLE, uint32_t, sd_power_pof_enable(uint8_t pof_enable)); - -/**@brief Sets the power-fail threshold value. - * - * @param[in] threshold The power-fail threshold value to use. - * - * @retval ::NRF_SUCCESS The power failure threshold was set. - * @retval ::NRF_ERROR_SOC_POWER_POF_THRESHOLD_UNKNOWN The power failure threshold is unknown. - */ -SVCALL(SD_POWER_POF_THRESHOLD_SET, uint32_t, sd_power_pof_threshold_set(nrf_power_failure_threshold_t threshold)); - -/**@brief Sets bits in the NRF_POWER->RAMON register. - * - * @param[in] ramon Contains the bits needed to be set in the NRF_POWER->RAMON register. - * - * @retval ::NRF_SUCCESS - */ -SVCALL(SD_POWER_RAMON_SET, uint32_t, sd_power_ramon_set(uint32_t ramon)); - -/** @brief Clears bits in the NRF_POWER->RAMON register. - * - * @param ramon Contains the bits needed to be cleared in the NRF_POWER->RAMON register. - * - * @retval ::NRF_SUCCESS - */ -SVCALL(SD_POWER_RAMON_CLR, uint32_t, sd_power_ramon_clr(uint32_t ramon)); - -/**@brief Get contents of NRF_POWER->RAMON register, indicates power status of ram blocks. - * - * @param[out] p_ramon Content of NRF_POWER->RAMON register. - * - * @retval ::NRF_SUCCESS - */ -SVCALL(SD_POWER_RAMON_GET, uint32_t, sd_power_ramon_get(uint32_t * p_ramon)); - -/**@brief Set bits in the NRF_POWER->GPREGRET register. - * - * @param[in] gpregret_msk Bits to be set in the GPREGRET register. - * - * @retval ::NRF_SUCCESS - */ -SVCALL(SD_POWER_GPREGRET_SET, uint32_t, sd_power_gpregret_set(uint32_t gpregret_msk)); - -/**@brief Clear bits in the NRF_POWER->GPREGRET register. - * - * @param[in] gpregret_msk Bits to be clear in the GPREGRET register. - * - * @retval ::NRF_SUCCESS - */ -SVCALL(SD_POWER_GPREGRET_CLR, uint32_t, sd_power_gpregret_clr(uint32_t gpregret_msk)); - -/**@brief Get contents of the NRF_POWER->GPREGRET register. - * - * @param[out] p_gpregret Contents of the GPREGRET register. - * - * @retval ::NRF_SUCCESS - */ -SVCALL(SD_POWER_GPREGRET_GET, uint32_t, sd_power_gpregret_get(uint32_t *p_gpregret)); - -/**@brief Sets the DCDC mode. - * - * Depending on the internal state of the SoftDevice, the mode change may not happen immediately. - * The DCDC mode switch will be blocked when occurring in close proximity to radio transmissions. When - * the radio transmission is done, the last mode will be used. - * - * @param[in] dcdc_mode The mode of the DCDC. - * - * @retval ::NRF_SUCCESS - * @retval ::NRF_ERROR_INVALID_PARAM The DCDC mode is invalid. - */ -SVCALL(SD_POWER_DCDC_MODE_SET, uint32_t, sd_power_dcdc_mode_set(nrf_power_dcdc_mode_t dcdc_mode)); - -/**@brief Request the high frequency crystal oscillator. - * - * Will start the high frequency crystal oscillator, the startup time of the crystal varies - * and the ::sd_clock_hfclk_is_running function can be polled to check if it has started. - * - * @see sd_clock_hfclk_is_running - * @see sd_clock_hfclk_release - * - * @retval ::NRF_SUCCESS - */ -SVCALL(SD_CLOCK_HFCLK_REQUEST, uint32_t, sd_clock_hfclk_request(void)); - -/**@brief Releases the high frequency crystal oscillator. - * - * Will stop the high frequency crystal oscillator, this happens immediately. - * - * @see sd_clock_hfclk_is_running - * @see sd_clock_hfclk_request - * - * @retval ::NRF_SUCCESS - */ -SVCALL(SD_CLOCK_HFCLK_RELEASE, uint32_t, sd_clock_hfclk_release(void)); - -/**@brief Checks if the high frequency crystal oscillator is running. - * - * @see sd_clock_hfclk_request - * @see sd_clock_hfclk_release - * - * @param[out] p_is_running 1 if the external crystal oscillator is running, 0 if not. - * - * @retval ::NRF_SUCCESS - */ -SVCALL(SD_CLOCK_HFCLK_IS_RUNNING, uint32_t, sd_clock_hfclk_is_running(uint32_t * p_is_running)); - -/**@brief Waits for an application event. - * - * An application event is either an application interrupt or a pended interrupt when the - * interrupt is disabled. When the interrupt is enabled it will be taken immediately since - * this function will wait in thread mode, then the execution will return in the application's - * main thread. When an interrupt is disabled and gets pended it will return to the application's - * thread main. The application must ensure that the pended flag is cleared using - * ::sd_nvic_ClearPendingIRQ in order to sleep using this function. This is only necessary for - * disabled interrupts, as the interrupt handler will clear the pending flag automatically for - * enabled interrupts. - * - * In order to wake up from disabled interrupts, the SEVONPEND flag has to be set in the Cortex-M0 - * System Control Register (SCR). @sa CMSIS_SCB - * - * @note If an application interrupt has happened since the last time sd_app_evt_wait was - * called this function will return immediately and not go to sleep. This is to avoid race - * conditions that can occur when a flag is updated in the interrupt handler and processed - * in the main loop. - * - * @post An application interrupt has happened or a interrupt pending flag is set. - * - * @retval ::NRF_SUCCESS - */ -SVCALL(SD_APP_EVT_WAIT, uint32_t, sd_app_evt_wait(void)); - -/**@brief Get PPI channel enable register contents. - * - * @param[out] p_channel_enable The contents of the PPI CHEN register. - * - * @retval ::NRF_SUCCESS - */ -SVCALL(SD_PPI_CHANNEL_ENABLE_GET, uint32_t, sd_ppi_channel_enable_get(uint32_t * p_channel_enable)); - -/**@brief Set PPI channel enable register. - * - * @param[in] channel_enable_set_msk Mask containing the bits to set in the PPI CHEN register. - * - * @retval ::NRF_SUCCESS - */ -SVCALL(SD_PPI_CHANNEL_ENABLE_SET, uint32_t, sd_ppi_channel_enable_set(uint32_t channel_enable_set_msk)); - -/**@brief Clear PPI channel enable register. - * - * @param[in] channel_enable_clr_msk Mask containing the bits to clear in the PPI CHEN register. - * - * @retval ::NRF_SUCCESS - */ -SVCALL(SD_PPI_CHANNEL_ENABLE_CLR, uint32_t, sd_ppi_channel_enable_clr(uint32_t channel_enable_clr_msk)); - -/**@brief Assign endpoints to a PPI channel. - * - * @param[in] channel_num Number of the PPI channel to assign. - * @param[in] evt_endpoint Event endpoint of the PPI channel. - * @param[in] task_endpoint Task endpoint of the PPI channel. - * - * @retval ::NRF_ERROR_SOC_PPI_INVALID_CHANNEL The channel number is invalid. - * @retval ::NRF_SUCCESS - */ -SVCALL(SD_PPI_CHANNEL_ASSIGN, uint32_t, sd_ppi_channel_assign(uint8_t channel_num, const volatile void * evt_endpoint, const volatile void * task_endpoint)); - -/**@brief Task to enable a channel group. - * - * @param[in] group_num Number of the channel group. - * - * @retval ::NRF_ERROR_SOC_PPI_INVALID_GROUP The group number is invalid - * @retval ::NRF_SUCCESS - */ -SVCALL(SD_PPI_GROUP_TASK_ENABLE, uint32_t, sd_ppi_group_task_enable(uint8_t group_num)); - -/**@brief Task to disable a channel group. - * - * @param[in] group_num Number of the PPI group. - * - * @retval ::NRF_ERROR_SOC_PPI_INVALID_GROUP The group number is invalid. - * @retval ::NRF_SUCCESS - */ -SVCALL(SD_PPI_GROUP_TASK_DISABLE, uint32_t, sd_ppi_group_task_disable(uint8_t group_num)); - -/**@brief Assign PPI channels to a channel group. - * - * @param[in] group_num Number of the channel group. - * @param[in] channel_msk Mask of the channels to assign to the group. - * - * @retval ::NRF_ERROR_SOC_PPI_INVALID_GROUP The group number is invalid. - * @retval ::NRF_SUCCESS - */ -SVCALL(SD_PPI_GROUP_ASSIGN, uint32_t, sd_ppi_group_assign(uint8_t group_num, uint32_t channel_msk)); - -/**@brief Gets the PPI channels of a channel group. - * - * @param[in] group_num Number of the channel group. - * @param[out] p_channel_msk Mask of the channels assigned to the group. - * - * @retval ::NRF_ERROR_SOC_PPI_INVALID_GROUP The group number is invalid. - * @retval ::NRF_SUCCESS - */ -SVCALL(SD_PPI_GROUP_GET, uint32_t, sd_ppi_group_get(uint8_t group_num, uint32_t * p_channel_msk)); - -/**@brief Configures the Radio Notification signal. - * - * @note - * - The notification signal latency depends on the interrupt priority settings of SWI used - * for notification signal. - * - In the period between the ACTIVE signal and the start of the Radio Event, the SoftDevice - * will interrupt the application to do Radio Event preparation. - * - Using the Radio Notification feature may limit the bandwidth, as the SoftDevice may have - * to shorten the connection events to have time for the Radio Notification signals. - * - * @param[in] type Type of notification signal. - * @ref NRF_RADIO_NOTIFICATION_TYPE_NONE shall be used to turn off radio - * notification. Using @ref NRF_RADIO_NOTIFICATION_DISTANCE_NONE is - * recommended (but not required) to be used with - * @ref NRF_RADIO_NOTIFICATION_TYPE_NONE. - * - * @param[in] distance Distance between the notification signal and start of radio activity. - * This parameter is ignored when @ref NRF_RADIO_NOTIFICATION_TYPE_NONE or - * @ref NRF_RADIO_NOTIFICATION_TYPE_INT_ON_INACTIVE is used. - * - * @retval ::NRF_ERROR_INVALID_PARAM The group number is invalid. - * @retval ::NRF_SUCCESS - */ -SVCALL(SD_RADIO_NOTIFICATION_CFG_SET, uint32_t, sd_radio_notification_cfg_set(nrf_radio_notification_type_t type, nrf_radio_notification_distance_t distance)); - -/**@brief Encrypts a block according to the specified parameters. - * - * 128-bit AES encryption. - * - * @param[in, out] p_ecb_data Pointer to the ECB parameters' struct (two input - * parameters and one output parameter). - * - * @retval ::NRF_SUCCESS - */ -SVCALL(SD_ECB_BLOCK_ENCRYPT, uint32_t, sd_ecb_block_encrypt(nrf_ecb_hal_data_t * p_ecb_data)); - -/**@brief Gets any pending events generated by the SoC API. - * - * The application should keep calling this function to get events, until ::NRF_ERROR_NOT_FOUND is returned. - * - * @param[out] p_evt_id Set to one of the values in @ref NRF_SOC_EVTS, if any events are pending. - * - * @retval ::NRF_SUCCESS An event was pending. The event id is written in the p_evt_id parameter. - * @retval ::NRF_ERROR_NOT_FOUND No pending events. - */ -SVCALL(SD_EVT_GET, uint32_t, sd_evt_get(uint32_t * p_evt_id)); - -/**@brief Get the temperature measured on the chip - * - * This function will block until the temperature measurement is done. - * It takes around 50us from call to return. - * - * @note Pan #28 in PAN-028 v 1.6 "Negative measured values are not represented correctly" is corrected by this function. - * - * @param[out] p_temp Result of temperature measurement. Die temperature in 0.25 degrees celsius. - * - * @retval ::NRF_SUCCESS A temperature measurement was done, and the temperature was written to temp - */ -SVCALL(SD_TEMP_GET, uint32_t, sd_temp_get(int32_t * p_temp)); - -/**@brief Flash Write - * - * Commands to write a buffer to flash - * - * This call initiates the flash access command, and its completion will be communicated to the - * application with exactly one of the following events: - * - NRF_EVT_FLASH_OPERATION_SUCCESS - The command was successfully completed. - * - NRF_EVT_FLASH_OPERATION_ERROR - The command could not be started. - * - * @note - * - This call takes control over the radio and the CPU during flash erase and write to make sure that - * they will not interfere with the flash access. This means that all interrupts will be blocked - * for a predictable time (depending on the NVMC specification in nRF51 Series Reference Manual - * and the command parameters). - * - * - * @param[in] p_dst Pointer to start of flash location to be written. - * @param[in] p_src Pointer to buffer with data to be written - * @param[in] size Number of 32-bit words to write. Maximum size is 256 32bit words. - * - * @retval ::NRF_ERROR_INVALID_ADDR Tried to write to a non existing flash address, or p_dst or p_src was unaligned. - * @retval ::NRF_ERROR_BUSY The previous command has not yet completed. - * @retval ::NRF_ERROR_INVALID_LENGTH Size was 0, or more than 256 words. - * @retval ::NRF_ERROR_FORBIDDEN Tried to write to or read from protected location. - * @retval ::NRF_SUCCESS The command was accepted. - */ -SVCALL(SD_FLASH_WRITE, uint32_t, sd_flash_write(uint32_t * const p_dst, uint32_t const * const p_src, uint32_t size)); - - -/**@brief Flash Erase page - * - * Commands to erase a flash page - * - * This call initiates the flash access command, and its completion will be communicated to the - * application with exactly one of the following events: - * - NRF_EVT_FLASH_OPERATION_SUCCESS - The command was successfully completed. - * - NRF_EVT_FLASH_OPERATION_ERROR - The command could not be started. - * - * @note - * - This call takes control over the radio and the CPU during flash erase and write to make sure that - * they will not interfere with the flash access. This means that all interrupts will be blocked - * for a predictable time (depending on the NVMC specification in nRF51 Series Reference Manual - * and the command parameters). - * - * - * @param[in] page_number Pagenumber of the page to erase - * @retval ::NRF_ERROR_INTERNAL If a new session could not be opened due to an internal error. - * @retval ::NRF_ERROR_INVALID_ADDR Tried to erase to a non existing flash page. - * @retval ::NRF_ERROR_BUSY The previous command has not yet completed. - * @retval ::NRF_ERROR_FORBIDDEN Tried to erase a protected page. - * @retval ::NRF_SUCCESS The command was accepted. - */ -SVCALL(SD_FLASH_ERASE_PAGE, uint32_t, sd_flash_page_erase(uint32_t page_number)); - - -/**@brief Flash Protection set - * - * Commands to set the flash protection registers PROTENSETx - * - * @note To read the values in PROTENSETx you can read them directly. They are only write-protected. - * - * @param[in] protenset0 Value to be written to PROTENSET0 - * @param[in] protenset1 Value to be written to PROTENSET1 - * - * @retval ::NRF_ERROR_FORBIDDEN Tried to protect the SoftDevice - * @retval ::NRF_SUCCESS Values successfully written to PROTENSETx - */ -SVCALL(SD_FLASH_PROTECT, uint32_t, sd_flash_protect(uint32_t protenset0, uint32_t protenset1)); - - -/** @} */ - -#endif // NRF_SOC_H__ - -/** - @} - */ diff --git a/libraries/ble/nRF51822/nordic/nrf-sdk/s110/nrf_svc.h b/libraries/ble/nRF51822/nordic/nrf-sdk/s110/nrf_svc.h deleted file mode 100644 index 8f9f8064ec..0000000000 --- a/libraries/ble/nRF51822/nordic/nrf-sdk/s110/nrf_svc.h +++ /dev/null @@ -1,35 +0,0 @@ -#ifndef NRF_SVC__ -#define NRF_SVC__ - -#include "nordic_global.h" - -#ifdef SVCALL_AS_NORMAL_FUNCTION -#define SVCALL(number, return_type, signature) return_type signature -#else - -#ifndef SVCALL -#if defined (__CC_ARM) -#define SVCALL(number, return_type, signature) return_type __svc(number) signature -#elif defined (__GNUC__) -#define SVCALL(number, return_type, signature) \ - _Pragma("GCC diagnostic ignored \"-Wreturn-type\"") \ - _Pragma("GCC diagnostic ignored \"-Wunused-function\"") \ - __attribute__((naked)) static return_type signature \ - { \ - __asm( \ - "svc %0\n" \ - "bx r14" : : "I" (number) : "r0" \ - ); \ - } -#elif defined (__ICCARM__) -#define PRAGMA(x) _Pragma(#x) -#define SVCALL(number, return_type, signature) \ -PRAGMA(swi_number = number) \ - __swi return_type signature; -#else -#define SVCALL(number, return_type, signature) return_type signature -#endif -#endif // SVCALL - -#endif // SVCALL_AS_NORMAL_FUNCTION -#endif // NRF_SVC__ diff --git a/libraries/ble/nRF51822/nordic/nrf-sdk/s110/softdevice_assert.h b/libraries/ble/nRF51822/nordic/nrf-sdk/s110/softdevice_assert.h deleted file mode 100644 index 7026ee4ce5..0000000000 --- a/libraries/ble/nRF51822/nordic/nrf-sdk/s110/softdevice_assert.h +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (c) 2012 Nordic Semiconductor. All Rights Reserved. - * - * The information contained herein is confidential property of Nordic Semiconductor. The use, - * copying, transfer or disclosure of such information is prohibited except by express written - * agreement with Nordic Semiconductor. - * - */ - -/** @brief Utilities for verifying program logic - */ - -#ifndef SOFTDEVICE_ASSERT_H_ -#define SOFTDEVICE_ASSERT_H_ - -#include -#include "nordic_global.h" - -/** @brief This function handles assertions. - * - * - * @note - * This function is called when an assertion has triggered. - * - * - * @param line_num The line number where the assertion is called - * @param file_name Pointer to the file name - */ -void assert_softdevice_callback(uint16_t line_num, const uint8_t *file_name); - - -/*lint -emacro(506, ASSERT) */ /* Suppress "Constant value Boolean */ -/*lint -emacro(774, ASSERT) */ /* Suppress "Boolean within 'if' always evaluates to True" */ \ -/** @brief Check intended for production code - * - * Check passes if "expr" evaluates to true. */ -#define ASSERT(expr) \ -if (expr) \ -{ \ -} \ -else \ -{ \ - assert_softdevice_callback((uint16_t)__LINE__, (uint8_t *)__FILE__); \ - /*lint -unreachable */ \ -} - -#endif /* SOFTDEVICE_ASSERT_H_ */ diff --git a/libraries/ble/nRF51822/nordic/nrf-sdk/sd_common/ant_stack_handler_types.h b/libraries/ble/nRF51822/nordic/nrf-sdk/sd_common/ant_stack_handler_types.h deleted file mode 100644 index f222b172e3..0000000000 --- a/libraries/ble/nRF51822/nordic/nrf-sdk/sd_common/ant_stack_handler_types.h +++ /dev/null @@ -1,70 +0,0 @@ -/* Copyright (c) 2013 Nordic Semiconductor. All Rights Reserved. - * - * The information contained herein is property of Nordic Semiconductor ASA. - * Terms and conditions of usage are described in detail in NORDIC - * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. - * - * Licensees are granted free, non-transferable use of the information. NO - * WARRANTY of ANY KIND is provided. This heading must NOT be removed from - * the file. - * - */ - -/**@file - * - * @defgroup ant_stack_handler_types Types definitions for ANT support in SoftDevice handler. - * @{ - * @ingroup app_common - * @brief This file contains the declarations of types required for ANT stack support. These - * types will be defined when the preprocessor define ANT_STACK_SUPPORT_REQD is defined. - */ - -#ifndef ANT_STACK_HANDLER_TYPES_H__ -#define ANT_STACK_HANDLER_TYPES_H__ - -#ifdef ANT_STACK_SUPPORT_REQD - -#include -#include "nordic_global.h" - -#define ANT_STACK_EVT_MSG_BUF_SIZE 32 /**< Size of ANT event message buffer. This will be provided to the SoftDevice while fetching an event. */ -#define ANT_STACK_EVT_STRUCT_SIZE (sizeof(ant_evt_t)) /**< Size of the @ref ant_evt_t structure. This will be used by the @ref softdevice_handler.h to internal event buffer size needed. */ - -/**@brief ANT stack event type. */ -typedef struct -{ - uint8_t channel; /**< Channel number. */ - uint8_t event; /**< Event code. */ - uint8_t evt_buffer[ANT_STACK_EVT_MSG_BUF_SIZE]; /**< Event message buffer. */ -} ant_evt_t; - -/**@brief Application ANT stack event handler type. */ -typedef void (*ant_evt_handler_t) (ant_evt_t * p_ant_evt); - -/**@brief Function for registering for ANT events. - * - * @details The application should use this function to register for receiving ANT events from - * the SoftDevice. If the application does not call this function, then any ANT event - * that may be generated by the SoftDevice will NOT be fetched. Once the application has - * registered for the events, it is not possible to possible to cancel the registration. - * However, it is possible to register a different function for handling the events at - * any point of time. - * - * @param[in] ant_evt_handler Function to be called for each received ANT event. - * - * @retval NRF_SUCCESS Successful registration. - * @retval NRF_ERROR_NULL Null pointer provided as input. - */ -uint32_t softdevice_ant_evt_handler_set(ant_evt_handler_t ant_evt_handler); - -#else - -// The ANT Stack support is not required. - -#define ANT_STACK_EVT_STRUCT_SIZE 0 /**< Since the ANT stack support is not required, this is equated to 0, so that the @ref softdevice_handler.h can compute the internal event buffer size without having to care for ANT events.*/ - -#endif // ANT_STACK_SUPPORT_REQD - -#endif // ANT_STACK_HANDLER_TYPES_H__ - -/** @} */ diff --git a/libraries/ble/nRF51822/nordic/nrf-sdk/sd_common/ble_stack_handler_types.h b/libraries/ble/nRF51822/nordic/nrf-sdk/sd_common/ble_stack_handler_types.h deleted file mode 100644 index 2f4824b306..0000000000 --- a/libraries/ble/nRF51822/nordic/nrf-sdk/sd_common/ble_stack_handler_types.h +++ /dev/null @@ -1,67 +0,0 @@ -/* Copyright (c) 2013 Nordic Semiconductor. All Rights Reserved. - * - * The information contained herein is property of Nordic Semiconductor ASA. - * Terms and conditions of usage are described in detail in NORDIC - * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. - * - * Licensees are granted free, non-transferable use of the information. NO - * WARRANTY of ANY KIND is provided. This heading must NOT be removed from - * the file. - * - */ - -/**@file - * - * @defgroup ble_stack_handler_types Types definitions for BLE support in SoftDevice handler. - * @{ - * @ingroup app_common - * @brief This file contains the declarations of types required for BLE stack support. These - * types will be defined when the preprocessor define BLE_STACK_SUPPORT_REQD is defined. - */ - -#ifndef BLE_STACK_HANDLER_TYPES_H__ -#define BLE_STACK_HANDLER_TYPES_H__ - -#include "nordic_global.h" - -#ifdef BLE_STACK_SUPPORT_REQD - -#include -#include "ble.h" -#include "nrf_sdm.h" -#include "app_error.h" -#include "app_scheduler.h" -#include "app_util.h" - -#define BLE_STACK_EVT_MSG_BUF_SIZE (sizeof(ble_evt_t) + (GATT_MTU_SIZE_DEFAULT)) /**< Size of BLE event message buffer. This will be provided to the SoftDevice while fetching an event. */ -#define BLE_STACK_HANDLER_SCHED_EVT_SIZE 0 /**< The size of the scheduler event used by SoftDevice handler when passing BLE events using the @ref app_scheduler. */ - -/**@brief Application stack event handler type. */ -typedef void (*ble_evt_handler_t) (ble_evt_t * p_ble_evt); - -/**@brief Function for registering for BLE events. - * - * @details The application should use this function to register for receiving BLE events from - * the SoftDevice. If the application does not call this function, then any BLE event - * that may be generated by the SoftDevice will NOT be fetched. Once the application has - * registered for the events, it is not possible to possible to cancel the registration. - * However, it is possible to register a different function for handling the events at - * any point of time. - * - * @param[in] ble_evt_handler Function to be called for each received BLE event. - * - * @retval NRF_SUCCESS Successful registration. - * @retval NRF_ERROR_NULL Null pointer provided as input. - */ -uint32_t softdevice_ble_evt_handler_set(ble_evt_handler_t ble_evt_handler); - -#else - -#define BLE_STACK_EVT_MSG_BUF_SIZE 0 /**< Since the BLE stack support is not required, this is equated to 0, so that the @ref softdevice_handler.h can compute the internal event buffer size without having to care for BLE events.*/ -#define BLE_STACK_HANDLER_SCHED_EVT_SIZE 0 - -#endif // BLE_STACK_SUPPORT_REQD - -#endif // BLE_STACK_HANDLER_TYPES_H__ - -/** @} */ diff --git a/libraries/ble/nRF51822/nordic/nrf-sdk/sd_common/softdevice_handler.h b/libraries/ble/nRF51822/nordic/nrf-sdk/sd_common/softdevice_handler.h deleted file mode 100644 index c73d4785cb..0000000000 --- a/libraries/ble/nRF51822/nordic/nrf-sdk/sd_common/softdevice_handler.h +++ /dev/null @@ -1,165 +0,0 @@ -/* Copyright (c) 2013 Nordic Semiconductor. All Rights Reserved. - * - * The information contained herein is property of Nordic Semiconductor ASA. - * Terms and conditions of usage are described in detail in NORDIC - * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. - * - * Licensees are granted free, non-transferable use of the information. NO - * WARRANTY of ANY KIND is provided. This heading must NOT be removed from - * the file. - * - */ - -/** @file - * - * @defgroup softdevice_handler SoftDevice Event Handler - * @{ - * @ingroup app_common - * @brief API for initializing and disabling the SoftDevice - * - * @details This API contains the functions and defines exposed by the @ref lib_softdevice_handler. - * For more information on the library and how the application should use it, please refer - * @ref lib_softdevice_handler. - * - * @note Use the USE_SCHEDULER parameter of the SOFTDEVICE_HANDLER_INIT() macro to select if - * the @ref app_scheduler is to be used or not. - * - * @note Even if the scheduler is not used, softdevice_handler.h will include app_scheduler.h. - * So when compiling, app_scheduler.h must be available in one of the compiler include - * paths. - */ - -#ifndef SOFTDEVICE_HANDLER_H__ -#define SOFTDEVICE_HANDLER_H__ - -#include -#include "nordic_global.h" -#include "nrf_sdm.h" -#include "app_error.h" -#include "app_scheduler.h" -#include "app_util.h" -#include "ble_stack_handler_types.h" -#include "ant_stack_handler_types.h" - -#define SOFTDEVICE_SCHED_EVT_SIZE 0 /**< Size of button events being passed through the scheduler (is to be used for computing the maximum size of scheduler events). For SoftDevice events, this size is 0, since the events are being pulled in the event handler. */ -#define SYS_EVT_MSG_BUF_SIZE sizeof(uint32_t) /**< Size of System (SOC) event message buffer. */ - -/**@brief Type of function for passing events from the stack handler module to the scheduler. */ -typedef uint32_t (*softdevice_evt_schedule_func_t) (void); - -/**@brief Application System (SOC) event handler type. */ -typedef void (*sys_evt_handler_t) (uint32_t evt_id); - - -/**@brief Macro for initializing the stack event handler. - * - * @details It will handle dimensioning and allocation of the memory buffer required for reading - * events from the stack, making sure the buffer is correctly aligned. It will also - * connect the stack event handler to the scheduler (if specified). - * - * @param[in] CLOCK_SOURCE Low frequency clock source and accuracy (type nrf_clock_lfclksrc_t, - * see sd_softdevice_enable() for details). - * @param[in] USE_SCHEDULER TRUE if the application is using the event scheduler, FALSE - * otherwise. - * - * @note Since this macro allocates a buffer, it must only be called once (it is OK to call it - * several times as long as it is from the same location, that is to do a - * reinitialization). - */ -/*lint -emacro(506, SOFTDEVICE_HANDLER_INIT) */ /* Suppress "Constant value Boolean */ -#define SOFTDEVICE_HANDLER_INIT(CLOCK_SOURCE, \ - USE_SCHEDULER) \ - do \ - { \ - static uint32_t EVT_BUFFER[CEIL_DIV(MAX( \ - MAX(BLE_STACK_EVT_MSG_BUF_SIZE, \ - ANT_STACK_EVT_STRUCT_SIZE), \ - SYS_EVT_MSG_BUF_SIZE \ - ), \ - sizeof(uint32_t))]; \ - uint32_t ERR_CODE; \ - ERR_CODE = softdevice_handler_init((CLOCK_SOURCE), \ - EVT_BUFFER, \ - sizeof(EVT_BUFFER), \ - (USE_SCHEDULER) ? softdevice_evt_schedule : NULL); \ - APP_ERROR_CHECK(ERR_CODE); \ - } while (0) - - -/**@brief Function for initializing the stack handler module. - * - * @details Enables the SoftDevice and the stack event interrupt handler. - * - * @note This function must be called before calling any function in the SoftDevice API. - * - * @note Normally initialization should be done using the SOFTDEVICE_HANDLER_INIT() macro, - * as that will both allocate the event buffer, and also align the buffer correctly. - * - * @param[in] clock_source Low frequency clock source to be used by the SoftDevice. - * @param[in] p_evt_buffer Buffer for holding one stack event. Since heap is not being - * used, this buffer must be provided by the application. The - * buffer must be large enough to hold the biggest stack event the - * application is supposed to handle. The buffer must be aligned to - * a 4 byte boundary. This parameter is unused if neither BLE nor - * ANT stack support is required. - * @param[in] evt_buffer_size Size of SoftDevice event buffer. This parameter is unused if - * BLE stack support is not required. - * @param[in] evt_schedule_func Function for passing events to the scheduler. Point to - * ble_ant_stack_evt_schedule() to connect to the scheduler. - * Set to NULL to make the stack handler module call the event - * handler directly from the stack event interrupt handler. - * - * @retval NRF_SUCCESS Successful initialization. - * @retval NRF_ERROR_INVALID_PARAM Invalid parameter (buffer not aligned to a 4 byte - * boundary) or NULL. - */ -uint32_t softdevice_handler_init(nrf_clock_lfclksrc_t clock_source, - void * p_evt_buffer, - uint16_t evt_buffer_size, - softdevice_evt_schedule_func_t evt_schedule_func); - - -/**@brief Function for disabling the SoftDevice. - * - * @details This function will disable the SoftDevice. It will also update the internal state - * of this module. - */ -uint32_t softdevice_handler_sd_disable(void); - - -/**@brief Function for registering for System (SOC) events. - * - * @details The application should use this function to register for receiving System (SOC) - * events from the SoftDevice. If the application does not call this function, then any - * System (SOC) events that may be generated by the SoftDevice will NOT be fetched. Once - * the application has registered for the events, it is not possible to possible to - * cancel the registration. However, it is possible to register a different function for - * handling the events at any point of time. - * - * @param[in] sys_evt_handler Function to be called for each received System (SOC) event. - * - * @retval NRF_SUCCESS Successful registration. - * @retval NRF_ERROR_NULL Null pointer provided as input. - */ -uint32_t softdevice_sys_evt_handler_set(sys_evt_handler_t sys_evt_handler); - - -// Functions for connecting the Stack Event Handler to the scheduler: -/**@cond NO_DOXYGEN */ -void intern_softdevice_events_execute(void); - -static __INLINE void softdevice_evt_get(void * p_event_data, uint16_t event_size) -{ - APP_ERROR_CHECK_BOOL(event_size == 0); - intern_softdevice_events_execute(); -} - -static __INLINE uint32_t softdevice_evt_schedule(void) -{ - return app_sched_event_put(NULL, 0, softdevice_evt_get); -} -/**@endcond */ - -#endif // SOFTDEVICE_HANDLER_H__ - -/** @} */ diff --git a/libraries/ble/nRF51822/nordic/nrf-sdk/system_nrf51.h b/libraries/ble/nRF51822/nordic/nrf-sdk/system_nrf51.h deleted file mode 100644 index b28bbf71ce..0000000000 --- a/libraries/ble/nRF51822/nordic/nrf-sdk/system_nrf51.h +++ /dev/null @@ -1,53 +0,0 @@ -/* Copyright (c) 2009 Nordic Semiconductor. All Rights Reserved. - * - * The information contained herein is property of Nordic Semiconductor ASA. - * Terms and conditions of usage are described in detail in NORDIC - * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. - * - * Licensees are granted free, non-transferable use of the information. NO - * WARRANTY of ANY KIND is provided. This heading must NOT be removed from - * the file. - * - */ - - -#ifndef SYSTEM_NRF51_H -#define SYSTEM_NRF51_H - -#ifdef __cplusplus -extern "C" { -#endif - -#include -#include "nordic_global.h" - - -extern uint32_t SystemCoreClock; /*!< System Clock Frequency (Core Clock) */ - -/** - * Initialize the system - * - * @param none - * @return none - * - * @brief Setup the microcontroller system. - * Initialize the System and update the SystemCoreClock variable. - */ -extern void SystemInit (void); - -/** - * Update SystemCoreClock variable - * - * @param none - * @return none - * - * @brief Updates the SystemCoreClock with current core Clock - * retrieved from cpu registers. - */ -extern void SystemCoreClockUpdate (void); - -#ifdef __cplusplus -} -#endif - -#endif /* SYSTEM_NRF51_H */ diff --git a/libraries/ble/nRF51822/nordic/pstorage_platform.h b/libraries/ble/nRF51822/nordic/pstorage_platform.h deleted file mode 100644 index b5fb6f7f59..0000000000 --- a/libraries/ble/nRF51822/nordic/pstorage_platform.h +++ /dev/null @@ -1,62 +0,0 @@ -/* Copyright (c) 2013 Nordic Semiconductor. All Rights Reserved. - * - * The information contained herein is property of Nordic Semiconductor ASA. - * Terms and conditions of usage are described in detail in NORDIC - * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. - * - * Licensees are granted free, non-transferable use of the information. NO - * WARRANTY of ANY KIND is provided. This heading must NOT be removed from - * the file. - * - */ - - /** @cond To make doxygen skip this file */ - -/** @file - * This header contains defines with respect persistent storage that are specific to - * persistent storage implementation and application use case. - */ -#ifndef PSTORAGE_PL_H__ -#define PSTORAGE_PL_H__ - -#include -#include "nordic_global.h" - -#define PSTORAGE_FLASH_PAGE_SIZE ((uint16_t)NRF_FICR->CODEPAGESIZE) /**< Size of one flash page. */ -#define PSTORAGE_FLASH_EMPTY_MASK 0xFFFFFFFF /**< Bit mask that defines an empty address in flash. */ - -#define PSTORAGE_FLASH_PAGE_END \ - ((NRF_UICR->BOOTLOADERADDR != PSTORAGE_FLASH_EMPTY_MASK) \ - ? (NRF_UICR->BOOTLOADERADDR / PSTORAGE_FLASH_PAGE_SIZE) \ - : NRF_FICR->CODESIZE) - - -#define PSTORAGE_MAX_APPLICATIONS 2 /**< Maximum number of applications that can be registered with the module, configurable based on system requirements. */ -#define PSTORAGE_MIN_BLOCK_SIZE 0x0010 /**< Minimum size of block that can be registered with the module. Should be configured based on system requirements, recommendation is not have this value to be at least size of word. */ - -#define PSTORAGE_DATA_START_ADDR ((PSTORAGE_FLASH_PAGE_END - PSTORAGE_MAX_APPLICATIONS) \ - * PSTORAGE_FLASH_PAGE_SIZE) /**< Start address for persistent data, configurable according to system requirements. */ -#define PSTORAGE_DATA_END_ADDR (PSTORAGE_FLASH_PAGE_END * PSTORAGE_FLASH_PAGE_SIZE) /**< End address for persistent data, configurable according to system requirements. */ - -#define PSTORAGE_MAX_BLOCK_SIZE PSTORAGE_FLASH_PAGE_SIZE /**< Maximum size of block that can be registered with the module. Should be configured based on system requirements. And should be greater than or equal to the minimum size. */ -#define PSTORAGE_CMD_QUEUE_SIZE 30 /**< Maximum number of flash access commands that can be maintained by the module for all applications. Configurable. */ - - -/** Abstracts persistently memory block identifier. */ -typedef uint32_t pstorage_block_t; - -typedef struct -{ - uint32_t module_id; /**< Module ID.*/ - pstorage_block_t block_id; /**< Block ID.*/ -} pstorage_handle_t; - -typedef uint16_t pstorage_size_t; /** Size of length and offset fields. */ - -/**@brief Handles Flash Access Result Events. To be called in the system event dispatcher of the application. */ -void pstorage_sys_event_handler (uint32_t sys_evt); - -#endif // PSTORAGE_PL_H__ - -/** @} */ -/** @endcond */ diff --git a/libraries/ble/nRF51822/nordic/softdevice_handler.cpp b/libraries/ble/nRF51822/nordic/softdevice_handler.cpp deleted file mode 100644 index f7229ef9a0..0000000000 --- a/libraries/ble/nRF51822/nordic/softdevice_handler.cpp +++ /dev/null @@ -1,313 +0,0 @@ -/* Copyright (c) 2013 Nordic Semiconductor. All Rights Reserved. - * - * The information contained herein is property of Nordic Semiconductor ASA. - * Terms and conditions of usage are described in detail in NORDIC - * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. - * - * Licensees are granted free, non-transferable use of the information. NO - * WARRANTY of ANY KIND is provided. This heading must NOT be removed from - * the file. - * - */ - -#include "softdevice_handler.h" -#include -#include "nordic_common.h" -#include "app_error.h" -#include "app_util.h" -#include "nrf_assert.h" -#include "nrf_soc.h" -#include "mbed.h" - -#if defined(ANT_STACK_SUPPORT_REQD) && defined(BLE_STACK_SUPPORT_REQD) - #include "ant_interface.h" -#elif defined(ANT_STACK_SUPPORT_REQD) - #include "ant_interface.h" -#elif defined(BLE_STACK_SUPPORT_REQD) - #include "ble.h" -#endif - - -static softdevice_evt_schedule_func_t m_evt_schedule_func; /**< Pointer to function for propagating SoftDevice events to the scheduler. */ - -#if defined (BLE_STACK_SUPPORT_REQD) || defined (ANT_STACK_SUPPORT_REQD) -// The following two definition is needed only if ANT or BLE events are needed to be pulled from the stack. -static uint8_t * m_evt_buffer; /**< Buffer for receiving events from the SoftDevice. */ -#endif - -#ifdef BLE_STACK_SUPPORT_REQD -static uint16_t m_ble_evt_buffer_size; /**< Size of BLE event buffer. */ -#endif - -static volatile bool m_softdevice_enabled = false; /**< Variable to indicate whether the SoftDevice is enabled. */ - -#ifdef BLE_STACK_SUPPORT_REQD -static ble_evt_handler_t m_ble_evt_handler; /**< Application event handler for handling BLE events. */ -#endif - -#ifdef ANT_STACK_SUPPORT_REQD -static ant_evt_handler_t m_ant_evt_handler; /**< Application event handler for handling ANT events. */ -#endif - -static sys_evt_handler_t m_sys_evt_handler; /**< Application event handler for handling System (SOC) events. */ - - -/**@brief Callback function for asserts in the SoftDevice. - * - * @details A pointer to this function will be passed to the SoftDevice. This function will be - * called if an ASSERT statement in the SoftDevice fails. - * - * @param[in] pc The value of the program counter when the ASSERT call failed. - * @param[in] line_num Line number of the failing ASSERT call. - * @param[in] file_name File name of the failing ASSERT call. - */ -void softdevice_assertion_handler(uint32_t pc, uint16_t line_num, const uint8_t * file_name) -{ - UNUSED_PARAMETER(pc); - assert_nrf_callback(line_num, file_name); -} - - -void intern_softdevice_events_execute(void) -{ - if (!m_softdevice_enabled) - { - // SoftDevice not enabled. This can be possible if the SoftDevice was enabled by the - // application without using this module's API (i.e softdevice_handler_init) - - return; - } - - bool no_more_soc_evts = (m_sys_evt_handler == NULL); -#ifdef BLE_STACK_SUPPORT_REQD - bool no_more_ble_evts = (m_ble_evt_handler == NULL); -#endif -#ifdef ANT_STACK_SUPPORT_REQD - bool no_more_ant_evts = (m_ant_evt_handler == NULL); -#endif - - for (;;) - { - uint32_t err_code; - - if (!no_more_soc_evts) - { - uint32_t evt_id; - - // Pull event from SOC. - err_code = sd_evt_get(&evt_id); - - if (err_code == NRF_ERROR_NOT_FOUND) - { - no_more_soc_evts = true; - } - else if (err_code != NRF_SUCCESS) - { - APP_ERROR_HANDLER(err_code); - } - else - { - // Call application's SOC event handler. - m_sys_evt_handler(evt_id); - } - } - -#ifdef BLE_STACK_SUPPORT_REQD - // Fetch BLE Events. - if (!no_more_ble_evts) - { - // Pull event from stack - uint16_t evt_len = m_ble_evt_buffer_size; - - err_code = sd_ble_evt_get(m_evt_buffer, &evt_len); - if (err_code == NRF_ERROR_NOT_FOUND) - { - no_more_ble_evts = true; - } - else if (err_code != NRF_SUCCESS) - { - APP_ERROR_HANDLER(err_code); - } - else - { - // Call application's BLE stack event handler. - m_ble_evt_handler((ble_evt_t *)m_evt_buffer); - } - } -#endif - -#ifdef ANT_STACK_SUPPORT_REQD - // Fetch ANT Events. - if (!no_more_ant_evts) - { - // Pull event from stack - err_code = sd_ant_event_get(&((ant_evt_t *)m_evt_buffer)->channel, - &((ant_evt_t *)m_evt_buffer)->event, - ((ant_evt_t *)m_evt_buffer)->evt_buffer); - if (err_code == NRF_ERROR_NOT_FOUND) - { - no_more_ant_evts = true; - } - else if (err_code != NRF_SUCCESS) - { - APP_ERROR_HANDLER(err_code); - } - else - { - // Call application's ANT stack event handler. - m_ant_evt_handler((ant_evt_t *)m_evt_buffer); - } - } -#endif - - if (no_more_soc_evts) - { - // There are no remaining System (SOC) events to be fetched from the SoftDevice. -#if defined(ANT_STACK_SUPPORT_REQD) && defined(BLE_STACK_SUPPORT_REQD) - // Check if there are any remaining BLE and ANT events. - if (no_more_ble_evts && no_more_ant_evts) - { - break; - } -#elif defined(BLE_STACK_SUPPORT_REQD) - // Check if there are any remaining BLE events. - if (no_more_ble_evts) - { - break; - } -#elif defined(ANT_STACK_SUPPORT_REQD) - // Check if there are any remaining ANT events. - if (no_more_ant_evts) - { - break; - } -#else - // No need to check for BLE or ANT events since there is no support for BLE and ANT - // required. - break; -#endif - } - } -} - - -uint32_t softdevice_handler_init(nrf_clock_lfclksrc_t clock_source, - void * p_evt_buffer, - uint16_t evt_buffer_size, - softdevice_evt_schedule_func_t evt_schedule_func) -{ - uint32_t err_code; - - // Save configuration. -#if defined (BLE_STACK_SUPPORT_REQD) || defined (ANT_STACK_SUPPORT_REQD) - // Check that buffer is not NULL. - if (p_evt_buffer == NULL) - { - return NRF_ERROR_INVALID_PARAM; - } - - // Check that buffer is correctly aligned. - if (!is_word_aligned(p_evt_buffer)) - { - return NRF_ERROR_INVALID_PARAM; - } - - m_evt_buffer = (uint8_t *)p_evt_buffer; -#else - // The variable p_evt_buffer is not needed if neither BLE Stack nor ANT stack support is - // required. - UNUSED_PARAMETER(p_evt_buffer); -#endif - -#if defined (BLE_STACK_SUPPORT_REQD) - m_ble_evt_buffer_size = evt_buffer_size; -#else - // The variable evt_buffer_size is not needed if BLE Stack support is NOT required. - UNUSED_PARAMETER(evt_buffer_size); -#endif - - m_evt_schedule_func = evt_schedule_func; - - // Initialize SoftDevice. - - err_code = sd_softdevice_enable(clock_source, softdevice_assertion_handler); - if (err_code != NRF_SUCCESS) - { - return err_code; - } - - m_softdevice_enabled = true; - // Enable BLE event interrupt (interrupt priority has already been set by the stack). - return sd_nvic_EnableIRQ(SWI2_IRQn); -} - - -uint32_t softdevice_handler_sd_disable(void) -{ - uint32_t err_code = sd_softdevice_disable(); - - m_softdevice_enabled = !(err_code == NRF_SUCCESS); - - return err_code; -} - - -#ifdef BLE_STACK_SUPPORT_REQD -uint32_t softdevice_ble_evt_handler_set(ble_evt_handler_t ble_evt_handler) -{ - if (ble_evt_handler == NULL) - { - return NRF_ERROR_NULL; - } - - m_ble_evt_handler = ble_evt_handler; - - return NRF_SUCCESS; -} -#endif - - -#ifdef ANT_STACK_SUPPORT_REQD -uint32_t softdevice_ant_evt_handler_set(ant_evt_handler_t ant_evt_handler) -{ - if (ant_evt_handler == NULL) - { - return NRF_ERROR_NULL; - } - - m_ant_evt_handler = ant_evt_handler; - - return NRF_SUCCESS; -} -#endif - - -uint32_t softdevice_sys_evt_handler_set(sys_evt_handler_t sys_evt_handler) -{ - if (sys_evt_handler == NULL) - { - return NRF_ERROR_NULL; - } - - m_sys_evt_handler = sys_evt_handler; - - return NRF_SUCCESS; -} - - -/**@brief Function for handling the Application's BLE Stack events interrupt. - * - * @details This function is called whenever an event is ready to be pulled. - */ -extern "C" void SWI2_IRQHandler(void) -{ - if (m_evt_schedule_func != NULL) - { - uint32_t err_code = m_evt_schedule_func(); - APP_ERROR_CHECK(err_code); - } - else - { - intern_softdevice_events_execute(); - } -} diff --git a/libraries/ble/nRF51822/projectconfig.h b/libraries/ble/nRF51822/projectconfig.h deleted file mode 100644 index 05ac2d72f2..0000000000 --- a/libraries/ble/nRF51822/projectconfig.h +++ /dev/null @@ -1,134 +0,0 @@ -/* mbed Microcontroller Library - * Copyright (c) 2006-2013 ARM Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef _PROJECTCONFIG_H_ -#define _PROJECTCONFIG_H_ - -/*========================================================================= - MCU & BOARD SELCTION - - CFG_BOARD is one of the value defined in board.h - -----------------------------------------------------------------------*/ - #define CFG_BOARD BOARD_PCA10001 - #define CFG_MCU_STRING "nRF51822" -/*=========================================================================*/ - - -/*========================================================================= - CODE BASE VERSION SETTINGS - - Please do not modify this version number. To set a version number - for your project or firmware, change the values in your 'boards/' - config file. - -----------------------------------------------------------------------*/ - #define CFG_CODEBASE_VERSION_MAJOR 0 - #define CFG_CODEBASE_VERSION_MINOR 1 - #define CFG_CODEBASE_VERSION_REVISION 0 -/*=========================================================================*/ - - -/*========================================================================= - FIRMWARE VERSION SETTINGS - -----------------------------------------------------------------------*/ - #define CFG_FIRMWARE_VERSION_MAJOR 0 - #define CFG_FIRMWARE_VERSION_MINOR 0 - #define CFG_FIRMWARE_VERSION_REVISION 0 -/*=========================================================================*/ - - -/*========================================================================= - DEBUG LEVEL - ----------------------------------------------------------------------- - - CFG_DEBUG Level 3: Full debug output, any failed assert - will produce a breakpoint for the - debugger - Level 2: ATTR_ALWAYS_INLINE is null, ASSERT - has text - Level 1: ATTR_ALWAYS_INLINE is an attribute, - ASSERT has no text - Level 0: No debug information generated - - -----------------------------------------------------------------------*/ - #define CFG_DEBUG (2) - - #if (CFG_DEBUG > 3) || (CFG_DEBUG < 0) - #error "CFG_DEBUG must be a value between 0 (no debug) and 3" - #endif -/*=========================================================================*/ - - -/*========================================================================= - GENERAL NRF51 PERIPHERAL SETTINGS - ----------------------------------------------------------------------- - - CFG_SCHEDULER_ENABLE Set this to 'true' or 'false' depending on - if you use the event scheduler or not - - -----------------------------------------------------------------------*/ - #define CFG_SCHEDULER_ENABLE false - - /*------------------------------- GPIOTE ------------------------------*/ - #define CFG_GPIOTE_MAX_USERS 1 /**< Maximum number of users of the GPIOTE handler. */ - - /*-------------------------------- TIMER ------------------------------*/ - #define CFG_TIMER_PRESCALER 0 /**< Value of the RTC1 PRESCALER register. freq = (32768/(PRESCALER+1)) */ - #define CFG_TIMER_MAX_INSTANCE 8 /**< Maximum number of simultaneously created timers. */ - #define CFG_TIMER_OPERATION_QUEUE_SIZE 5 /**< Size of timer operation queues. */ -/*=========================================================================*/ - - -/*========================================================================= - BTLE SETTINGS - -----------------------------------------------------------------------*/ - - #define CFG_BLE_TX_POWER_LEVEL 4 /**< in dBm (Valid values are -40, -20, -16, -12, -8, -4, 0, 4) */ - - /*---------------------------- BOND MANAGER ---------------------------*/ - #define CFG_BLE_BOND_FLASH_PAGE_BOND (BLE_FLASH_PAGE_END-1) /**< Flash page used for bond manager bonding information.*/ - #define CFG_BLE_BOND_FLASH_PAGE_SYS_ATTR (BLE_FLASH_PAGE_END-3) /**< Flash page used for bond manager system attribute information. TODO check if we can use BLE_FLASH_PAGE_END-2*/ - #define CFG_BLE_BOND_DELETE_BUTTON_NUM 0 /**< Button to press to delete bond details during init */ - - /*------------------------------ SECURITY -----------------------------*/ - #define CFG_BLE_SEC_PARAM_MITM 0 /**< Man In The Middle protection not required. */ - #define CFG_BLE_SEC_PARAM_IO_CAPABILITIES BLE_GAP_IO_CAPS_NONE /**< No I/O capabilities. */ - #define CFG_BLE_SEC_PARAM_OOB 0 /**< Out Of Band data not available. */ - #define CFG_BLE_SEC_PARAM_MIN_KEY_SIZE 7 /**< Minimum encryption key size. */ - #define CFG_BLE_SEC_PARAM_MAX_KEY_SIZE 16 - - /*--------------------------------- GAP -------------------------------*/ - #define CFG_GAP_APPEARANCE BLE_APPEARANCE_GENERIC_TAG - #define CFG_GAP_LOCAL_NAME "nRF5x" - - #define CFG_GAP_CONNECTION_MIN_INTERVAL_MS 500 /**< Minimum acceptable connection interval */ - #define CFG_GAP_CONNECTION_MAX_INTERVAL_MS 1000 /**< Maximum acceptable connection interval */ - #define CFG_GAP_CONNECTION_SUPERVISION_TIMEOUT_MS 4000 /**< Connection supervisory timeout */ - #define CFG_GAP_CONNECTION_SLAVE_LATENCY 0 /**< Slave Latency in number of connection events. */ - - #define CFG_GAP_ADV_INTERVAL_MS 25 /**< The advertising interval in miliseconds, should be multiply of 0.625 */ - #define CFG_GAP_ADV_TIMEOUT_S 180 /**< The advertising timeout in units of seconds. */ -/*=========================================================================*/ - - -/*========================================================================= - VALIDATION - -----------------------------------------------------------------------*/ - #if CFG_BLE_TX_POWER_LEVEL != -40 && CFG_BLE_TX_POWER_LEVEL != -20 && CFG_BLE_TX_POWER_LEVEL != -16 && CFG_BLE_TX_POWER_LEVEL != -12 && CFG_BLE_TX_POWER_LEVEL != -8 && CFG_BLE_TX_POWER_LEVEL != -4 && CFG_BLE_TX_POWER_LEVEL != 0 && CFG_BLE_TX_POWER_LEVEL != 4 - #error "CFG_BLE_TX_POWER_LEVEL must be -40, -20, -16, -12, -8, -4, 0 or 4" - #endif -/*=========================================================================*/ - -#endif /* _PROJECTCONFIG_H_ */ diff --git a/libraries/fs/fat/ChaN/diskio.cpp b/libraries/fs/fat/ChaN/diskio.cpp index 0ecf295ff8..5bffcd6d89 100644 --- a/libraries/fs/fat/ChaN/diskio.cpp +++ b/libraries/fs/fat/ChaN/diskio.cpp @@ -14,7 +14,7 @@ using namespace mbed; DSTATUS disk_initialize ( BYTE drv /* Physical drive nmuber (0..) */ -) +) { debug_if(FFS_DBG, "disk_initialize on drv [%d]\n", drv); return (DSTATUS)FATFileSystem::_ffs[drv]->disk_initialize(); @@ -22,7 +22,7 @@ DSTATUS disk_initialize ( DSTATUS disk_status ( BYTE drv /* Physical drive nmuber (0..) */ -) +) { debug_if(FFS_DBG, "disk_status on drv [%d]\n", drv); return (DSTATUS)FATFileSystem::_ffs[drv]->disk_status(); diff --git a/libraries/fs/fat/FATFileHandle.cpp b/libraries/fs/fat/FATFileHandle.cpp index 768d585ba7..8c2bf881e4 100644 --- a/libraries/fs/fat/FATFileHandle.cpp +++ b/libraries/fs/fat/FATFileHandle.cpp @@ -38,13 +38,13 @@ int FATFileHandle::close() { ssize_t FATFileHandle::write(const void* buffer, size_t length) { UINT n; FRESULT res = f_write(&_fh, buffer, length, &n); - if (res) { + if (res) { debug_if(FFS_DBG, "f_write() failed: %d", res); return -1; } return n; } - + ssize_t FATFileHandle::read(void* buffer, size_t length) { debug_if(FFS_DBG, "read(%d)\n", length); UINT n; diff --git a/libraries/fs/fat/FATFileSystem.cpp b/libraries/fs/fat/FATFileSystem.cpp index 6e48681987..ee7172c0a8 100644 --- a/libraries/fs/fat/FATFileSystem.cpp +++ b/libraries/fs/fat/FATFileSystem.cpp @@ -69,7 +69,7 @@ FileHandle *FATFileSystem::open(const char* name, int flags) { debug_if(FFS_DBG, "open(%s) on filesystem [%s], drv [%d]\n", name, _name, _fsid); char n[64]; sprintf(n, "%d:/%s", _fsid, name); - + /* POSIX flags -> FatFS open mode */ BYTE openmode; if (flags & O_RDWR) { @@ -86,10 +86,10 @@ FileHandle *FATFileSystem::open(const char* name, int flags) { openmode |= FA_OPEN_ALWAYS; } } - + FIL fh; FRESULT res = f_open(&fh, n, openmode); - if (res) { + if (res) { debug_if(FFS_DBG, "f_open('w') failed: %d\n", res); return NULL; } @@ -98,10 +98,10 @@ FileHandle *FATFileSystem::open(const char* name, int flags) { } return new FATFileHandle(fh); } - + int FATFileSystem::remove(const char *filename) { FRESULT res = f_unlink(filename); - if (res) { + if (res) { debug_if(FFS_DBG, "f_unlink() failed: %d\n", res); return -1; } diff --git a/libraries/fs/sd/SDFileSystem.cpp b/libraries/fs/sd/SDFileSystem.cpp index 54208b66d0..2e7513b13d 100644 --- a/libraries/fs/sd/SDFileSystem.cpp +++ b/libraries/fs/sd/SDFileSystem.cpp @@ -153,13 +153,13 @@ int SDFileSystem::initialise_card() { for (int i = 0; i < 16; i++) { _spi.write(0xFF); } - + // send CMD0, should return with all zeros except IDLE STATE set (bit 0) if (_cmd(0, 0) != R1_IDLE_STATE) { debug("No disk, or could not put SD card in to SPI idle state\n"); return SDCARD_FAIL; } - + // send CMD8 to determine whther it is ver 2.x int r = _cmd8(); if (r == R1_IDLE_STATE) { @@ -181,7 +181,7 @@ int SDFileSystem::initialise_card_v1() { return SDCARD_V1; } } - + debug("Timeout waiting for v1.x card\n"); return SDCARD_FAIL; } @@ -198,7 +198,7 @@ int SDFileSystem::initialise_card_v2() { return SDCARD_V2; } } - + debug("Timeout waiting for v2.x card\n"); return SDCARD_FAIL; } @@ -211,7 +211,7 @@ int SDFileSystem::disk_initialize() { } debug_if(SD_DBG, "init card = %d\n", _is_initialized); _sectors = _sd_sectors(); - + // Set block length to 512 (CMD16) if (_cmd(16, 512) != 0) { debug("Set 512-byte block timed out\n"); @@ -232,7 +232,7 @@ int SDFileSystem::disk_write(const uint8_t *buffer, uint64_t block_number) { if (_cmd(24, block_number * cdv) != 0) { return 1; } - + // send the data block _write(buffer, 512); return 0; @@ -247,7 +247,7 @@ int SDFileSystem::disk_read(uint8_t *buffer, uint64_t block_number) { if (_cmd(17, block_number * cdv) != 0) { return 1; } - + // receive the data _read(buffer, 512); return 0; @@ -269,7 +269,7 @@ uint64_t SDFileSystem::disk_sectors() { return _sectors; } // PRIVATE FUNCTIONS int SDFileSystem::_cmd(int cmd, int arg) { _cs = 0; - + // send a command _spi.write(0x40 | cmd); _spi.write(arg >> 24); @@ -277,7 +277,7 @@ int SDFileSystem::_cmd(int cmd, int arg) { _spi.write(arg >> 8); _spi.write(arg >> 0); _spi.write(0x95); - + // wait for the repsonse (response[7] == 0) for (int i = 0; i < SD_COMMAND_TIMEOUT; i++) { int response = _spi.write(0xFF); @@ -293,7 +293,7 @@ int SDFileSystem::_cmd(int cmd, int arg) { } int SDFileSystem::_cmdx(int cmd, int arg) { _cs = 0; - + // send a command _spi.write(0x40 | cmd); _spi.write(arg >> 24); @@ -301,7 +301,7 @@ int SDFileSystem::_cmdx(int cmd, int arg) { _spi.write(arg >> 8); _spi.write(arg >> 0); _spi.write(0x95); - + // wait for the repsonse (response[7] == 0) for (int i = 0; i < SD_COMMAND_TIMEOUT; i++) { int response = _spi.write(0xFF); @@ -318,7 +318,7 @@ int SDFileSystem::_cmdx(int cmd, int arg) { int SDFileSystem::_cmd58() { _cs = 0; int arg = 0; - + // send a command _spi.write(0x40 | 58); _spi.write(arg >> 24); @@ -326,7 +326,7 @@ int SDFileSystem::_cmd58() { _spi.write(arg >> 8); _spi.write(arg >> 0); _spi.write(0x95); - + // wait for the repsonse (response[7] == 0) for (int i = 0; i < SD_COMMAND_TIMEOUT; i++) { int response = _spi.write(0xFF); @@ -347,7 +347,7 @@ int SDFileSystem::_cmd58() { int SDFileSystem::_cmd8() { _cs = 0; - + // send a command _spi.write(0x40 | 8); // CMD8 _spi.write(0x00); // reserved @@ -355,7 +355,7 @@ int SDFileSystem::_cmd8() { _spi.write(0x01); // 3.3v _spi.write(0xAA); // check pattern _spi.write(0x87); // crc - + // wait for the repsonse (response[7] == 0) for (int i = 0; i < SD_COMMAND_TIMEOUT * 1000; i++) { char response[5]; @@ -376,17 +376,17 @@ int SDFileSystem::_cmd8() { int SDFileSystem::_read(uint8_t *buffer, uint32_t length) { _cs = 0; - + // read until start byte (0xFF) while (_spi.write(0xFF) != 0xFE); - + // read data for (uint32_t i = 0; i < length; i++) { buffer[i] = _spi.write(0xFF); } _spi.write(0xFF); // checksum _spi.write(0xFF); - + _cs = 1; _spi.write(0xFF); return 0; @@ -394,29 +394,29 @@ int SDFileSystem::_read(uint8_t *buffer, uint32_t length) { int SDFileSystem::_write(const uint8_t*buffer, uint32_t length) { _cs = 0; - + // indicate start of block _spi.write(0xFE); - + // write the data for (uint32_t i = 0; i < length; i++) { _spi.write(buffer[i]); } - + // write the checksum _spi.write(0xFF); _spi.write(0xFF); - + // check the response token if ((_spi.write(0xFF) & 0x1F) != 0x05) { _cs = 1; _spi.write(0xFF); return 1; } - + // wait for write to finish while (_spi.write(0xFF) == 0); - + _cs = 1; _spi.write(0xFF); return 0; @@ -440,33 +440,33 @@ uint64_t SDFileSystem::_sd_sectors() { uint32_t block_len, mult, blocknr, capacity; uint32_t hc_c_size; uint64_t blocks; - + // CMD9, Response R2 (R1 byte + 16-byte block read) if (_cmdx(9, 0) != 0) { debug("Didn't get a response from the disk\n"); return 0; } - + uint8_t csd[16]; if (_read(csd, 16) != 0) { debug("Couldn't read csd response from disk\n"); return 0; } - + // csd_structure : csd[127:126] // c_size : csd[73:62] // c_size_mult : csd[49:47] // read_bl_len : csd[83:80] - the *maximum* read block length - + int csd_structure = ext_bits(csd, 127, 126); - + switch (csd_structure) { case 0: cdv = 512; c_size = ext_bits(csd, 73, 62); c_size_mult = ext_bits(csd, 49, 47); read_bl_len = ext_bits(csd, 83, 80); - + block_len = 1 << read_bl_len; mult = 1 << (c_size_mult + 2); blocknr = (c_size + 1) * mult; @@ -474,14 +474,14 @@ uint64_t SDFileSystem::_sd_sectors() { blocks = capacity / 512; debug_if(SD_DBG, "\n\rSDCard\n\rc_size: %d \n\rcapacity: %ld \n\rsectors: %lld\n\r", c_size, capacity, blocks); break; - + case 1: cdv = 1; hc_c_size = ext_bits(csd, 63, 48); blocks = (hc_c_size+1)*1024; debug_if(SD_DBG, "\n\rSDHC Card \n\rhc_c_size: %d\n\rcapacity: %lld \n\rsectors: %lld\n\r", hc_c_size, blocks*512, blocks); break; - + default: debug("CSD struct unsupported\r\n"); return 0; diff --git a/libraries/fs/sd/SDFileSystem.h b/libraries/fs/sd/SDFileSystem.h index 85185546c0..bd74ebf94e 100644 --- a/libraries/fs/sd/SDFileSystem.h +++ b/libraries/fs/sd/SDFileSystem.h @@ -33,7 +33,7 @@ * #include "SDFileSystem.h" * * SDFileSystem sd(p5, p6, p7, p12, "sd"); // mosi, miso, sclk, cs - * + * * int main() { * FILE *fp = fopen("/sd/myfile.txt", "w"); * fprintf(fp, "Hello World!\n"); @@ -68,7 +68,7 @@ protected: int initialise_card(); int initialise_card_v1(); int initialise_card_v2(); - + int _read(uint8_t * buffer, uint32_t length); int _write(const uint8_t *buffer, uint32_t length); uint64_t _sd_sectors(); diff --git a/libraries/mbed/api/BusIn.h b/libraries/mbed/api/BusIn.h index 704282f109..c5ece1df68 100644 --- a/libraries/mbed/api/BusIn.h +++ b/libraries/mbed/api/BusIn.h @@ -51,13 +51,13 @@ public: * An integer with each bit corresponding to the value read from the associated DigitalIn pin */ int read(); - + /** Set the input pin mode * * @param mode PullUp, PullDown, PullNone */ void mode(PinMode pull); - + #ifdef MBED_OPERATORS /** A shorthand for read() */ @@ -66,6 +66,11 @@ public: protected: DigitalIn* _pin[16]; + + /* disallow copy constructor and assignment operators */ +private: + BusIn(const BusIn&); + BusIn & operator = (const BusIn&); }; } // namespace mbed diff --git a/libraries/mbed/api/BusInOut.h b/libraries/mbed/api/BusInOut.h index 245fb411bd..63dfda1606 100644 --- a/libraries/mbed/api/BusInOut.h +++ b/libraries/mbed/api/BusInOut.h @@ -86,6 +86,11 @@ public: protected: DigitalInOut* _pin[16]; + + /* disallow copy constructor and assignment operators */ +private: + BusInOut(const BusInOut&); + BusInOut & operator = (const BusInOut&); }; } // namespace mbed diff --git a/libraries/mbed/api/BusOut.h b/libraries/mbed/api/BusOut.h index f76c4a5773..9a6608e89e 100644 --- a/libraries/mbed/api/BusOut.h +++ b/libraries/mbed/api/BusOut.h @@ -69,6 +69,11 @@ public: protected: DigitalOut* _pin[16]; + + /* disallow copy constructor and assignment operators */ +private: + BusOut(const BusOut&); + BusOut & operator = (const BusOut&); }; } // namespace mbed diff --git a/libraries/mbed/api/CAN.h b/libraries/mbed/api/CAN.h index f494e77523..db613f6616 100644 --- a/libraries/mbed/api/CAN.h +++ b/libraries/mbed/api/CAN.h @@ -33,7 +33,7 @@ class CANMessage : public CAN_Message { public: /** Creates empty CAN message. */ - CANMessage() { + CANMessage() : CAN_Message() { len = 8; type = CANData; format = CANStandard; @@ -159,17 +159,17 @@ public: GlobalTest, SilentTest }; - + /** Change CAN operation to the specified mode * * @param mode The new operation mode (CAN::Normal, CAN::Silent, CAN::LocalTest, CAN::GlobalTest, CAN::SilentTest) * * @returns * 0 if mode change failed or unsupported, - * 1 if mode change was successful + * 1 if mode change was successful */ int mode(Mode mode); - + /** Filter out incomming messages * * @param id the id to filter on @@ -182,7 +182,7 @@ public: * new filter handle if successful */ int filter(unsigned int id, unsigned int mask, CANFormat format = CANAny, int handle = 0); - + /** Returns number of read errors to detect read overflow errors. */ unsigned char rderror(); @@ -202,7 +202,7 @@ public: BeIrq, IdIrq }; - + /** Attach a function to call whenever a CAN frame received interrupt is * generated. * diff --git a/libraries/mbed/api/CallChain.h b/libraries/mbed/api/CallChain.h index a48685b345..ebb796a3cd 100644 --- a/libraries/mbed/api/CallChain.h +++ b/libraries/mbed/api/CallChain.h @@ -56,7 +56,7 @@ namespace mbed { * } * @endcode */ - + typedef FunctionPointer* pFunctionPointer_t; class CallChain { @@ -64,7 +64,7 @@ public: /** Create an empty chain * * @param size (optional) Initial size of the chain - */ + */ CallChain(int size = 4); virtual ~CallChain(); @@ -98,7 +98,7 @@ public: * The function object created for 'function' */ pFunctionPointer_t add_front(void (*function)(void)); - + /** Add a function at the beginning of the chain * * @param tptr pointer to the object to call the member function on @@ -150,7 +150,7 @@ public: /** Call all the functions in the chain in sequence */ void call(); - + #ifdef MBED_OPERATORS void operator ()(void) { call(); @@ -168,6 +168,11 @@ private: pFunctionPointer_t* _chain; int _size; int _elements; + + /* disallow copy constructor and assignment operators */ +private: + CallChain(const CallChain&); + CallChain & operator = (const CallChain&); }; } // namespace mbed diff --git a/libraries/mbed/api/DigitalIn.h b/libraries/mbed/api/DigitalIn.h index ac6812afff..d81038b8cf 100644 --- a/libraries/mbed/api/DigitalIn.h +++ b/libraries/mbed/api/DigitalIn.h @@ -50,7 +50,7 @@ public: * * @param pin DigitalIn pin to connect to */ - DigitalIn(PinName pin) { + DigitalIn(PinName pin) : gpio() { gpio_init_in(&gpio, pin); } @@ -59,7 +59,7 @@ public: * @param pin DigitalIn pin to connect to * @param mode the initial mode of the pin */ - DigitalIn(PinName pin, PinMode mode) { + DigitalIn(PinName pin, PinMode mode) : gpio() { gpio_init_in_ex(&gpio, pin, mode); } /** Read the input, represented as 0 or 1 (int) diff --git a/libraries/mbed/api/DigitalInOut.h b/libraries/mbed/api/DigitalInOut.h index 6778188d34..5d9221b5dc 100644 --- a/libraries/mbed/api/DigitalInOut.h +++ b/libraries/mbed/api/DigitalInOut.h @@ -31,7 +31,7 @@ public: * * @param pin DigitalInOut pin to connect to */ - DigitalInOut(PinName pin) { + DigitalInOut(PinName pin) : gpio() { gpio_init_in(&gpio, pin); } @@ -42,7 +42,7 @@ public: * @param mode the initial mode of the pin * @param value the initial value of the pin if is an output */ - DigitalInOut(PinName pin, PinDirection direction, PinMode mode, int value) { + DigitalInOut(PinName pin, PinDirection direction, PinMode mode, int value) : gpio() { gpio_init_inout(&gpio, pin, direction, mode, value); } diff --git a/libraries/mbed/api/DigitalOut.h b/libraries/mbed/api/DigitalOut.h index 5ed609765a..0281770ff8 100644 --- a/libraries/mbed/api/DigitalOut.h +++ b/libraries/mbed/api/DigitalOut.h @@ -45,7 +45,7 @@ public: * * @param pin DigitalOut pin to connect to */ - DigitalOut(PinName pin) { + DigitalOut(PinName pin) : gpio() { gpio_init_out(&gpio, pin); } @@ -54,7 +54,7 @@ public: * @param pin DigitalOut pin to connect to * @param value the initial pin value */ - DigitalOut(PinName pin, int value){ + DigitalOut(PinName pin, int value) : gpio() { gpio_init_out_ex(&gpio, pin, value); } diff --git a/libraries/mbed/api/FileBase.h b/libraries/mbed/api/FileBase.h index 86df2d1bc9..88f87842c9 100644 --- a/libraries/mbed/api/FileBase.h +++ b/libraries/mbed/api/FileBase.h @@ -68,6 +68,11 @@ protected: FileBase *_next; const char *_name; PathType _path_type; + + /* disallow copy constructor and assignment operators */ +private: + FileBase(const FileBase&); + FileBase & operator = (const FileBase&); }; } // namespace mbed diff --git a/libraries/mbed/api/FunctionPointer.h b/libraries/mbed/api/FunctionPointer.h index ae4d431c19..1ae4922839 100644 --- a/libraries/mbed/api/FunctionPointer.h +++ b/libraries/mbed/api/FunctionPointer.h @@ -83,10 +83,10 @@ private: (o->*m)(); } - void (*_function)(void); // static function pointer - 0 if none attached - void *_object; // object this pointer - 0 if none attached - char _member[16]; // raw member function pointer storage - converted back by registered _membercaller - void (*_membercaller)(void*, char*); // registered membercaller function to convert back and call _member on _object + void (*_function)(void); // static function pointer - 0 if none attached + void *_object; // object this pointer - 0 if none attached + char _member[16]; // raw member function pointer storage - converted back by registered _membercaller + void (*_membercaller)(void*, char*); // registered membercaller function to convert back and call _member on _object }; } // namespace mbed diff --git a/libraries/mbed/api/InterruptManager.h b/libraries/mbed/api/InterruptManager.h index 6f3fa49c5d..4959a64699 100644 --- a/libraries/mbed/api/InterruptManager.h +++ b/libraries/mbed/api/InterruptManager.h @@ -13,19 +13,19 @@ namespace mbed { * @code * #include "InterruptManager.h" * #include "mbed.h" - * + * * Ticker flipper; * DigitalOut led1(LED1); * DigitalOut led2(LED2); - * + * * void flip(void) { * led1 = !led1; * } - * + * * void handler(void) { * led2 = !led1; * } - * + * * int main() { * led1 = led2 = 0; * flipper.attach(&flip, 1.0); @@ -42,7 +42,7 @@ public: /** Destroy the current instance of the interrupt manager */ static void destroy(); - + /** Add a handler for an interrupt at the end of the handler list * * @param function the handler to add diff --git a/libraries/mbed/api/SPI.h b/libraries/mbed/api/SPI.h index 9d9163919e..7fa1a6be8e 100644 --- a/libraries/mbed/api/SPI.h +++ b/libraries/mbed/api/SPI.h @@ -92,6 +92,10 @@ public: */ virtual int write(int value); +public: + virtual ~SPI() { + } + protected: spi_t _spi; diff --git a/libraries/mbed/api/Serial.h b/libraries/mbed/api/Serial.h index d9fb6954f7..edd762d018 100644 --- a/libraries/mbed/api/Serial.h +++ b/libraries/mbed/api/Serial.h @@ -59,7 +59,7 @@ public: protected: virtual int _getc(); - virtual int _putc(int c); + virtual int _putc(int c); }; } // namespace mbed diff --git a/libraries/mbed/api/SerialBase.h b/libraries/mbed/api/SerialBase.h index 57705f3262..07bc4b4631 100644 --- a/libraries/mbed/api/SerialBase.h +++ b/libraries/mbed/api/SerialBase.h @@ -106,11 +106,11 @@ public: /** Generate a break condition on the serial line */ void send_break(); - + #if DEVICE_SERIAL_FC /** Set the flow control type on the serial port * - * @param type the flow control type (Disabled, RTS, CTS, RTSCTS) + * @param type the flow control type (Disabled, RTS, CTS, RTSCTS) * @param flow1 the first flow control pin (RTS for RTS or RTSCTS, CTS for CTS) * @param flow2 the second flow control pin (CTS for RTSCTS) */ @@ -121,7 +121,9 @@ public: protected: SerialBase(PinName tx, PinName rx); - + virtual ~SerialBase() { + } + int _base_getc(); int _base_putc(int c); diff --git a/libraries/mbed/api/Stream.h b/libraries/mbed/api/Stream.h index 8b1a56879b..637fb45961 100644 --- a/libraries/mbed/api/Stream.h +++ b/libraries/mbed/api/Stream.h @@ -49,6 +49,11 @@ protected: virtual int _getc() = 0; std::FILE *_file; + + /* disallow copy constructor and assignment operators */ +private: + Stream(const Stream&); + Stream & operator = (const Stream&); }; } // namespace mbed diff --git a/libraries/mbed/api/mbed.h b/libraries/mbed/api/mbed.h index f2648e56db..ca208ef44e 100644 --- a/libraries/mbed/api/mbed.h +++ b/libraries/mbed/api/mbed.h @@ -16,7 +16,7 @@ #ifndef MBED_H #define MBED_H -#define MBED_LIBRARY_VERSION 83 +#define MBED_LIBRARY_VERSION 84 #include "platform.h" diff --git a/libraries/mbed/common/CAN.cpp b/libraries/mbed/common/CAN.cpp index b74c8d73ba..407e00bf17 100644 --- a/libraries/mbed/common/CAN.cpp +++ b/libraries/mbed/common/CAN.cpp @@ -21,7 +21,7 @@ namespace mbed { -CAN::CAN(PinName rd, PinName td) { +CAN::CAN(PinName rd, PinName td) : _can(), _irq() { can_init(&_can, rd, td); can_irq_init(&_can, (&CAN::_irq_handler), (uint32_t)this); } diff --git a/libraries/mbed/common/CallChain.cpp b/libraries/mbed/common/CallChain.cpp index d91bdbe8a8..e950903059 100644 --- a/libraries/mbed/common/CallChain.cpp +++ b/libraries/mbed/common/CallChain.cpp @@ -3,13 +3,13 @@ namespace mbed { -CallChain::CallChain(int size) : _size(size), _elements(0) { +CallChain::CallChain(int size) : _chain(), _size(size), _elements(0) { _chain = new pFunctionPointer_t[size](); } CallChain::~CallChain() { clear(); - delete _chain; + delete _chain; } pFunctionPointer_t CallChain::add(void (*function)(void)) { diff --git a/libraries/mbed/common/FileBase.cpp b/libraries/mbed/common/FileBase.cpp index bf0a91e189..fce113d88c 100644 --- a/libraries/mbed/common/FileBase.cpp +++ b/libraries/mbed/common/FileBase.cpp @@ -19,10 +19,9 @@ namespace mbed { FileBase *FileBase::_head = NULL; -FileBase::FileBase(const char *name, PathType t) { - _name = name; - _path_type = t; - +FileBase::FileBase(const char *name, PathType t) : _next(NULL), + _name(name), + _path_type(t) { if (name != NULL) { // put this object at head of the list _next = _head; diff --git a/libraries/mbed/common/FileSystemLike.cpp b/libraries/mbed/common/FileSystemLike.cpp index 87ff3cc4f5..df5d86da81 100644 --- a/libraries/mbed/common/FileSystemLike.cpp +++ b/libraries/mbed/common/FileSystemLike.cpp @@ -29,8 +29,7 @@ public: off_t n; struct dirent cur_entry; - BaseDirHandle() { - n = 0; + BaseDirHandle() : n(0), cur_entry() { } virtual int closedir() { diff --git a/libraries/mbed/common/FunctionPointer.cpp b/libraries/mbed/common/FunctionPointer.cpp index 04e7ca7c12..7c43916c7e 100644 --- a/libraries/mbed/common/FunctionPointer.cpp +++ b/libraries/mbed/common/FunctionPointer.cpp @@ -17,7 +17,9 @@ namespace mbed { -FunctionPointer::FunctionPointer(void (*function)(void)) { +FunctionPointer::FunctionPointer(void (*function)(void)): _function(), + _object(), + _membercaller() { attach(function); } diff --git a/libraries/mbed/common/I2C.cpp b/libraries/mbed/common/I2C.cpp index 8d4e48f0ac..fb1d03048e 100644 --- a/libraries/mbed/common/I2C.cpp +++ b/libraries/mbed/common/I2C.cpp @@ -21,10 +21,9 @@ namespace mbed { I2C *I2C::_owner = NULL; -I2C::I2C(PinName sda, PinName scl) { +I2C::I2C(PinName sda, PinName scl) : _i2c(), _hz(100000) { // The init function also set the frequency to 100000 i2c_init(&_i2c, sda, scl); - _hz = 100000; // Used to avoid unnecessary frequency updates _owner = this; diff --git a/libraries/mbed/common/I2CSlave.cpp b/libraries/mbed/common/I2CSlave.cpp index 3db7f52589..43940939c4 100644 --- a/libraries/mbed/common/I2CSlave.cpp +++ b/libraries/mbed/common/I2CSlave.cpp @@ -19,7 +19,7 @@ namespace mbed { -I2CSlave::I2CSlave(PinName sda, PinName scl) { +I2CSlave::I2CSlave(PinName sda, PinName scl) : _i2c() { i2c_init(&_i2c, sda, scl); i2c_frequency(&_i2c, 100000); i2c_slave_mode(&_i2c, 1); diff --git a/libraries/mbed/common/InterruptIn.cpp b/libraries/mbed/common/InterruptIn.cpp index 768b517635..8692124c14 100644 --- a/libraries/mbed/common/InterruptIn.cpp +++ b/libraries/mbed/common/InterruptIn.cpp @@ -19,7 +19,10 @@ namespace mbed { -InterruptIn::InterruptIn(PinName pin) { +InterruptIn::InterruptIn(PinName pin) : gpio(), + gpio_irq(), + _rise(), + _fall() { gpio_irq_init(&gpio_irq, pin, (&InterruptIn::_irq_handler), (uint32_t)this); gpio_init_in(&gpio, pin); } diff --git a/libraries/mbed/common/InterruptManager.cpp b/libraries/mbed/common/InterruptManager.cpp index 7bf41d15b5..6fe31f6531 100644 --- a/libraries/mbed/common/InterruptManager.cpp +++ b/libraries/mbed/common/InterruptManager.cpp @@ -58,7 +58,7 @@ pFunctionPointer_t InterruptManager::add_common(void (*function)(void), IRQn_Typ bool InterruptManager::remove_handler(pFunctionPointer_t handler, IRQn_Type irq) { int irq_pos = get_irq_index(irq); - + if (NULL == _chains[irq_pos]) return false; if (!_chains[irq_pos]->remove(handler)) diff --git a/libraries/mbed/common/LocalFileSystem.cpp b/libraries/mbed/common/LocalFileSystem.cpp index 691eb1f22e..9505d91a9a 100644 --- a/libraries/mbed/common/LocalFileSystem.cpp +++ b/libraries/mbed/common/LocalFileSystem.cpp @@ -107,9 +107,7 @@ FILEHANDLE local_file_open(const char* name, int flags) { return fh; } -LocalFileHandle::LocalFileHandle(FILEHANDLE fh) { - _fh = fh; - pos = 0; +LocalFileHandle::LocalFileHandle(FILEHANDLE fh) : _fh(fh), pos(0) { } int LocalFileHandle::close() { @@ -163,8 +161,7 @@ public: struct dirent cur_entry; XFINFO info; - LocalDirHandle() { - info.fileID = 0; + LocalDirHandle() : cur_entry(), info() { } virtual int closedir() { diff --git a/libraries/mbed/common/SPI.cpp b/libraries/mbed/common/SPI.cpp index e8b2e1dcec..4bca2b69ce 100644 --- a/libraries/mbed/common/SPI.cpp +++ b/libraries/mbed/common/SPI.cpp @@ -19,11 +19,12 @@ namespace mbed { -SPI::SPI(PinName mosi, PinName miso, PinName sclk, PinName _unused) { +SPI::SPI(PinName mosi, PinName miso, PinName sclk, PinName _unused) : + _spi(), + _bits(8), + _mode(0), + _hz(1000000) { spi_init(&_spi, mosi, miso, sclk, NC); - _bits = 8; - _mode = 0; - _hz = 1000000; spi_format(&_spi, _bits, _mode, 0); spi_frequency(&_spi, _hz); } diff --git a/libraries/mbed/common/SPISlave.cpp b/libraries/mbed/common/SPISlave.cpp index 86c63333ec..5e503165b2 100644 --- a/libraries/mbed/common/SPISlave.cpp +++ b/libraries/mbed/common/SPISlave.cpp @@ -19,11 +19,13 @@ namespace mbed { -SPISlave::SPISlave(PinName mosi, PinName miso, PinName sclk, PinName ssel) { +SPISlave::SPISlave(PinName mosi, PinName miso, PinName sclk, PinName ssel) : + _spi(), + _bits(8), + _mode(0), + _hz(1000000) + { spi_init(&_spi, mosi, miso, sclk, ssel); - _bits = 8; - _mode = 0; - _hz = 1000000; spi_format(&_spi, _bits, _mode, 1); spi_frequency(&_spi, _hz); } diff --git a/libraries/mbed/common/SerialBase.cpp b/libraries/mbed/common/SerialBase.cpp index 926a910027..68cf7c381c 100644 --- a/libraries/mbed/common/SerialBase.cpp +++ b/libraries/mbed/common/SerialBase.cpp @@ -20,9 +20,8 @@ namespace mbed { -SerialBase::SerialBase(PinName tx, PinName rx) { +SerialBase::SerialBase(PinName tx, PinName rx) : _serial(), _baud(9600) { serial_init(&_serial, tx, rx); - _baud = 9600; serial_irq_handler(&_serial, SerialBase::_irq_handler, (uint32_t)this); } @@ -71,7 +70,7 @@ void SerialBase::send_break() { // Wait for 1.5 frames before clearing the break condition // This will have different effects on our platforms, but should // ensure that we keep the break active for at least one frame. - // We consider a full frame (1 start bit + 8 data bits bits + + // We consider a full frame (1 start bit + 8 data bits bits + // 1 parity bit + 2 stop bits = 12 bits) for computation. // One bit time (in us) = 1000000/_baud // Twelve bits: 12000000/baud delay @@ -81,23 +80,23 @@ void SerialBase::send_break() { serial_break_clear(&_serial); } -#ifdef DEVICE_SERIAL_FC +#if DEVICE_SERIAL_FC void SerialBase::set_flow_control(Flow type, PinName flow1, PinName flow2) { FlowControl flow_type = (FlowControl)type; switch(type) { case RTS: serial_set_flow_control(&_serial, flow_type, flow1, NC); break; - + case CTS: serial_set_flow_control(&_serial, flow_type, NC, flow1); break; - + case RTSCTS: case Disabled: serial_set_flow_control(&_serial, flow_type, flow1, flow2); break; - + default: break; } diff --git a/libraries/mbed/common/Stream.cpp b/libraries/mbed/common/Stream.cpp index a0cc8b891e..8447238dd2 100644 --- a/libraries/mbed/common/Stream.cpp +++ b/libraries/mbed/common/Stream.cpp @@ -19,7 +19,7 @@ namespace mbed { -Stream::Stream(const char *name) : FileLike(name) { +Stream::Stream(const char *name) : FileLike(name), _file(NULL) { /* open ourselves */ char buf[12]; /* :0x12345678 + null byte */ std::sprintf(buf, ":%p", this); diff --git a/libraries/mbed/common/Timer.cpp b/libraries/mbed/common/Timer.cpp index 8581e256f9..d4ed133125 100644 --- a/libraries/mbed/common/Timer.cpp +++ b/libraries/mbed/common/Timer.cpp @@ -18,7 +18,7 @@ namespace mbed { -Timer::Timer() { +Timer::Timer() : _running(), _start(), _time() { reset(); } diff --git a/libraries/mbed/common/TimerEvent.cpp b/libraries/mbed/common/TimerEvent.cpp index a4057b6f7f..6af80dd09a 100644 --- a/libraries/mbed/common/TimerEvent.cpp +++ b/libraries/mbed/common/TimerEvent.cpp @@ -20,7 +20,7 @@ namespace mbed { -TimerEvent::TimerEvent() { +TimerEvent::TimerEvent() : event() { us_ticker_set_handler((&TimerEvent::irq)); } diff --git a/libraries/mbed/common/board.c b/libraries/mbed/common/board.c index ab24b09ec0..a9e749b811 100644 --- a/libraries/mbed/common/board.c +++ b/libraries/mbed/common/board.c @@ -30,7 +30,7 @@ WEAK void mbed_die(void) { gpio_t led_3; gpio_init_out(&led_3, LED3); gpio_t led_4; gpio_init_out(&led_4, LED4); #endif - + while (1) { #if (DEVICE_ERROR_RED == 1) gpio_write(&led_red, 1); @@ -41,7 +41,7 @@ WEAK void mbed_die(void) { gpio_write(&led_3, 0); gpio_write(&led_4, 1); #endif - + wait_ms(150); #if (DEVICE_ERROR_RED == 1) @@ -53,7 +53,7 @@ WEAK void mbed_die(void) { gpio_write(&led_3, 1); gpio_write(&led_4, 0); #endif - + wait_ms(150); } } diff --git a/libraries/mbed/common/gpio.c b/libraries/mbed/common/gpio.c index b9dc4b9f9c..3839e8bb2d 100644 --- a/libraries/mbed/common/gpio.c +++ b/libraries/mbed/common/gpio.c @@ -17,13 +17,13 @@ static inline void _gpio_init_in(gpio_t* gpio, PinName pin, PinMode mode) { - gpio_init(gpio, pin); - if (pin != NC) { + gpio_init(gpio, pin); + if (pin != NC) { gpio_dir(gpio, PIN_INPUT); gpio_mode(gpio, mode); } } - + static inline void _gpio_init_out(gpio_t* gpio, PinName pin, PinMode mode, int value) { gpio_init(gpio, pin); diff --git a/libraries/mbed/common/mbed_interface.c b/libraries/mbed/common/mbed_interface.c index 01c734c661..0055843e55 100644 --- a/libraries/mbed/common/mbed_interface.c +++ b/libraries/mbed/common/mbed_interface.c @@ -88,7 +88,7 @@ WEAK void mbed_mac_address(char *mac) { #if DEVICE_SEMIHOST char uid[DEVICE_ID_LENGTH + 1]; int i; - + // if we have a UID, extract the MAC if (mbed_interface_uid(uid) == 0) { char *p = uid; diff --git a/libraries/mbed/common/pinmap_common.c b/libraries/mbed/common/pinmap_common.c index eef617fd45..10b981e784 100644 --- a/libraries/mbed/common/pinmap_common.c +++ b/libraries/mbed/common/pinmap_common.c @@ -22,7 +22,7 @@ void pinmap_pinout(PinName pin, const PinMap *map) { while (map->pin != NC) { if (map->pin == pin) { pin_function(pin, map->function); - + pin_mode(pin, PullNone); return; } diff --git a/libraries/mbed/common/retarget.cpp b/libraries/mbed/common/retarget.cpp index 35a815916c..168d319a97 100644 --- a/libraries/mbed/common/retarget.cpp +++ b/libraries/mbed/common/retarget.cpp @@ -126,7 +126,7 @@ extern "C" FILEHANDLE PREFIX(_open)(const char* name, int openmode) { // This is the workaround that the microlib author suggested us static int n = 0; if (!std::strcmp(name, ":tt")) return n++; - + #else /* Use the posix convention that stdin,out,err are filehandles 0,1,2. */ @@ -141,7 +141,7 @@ extern "C" FILEHANDLE PREFIX(_open)(const char* name, int openmode) { return 2; } #endif - + // find the first empty slot in filehandles unsigned int fh_i; for (fh_i = 0; fh_i < sizeof(filehandles)/sizeof(*filehandles); fh_i++) { @@ -466,7 +466,7 @@ extern "C" caddr_t _sbrk(int incr) { errno = ENOMEM; return (caddr_t)-1; } - + heap = new_heap; return (caddr_t) prev_heap; } diff --git a/libraries/mbed/common/rtc_time.c b/libraries/mbed/common/rtc_time.c index d0114e2f51..0405e9adc3 100644 --- a/libraries/mbed/common/rtc_time.c +++ b/libraries/mbed/common/rtc_time.c @@ -21,7 +21,7 @@ #ifdef __cplusplus extern "C" { -#endif +#endif #if defined (__ICCARM__) time_t __time32(time_t *timer) #else @@ -60,4 +60,4 @@ clock_t clock() { #ifdef __cplusplus } -#endif +#endif diff --git a/libraries/mbed/common/us_ticker_api.c b/libraries/mbed/common/us_ticker_api.c index 5b5d780636..434f705938 100644 --- a/libraries/mbed/common/us_ticker_api.c +++ b/libraries/mbed/common/us_ticker_api.c @@ -22,13 +22,13 @@ static ticker_event_t *head = NULL; void us_ticker_set_handler(ticker_event_handler handler) { us_ticker_init(); - + event_handler = handler; } void us_ticker_irq_handler(void) { us_ticker_clear_interrupt(); - + /* Go through all the pending TimerEvents */ while (1) { if (head == NULL) { @@ -36,7 +36,7 @@ void us_ticker_irq_handler(void) { us_ticker_disable_interrupt(); return; } - + if ((int)(head->timestamp - us_ticker_read()) <= 0) { // This event was in the past: // point to the following one and execute its handler @@ -57,11 +57,11 @@ void us_ticker_irq_handler(void) { void us_ticker_insert_event(ticker_event_t *obj, unsigned int timestamp, uint32_t id) { /* disable interrupts for the duration of the function */ __disable_irq(); - + // initialise our data obj->timestamp = timestamp; obj->id = id; - + /* Go through the list until we either reach the end, or find an element this should come before (which is possibly the head). */ @@ -84,13 +84,13 @@ void us_ticker_insert_event(ticker_event_t *obj, unsigned int timestamp, uint32_ } /* if we're at the end p will be NULL, which is correct */ obj->next = p; - + __enable_irq(); } void us_ticker_remove_event(ticker_event_t *obj) { __disable_irq(); - + // remove this object from the list if (head == obj) { // first in the list, so just drop me @@ -109,6 +109,6 @@ void us_ticker_remove_event(ticker_event_t *obj) { p = p->next; } } - + __enable_irq(); } diff --git a/libraries/mbed/targets/cmsis/TARGET_Freescale/TARGET_K64F/TOOLCHAIN_GCC_ARM/K64FN1M0xxx12.ld b/libraries/mbed/targets/cmsis/TARGET_Freescale/TARGET_K64F/TOOLCHAIN_GCC_ARM/K64FN1M0xxx12.ld new file mode 100644 index 0000000000..f6839ccde3 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_Freescale/TARGET_K64F/TOOLCHAIN_GCC_ARM/K64FN1M0xxx12.ld @@ -0,0 +1,164 @@ +/* + * K64F ARM GCC linker script file + */ + +MEMORY +{ + VECTORS (rx) : ORIGIN = 0x00000000, LENGTH = 0x00000400 + FLASH_PROTECTION (rx) : ORIGIN = 0x00000400, LENGTH = 0x00000010 + FLASH (rx) : ORIGIN = 0x00000410, LENGTH = 0x00100000 - 0x00000410 + RAM (rwx) : ORIGIN = 0x1FFF0400, LENGTH = 0x00040000 - 0x00000400 +} + +/* Linker script to place sections and symbol values. Should be used together + * with other linker script that defines memory regions FLASH and RAM. + * It references following symbols, which must be defined in code: + * _reset_init : Entry of reset handler + * + * It defines following symbols, which code can use without definition: + * __exidx_start + * __exidx_end + * __etext + * __data_start__ + * __preinit_array_start + * __preinit_array_end + * __init_array_start + * __init_array_end + * __fini_array_start + * __fini_array_end + * __data_end__ + * __bss_start__ + * __bss_end__ + * __end__ + * end + * __HeapLimit + * __StackLimit + * __StackTop + * __stack + */ +ENTRY(Reset_Handler) + +SECTIONS +{ + .isr_vector : + { + __vector_table = .; + KEEP(*(.vector_table)) + *(.text.Reset_Handler) + *(.text.System_Init) + . = ALIGN(4); + } > VECTORS + + .flash_protect : + { + KEEP(*(.kinetis_flash_config_field)) + . = ALIGN(4); + } > FLASH_PROTECTION + + .text : + { + *(.text*) + + KEEP(*(.init)) + KEEP(*(.fini)) + + /* .ctors */ + *crtbegin.o(.ctors) + *crtbegin?.o(.ctors) + *(EXCLUDE_FILE(*crtend?.o *crtend.o) .ctors) + *(SORT(.ctors.*)) + *(.ctors) + + /* .dtors */ + *crtbegin.o(.dtors) + *crtbegin?.o(.dtors) + *(EXCLUDE_FILE(*crtend?.o *crtend.o) .dtors) + *(SORT(.dtors.*)) + *(.dtors) + + *(.rodata*) + + KEEP(*(.eh_frame*)) + } > FLASH + + .ARM.extab : + { + *(.ARM.extab* .gnu.linkonce.armextab.*) + } > FLASH + + __exidx_start = .; + .ARM.exidx : + { + *(.ARM.exidx* .gnu.linkonce.armexidx.*) + } > FLASH + __exidx_end = .; + + __etext = .; + + .data : AT (__etext) + { + __data_start__ = .; + *(vtable) + *(.data*) + + . = ALIGN(4); + /* preinit data */ + PROVIDE_HIDDEN (__preinit_array_start = .); + KEEP(*(.preinit_array)) + PROVIDE_HIDDEN (__preinit_array_end = .); + + . = ALIGN(4); + /* init data */ + PROVIDE_HIDDEN (__init_array_start = .); + KEEP(*(SORT(.init_array.*))) + KEEP(*(.init_array)) + PROVIDE_HIDDEN (__init_array_end = .); + + + . = ALIGN(4); + /* finit data */ + PROVIDE_HIDDEN (__fini_array_start = .); + KEEP(*(SORT(.fini_array.*))) + KEEP(*(.fini_array)) + PROVIDE_HIDDEN (__fini_array_end = .); + + . = ALIGN(4); + /* All data end */ + __data_end__ = .; + + } > RAM + + .bss : + { + __bss_start__ = .; + *(.bss*) + *(COMMON) + __bss_end__ = .; + } > RAM + + .heap : + { + __end__ = .; + end = __end__; + *(.heap*) + __HeapLimit = .; + } > RAM + + /* .stack_dummy section doesn't contains any symbols. It is only + * used for linker to calculate size of stack sections, and assign + * values to stack symbols later */ + .stack_dummy : + { + *(.stack) + } > RAM + + /* Set stack top to end of RAM, and stack limit move down by + * size of stack_dummy section */ + __StackTop = ORIGIN(RAM) + LENGTH(RAM); + __StackLimit = __StackTop - SIZEOF(.stack_dummy); + PROVIDE(__stack = __StackTop); + + /* Check if data + heap + stack exceeds RAM limit */ + ASSERT(__StackLimit >= __HeapLimit, "region RAM overflowed with stack") +} + diff --git a/libraries/mbed/targets/cmsis/TARGET_Freescale/TARGET_K64F/TOOLCHAIN_GCC_ARM/startup_MK64F12.s b/libraries/mbed/targets/cmsis/TARGET_Freescale/TARGET_K64F/TOOLCHAIN_GCC_ARM/startup_MK64F12.s new file mode 100644 index 0000000000..20021433c4 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_Freescale/TARGET_K64F/TOOLCHAIN_GCC_ARM/startup_MK64F12.s @@ -0,0 +1,357 @@ +/* K64F startup ARM GCC + * Purpose: startup file for Cortex-M4 devices. Should use with + * GCC for ARM Embedded Processors + * Version: V1.2 + * Date: 15 Nov 2011 + * + * Copyright (c) 2011, ARM Limited + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the ARM Limited nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ARM LIMITED BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + .syntax unified + .arch armv7-m + +/* Memory Model + The HEAP starts at the end of the DATA section and grows upward. + + The STACK starts at the end of the RAM and grows downward. + + The HEAP and stack STACK are only checked at compile time: + (DATA_SIZE + HEAP_SIZE + STACK_SIZE) < RAM_SIZE + + This is just a check for the bare minimum for the Heap+Stack area before + aborting compilation, it is not the run time limit: + Heap_Size + Stack_Size = 0x80 + 0x80 = 0x100 + */ + .section .stack + .align 3 +#ifdef __STACK_SIZE + .equ Stack_Size, __STACK_SIZE +#else + .equ Stack_Size, 0x400 +#endif + .globl __StackTop + .globl __StackLimit +__StackLimit: + .space Stack_Size + .size __StackLimit, . - __StackLimit +__StackTop: + .size __StackTop, . - __StackTop + + .section .heap + .align 3 +#ifdef __HEAP_SIZE + .equ Heap_Size, __HEAP_SIZE +#else + .equ Heap_Size, 0x80 +#endif + .globl __HeapBase + .globl __HeapLimit +__HeapBase: + .space Heap_Size + .size __HeapBase, . - __HeapBase +__HeapLimit: + .size __HeapLimit, . - __HeapLimit + + .section .vector_table,"a",%progbits + .align 2 + .globl __isr_vector +__isr_vector: + .long __StackTop /* Top of Stack */ + .long Reset_Handler /* Reset Handler */ + .long NMI_Handler /* NMI Handler */ + .long HardFault_Handler /* Hard Fault Handler */ + .long MemManage_Handler /* MPU Fault Handler */ + .long BusFault_Handler /* Bus Fault Handler */ + .long UsageFault_Handler /* Usage Fault Handler */ + .long 0 /* Reserved */ + .long 0 /* Reserved */ + .long 0 /* Reserved */ + .long 0 /* Reserved */ + .long SVC_Handler /* SVCall Handler */ + .long DebugMon_Handler /* Debug Monitor Handler */ + .long 0 /* Reserved */ + .long PendSV_Handler /* PendSV Handler */ + .long SysTick_Handler /* SysTick Handler */ + + /* External Interrupts */ + .long DMA0_IRQHandler /* DMA Channel 0 Transfer Complete */ + .long DMA1_IRQHandler /* DMA Channel 1 Transfer Complete */ + .long DMA2_IRQHandler /* DMA Channel 2 Transfer Complete */ + .long DMA3_IRQHandler /* DMA Channel 3 Transfer Complete */ + .long DMA4_IRQHandler /* DMA Channel 4 Transfer Complete */ + .long DMA5_IRQHandler /* DMA Channel 5 Transfer Complete */ + .long DMA6_IRQHandler /* DMA Channel 6 Transfer Complete */ + .long DMA7_IRQHandler /* DMA Channel 7 Transfer Complete */ + .long DMA8_IRQHandler /* DMA Channel 8 Transfer Complete */ + .long DMA9_IRQHandler /* DMA Channel 9 Transfer Complete */ + .long DMA10_IRQHandler /* DMA Channel 10 Transfer Complete */ + .long DMA11_IRQHandler /* DMA Channel 11 Transfer Complete */ + .long DMA12_IRQHandler /* DMA Channel 12 Transfer Complete */ + .long DMA13_IRQHandler /* DMA Channel 13 Transfer Complete */ + .long DMA14_IRQHandler /* DMA Channel 14 Transfer Complete */ + .long DMA15_IRQHandler /* DMA Channel 15 Transfer Complete */ + .long DMA_Error_IRQHandler /* DMA Error Interrupt */ + .long MCM_IRQHandler /* Normal Interrupt */ + .long FTFE_IRQHandler /* FTFE Command complete interrupt */ + .long Read_Collision_IRQHandler /* Read Collision Interrupt */ + .long LVD_LVW_IRQHandler /* Low Voltage Detect, Low Voltage Warning */ + .long LLW_IRQHandler /* Low Leakage Wakeup */ + .long Watchdog_IRQHandler /* WDOG Interrupt */ + .long RNG_IRQHandler /* RNG Interrupt */ + .long I2C0_IRQHandler /* I2C0 interrupt */ + .long I2C1_IRQHandler /* I2C1 interrupt */ + .long SPI0_IRQHandler /* SPI0 Interrupt */ + .long SPI1_IRQHandler /* SPI1 Interrupt */ + .long I2S0_Tx_IRQHandler /* I2S0 transmit interrupt */ + .long I2S0_Rx_IRQHandler /* I2S0 receive interrupt */ + .long UART0_LON_IRQHandler /* UART0 LON interrupt */ + .long UART0_RX_TX_IRQHandler /* UART0 Receive/Transmit interrupt */ + .long UART0_ERR_IRQHandler /* UART0 Error interrupt */ + .long UART1_RX_TX_IRQHandler /* UART1 Receive/Transmit interrupt */ + .long UART1_ERR_IRQHandler /* UART1 Error interrupt */ + .long UART2_RX_TX_IRQHandler /* UART2 Receive/Transmit interrupt */ + .long UART2_ERR_IRQHandler /* UART2 Error interrupt */ + .long UART3_RX_TX_IRQHandler /* UART3 Receive/Transmit interrupt */ + .long UART3_ERR_IRQHandler /* UART3 Error interrupt */ + .long ADC0_IRQHandler /* ADC0 interrupt */ + .long CMP0_IRQHandler /* CMP0 interrupt */ + .long CMP1_IRQHandler /* CMP1 interrupt */ + .long FTM0_IRQHandler /* FTM0 fault, overflow and channels interrupt */ + .long FTM1_IRQHandler /* FTM1 fault, overflow and channels interrupt */ + .long FTM2_IRQHandler /* FTM2 fault, overflow and channels interrupt */ + .long CMT_IRQHandler /* CMT interrupt */ + .long RTC_IRQHandler /* RTC interrupt */ + .long RTC_Seconds_IRQHandler /* RTC seconds interrupt */ + .long PIT0_IRQHandler /* PIT timer channel 0 interrupt */ + .long PIT1_IRQHandler /* PIT timer channel 1 interrupt */ + .long PIT2_IRQHandler /* PIT timer channel 2 interrupt */ + .long PIT3_IRQHandler /* PIT timer channel 3 interrupt */ + .long PDB0_IRQHandler /* PDB0 Interrupt */ + .long USB0_IRQHandler /* USB0 interrupt */ + .long USBDCD_IRQHandler /* USBDCD Interrupt */ + .long Reserved71_IRQHandler /* Reserved interrupt 71 */ + .long DAC0_IRQHandler /* DAC0 interrupt */ + .long MCG_IRQHandler /* MCG Interrupt */ + .long LPTimer_IRQHandler /* LPTimer interrupt */ + .long PORTA_IRQHandler /* Port A interrupt */ + .long PORTB_IRQHandler /* Port B interrupt */ + .long PORTC_IRQHandler /* Port C interrupt */ + .long PORTD_IRQHandler /* Port D interrupt */ + .long PORTE_IRQHandler /* Port E interrupt */ + .long SWI_IRQHandler /* Software interrupt */ + .long SPI2_IRQHandler /* SPI2 Interrupt */ + .long UART4_RX_TX_IRQHandler /* UART4 Receive/Transmit interrupt */ + .long UART4_ERR_IRQHandler /* UART4 Error interrupt */ + .long UART5_RX_TX_IRQHandler /* UART5 Receive/Transmit interrupt */ + .long UART5_ERR_IRQHandler /* UART5 Error interrupt */ + .long CMP2_IRQHandler /* CMP2 interrupt */ + .long FTM3_IRQHandler /* FTM3 fault, overflow and channels interrupt */ + .long DAC1_IRQHandler /* DAC1 interrupt */ + .long ADC1_IRQHandler /* ADC1 interrupt */ + .long I2C2_IRQHandler /* I2C2 interrupt */ + .long CAN0_ORed_Message_buffer_IRQHandler /* CAN0 OR'd message buffers interrupt */ + .long CAN0_Bus_Off_IRQHandler /* CAN0 bus off interrupt */ + .long CAN0_Error_IRQHandler /* CAN0 error interrupt */ + .long CAN0_Tx_Warning_IRQHandler /* CAN0 Tx warning interrupt */ + .long CAN0_Rx_Warning_IRQHandler /* CAN0 Rx warning interrupt */ + .long CAN0_Wake_Up_IRQHandler /* CAN0 wake up interrupt */ + .long SDHC_IRQHandler /* SDHC interrupt */ + .long ENET_1588_Timer_IRQHandler /* Ethernet MAC IEEE 1588 Timer Interrupt */ + .long ENET_Transmit_IRQHandler /* Ethernet MAC Transmit Interrupt */ + .long ENET_Receive_IRQHandler /* Ethernet MAC Receive Interrupt */ + .long ENET_Error_IRQHandler /* Ethernet MAC Error and miscelaneous Interrupt */ + + .size __isr_vector, . - __isr_vector + + .section .text.Reset_Handler + .thumb + .thumb_func + .align 2 + .globl Reset_Handler + .type Reset_Handler, %function +Reset_Handler: +/* Loop to copy data from read only memory to RAM. The ranges + * of copy from/to are specified by following symbols evaluated in + * linker script. + * __etext: End of code section, i.e., begin of data sections to copy from. + * __data_start__/__data_end__: RAM address range that data should be + * copied to. Both must be aligned to 4 bytes boundary. */ + + ldr r1, =__etext + ldr r2, =__data_start__ + ldr r3, =__data_end__ + + subs r3, r2 + ble .Lflash_to_ram_loop_end + + movs r4, 0 +.Lflash_to_ram_loop: + ldr r0, [r1,r4] + str r0, [r2,r4] + adds r4, 4 + cmp r4, r3 + blt .Lflash_to_ram_loop +.Lflash_to_ram_loop_end: + + ldr r0, =SystemInit + blx r0 + ldr r0, =_start + bx r0 + .pool + .size Reset_Handler, . - Reset_Handler + + .text +/* Macro to define default handlers. Default handler + * will be weak symbol and just dead loops. They can be + * overwritten by other handlers */ + .macro def_default_handler handler_name + .align 1 + .thumb_func + .weak \handler_name + .type \handler_name, %function +\handler_name : + b . + .size \handler_name, . - \handler_name + .endm + +/* Exception Handlers */ + + def_default_handler NMI_Handler + def_default_handler HardFault_Handler + def_default_handler MemManage_Handler + def_default_handler BusFault_Handler + def_default_handler UsageFault_Handler + def_default_handler SVC_Handler + def_default_handler DebugMon_Handler + def_default_handler PendSV_Handler + def_default_handler SysTick_Handler + def_default_handler Default_Handler + + .macro def_irq_default_handler handler_name + .weak \handler_name + .set \handler_name, Default_Handler + .endm + +/* IRQ Handlers */ + def_irq_default_handler DMA0_IRQHandler + def_irq_default_handler DMA1_IRQHandler + def_irq_default_handler DMA2_IRQHandler + def_irq_default_handler DMA3_IRQHandler + def_irq_default_handler DMA4_IRQHandler + def_irq_default_handler DMA5_IRQHandler + def_irq_default_handler DMA6_IRQHandler + def_irq_default_handler DMA7_IRQHandler + def_irq_default_handler DMA8_IRQHandler + def_irq_default_handler DMA9_IRQHandler + def_irq_default_handler DMA10_IRQHandler + def_irq_default_handler DMA11_IRQHandler + def_irq_default_handler DMA12_IRQHandler + def_irq_default_handler DMA13_IRQHandler + def_irq_default_handler DMA14_IRQHandler + def_irq_default_handler DMA15_IRQHandler + def_irq_default_handler DMA_Error_IRQHandler + def_irq_default_handler MCM_IRQHandler + def_irq_default_handler FTFE_IRQHandler + def_irq_default_handler Read_Collision_IRQHandler + def_irq_default_handler LVD_LVW_IRQHandler + def_irq_default_handler LLW_IRQHandler + def_irq_default_handler Watchdog_IRQHandler + def_irq_default_handler RNG_IRQHandler + def_irq_default_handler I2C0_IRQHandler + def_irq_default_handler I2C1_IRQHandler + def_irq_default_handler SPI0_IRQHandler + def_irq_default_handler SPI1_IRQHandler + def_irq_default_handler I2S0_Tx_IRQHandler + def_irq_default_handler I2S0_Rx_IRQHandler + def_irq_default_handler UART0_LON_IRQHandler + def_irq_default_handler UART0_RX_TX_IRQHandler + def_irq_default_handler UART0_ERR_IRQHandler + def_irq_default_handler UART1_RX_TX_IRQHandler + def_irq_default_handler UART1_ERR_IRQHandler + def_irq_default_handler UART2_RX_TX_IRQHandler + def_irq_default_handler UART2_ERR_IRQHandler + def_irq_default_handler UART3_RX_TX_IRQHandler + def_irq_default_handler UART3_ERR_IRQHandler + def_irq_default_handler ADC0_IRQHandler + def_irq_default_handler CMP0_IRQHandler + def_irq_default_handler CMP1_IRQHandler + def_irq_default_handler FTM0_IRQHandler + def_irq_default_handler FTM1_IRQHandler + def_irq_default_handler FTM2_IRQHandler + def_irq_default_handler CMT_IRQHandler + def_irq_default_handler RTC_IRQHandler + def_irq_default_handler RTC_Seconds_IRQHandler + def_irq_default_handler PIT0_IRQHandler + def_irq_default_handler PIT1_IRQHandler + def_irq_default_handler PIT2_IRQHandler + def_irq_default_handler PIT3_IRQHandler + def_irq_default_handler PDB0_IRQHandler + def_irq_default_handler USB0_IRQHandler + def_irq_default_handler USBDCD_IRQHandler + def_irq_default_handler Reserved71_IRQHandler + def_irq_default_handler DAC0_IRQHandler + def_irq_default_handler MCG_IRQHandler + def_irq_default_handler LPTimer_IRQHandler + def_irq_default_handler PORTA_IRQHandler + def_irq_default_handler PORTB_IRQHandler + def_irq_default_handler PORTC_IRQHandler + def_irq_default_handler PORTD_IRQHandler + def_irq_default_handler PORTE_IRQHandler + def_irq_default_handler SWI_IRQHandler + def_irq_default_handler SPI2_IRQHandler + def_irq_default_handler UART4_RX_TX_IRQHandler + def_irq_default_handler UART4_ERR_IRQHandler + def_irq_default_handler UART5_RX_TX_IRQHandler + def_irq_default_handler UART5_ERR_IRQHandler + def_irq_default_handler CMP2_IRQHandler + def_irq_default_handler FTM3_IRQHandler + def_irq_default_handler DAC1_IRQHandler + def_irq_default_handler ADC1_IRQHandler + def_irq_default_handler I2C2_IRQHandler + def_irq_default_handler CAN0_ORed_Message_buffer_IRQHandler + def_irq_default_handler CAN0_Bus_Off_IRQHandler + def_irq_default_handler CAN0_Error_IRQHandler + def_irq_default_handler CAN0_Tx_Warning_IRQHandler + def_irq_default_handler CAN0_Rx_Warning_IRQHandler + def_irq_default_handler CAN0_Wake_Up_IRQHandler + def_irq_default_handler SDHC_IRQHandler + def_irq_default_handler ENET_1588_Timer_IRQHandler + def_irq_default_handler ENET_Transmit_IRQHandler + def_irq_default_handler ENET_Receive_IRQHandler + def_irq_default_handler ENET_Error_IRQHandler + def_irq_default_handler DefaultISR + +/* Flash protection region, placed at 0x400 */ + .text + .thumb + .align 2 + .section .kinetis_flash_config_field,"a",%progbits +kinetis_flash_config: + .long 0xffffffff + .long 0xffffffff + .long 0xffffffff + .long 0xfffffffe + + .end diff --git a/libraries/mbed/targets/cmsis/TARGET_Freescale/TARGET_KLXX/TARGET_KL46Z/TOOLCHAIN_GCC_ARM/startup_MKL46Z4.s b/libraries/mbed/targets/cmsis/TARGET_Freescale/TARGET_KLXX/TARGET_KL46Z/TOOLCHAIN_GCC_ARM/startup_MKL46Z4.s index 9d297079d5..5d5eae6e53 100644 --- a/libraries/mbed/targets/cmsis/TARGET_Freescale/TARGET_KLXX/TARGET_KL46Z/TOOLCHAIN_GCC_ARM/startup_MKL46Z4.s +++ b/libraries/mbed/targets/cmsis/TARGET_Freescale/TARGET_KLXX/TARGET_KL46Z/TOOLCHAIN_GCC_ARM/startup_MKL46Z4.s @@ -1,4 +1,4 @@ -/* KL25Z startup ARM GCC +/* KL46Z startup ARM GCC * Purpose: startup file for Cortex-M0 devices. Should use with * GCC for ARM Embedded Processors * Version: V1.2 @@ -134,8 +134,8 @@ __isr_vector: .section .text.Reset_Handler .thumb .thumb_func - .align 2 - .globl Reset_Handler + .align 2 + .globl Reset_Handler .type Reset_Handler, %function Reset_Handler: /* Loop to copy data from read only memory to RAM. The ranges @@ -149,21 +149,21 @@ Reset_Handler: ldr r2, =__data_start__ ldr r3, =__data_end__ - subs r3, r2 + subs r3, r2 ble .Lflash_to_ram_loop_end movs r4, 0 .Lflash_to_ram_loop: ldr r0, [r1,r4] str r0, [r2,r4] - adds r4, 4 + adds r4, 4 cmp r4, r3 blt .Lflash_to_ram_loop .Lflash_to_ram_loop_end: - ldr r0, =SystemInit - blx r0 - ldr r0, =_start + ldr r0, =SystemInit + blx r0 + ldr r0, =_start bx r0 .pool .size Reset_Handler, . - Reset_Handler diff --git a/libraries/mbed/targets/cmsis/TARGET_NXP/TARGET_LPC11U6X/system_LPC11U6x.c b/libraries/mbed/targets/cmsis/TARGET_NXP/TARGET_LPC11U6X/system_LPC11U6x.c index 9e08b5e0d2..71d5340b47 100644 --- a/libraries/mbed/targets/cmsis/TARGET_NXP/TARGET_LPC11U6X/system_LPC11U6x.c +++ b/libraries/mbed/targets/cmsis/TARGET_NXP/TARGET_LPC11U6X/system_LPC11U6x.c @@ -91,7 +91,7 @@ // <2=> P = 4 // <3=> P = 8 // -#define SYSPLLCTRL_Val 0x00000003 // Reset value: 0x000 +#define SYSPLLCTRL_Val 0x00000023 // Reset value: 0x000 // // Main Clock Source Select (MAINCLKSEL) // <0=> IRC Oscillator @@ -445,6 +445,25 @@ void SystemCoreClockUpdate (void) /* Get Core Clock Frequency */ } +#define PDRUN_VALID_BITS 0x000025FFL +#define PDRUN_RESERVED_ONE 0x0000C800L + +static void power_down_config(uint32_t val) +{ + volatile uint32_t tmp; + tmp = (LPC_SYSCON->PDRUNCFG & PDRUN_VALID_BITS); + tmp |= (val & PDRUN_VALID_BITS); + LPC_SYSCON->PDRUNCFG = (tmp | PDRUN_RESERVED_ONE); +} + +static void power_up_config(uint32_t val) +{ + volatile uint32_t tmp; + tmp = (LPC_SYSCON->PDRUNCFG & PDRUN_VALID_BITS); + tmp &= ~(val & PDRUN_VALID_BITS); + LPC_SYSCON->PDRUNCFG = (tmp | PDRUN_RESERVED_ONE); +} + /** * Initialize the system * @@ -455,27 +474,30 @@ void SystemCoreClockUpdate (void) /* Get Core Clock Frequency */ */ void SystemInit (void) { #if (CLOCK_SETUP) - volatile uint32_t i; + volatile uint32_t i, tmp; #endif LPC_SYSCON->SYSAHBCLKCTRL |= (1<<16); LPC_SYSCON->SYSPLLCTRL = SYSPLLCTRL_Val; -#warning "should not return here, need to fix an issue with PLL lock" - return; #if (CLOCK_SETUP) /* Clock Setup */ #if ((SYSPLLCLKSEL_Val & 0x03) == 1) + // Initialize XTALIN/XTALOUT pins + LPC_IOCON->PIO2_0 = 0x01; + LPC_IOCON->PIO2_1 = 0x01; + LPC_SYSCON->SYSOSCCTRL = SYSOSCCTRL_Val; - LPC_SYSCON->PDRUNCFG &= ~(1 << 5); /* Power-up sysosc */ - for (i = 0; i < 200; i++) __NOP(); /* Wait for osc to stabilize */ + power_up_config(1<<5); /* Power-up sysosc */ + for (i = 0; i < 2500; i++) __NOP(); /* Wait for osc to stabilize */ #endif + #if ((SYSPLLCLKSEL_Val & 0x03) == 3) LPC_SYSCON->RTCOSCCTRL = (1 << 0); /* Enable 32 kHz output */ for (i = 0; i < 200; i++) __NOP(); /* Wait for osc to stabilize */ #endif LPC_SYSCON->SYSPLLCLKSEL = SYSPLLCLKSEL_Val; /* Select PLL Input */ - //LPC_SYSCON->SYSPLLCLKUEN = 0x01; /* Update Clock Source */ + LPC_SYSCON->SYSPLLCLKUEN = 0x01; /* Update Clock Source */ LPC_SYSCON->SYSPLLCLKUEN = 0x00; /* Toggle Update Register */ LPC_SYSCON->SYSPLLCLKUEN = 0x01; while (!(LPC_SYSCON->SYSPLLCLKUEN & 0x01)); /* Wait Until Updated */ @@ -485,13 +507,13 @@ void SystemInit (void) { #if (((MAINCLKSEL_Val & 0x03) == 2) ) LPC_SYSCON->WDTOSCCTRL = WDTOSCCTRL_Val; LPC_SYSCON->PDRUNCFG &= ~(1 << 6); /* Power-up WDT Clock */ - for (i = 0; i < 2000; i++) __NOP(); /* Wait for osc to stabilize */ + for (i = 0; i < 2000; i++) __NOP(); /* Wait for osc to stabilize */ #endif #if ((MAINCLKSEL_Val & 0x03) == 3) /* Main Clock is PLL Out */ - LPC_SYSCON->PDRUNCFG |= (1 << 7); /* Power-down SYSPLL */ + power_down_config(1<<7); /* Power-down SYSPLL */ LPC_SYSCON->SYSPLLCTRL = SYSPLLCTRL_Val; - LPC_SYSCON->PDRUNCFG &= ~(1 << 7); /* Power-up SYSPLL */ + power_up_config(1<<7); /* Power-up SYSPLL */ while (!(LPC_SYSCON->SYSPLLSTAT & 0x01)); /* Wait Until PLL Locked */ #endif @@ -549,7 +571,4 @@ void SystemInit (void) { #endif /* Clock Setup */ - /* System clock to the IOCON needs to be enabled or - most of the I/O related peripherals won't work. */ - LPC_SYSCON->SYSAHBCLKCTRL |= (1<<16); } diff --git a/libraries/mbed/targets/cmsis/TARGET_NXP/TARGET_LPC176X/cmsis_nvic.c b/libraries/mbed/targets/cmsis/TARGET_NXP/TARGET_LPC176X/cmsis_nvic.c index 9e08052795..f47d5de754 100644 --- a/libraries/mbed/targets/cmsis/TARGET_NXP/TARGET_LPC176X/cmsis_nvic.c +++ b/libraries/mbed/targets/cmsis/TARGET_NXP/TARGET_LPC176X/cmsis_nvic.c @@ -13,7 +13,7 @@ void NVIC_SetVector(IRQn_Type IRQn, uint32_t vector) { uint32_t i; // Copy and switch to dynamic vectors if the first time called - if (SCB->VTOR == NVIC_FLASH_VECTOR_ADDRESS) { + if (SCB->VTOR < NVIC_RAM_VECTOR_ADDRESS) { uint32_t *old_vectors = vectors; vectors = (uint32_t*)NVIC_RAM_VECTOR_ADDRESS; for (i=0; i>> +;******************************************************************************* +; +;* Redistribution and use in source and binary forms, with or without modification, +;* are permitted provided that the following conditions are met: +;* 1. Redistributions of source code must retain the above copyright notice, +;* this list of conditions and the following disclaimer. +;* 2. Redistributions in binary form must reproduce the above copyright notice, +;* this list of conditions and the following disclaimer in the documentation +;* and/or other materials provided with the distribution. +;* 3. Neither the name of STMicroelectronics nor the names of its contributors +;* may be used to endorse or promote products derived from this software +;* without specific prior written permission. +;* +;* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +;* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +;* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +;* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +;* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +;* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +;* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +;* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +;* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +;* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +; +;******************************************************************************* + +; Amount of memory (in bytes) allocated for Stack +; Tailor this value to your application needs +; Stack Configuration +; Stack Size (in Bytes) <0x0-0xFFFFFFFF:8> +; + +Stack_Size EQU 0x00000400 + + AREA STACK, NOINIT, READWRITE, ALIGN=3 + EXPORT __initial_sp + +Stack_Mem SPACE Stack_Size +__initial_sp EQU 0x20004000 ; Top of RAM (16KB) + + +; Heap Configuration +; Heap Size (in Bytes) <0x0-0xFFFFFFFF:8> +; + +Heap_Size EQU 0x00000200 + + AREA HEAP, NOINIT, READWRITE, ALIGN=3 + EXPORT __heap_base + EXPORT __heap_limit + +__heap_base +Heap_Mem SPACE Heap_Size +__heap_limit + + PRESERVE8 + THUMB + + +; Vector Table Mapped to Address 0 at Reset + AREA RESET, DATA, READONLY + EXPORT __Vectors + EXPORT __Vectors_End + EXPORT __Vectors_Size + +__Vectors DCD __initial_sp ; Top of Stack + DCD Reset_Handler ; Reset Handler + DCD NMI_Handler ; NMI Handler + DCD HardFault_Handler ; Hard Fault Handler + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD SVC_Handler ; SVCall Handler + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD PendSV_Handler ; PendSV Handler + DCD SysTick_Handler ; SysTick Handler + + ; External Interrupts + DCD WWDG_IRQHandler ; Window Watchdog + DCD PVD_VDDIO2_IRQHandler ; PVD through EXTI Line detect + DCD RTC_IRQHandler ; RTC through EXTI Line + DCD FLASH_IRQHandler ; FLASH + DCD RCC_CRS_IRQHandler ; RCC and CRS + DCD EXTI0_1_IRQHandler ; EXTI Line 0 and 1 + DCD EXTI2_3_IRQHandler ; EXTI Line 2 and 3 + DCD EXTI4_15_IRQHandler ; EXTI Line 4 to 15 + DCD TSC_IRQHandler ; TS + DCD DMA1_Channel1_IRQHandler ; DMA1 Channel 1 + DCD DMA1_Channel2_3_IRQHandler ; DMA1 Channel 2 and Channel 3 + DCD DMA1_Channel4_5_6_7_IRQHandler ; DMA1 Channel 4, Channel 5, Channel 6 and Channel 7 + DCD ADC1_COMP_IRQHandler ; ADC1, COMP1 and COMP2 + DCD TIM1_BRK_UP_TRG_COM_IRQHandler ; TIM1 Break, Update, Trigger and Commutation + DCD TIM1_CC_IRQHandler ; TIM1 Capture Compare + DCD TIM2_IRQHandler ; TIM2 + DCD TIM3_IRQHandler ; TIM3 + DCD TIM6_DAC_IRQHandler ; TIM6 and DAC + DCD TIM7_IRQHandler ; TIM7 + DCD TIM14_IRQHandler ; TIM14 + DCD TIM15_IRQHandler ; TIM15 + DCD TIM16_IRQHandler ; TIM16 + DCD TIM17_IRQHandler ; TIM17 + DCD I2C1_IRQHandler ; I2C1 + DCD I2C2_IRQHandler ; I2C2 + DCD SPI1_IRQHandler ; SPI1 + DCD SPI2_IRQHandler ; SPI2 + DCD USART1_IRQHandler ; USART1 + DCD USART2_IRQHandler ; USART2 + DCD USART3_4_IRQHandler ; USART3 & USART4 + DCD CEC_CAN_IRQHandler ; CEC and CAN + DCD USB_IRQHandler ; USB + +__Vectors_End + +__Vectors_Size EQU __Vectors_End - __Vectors + + AREA |.text|, CODE, READONLY + +; Reset handler routine +Reset_Handler PROC + EXPORT Reset_Handler [WEAK] + IMPORT __main + IMPORT SystemInit + LDR R0, =SystemInit + BLX R0 + LDR R0, =__main + BX R0 + ENDP + +; Dummy Exception Handlers (infinite loops which can be modified) + +NMI_Handler PROC + EXPORT NMI_Handler [WEAK] + B . + ENDP +HardFault_Handler\ + PROC + EXPORT HardFault_Handler [WEAK] + B . + ENDP +SVC_Handler PROC + EXPORT SVC_Handler [WEAK] + B . + ENDP +PendSV_Handler PROC + EXPORT PendSV_Handler [WEAK] + B . + ENDP +SysTick_Handler PROC + EXPORT SysTick_Handler [WEAK] + B . + ENDP + +Default_Handler PROC + + EXPORT WWDG_IRQHandler [WEAK] + EXPORT PVD_VDDIO2_IRQHandler [WEAK] + EXPORT RTC_IRQHandler [WEAK] + EXPORT FLASH_IRQHandler [WEAK] + EXPORT RCC_CRS_IRQHandler [WEAK] + EXPORT EXTI0_1_IRQHandler [WEAK] + EXPORT EXTI2_3_IRQHandler [WEAK] + EXPORT EXTI4_15_IRQHandler [WEAK] + EXPORT TSC_IRQHandler [WEAK] + EXPORT DMA1_Channel1_IRQHandler [WEAK] + EXPORT DMA1_Channel2_3_IRQHandler [WEAK] + EXPORT DMA1_Channel4_5_6_7_IRQHandler [WEAK] + EXPORT ADC1_COMP_IRQHandler [WEAK] + EXPORT TIM1_BRK_UP_TRG_COM_IRQHandler [WEAK] + EXPORT TIM1_CC_IRQHandler [WEAK] + EXPORT TIM2_IRQHandler [WEAK] + EXPORT TIM3_IRQHandler [WEAK] + EXPORT TIM6_DAC_IRQHandler [WEAK] + EXPORT TIM7_IRQHandler [WEAK] + EXPORT TIM14_IRQHandler [WEAK] + EXPORT TIM15_IRQHandler [WEAK] + EXPORT TIM16_IRQHandler [WEAK] + EXPORT TIM17_IRQHandler [WEAK] + EXPORT I2C1_IRQHandler [WEAK] + EXPORT I2C2_IRQHandler [WEAK] + EXPORT SPI1_IRQHandler [WEAK] + EXPORT SPI2_IRQHandler [WEAK] + EXPORT USART1_IRQHandler [WEAK] + EXPORT USART2_IRQHandler [WEAK] + EXPORT USART3_4_IRQHandler [WEAK] + EXPORT CEC_CAN_IRQHandler [WEAK] + EXPORT USB_IRQHandler [WEAK] + + +WWDG_IRQHandler +PVD_VDDIO2_IRQHandler +RTC_IRQHandler +FLASH_IRQHandler +RCC_CRS_IRQHandler +EXTI0_1_IRQHandler +EXTI2_3_IRQHandler +EXTI4_15_IRQHandler +TSC_IRQHandler +DMA1_Channel1_IRQHandler +DMA1_Channel2_3_IRQHandler +DMA1_Channel4_5_6_7_IRQHandler +ADC1_COMP_IRQHandler +TIM1_BRK_UP_TRG_COM_IRQHandler +TIM1_CC_IRQHandler +TIM2_IRQHandler +TIM3_IRQHandler +TIM6_DAC_IRQHandler +TIM7_IRQHandler +TIM14_IRQHandler +TIM15_IRQHandler +TIM16_IRQHandler +TIM17_IRQHandler +I2C1_IRQHandler +I2C2_IRQHandler +SPI1_IRQHandler +SPI2_IRQHandler +USART1_IRQHandler +USART2_IRQHandler +USART3_4_IRQHandler +CEC_CAN_IRQHandler +USB_IRQHandler + + B . + + ENDP + + ALIGN + END diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/TOOLCHAIN_ARM_MICRO/stm32f072rb.sct b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/TOOLCHAIN_ARM_MICRO/stm32f072rb.sct new file mode 100644 index 0000000000..e0e5a5f5aa --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/TOOLCHAIN_ARM_MICRO/stm32f072rb.sct @@ -0,0 +1,45 @@ +; Scatter-Loading Description File +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +; Copyright (c) 2014, STMicroelectronics +; All rights reserved. +; +; Redistribution and use in source and binary forms, with or without +; modification, are permitted provided that the following conditions are met: +; +; 1. Redistributions of source code must retain the above copyright notice, +; this list of conditions and the following disclaimer. +; 2. Redistributions in binary form must reproduce the above copyright notice, +; this list of conditions and the following disclaimer in the documentation +; and/or other materials provided with the distribution. +; 3. Neither the name of STMicroelectronics nor the names of its contributors +; may be used to endorse or promote products derived from this software +; without specific prior written permission. +; +; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +; FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +; OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +; STM32F072RB: 128KB FLASH (0x20000) + 16KB RAM (0x4000) + + LR_IROM1 0x08000000 0x20000 { ; load region size_region + ER_IROM1 0x08000000 0x20000 { ; load address = execution address + *.o (RESET, +First) + *(InRoot$$Sections) + .ANY (+RO) + } + + ; 48 vectors = 192 bytes (0xC0) to be reserved in RAM + RW_IRAM1 (0x20000000+0xC0) (0x4000-0xC0) { ; RW data + .ANY (+RW +ZI) + } + +} + diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/TOOLCHAIN_ARM_MICRO/sys.cpp b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/TOOLCHAIN_ARM_MICRO/sys.cpp new file mode 100644 index 0000000000..bb665909b9 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/TOOLCHAIN_ARM_MICRO/sys.cpp @@ -0,0 +1,56 @@ +/* mbed Microcontroller Library - stackheap + * Setup a fixed single stack/heap memory model, + * between the top of the RW/ZI region and the stackpointer + ******************************************************************************* + * Copyright (c) 2014, STMicroelectronics + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ******************************************************************************* + */ + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include + +extern char Image$$RW_IRAM1$$ZI$$Limit[]; + +extern __value_in_regs struct __initial_stackheap __user_setup_stackheap(uint32_t R0, uint32_t R1, uint32_t R2, uint32_t R3) { + uint32_t zi_limit = (uint32_t)Image$$RW_IRAM1$$ZI$$Limit; + uint32_t sp_limit = __current_sp(); + + zi_limit = (zi_limit + 7) & ~0x7; // ensure zi_limit is 8-byte aligned + + struct __initial_stackheap r; + r.heap_base = zi_limit; + r.heap_limit = sp_limit; + return r; +} + +#ifdef __cplusplus +} +#endif diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/TOOLCHAIN_ARM_STD/startup_stm32f072xb.s b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/TOOLCHAIN_ARM_STD/startup_stm32f072xb.s new file mode 100644 index 0000000000..33050eb33d --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/TOOLCHAIN_ARM_STD/startup_stm32f072xb.s @@ -0,0 +1,220 @@ +;******************** (C) COPYRIGHT 2014 STMicroelectronics ******************** +;* File Name : startup_stm32f072xb.s +;* Author : MCD Application Team +;* Version : V2.0.0 +;* Date : 20-May-2014 +;* Description : STM32F072x8/STM32F072xB devices vector table for MDK-ARM_STD toolchain. +;* This module performs: +;* - Set the initial SP +;* - Set the initial PC == Reset_Handler +;* - Set the vector table entries with the exceptions ISR address +;* - Branches to __main in the C library (which eventually +;* calls main()). +;* After Reset the CortexM0 processor is in Thread mode, +;* priority is Privileged, and the Stack is set to Main. +;* <<< Use Configuration Wizard in Context Menu >>> +;******************************************************************************* +; +;* Redistribution and use in source and binary forms, with or without modification, +;* are permitted provided that the following conditions are met: +;* 1. Redistributions of source code must retain the above copyright notice, +;* this list of conditions and the following disclaimer. +;* 2. Redistributions in binary form must reproduce the above copyright notice, +;* this list of conditions and the following disclaimer in the documentation +;* and/or other materials provided with the distribution. +;* 3. Neither the name of STMicroelectronics nor the names of its contributors +;* may be used to endorse or promote products derived from this software +;* without specific prior written permission. +;* +;* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +;* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +;* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +;* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +;* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +;* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +;* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +;* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +;* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +;* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +; +;******************************************************************************* + +__initial_sp EQU 0x20004000 ; Top of RAM (16KB) + + PRESERVE8 + THUMB + + +; Vector Table Mapped to Address 0 at Reset + AREA RESET, DATA, READONLY + EXPORT __Vectors + EXPORT __Vectors_End + EXPORT __Vectors_Size + +__Vectors DCD __initial_sp ; Top of Stack + DCD Reset_Handler ; Reset Handler + DCD NMI_Handler ; NMI Handler + DCD HardFault_Handler ; Hard Fault Handler + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD SVC_Handler ; SVCall Handler + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD PendSV_Handler ; PendSV Handler + DCD SysTick_Handler ; SysTick Handler + + ; External Interrupts + DCD WWDG_IRQHandler ; Window Watchdog + DCD PVD_VDDIO2_IRQHandler ; PVD through EXTI Line detect + DCD RTC_IRQHandler ; RTC through EXTI Line + DCD FLASH_IRQHandler ; FLASH + DCD RCC_CRS_IRQHandler ; RCC and CRS + DCD EXTI0_1_IRQHandler ; EXTI Line 0 and 1 + DCD EXTI2_3_IRQHandler ; EXTI Line 2 and 3 + DCD EXTI4_15_IRQHandler ; EXTI Line 4 to 15 + DCD TSC_IRQHandler ; TS + DCD DMA1_Channel1_IRQHandler ; DMA1 Channel 1 + DCD DMA1_Channel2_3_IRQHandler ; DMA1 Channel 2 and Channel 3 + DCD DMA1_Channel4_5_6_7_IRQHandler ; DMA1 Channel 4, Channel 5, Channel 6 and Channel 7 + DCD ADC1_COMP_IRQHandler ; ADC1, COMP1 and COMP2 + DCD TIM1_BRK_UP_TRG_COM_IRQHandler ; TIM1 Break, Update, Trigger and Commutation + DCD TIM1_CC_IRQHandler ; TIM1 Capture Compare + DCD TIM2_IRQHandler ; TIM2 + DCD TIM3_IRQHandler ; TIM3 + DCD TIM6_DAC_IRQHandler ; TIM6 and DAC + DCD TIM7_IRQHandler ; TIM7 + DCD TIM14_IRQHandler ; TIM14 + DCD TIM15_IRQHandler ; TIM15 + DCD TIM16_IRQHandler ; TIM16 + DCD TIM17_IRQHandler ; TIM17 + DCD I2C1_IRQHandler ; I2C1 + DCD I2C2_IRQHandler ; I2C2 + DCD SPI1_IRQHandler ; SPI1 + DCD SPI2_IRQHandler ; SPI2 + DCD USART1_IRQHandler ; USART1 + DCD USART2_IRQHandler ; USART2 + DCD USART3_4_IRQHandler ; USART3 & USART4 + DCD CEC_CAN_IRQHandler ; CEC and CAN + DCD USB_IRQHandler ; USB + +__Vectors_End + +__Vectors_Size EQU __Vectors_End - __Vectors + + AREA |.text|, CODE, READONLY + +; Reset handler routine +Reset_Handler PROC + EXPORT Reset_Handler [WEAK] + IMPORT __main + IMPORT SystemInit + LDR R0, =SystemInit + BLX R0 + LDR R0, =__main + BX R0 + ENDP + +; Dummy Exception Handlers (infinite loops which can be modified) + +NMI_Handler PROC + EXPORT NMI_Handler [WEAK] + B . + ENDP +HardFault_Handler\ + PROC + EXPORT HardFault_Handler [WEAK] + B . + ENDP +SVC_Handler PROC + EXPORT SVC_Handler [WEAK] + B . + ENDP +PendSV_Handler PROC + EXPORT PendSV_Handler [WEAK] + B . + ENDP +SysTick_Handler PROC + EXPORT SysTick_Handler [WEAK] + B . + ENDP + +Default_Handler PROC + + EXPORT WWDG_IRQHandler [WEAK] + EXPORT PVD_VDDIO2_IRQHandler [WEAK] + EXPORT RTC_IRQHandler [WEAK] + EXPORT FLASH_IRQHandler [WEAK] + EXPORT RCC_CRS_IRQHandler [WEAK] + EXPORT EXTI0_1_IRQHandler [WEAK] + EXPORT EXTI2_3_IRQHandler [WEAK] + EXPORT EXTI4_15_IRQHandler [WEAK] + EXPORT TSC_IRQHandler [WEAK] + EXPORT DMA1_Channel1_IRQHandler [WEAK] + EXPORT DMA1_Channel2_3_IRQHandler [WEAK] + EXPORT DMA1_Channel4_5_6_7_IRQHandler [WEAK] + EXPORT ADC1_COMP_IRQHandler [WEAK] + EXPORT TIM1_BRK_UP_TRG_COM_IRQHandler [WEAK] + EXPORT TIM1_CC_IRQHandler [WEAK] + EXPORT TIM2_IRQHandler [WEAK] + EXPORT TIM3_IRQHandler [WEAK] + EXPORT TIM6_DAC_IRQHandler [WEAK] + EXPORT TIM7_IRQHandler [WEAK] + EXPORT TIM14_IRQHandler [WEAK] + EXPORT TIM15_IRQHandler [WEAK] + EXPORT TIM16_IRQHandler [WEAK] + EXPORT TIM17_IRQHandler [WEAK] + EXPORT I2C1_IRQHandler [WEAK] + EXPORT I2C2_IRQHandler [WEAK] + EXPORT SPI1_IRQHandler [WEAK] + EXPORT SPI2_IRQHandler [WEAK] + EXPORT USART1_IRQHandler [WEAK] + EXPORT USART2_IRQHandler [WEAK] + EXPORT USART3_4_IRQHandler [WEAK] + EXPORT CEC_CAN_IRQHandler [WEAK] + EXPORT USB_IRQHandler [WEAK] + + +WWDG_IRQHandler +PVD_VDDIO2_IRQHandler +RTC_IRQHandler +FLASH_IRQHandler +RCC_CRS_IRQHandler +EXTI0_1_IRQHandler +EXTI2_3_IRQHandler +EXTI4_15_IRQHandler +TSC_IRQHandler +DMA1_Channel1_IRQHandler +DMA1_Channel2_3_IRQHandler +DMA1_Channel4_5_6_7_IRQHandler +ADC1_COMP_IRQHandler +TIM1_BRK_UP_TRG_COM_IRQHandler +TIM1_CC_IRQHandler +TIM2_IRQHandler +TIM3_IRQHandler +TIM6_DAC_IRQHandler +TIM7_IRQHandler +TIM14_IRQHandler +TIM15_IRQHandler +TIM16_IRQHandler +TIM17_IRQHandler +I2C1_IRQHandler +I2C2_IRQHandler +SPI1_IRQHandler +SPI2_IRQHandler +USART1_IRQHandler +USART2_IRQHandler +USART3_4_IRQHandler +CEC_CAN_IRQHandler +USB_IRQHandler + + B . + + ENDP + + ALIGN + END diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/TOOLCHAIN_ARM_STD/stm32f072rb.sct b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/TOOLCHAIN_ARM_STD/stm32f072rb.sct new file mode 100644 index 0000000000..e0e5a5f5aa --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/TOOLCHAIN_ARM_STD/stm32f072rb.sct @@ -0,0 +1,45 @@ +; Scatter-Loading Description File +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +; Copyright (c) 2014, STMicroelectronics +; All rights reserved. +; +; Redistribution and use in source and binary forms, with or without +; modification, are permitted provided that the following conditions are met: +; +; 1. Redistributions of source code must retain the above copyright notice, +; this list of conditions and the following disclaimer. +; 2. Redistributions in binary form must reproduce the above copyright notice, +; this list of conditions and the following disclaimer in the documentation +; and/or other materials provided with the distribution. +; 3. Neither the name of STMicroelectronics nor the names of its contributors +; may be used to endorse or promote products derived from this software +; without specific prior written permission. +; +; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +; FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +; OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +; STM32F072RB: 128KB FLASH (0x20000) + 16KB RAM (0x4000) + + LR_IROM1 0x08000000 0x20000 { ; load region size_region + ER_IROM1 0x08000000 0x20000 { ; load address = execution address + *.o (RESET, +First) + *(InRoot$$Sections) + .ANY (+RO) + } + + ; 48 vectors = 192 bytes (0xC0) to be reserved in RAM + RW_IRAM1 (0x20000000+0xC0) (0x4000-0xC0) { ; RW data + .ANY (+RW +ZI) + } + +} + diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/TOOLCHAIN_ARM_STD/sys.cpp b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/TOOLCHAIN_ARM_STD/sys.cpp new file mode 100644 index 0000000000..bb665909b9 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/TOOLCHAIN_ARM_STD/sys.cpp @@ -0,0 +1,56 @@ +/* mbed Microcontroller Library - stackheap + * Setup a fixed single stack/heap memory model, + * between the top of the RW/ZI region and the stackpointer + ******************************************************************************* + * Copyright (c) 2014, STMicroelectronics + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ******************************************************************************* + */ + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include + +extern char Image$$RW_IRAM1$$ZI$$Limit[]; + +extern __value_in_regs struct __initial_stackheap __user_setup_stackheap(uint32_t R0, uint32_t R1, uint32_t R2, uint32_t R3) { + uint32_t zi_limit = (uint32_t)Image$$RW_IRAM1$$ZI$$Limit; + uint32_t sp_limit = __current_sp(); + + zi_limit = (zi_limit + 7) & ~0x7; // ensure zi_limit is 8-byte aligned + + struct __initial_stackheap r; + r.heap_base = zi_limit; + r.heap_limit = sp_limit; + return r; +} + +#ifdef __cplusplus +} +#endif diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/cmsis.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/cmsis.h new file mode 100644 index 0000000000..be4a7706f3 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/cmsis.h @@ -0,0 +1,38 @@ +/* mbed Microcontroller Library + * A generic CMSIS include header + ******************************************************************************* + * Copyright (c) 2014, STMicroelectronics + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ******************************************************************************* + */ + +#ifndef MBED_CMSIS_H +#define MBED_CMSIS_H + +#include "stm32f0xx.h" +#include "cmsis_nvic.h" + +#endif diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/cmsis_nvic.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/cmsis_nvic.c new file mode 100644 index 0000000000..8b706e8d5e --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/cmsis_nvic.c @@ -0,0 +1,61 @@ +/* mbed Microcontroller Library + * CMSIS-style functionality to support dynamic vectors + ******************************************************************************* + * Copyright (c) 2014, STMicroelectronics + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ******************************************************************************* + */ +#include "cmsis_nvic.h" + +#define NVIC_RAM_VECTOR_ADDRESS (0x20000000) // Vectors positioned at start of RAM +#define NVIC_FLASH_VECTOR_ADDRESS (0x08000000) // Initial vector position in flash + +static unsigned char vtor_remap = 0; // To keep track that the vectors remap is done + +void NVIC_SetVector(IRQn_Type IRQn, uint32_t vector) { + int i; + // Space for dynamic vectors, initialised to allocate in R/W + static volatile uint32_t *vectors = (uint32_t *)NVIC_RAM_VECTOR_ADDRESS; + + // Copy and switch to dynamic vectors if first time called + if (vtor_remap == 0) { + uint32_t *old_vectors = (uint32_t *)NVIC_FLASH_VECTOR_ADDRESS; + for (i = 0; i < NVIC_NUM_VECTORS; i++) { + vectors[i] = old_vectors[i]; + } + SYSCFG->CFGR1 |= 0x03; // Embedded SRAM mapped at 0x00000000 + vtor_remap = 1; // The vectors remap is done + } + + // Set the vector + vectors[IRQn + 16] = vector; +} + +uint32_t NVIC_GetVector(IRQn_Type IRQn) { + uint32_t *vectors = (uint32_t*)NVIC_RAM_VECTOR_ADDRESS; + // Return the vector + return vectors[IRQn + 16]; +} diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/cmsis_nvic.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/cmsis_nvic.h new file mode 100644 index 0000000000..5b41f231dd --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/cmsis_nvic.h @@ -0,0 +1,55 @@ +/* mbed Microcontroller Library + * CMSIS-style functionality to support dynamic vectors + ******************************************************************************* + * Copyright (c) 2014, STMicroelectronics + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ******************************************************************************* + */ + +#ifndef MBED_CMSIS_NVIC_H +#define MBED_CMSIS_NVIC_H + +// STM32F072RB +// CORE: 16 vectors = 64 bytes from 0x00 to 0x3F +// MCU Peripherals: 32 vectors = 128 bytes from 0x40 to 0xBF +// Total: 48 vectors = 192 bytes (0xC0) to be reserved in RAM +#define NVIC_NUM_VECTORS 48 +#define NVIC_USER_IRQ_OFFSET 16 + +#include "cmsis.h" + +#ifdef __cplusplus +extern "C" { +#endif + +void NVIC_SetVector(IRQn_Type IRQn, uint32_t vector); +uint32_t NVIC_GetVector(IRQn_Type IRQn); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f072xb.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f072xb.h new file mode 100644 index 0000000000..646206fc99 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f072xb.h @@ -0,0 +1,5578 @@ +/** + ****************************************************************************** + * @file stm32f072xb.h + * @author MCD Application Team + * @version V2.0.0 + * @date 28-May-2014 + * @brief CMSIS STM32F072x8/STM32F072xB devices Peripheral Access Layer Header File. + * + * This file contains: + * - Data structures and the address mapping for all peripherals + * - Peripheral's registers declarations and bits definition + * - Macros to access peripheral’s registers hardware + * + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/** @addtogroup CMSIS_Device + * @{ + */ + +/** @addtogroup stm32f072xb + * @{ + */ + +#ifndef __STM32F072xB_H +#define __STM32F072xB_H + +#ifdef __cplusplus + extern "C" { +#endif /* __cplusplus */ + +/** @addtogroup Configuration_section_for_CMSIS + * @{ + */ + +/** + * @brief Configuration of the Cortex-M0 Processor and Core Peripherals + */ +#define __CM0_REV 0 /*!< Core Revision r0p0 */ +#define __MPU_PRESENT 0 /*!< STM32F0xx do not provide MPU */ +#define __NVIC_PRIO_BITS 2 /*!< STM32F0xx uses 2 Bits for the Priority Levels */ +#define __Vendor_SysTickConfig 0 /*!< Set to 1 if different SysTick Config is used */ + +/** + * @} + */ + +/** @addtogroup Peripheral_interrupt_number_definition + * @{ + */ + +/** + * @brief STM32F072x8/STM32F072xB device Interrupt Number Definition + */ +typedef enum +{ +/****** Cortex-M0 Processor Exceptions Numbers **************************************************************/ + NonMaskableInt_IRQn = -14, /*!< 2 Non Maskable Interrupt */ + HardFault_IRQn = -13, /*!< 3 Cortex-M0 Hard Fault Interrupt */ + SVC_IRQn = -5, /*!< 11 Cortex-M0 SV Call Interrupt */ + PendSV_IRQn = -2, /*!< 14 Cortex-M0 Pend SV Interrupt */ + SysTick_IRQn = -1, /*!< 15 Cortex-M0 System Tick Interrupt */ + +/****** STM32F072x8/STM32F072xB specific Interrupt Numbers **************************************************/ + WWDG_IRQn = 0, /*!< Window WatchDog Interrupt */ + PVD_VDDIO2_IRQn = 1, /*!< PVD & VDDIO2 Interrupts through EXTI Lines 16 and 31 */ + RTC_IRQn = 2, /*!< RTC Interrupt through EXTI Lines 17, 19 and 20 */ + FLASH_IRQn = 3, /*!< FLASH global Interrupt */ + RCC_CRS_IRQn = 4, /*!< RCC & CRS global Interrupts */ + EXTI0_1_IRQn = 5, /*!< EXTI Line 0 and 1 Interrupts */ + EXTI2_3_IRQn = 6, /*!< EXTI Line 2 and 3 Interrupts */ + EXTI4_15_IRQn = 7, /*!< EXTI Line 4 to 15 Interrupts */ + TSC_IRQn = 8, /*!< Touch Sensing Controller Interrupts */ + DMA1_Channel1_IRQn = 9, /*!< DMA1 Channel 1 Interrupt */ + DMA1_Channel2_3_IRQn = 10, /*!< DMA1 Channel 2 and Channel 3 Interrupts */ + DMA1_Channel4_5_6_7_IRQn = 11, /*!< DMA1 Channel 4 to Channel 7 Interrupts */ + ADC1_COMP_IRQn = 12, /*!< ADC1 and COMP interrupts (ADC interrupt combined with EXTI Lines 21 and 22 */ + TIM1_BRK_UP_TRG_COM_IRQn = 13, /*!< TIM1 Break, Update, Trigger and Commutation Interrupts */ + TIM1_CC_IRQn = 14, /*!< TIM1 Capture Compare Interrupt */ + TIM2_IRQn = 15, /*!< TIM2 global Interrupt */ + TIM3_IRQn = 16, /*!< TIM3 global Interrupt */ + TIM6_DAC_IRQn = 17, /*!< TIM6 global and DAC channel underrun error Interrupts */ + TIM7_IRQn = 18, /*!< TIM7 global Interrupt */ + TIM14_IRQn = 19, /*!< TIM14 global Interrupt */ + TIM15_IRQn = 20, /*!< TIM15 global Interrupt */ + TIM16_IRQn = 21, /*!< TIM16 global Interrupt */ + TIM17_IRQn = 22, /*!< TIM17 global Interrupt */ + I2C1_IRQn = 23, /*!< I2C1 Event Interrupt & EXTI Line23 Interrupt (I2C1 wakeup) */ + I2C2_IRQn = 24, /*!< I2C2 Event Interrupt & EXTI Line24 Interrupt (I2C2 wakeup) */ + SPI1_IRQn = 25, /*!< SPI1 global Interrupt */ + SPI2_IRQn = 26, /*!< SPI2 global Interrupt */ + USART1_IRQn = 27, /*!< USART1 global Interrupt & EXTI Line25 Interrupt (USART1 wakeup) */ + USART2_IRQn = 28, /*!< USART2 global Interrupt & EXTI Line26 Interrupt (USART2 wakeup) */ + USART3_4_IRQn = 29, /*!< USART3 and USART4 global Interrupts */ + CEC_CAN_IRQn = 30, /*!< CEC and CAN global Interrupts & EXTI Line27 Interrupt */ + USB_IRQn = 31 /*!< USB global Interrupts & EXTI Line18 Interrupt */ +} IRQn_Type; + +/** + * @} + */ + +#include "core_cm0.h" /* Cortex-M0 processor and core peripherals */ +#include "system_stm32f0xx.h" /* STM32F0xx System Header */ +#include + +/** @addtogroup Peripheral_registers_structures + * @{ + */ + +/** + * @brief Analog to Digital Converter + */ + +typedef struct +{ + __IO uint32_t ISR; /*!< ADC Interrupt and Status register, Address offset:0x00 */ + __IO uint32_t IER; /*!< ADC Interrupt Enable register, Address offset:0x04 */ + __IO uint32_t CR; /*!< ADC Control register, Address offset:0x08 */ + __IO uint32_t CFGR1; /*!< ADC Configuration register 1, Address offset:0x0C */ + __IO uint32_t CFGR2; /*!< ADC Configuration register 2, Address offset:0x10 */ + __IO uint32_t SMPR; /*!< ADC Sampling time register, Address offset:0x14 */ + uint32_t RESERVED1; /*!< Reserved, 0x18 */ + uint32_t RESERVED2; /*!< Reserved, 0x1C */ + __IO uint32_t TR; /*!< ADC watchdog threshold register, Address offset:0x20 */ + uint32_t RESERVED3; /*!< Reserved, 0x24 */ + __IO uint32_t CHSELR; /*!< ADC channel selection register, Address offset:0x28 */ + uint32_t RESERVED4[5]; /*!< Reserved, 0x2C */ + __IO uint32_t DR; /*!< ADC data register, Address offset:0x40 */ +}ADC_TypeDef; + +typedef struct +{ + __IO uint32_t CCR; +}ADC_Common_TypeDef; + +/** + * @brief Controller Area Network TxMailBox + */ +typedef struct +{ + __IO uint32_t TIR; /*!< CAN TX mailbox identifier register */ + __IO uint32_t TDTR; /*!< CAN mailbox data length control and time stamp register */ + __IO uint32_t TDLR; /*!< CAN mailbox data low register */ + __IO uint32_t TDHR; /*!< CAN mailbox data high register */ +}CAN_TxMailBox_TypeDef; + +/** + * @brief Controller Area Network FIFOMailBox + */ +typedef struct +{ + __IO uint32_t RIR; /*!< CAN receive FIFO mailbox identifier register */ + __IO uint32_t RDTR; /*!< CAN receive FIFO mailbox data length control and time stamp register */ + __IO uint32_t RDLR; /*!< CAN receive FIFO mailbox data low register */ + __IO uint32_t RDHR; /*!< CAN receive FIFO mailbox data high register */ +}CAN_FIFOMailBox_TypeDef; + +/** + * @brief Controller Area Network FilterRegister + */ +typedef struct +{ + __IO uint32_t FR1; /*!< CAN Filter bank register 1 */ + __IO uint32_t FR2; /*!< CAN Filter bank register 1 */ +}CAN_FilterRegister_TypeDef; + +/** + * @brief Controller Area Network + */ +typedef struct +{ + __IO uint32_t MCR; /*!< CAN master control register, Address offset: 0x00 */ + __IO uint32_t MSR; /*!< CAN master status register, Address offset: 0x04 */ + __IO uint32_t TSR; /*!< CAN transmit status register, Address offset: 0x08 */ + __IO uint32_t RF0R; /*!< CAN receive FIFO 0 register, Address offset: 0x0C */ + __IO uint32_t RF1R; /*!< CAN receive FIFO 1 register, Address offset: 0x10 */ + __IO uint32_t IER; /*!< CAN interrupt enable register, Address offset: 0x14 */ + __IO uint32_t ESR; /*!< CAN error status register, Address offset: 0x18 */ + __IO uint32_t BTR; /*!< CAN bit timing register, Address offset: 0x1C */ + uint32_t RESERVED0[88]; /*!< Reserved, 0x020 - 0x17F */ + CAN_TxMailBox_TypeDef sTxMailBox[3]; /*!< CAN Tx MailBox, Address offset: 0x180 - 0x1AC */ + CAN_FIFOMailBox_TypeDef sFIFOMailBox[2]; /*!< CAN FIFO MailBox, Address offset: 0x1B0 - 0x1CC */ + uint32_t RESERVED1[12]; /*!< Reserved, 0x1D0 - 0x1FF */ + __IO uint32_t FMR; /*!< CAN filter master register, Address offset: 0x200 */ + __IO uint32_t FM1R; /*!< CAN filter mode register, Address offset: 0x204 */ + uint32_t RESERVED2; /*!< Reserved, 0x208 */ + __IO uint32_t FS1R; /*!< CAN filter scale register, Address offset: 0x20C */ + uint32_t RESERVED3; /*!< Reserved, 0x210 */ + __IO uint32_t FFA1R; /*!< CAN filter FIFO assignment register, Address offset: 0x214 */ + uint32_t RESERVED4; /*!< Reserved, 0x218 */ + __IO uint32_t FA1R; /*!< CAN filter activation register, Address offset: 0x21C */ + uint32_t RESERVED5[8]; /*!< Reserved, 0x220-0x23F */ + CAN_FilterRegister_TypeDef sFilterRegister[28]; /*!< CAN Filter Register, Address offset: 0x240-0x31C */ +}CAN_TypeDef; + +/** + * @brief HDMI-CEC + */ + +typedef struct +{ + __IO uint32_t CR; /*!< CEC control register, Address offset:0x00 */ + __IO uint32_t CFGR; /*!< CEC configuration register, Address offset:0x04 */ + __IO uint32_t TXDR; /*!< CEC Tx data register , Address offset:0x08 */ + __IO uint32_t RXDR; /*!< CEC Rx Data Register, Address offset:0x0C */ + __IO uint32_t ISR; /*!< CEC Interrupt and Status Register, Address offset:0x10 */ + __IO uint32_t IER; /*!< CEC interrupt enable register, Address offset:0x14 */ +}CEC_TypeDef; + +/** + * @brief Comparator + */ + +typedef struct +{ + __IO uint32_t CSR; /*!< COMP comparator control and status register, Address offset: 0x1C */ +}COMP_TypeDef; + +/** + * @brief CRC calculation unit + */ + +typedef struct +{ + __IO uint32_t DR; /*!< CRC Data register, Address offset: 0x00 */ + __IO uint8_t IDR; /*!< CRC Independent data register, Address offset: 0x04 */ + uint8_t RESERVED0; /*!< Reserved, 0x05 */ + uint16_t RESERVED1; /*!< Reserved, 0x06 */ + __IO uint32_t CR; /*!< CRC Control register, Address offset: 0x08 */ + uint32_t RESERVED2; /*!< Reserved, 0x0C */ + __IO uint32_t INIT; /*!< Initial CRC value register, Address offset: 0x10 */ + __IO uint32_t POL; /*!< CRC polynomial register, Address offset: 0x14 */ +}CRC_TypeDef; + +/** + * @brief Clock Recovery System + */ +typedef struct +{ +__IO uint32_t CR; /*!< CRS ccontrol register, Address offset: 0x00 */ +__IO uint32_t CFGR; /*!< CRS configuration register, Address offset: 0x04 */ +__IO uint32_t ISR; /*!< CRS interrupt and status register, Address offset: 0x08 */ +__IO uint32_t ICR; /*!< CRS interrupt flag clear register, Address offset: 0x0C */ +}CRS_TypeDef; + +/** + * @brief Digital to Analog Converter + */ + +typedef struct +{ + __IO uint32_t CR; /*!< DAC control register, Address offset: 0x00 */ + __IO uint32_t SWTRIGR; /*!< DAC software trigger register, Address offset: 0x04 */ + __IO uint32_t DHR12R1; /*!< DAC channel1 12-bit right-aligned data holding register, Address offset: 0x08 */ + __IO uint32_t DHR12L1; /*!< DAC channel1 12-bit left aligned data holding register, Address offset: 0x0C */ + __IO uint32_t DHR8R1; /*!< DAC channel1 8-bit right aligned data holding register, Address offset: 0x10 */ + __IO uint32_t DHR12R2; /*!< DAC channel2 12-bit right aligned data holding register, Address offset: 0x14 */ + __IO uint32_t DHR12L2; /*!< DAC channel2 12-bit left aligned data holding register, Address offset: 0x18 */ + __IO uint32_t DHR8R2; /*!< DAC channel2 8-bit right-aligned data holding register, Address offset: 0x1C */ + __IO uint32_t DHR12RD; /*!< Dual DAC 12-bit right-aligned data holding register, Address offset: 0x20 */ + __IO uint32_t DHR12LD; /*!< DUAL DAC 12-bit left aligned data holding register, Address offset: 0x24 */ + __IO uint32_t DHR8RD; /*!< DUAL DAC 8-bit right aligned data holding register, Address offset: 0x28 */ + __IO uint32_t DOR1; /*!< DAC channel1 data output register, Address offset: 0x2C */ + __IO uint32_t DOR2; /*!< DAC channel2 data output register, Address offset: 0x30 */ + __IO uint32_t SR; /*!< DAC status register, Address offset: 0x34 */ +}DAC_TypeDef; + +/** + * @brief Debug MCU + */ + +typedef struct +{ + __IO uint32_t IDCODE; /*!< MCU device ID code, Address offset: 0x00 */ + __IO uint32_t CR; /*!< Debug MCU configuration register, Address offset: 0x04 */ + __IO uint32_t APB1FZ; /*!< Debug MCU APB1 freeze register, Address offset: 0x08 */ + __IO uint32_t APB2FZ; /*!< Debug MCU APB2 freeze register, Address offset: 0x0C */ +}DBGMCU_TypeDef; + +/** + * @brief DMA Controller + */ + +typedef struct +{ + __IO uint32_t CCR; /*!< DMA channel x configuration register */ + __IO uint32_t CNDTR; /*!< DMA channel x number of data register */ + __IO uint32_t CPAR; /*!< DMA channel x peripheral address register */ + __IO uint32_t CMAR; /*!< DMA channel x memory address register */ +}DMA_Channel_TypeDef; + +typedef struct +{ + __IO uint32_t ISR; /*!< DMA interrupt status register, Address offset: 0x00 */ + __IO uint32_t IFCR; /*!< DMA interrupt flag clear register, Address offset: 0x04 */ +}DMA_TypeDef; + +/** + * @brief External Interrupt/Event Controller + */ + +typedef struct +{ + __IO uint32_t IMR; /*!
© COPYRIGHT(c) 2014 STMicroelectronics
+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/** @addtogroup CMSIS + * @{ + */ + +/** @addtogroup stm32f0xx + * @{ + */ + +#ifndef __STM32F0xx_H +#define __STM32F0xx_H + +#ifdef __cplusplus + extern "C" { +#endif /* __cplusplus */ + +/** @addtogroup Library_configuration_section + * @{ + */ + +/* Uncomment the line below according to the target STM32 device used in your + application + */ + +#if !defined (STM32F030x6) && !defined (STM32F030x8) && \ + !defined (STM32F031x6) && !defined (STM32F038xx) && \ + !defined (STM32F042x6) && !defined (STM32F048xx) && \ + !defined (STM32F051x8) && !defined (STM32F058xx) && \ + !defined (STM32F071xB) && !defined (STM32F072xB) && !defined (STM32F078xx) + /* #define STM32F030x6 */ /*!< STM32F030x4, STM32F030x6 Devices (STM32F030xx microcontrollers where the Flash memory ranges between 16 and 32 Kbytes) */ + /* #define STM32F030x8 */ /*!< STM32F030x8 Devices (STM32F030xx microcontrollers where the Flash memory is 64 Kbytes) */ + /* #define STM32F031x6 */ /*!< STM32F031x4, STM32F031x6 Devices (STM32F031xx microcontrollers where the Flash memory ranges between 16 and 32 Kbytes) */ + /* #define STM32F038xx */ /*!< STM32F038xx Devices (STM32F038xx microcontrollers where the Flash memory is 32 Kbytes) */ + /* #define STM32F042x6 */ /*!< STM32F042x4, STM32F042x6 Devices (STM32F042xx microcontrollers where the Flash memory ranges between 16 and 32 Kbytes) */ + /* #define STM32F048x6 */ /*!< STM32F048xx Devices (STM32F042xx microcontrollers where the Flash memory is 32 Kbytes) */ + /* #define STM32F051x8 */ /*!< STM32F051x4, STM32F051x6, STM32F051x8 Devices (STM32F051xx microcontrollers where the Flash memory ranges between 16 and 64 Kbytes) */ + /* #define STM32F058xx */ /*!< STM32F058xx Devices (STM32F058xx microcontrollers where the Flash memory is 64 Kbytes) */ + /* #define STM32F071xB */ /*!< STM32F071x8, STM32F071xB Devices (STM32F071xx microcontrollers where the Flash memory ranges between 64 and 128 Kbytes) */ +#define STM32F072xB /*!< STM32F072x8, STM32F072xB Devices (STM32F072xx microcontrollers where the Flash memory ranges between 64 and 128 Kbytes) */ + /* #define STM32F078xx */ /*!< STM32F078xx Devices (STM32F078xx microcontrollers where the Flash memory is 128 Kbytes) */ +#endif + +/* Tip: To avoid modifying this file each time you need to switch between these + devices, you can define the device in your toolchain compiler preprocessor. + */ +#if !defined (USE_HAL_DRIVER) +/** + * @brief Comment the line below if you will not use the peripherals drivers. + In this case, these drivers will not be included and the application code will + be based on direct access to peripherals registers + */ +#define USE_HAL_DRIVER +#endif /* USE_HAL_DRIVER */ + +/** + * @brief CMSIS Device version number V2.0.0 + */ +#define __STM32F0xx_CMSIS_DEVICE_VERSION_MAIN (0x02) /*!< [31:24] main version */ +#define __STM32F0xx_CMSIS_DEVICE_VERSION_SUB1 (0x00) /*!< [23:16] sub1 version */ +#define __STM32F0xx_CMSIS_DEVICE_VERSION_SUB2 (0x00) /*!< [15:8] sub2 version */ +#define __STM32F0xx_CMSIS_DEVICE_VERSION_RC (0x00) /*!< [7:0] release candidate */ +#define __STM32F0xx_CMSIS_DEVICE_VERSION ((__CMSIS_DEVICE_VERSION_MAIN << 24)\ + |(__CMSIS_DEVICE_HAL_VERSION_SUB1 << 16)\ + |(__CMSIS_DEVICE_HAL_VERSION_SUB2 << 8 )\ + |(__CMSIS_DEVICE_HAL_VERSION_RC)) + +/** + * @} + */ + +/** @addtogroup Device_Included + * @{ + */ + +#if defined(STM32F030x6) + #include "stm32f030x6.h" +#elif defined(STM32F030x8) + #include "stm32f030x8.h" +#elif defined(STM32F031x6) + #include "stm32f031x6.h" +#elif defined(STM32F038xx) + #include "stm32f038xx.h" +#elif defined(STM32F042x6) + #include "stm32f042x6.h" +#elif defined(STM32F048xx) + #include "stm32f048xx.h" +#elif defined(STM32F051x8) + #include "stm32f051x8.h" +#elif defined(STM32F058xx) + #include "stm32f058xx.h" +#elif defined(STM32F071xB) + #include "stm32f071xb.h" +#elif defined(STM32F072xB) + #include "stm32f072xb.h" +#elif defined(STM32F078xx) + #include "stm32f078xx.h" +#else + #error "Please select first the target STM32F0xx device used in your application (in stm32f0xx.h file)" +#endif + +/** + * @} + */ + +/** @addtogroup Exported_types + * @{ + */ +typedef enum +{ + RESET = 0, + SET = !RESET +} FlagStatus, ITStatus; + +typedef enum +{ + DISABLE = 0, + ENABLE = !DISABLE +} FunctionalState; +#define IS_FUNCTIONAL_STATE(STATE) (((STATE) == DISABLE) || ((STATE) == ENABLE)) + +typedef enum +{ + ERROR = 0, + SUCCESS = !ERROR +} ErrorStatus; + +/** + * @} + */ + + +/** @addtogroup Exported_macros + * @{ + */ +#define SET_BIT(REG, BIT) ((REG) |= (BIT)) + +#define CLEAR_BIT(REG, BIT) ((REG) &= ~(BIT)) + +#define READ_BIT(REG, BIT) ((REG) & (BIT)) + +#define CLEAR_REG(REG) ((REG) = (0x0)) + +#define WRITE_REG(REG, VAL) ((REG) = (VAL)) + +#define READ_REG(REG) ((REG)) + +#define MODIFY_REG(REG, CLEARMASK, SETMASK) WRITE_REG((REG), (((READ_REG(REG)) & (~(CLEARMASK))) | (SETMASK))) + +#define POSITION_VAL(VAL) (__CLZ(__RBIT(VAL))) + + +/** + * @} + */ + +#if defined (USE_HAL_DRIVER) + #include "stm32f0xx_hal.h" +#endif /* USE_HAL_DRIVER */ + + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* __STM32F0xx_H */ +/** + * @} + */ + +/** + * @} + */ + + + + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal.c new file mode 100644 index 0000000000..63aafb38d4 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal.c @@ -0,0 +1,430 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal.c + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief HAL module driver. + * This is the common part of the HAL initialization + * + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + The common HAL driver contains a set of generic and common APIs that can be + used by the PPP peripheral drivers and the user to start using the HAL. + [..] + The HAL contains two APIs categories: + (+) Common HAL APIs + (+) Services HAL APIs + + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @defgroup HAL + * @brief HAL module driver. + * @{ + */ + +#ifdef HAL_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/** + * @brief STM32F0xx HAL Driver version number V1.0.0 + */ +#define __STM32F0xx_HAL_VERSION_MAIN (0x01) /*!< [31:24] main version */ +#define __STM32F0xx_HAL_VERSION_SUB1 (0x00) /*!< [23:16] sub1 version */ +#define __STM32F0xx_HAL_VERSION_SUB2 (0x00) /*!< [15:8] sub2 version */ +#define __STM32F0xx_HAL_VERSION_RC (0x00) /*!< [7:0] release candidate */ +#define __STM32F0xx_HAL_VERSION ((__STM32F0xx_HAL_VERSION_MAIN << 24)\ + |(__STM32F0xx_HAL_VERSION_SUB1 << 16)\ + |(__STM32F0xx_HAL_VERSION_SUB2 << 8 )\ + |(__STM32F0xx_HAL_VERSION_RC)) + +#define IDCODE_DEVID_MASK ((uint32_t)0x00000FFF) + +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +static __IO uint32_t uwTick; +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup HAL_Private_Functions + * @{ + */ + +/** @defgroup HAL_Group1 Initialization and de-initialization Functions + * @brief Initialization and de-initialization functions + * +@verbatim + =============================================================================== + ##### Initialization and de-initialization functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Initializes the Flash interface, the NVIC allocation and initial clock + configuration. It initializes the source of time base also when timeout + is needed and the backup domain when enabled. + (+) de-Initializes common part of the HAL. + (+) Configure The time base source to have 1ms time base with a dedicated + Tick interrupt priority. + (++) Systick timer is used by default as source of time base, but user + can eventually implement his proper time base source (a general purpose + timer for example or other time source), keeping in mind that Time base + duration should be kept 1ms since PPP_TIMEOUT_VALUEs are defined and + handled in milliseconds basis. + (++) Time base configuration function (HAL_InitTick ()) is called automatically + at the beginning of the program after reset by HAL_Init() or at any time + when clock is configured, by HAL_RCC_ClockConfig(). + (++) Source of time base is configured to generate interrupts at regular + time intervals. Care must be taken if HAL_Delay() is called from a + peripheral ISR process, the Tick interrupt line must have higher priority + (numerically lower) than the peripheral interrupt. Otherwise the caller + ISR process will be blocked. + (++) functions affecting time base configurations are declared as __Weak + to make override possible in case of other implementations in user file. + +@endverbatim + * @{ + */ + +/** + * @brief This function configures the Flash prefetch, + * Configures time base source, NVIC and Low level hardware + * @note This function is called at the beginning of program after reset and before + * the clock configuration + * @note The time base configuration is based on HSI clock when exiting from Reset. + * Once done, time base tick start incrementing. + * In the default implementation,Systick is used as source of time base. + * The tick variable is incremented each 1ms in its ISR. + * @param None + * @retval HAL status + */ +HAL_StatusTypeDef HAL_Init(void) +{ + /* Configure Flash prefetch */ +#if (PREFETCH_ENABLE != 0) + __HAL_FLASH_PREFETCH_BUFFER_ENABLE(); +#endif /* PREFETCH_ENABLE */ + + /* Use systick as time base source and configure 1ms tick (default clock after Reset is HSI) */ + + HAL_InitTick(TICK_INT_PRIORITY); + + /* Init the low level hardware */ + HAL_MspInit(); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief This function de-Initializes common part of the HAL and stops the source + * of time base. + * @note This function is optional. + * @param None + * @retval HAL status + */ +HAL_StatusTypeDef HAL_DeInit(void) +{ + /* Reset of all peripherals */ + __APB1_FORCE_RESET(); + __APB1_RELEASE_RESET(); + + __APB2_FORCE_RESET(); + __APB2_RELEASE_RESET(); + + __AHB_FORCE_RESET(); + __AHB_RELEASE_RESET(); + + /* De-Init the low level hardware */ + HAL_MspDeInit(); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Initializes the MSP. + * @param None + * @retval None + */ +__weak void HAL_MspInit(void) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_MspInit could be implemented in the user file + */ +} + +/** + * @brief DeInitializes the MSP. + * @param None + * @retval None + */ +__weak void HAL_MspDeInit(void) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_MspDeInit could be implemented in the user file + */ +} + +/** + * @brief This function configures the source of the time base. + * The time source is configured to have 1ms time base with a dedicated + * Tick interrupt priority. + * @note This function is called automatically at the beginning of program after + * reset by HAL_Init() or at any time when clock is reconfigured by HAL_RCC_ClockConfig(). + * @note In the default implementation, SysTick timer is the source of time base. + * It is used to generate interrupts at regular time intervals. + * Care must be taken if HAL_Delay() is called from a peripheral ISR process, + * The the SysTick interrupt must have higher priority (numerically lower) + * than the peripheral interrupt. Otherwise the caller ISR process will be blocked. + * The function is declared as __Weak to be overwritten in case of other + * implementation in user file. + * @param TickPriority: Tick interrupt priority. + * @retval HAL status + */ +__weak HAL_StatusTypeDef HAL_InitTick(uint32_t TickPriority) +{ + /*Configure the SysTick to have interrupt in 1ms time basis*/ + HAL_SYSTICK_Config(HAL_RCC_GetHCLKFreq()/1000); + + /*Configure the SysTick IRQ priority */ + HAL_NVIC_SetPriority(SysTick_IRQn, TickPriority ,0); + + /* Return function status */ + return HAL_OK; +} + +/** + * @} + */ + +/** @defgroup HAL_Group2 HAL Control function + * @brief HAL Control functions + * +@verbatim + =============================================================================== + ##### HAL Control functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Provide a tick value in millisecond + (+) Provide a blocking delay in millisecond + (+) Suspend the time base source interrupt + (+) Resume the time base source interrupt + (+) Get the HAL API driver version + (+) Get the device identifier + (+) Get the device revision identifier + (+) Enable/Disable Debug module during Sleep mode + (+) Enable/Disable Debug module during STOP mode + (+) Enable/Disable Debug module during STANDBY mode + +@endverbatim + * @{ + */ + +/** + * @brief This function is called to increment a global variable "uwTick" + * used as application time base. + * @note In the default implementation, this variable is incremented each 1ms + * in Systick ISR. + * @note This function is declared as __weak to be overwritten in case of other + * implementations in user file. + * @param None + * @retval None + */ +__weak void HAL_IncTick(void) +{ + uwTick++; +} + +/** + * @brief Provides a tick value in millisecond. + * @note This function is declared as __weak to be overwritten in case of other + * implementations in user file. + * @param None + * @retval tick value + */ +__weak uint32_t HAL_GetTick(void) +{ + return uwTick; +} + +/** + * @brief Suspend Tick increment. + * @note In the default implementation , SysTick timer is the source of time base. It is + * used to generate interrupts at regular time intervals. Once HAL_SuspendTick() + * is called, the the SysTick interrupt will be disabled and so Tick increment + * is suspended. + * @note This function is declared as __weak to be overwritten in case of other + * implementations in user file. + * @param None + * @retval None + */ +__weak void HAL_SuspendTick(void) +{ + /* Disable SysTick Interrupt */ + SysTick->CTRL &= ~SysTick_CTRL_TICKINT_Msk; +} + +/** + * @brief Resume Tick increment. + * @note In the default implementation , SysTick timer is the source of time base. It is + * used to generate interrupts at regular time intervals. Once HAL_ResumeTick() + * is called, the the SysTick interrupt will be enabled and so Tick increment + * is resumed. + * @note This function is declared as __weak to be overwritten in case of other + * implementations in user file. + * @param None + * @retval None + */ +__weak void HAL_ResumeTick(void) +{ + /* Enable SysTick Interrupt */ + SysTick->CTRL |= SysTick_CTRL_TICKINT_Msk; +} + +/** + * @brief This function provides accurate delay (in milliseconds) based + * on variable incremented. + * @note In the default implementation , SysTick timer is the source of time base. + * It is used to generate interrupts at regular time intervals where uwTick + * is incremented. + * @note ThiS function is declared as __weak to be overwritten in case of other + * implementations in user file. + * @param Delay: specifies the delay time length, in milliseconds. + * @retval None + */ +__weak void HAL_Delay(__IO uint32_t Delay) +{ + uint32_t tickstart = 0; + tickstart = HAL_GetTick(); + while((HAL_GetTick() - tickstart) < Delay) + { + } +} + +/** + * @brief This method returns the HAL revision + * @param None + * @retval version : 0xXYZR (8bits for each decimal, R for RC) + */ +uint32_t HAL_GetHalVersion(void) +{ + return __STM32F0xx_HAL_VERSION; +} + +/** + * @brief Returns the device revision identifier. + * @param None + * @retval Device revision identifier + */ +uint32_t HAL_GetREVID(void) +{ + return(DBGMCU->IDCODE >> 16); +} + +/** + * @brief Returns the device identifier. + * @param None + * @retval Device identifier + */ +uint32_t HAL_GetDEVID(void) +{ + return(DBGMCU->IDCODE & IDCODE_DEVID_MASK); +} + +/** + * @brief Enable the Debug Module during STOP mode + * @param None + * @retval None + */ +void HAL_EnableDBGStopMode(void) +{ + SET_BIT(DBGMCU->CR, DBGMCU_CR_DBG_STOP); +} + +/** + * @brief Disable the Debug Module during STOP mode + * @param None + * @retval None + */ +void HAL_DisableDBGStopMode(void) +{ + CLEAR_BIT(DBGMCU->CR, DBGMCU_CR_DBG_STOP); +} + +/** + * @brief Enable the Debug Module during STANDBY mode + * @param None + * @retval None + */ +void HAL_EnableDBGStandbyMode(void) +{ + SET_BIT(DBGMCU->CR, DBGMCU_CR_DBG_STANDBY); +} + +/** + * @brief Disable the Debug Module during STANDBY mode + * @param None + * @retval None + */ +void HAL_DisableDBGStandbyMode(void) +{ + CLEAR_BIT(DBGMCU->CR, DBGMCU_CR_DBG_STANDBY); +} + +/** + * @} + */ + +/** + * @} + */ + +#endif /* HAL_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal.h new file mode 100644 index 0000000000..6f1f448e7e --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal.h @@ -0,0 +1,388 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal.h + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief This file contains all the functions prototypes for the HAL + * module driver. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32F0xx_HAL_H +#define __STM32F0xx_HAL_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal_conf.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @addtogroup HAL + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/* Exported constants --------------------------------------------------------*/ + +/** @defgroup HAL_DMA_Remapping + * Elements values convention: 0xYYYYYYYY + * - YYYYYYYY : Position in the SYSCFG register CFGR1 + * @{ + */ +#define HAL_REMAPDMA_ADC_DMA_CH2 ((uint32_t)SYSCFG_CFGR1_ADC_DMA_RMP) /*!< ADC DMA remap + 0: No remap (ADC DMA requests mapped on DMA channel 1 + 1: Remap (ADC DMA requests mapped on DMA channel 2 */ +#define HAL_REMAPDMA_USART1_TX_DMA_CH4 ((uint32_t)SYSCFG_CFGR1_USART1TX_DMA_RMP) /*!< USART1 TX DMA remap + 0: No remap (USART1_TX DMA request mapped on DMA channel 2 + 1: Remap (USART1_TX DMA request mapped on DMA channel 4 */ +#define HAL_REMAPDMA_USART1_RX_DMA_CH5 ((uint32_t)SYSCFG_CFGR1_USART1RX_DMA_RMP) /*!< USART1 RX DMA remap + 0: No remap (USART1_RX DMA request mapped on DMA channel 3 + 1: Remap (USART1_RX DMA request mapped on DMA channel 5 */ +#define HAL_REMAPDMA_TIM16_DMA_CH4 ((uint32_t)SYSCFG_CFGR1_TIM16_DMA_RMP) /*!< TIM16 DMA request remap + 0: No remap (TIM16_CH1 and TIM16_UP DMA requests mapped on DMA channel 3) + 1: Remap (TIM16_CH1 and TIM16_UP DMA requests mapped on DMA channel 4) */ +#define HAL_REMAPDMA_TIM17_DMA_CH2 ((uint32_t)SYSCFG_CFGR1_TIM17_DMA_RMP) /*!< TIM17 DMA request remap + 0: No remap (TIM17_CH1 and TIM17_UP DMA requests mapped on DMA channel 1 + 1: Remap (TIM17_CH1 and TIM17_UP DMA requests mapped on DMA channel 2) */ + +#if defined (STM32F071xB) || defined (STM32F072xB) || defined (STM32F078xx) +#define HAL_REMAPDMA_TIM16_DMA_CH6 ((uint32_t)SYSCFG_CFGR1_TIM16_DMA_RMP2) /*!< TIM16 alternate DMA request remapping bit. Available on STM32F07x devices only + 0: No alternate remap (TIM16 DMA requestsmapped according to TIM16_DMA_RMP bit) + 1: Alternate remap (TIM16_CH1 and TIM16_UP DMA requests mapped on DMA channel 6) */ +#define HAL_REMAPDMA_TIM17_DMA_CH7 ((uint32_t)SYSCFG_CFGR1_TIM17_DMA_RMP2) /*!< TIM17 alternate DMA request remapping bit. Available on STM32F07x devices only + 0: No alternate remap (TIM17 DMA requestsmapped according to TIM17_DMA_RMP bit) + 1: Alternate remap (TIM17_CH1 and TIM17_UP DMA requests mapped on DMA channel 7) */ +#define HAL_REMAPDMA_SPI2_DMA_CH67 ((uint32_t)SYSCFG_CFGR1_SPI2_DMA_RMP) /*!< SPI2 DMA request remapping bit. Available on STM32F07x devices only. + 0: No remap (SPI2_RX and SPI2_TX DMA requests mapped on DMA channel 4 and 5 respectively) + 1: 1: Remap (SPI2_RX and SPI2_TX DMA requests mapped on DMA channel 6 and 7 respectively) */ +#define HAL_REMAPDMA_USART2_DMA_CH67 ((uint32_t)SYSCFG_CFGR1_USART2_DMA_RMP) /*!< USART2 DMA request remapping bit. Available on STM32F07x devices only. + 0: No remap (USART2_RX and USART2_TX DMA requests mapped on DMA channel 5 and 4 respectively) + 1: 1: Remap (USART2_RX and USART2_TX DMA requests mapped on DMA channel 6 and 7 respectively) */ +#define HAL_REMAPDMA_USART3_DMA_CH32 ((uint32_t)SYSCFG_CFGR1_USART3_DMA_RMP) /*!< USART3 DMA request remapping bit. Available on STM32F07x devices only. + 0: No remap (USART3_RX and USART3_TX DMA requests mapped on DMA channel 6 and 7 respectively) + 1: 1: Remap (USART3_RX and USART3_TX DMA requests mapped on DMA channel 3 and 2 respectively) */ +#define HAL_REMAPDMA_I2C1_DMA_CH76 ((uint32_t)SYSCFG_CFGR1_I2C1_DMA_RMP) /*!< I2C1 DMA request remapping bit. Available on STM32F07x devices only. + 0: No remap (I2C1_RX and I2C1_TX DMA requests mapped on DMA channel 3 and 2 respectively) + 1: Remap (I2C1_RX and I2C1_TX DMA requests mapped on DMA channel 7 and 6 respectively) */ +#define HAL_REMAPDMA_TIM1_DMA_CH6 ((uint32_t)SYSCFG_CFGR1_TIM1_DMA_RMP) /*!< TIM1 DMA request remapping bit. Available on STM32F07x devices only. + 0: No remap (TIM1_CH1, TIM1_CH2 and TIM1_CH3 DMA requests mapped on DMA channel 2, 3 and 4 respectively) + 1: Remap (TIM1_CH1, TIM1_CH2 and TIM1_CH3 DMA requests mapped on DMA channel 6 */ +#define HAL_REMAPDMA_TIM2_DMA_CH7 ((uint32_t)SYSCFG_CFGR1_TIM2_DMA_RMP) /*!< TIM2 DMA request remapping bit. Available on STM32F07x devices only. + 0: No remap (TIM2_CH2 and TIM2_CH4 DMA requests mapped on DMA channel 3 and 4 respectively) + 1: Remap (TIM2_CH2 and TIM2_CH4 DMA requests mapped on DMA channel 7 */ +#define HAL_REMAPDMA_TIM3_DMA_CH6 ((uint32_t)SYSCFG_CFGR1_TIM3_DMA_RMP) /*!< TIM3 DMA request remapping bit. Available on STM32F07x devices only. + 0: No remap (TIM3_CH1 and TIM3_TRIG DMA requests mapped on DMA channel 4) + 1: Remap (TIM3_CH1 and TIM3_TRIG DMA requests mapped on DMA channel 6) */ +#endif + +#if defined (STM32F071xB) || defined (STM32F072xB) || defined (STM32F078xx) +#define IS_HAL_REMAPDMA(RMP) (((RMP) == HAL_REMAPDMA_ADC_DMA_CH2) || \ + ((RMP) == HAL_REMAPDMA_USART1_TX_DMA_CH4) || \ + ((RMP) == HAL_REMAPDMA_USART1_RX_DMA_CH5) || \ + ((RMP) == HAL_REMAPDMA_TIM16_DMA_CH4) || \ + ((RMP) == HAL_REMAPDMA_TIM17_DMA_CH2) || \ + ((RMP) == HAL_REMAPDMA_TIM16_DMA_CH6) || \ + ((RMP) == HAL_REMAPDMA_TIM17_DMA_CH7) || \ + ((RMP) == HAL_REMAPDMA_SPI2_DMA_CH67) || \ + ((RMP) == HAL_REMAPDMA_USART2_DMA_CH67) || \ + ((RMP) == HAL_REMAPDMA_USART3_DMA_CH32) || \ + ((RMP) == HAL_REMAPDMA_I2C1_DMA_CH76) || \ + ((RMP) == HAL_REMAPDMA_TIM1_DMA_CH6) || \ + ((RMP) == HAL_REMAPDMA_TIM2_DMA_CH7) || \ + ((RMP) == HAL_REMAPDMA_TIM3_DMA_CH6)) +#else +#define IS_HAL_REMAPDMA(RMP) (((RMP) == HAL_REMAPDMA_ADC_DMA_CH2) || \ + ((RMP) == HAL_REMAPDMA_USART1_TX_DMA_CH4) || \ + ((RMP) == HAL_REMAPDMA_USART1_RX_DMA_CH5) || \ + ((RMP) == HAL_REMAPDMA_TIM16_DMA_CH4) || \ + ((RMP) == HAL_REMAPDMA_TIM17_DMA_CH2)) +#endif +/** + * @} + */ + +#if defined(STM32F042x6) || defined(STM32F048xx) +/** @defgroup HAL_Pin_Remapping + * @{ + */ +#define HAL_REMAP_PA11_PA12 (SYSCFG_CFGR1_PA11_PA12_RMP) /*!< PA11 and PA12 remapping bit for small packages (28 and 20 pins). + 0: No remap (pin pair PA9/10 mapped on the pins) + 1: Remap (pin pair PA11/12 mapped instead of PA9/10) */ + +#define IS_HAL_REMAP_PIN(RMP) ((RMP) == HAL_REMAP_PA11_PA12) +/** + * @} + */ +#endif /* STM32F042x6 || STM32F048xx */ + +/** @defgroup HAL_FastModePlus_I2C + * @{ + */ +#define HAL_SYSCFG_FASTMODEPLUS_I2C_PB6 (SYSCFG_CFGR1_I2C_FMP_PB6) /*!< Fast Mode Plus (FM+) driving capability activation on the pad + 0: PB6 pin operates in standard mode + 1: I2C FM+ mode enabled on PB6 pin, and the Speed control is bypassed */ +#define HAL_SYSCFG_FASTMODEPLUS_I2C_PB7 (SYSCFG_CFGR1_I2C_FMP_PB7) /*!< Fast Mode Plus (FM+) driving capability activation on the pad + 0: PB7 pin operates in standard mode + 1: I2C FM+ mode enabled on PB7 pin, and the Speed control is bypassed */ +#define HAL_SYSCFG_FASTMODEPLUS_I2C_PB8 (SYSCFG_CFGR1_I2C_FMP_PB8) /*!< Fast Mode Plus (FM+) driving capability activation on the pad + 0: PB8 pin operates in standard mode + 1: I2C FM+ mode enabled on PB8 pin, and the Speed control is bypassed */ +#define HAL_SYSCFG_FASTMODEPLUS_I2C_PB9 (SYSCFG_CFGR1_I2C_FMP_PB9) /*!< Fast Mode Plus (FM+) driving capability activation on the pad + 0: PB9 pin operates in standard mode + 1: I2C FM+ mode enabled on PB9 pin, and the Speed control is bypassed */ + +#if defined(STM32F030x6) || defined(STM32F031x6) || defined(STM32F038xx) || \ + defined(STM32F042x6) || defined(STM32F048xx) || \ + defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) +#define HAL_SYSCFG_FASTMODEPLUS_I2C1 (SYSCFG_CFGR1_I2C_FMP_I2C1) /*!< I2C1 fast mode Plus driving capability activation + 0: FM+ mode is not enabled on I2C1 pins selected through AF selection bits + 1: FM+ mode is enabled on I2C1 pins selected through AF selection bits */ +#endif + +#if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) +#define HAL_SYSCFG_FASTMODEPLUS_I2C2 (SYSCFG_CFGR1_I2C_FMP_I2C2) /*!< I2C2 fast mode Plus driving capability activation + 0: FM+ mode is not enabled on I2C2 pins selected through AF selection bits + 1: FM+ mode is enabled on I2C2 pins selected through AF selection bits */ +#endif + +#if defined(STM32F030x6) || defined(STM32F031x6) || defined(STM32F038xx) +#define HAL_SYSCFG_FASTMODEPLUS_I2C2_PA9 (SYSCFG_CFGR1_I2C_FMP_PA9) /*!< Fast Mode Plus (FM+) driving capability activation on the pad + 0: PA9 pin operates in standard mode + 1: FM+ mode is enabled on PA9 pin, and the Speed control is bypassed */ +#define HAL_SYSCFG_FASTMODEPLUS_I2C2_PA10 (SYSCFG_CFGR1_I2C_FMP_PA10) /*!< Fast Mode Plus (FM+) driving capability activation on the pad + 0: PA10 pin operates in standard mode + 1: FM+ mode is enabled on PA10 pin, and the Speed control is bypassed */ +#endif + +/** + * @} + */ + + +/* Exported macros -----------------------------------------------------------*/ + +/** @brief Freeze/Unfreeze Peripherals in Debug mode + */ +#define __HAL_FREEZE_TIM3_DBGMCU() (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_TIM3_STOP)) +#define __HAL_UNFREEZE_TIM3_DBGMCU() (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_TIM3_STOP)) + +#define __HAL_FREEZE_TIM14_DBGMCU() (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_TIM14_STOP)) +#define __HAL_UNFREEZE_TIM14_DBGMCU() (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_TIM14_STOP)) + +#define __HAL_FREEZE_RTC_DBGMCU() (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_RTC_STOP)) +#define __HAL_UNFREEZE_RTC_DBGMCU() (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_RTC_STOP)) + +#define __HAL_FREEZE_WWDG_DBGMCU() (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_WWDG_STOP)) +#define __HAL_UNFREEZE_WWDG_DBGMCU() (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_WWDG_STOP)) + +#define __HAL_FREEZE_IWDG_DBGMCU() (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_IWDG_STOP)) +#define __HAL_UNFREEZE_IWDG_DBGMCU() (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_IWDG_STOP)) + +#define __HAL_FREEZE_I2C1_TIMEOUT_DBGMCU() (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_I2C1_SMBUS_TIMEOUT)) +#define __HAL_UNFREEZE_I2C1_TIMEOUT_DBGMCU() (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_I2C1_SMBUS_TIMEOUT)) + +#if defined(STM32F031x6) || defined(STM32F042x6) || defined(STM32F048xx) || defined(STM32F051x8) || \ + defined(STM32F071xB) || defined(STM32F072xB) || \ + defined(STM32F038xx) || defined(STM32F058xx) || defined(STM32F078xx) +#define __HAL_FREEZE_TIM2_DBGMCU() (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_TIM2_STOP)) +#define __HAL_UNFREEZE_TIM2_DBGMCU() (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_TIM2_STOP)) +#endif /* STM32F031x6 || STM32F042x6 || STM32F048xx || STM32F051x8 || */ + /* STM32F071xB || STM32F072xB || */ + /* STM32F038xx || STM32F058xx || STM32F078xx */ + +#if defined(STM32F030x8) || defined(STM32F051x8) || \ + defined(STM32F071xB) || defined(STM32F072xB) || \ + defined(STM32F058xx) || defined(STM32F078xx) +#define __HAL_FREEZE_TIM6_DBGMCU() (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_TIM6_STOP)) +#define __HAL_UNFREEZE_TIM6_DBGMCU() (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_TIM6_STOP)) +#endif /* STM32F030x8 || STM32F051x8 || */ + /* STM32F071xB || STM32F072xB || */ + /* STM32F058xx || STM32F078xx */ + +#if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) +#define __HAL_FREEZE_TIM7_DBGMCU() (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_TIM7_STOP)) +#define __HAL_UNFREEZE_TIM7_DBGMCU() (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_TIM7_STOP)) +#endif /* STM32F071xB || STM32F072xB || STM32F078xx */ + +#if defined(STM32F042x6) || defined(STM32F048xx) || defined(STM32F072xB) +#define __HAL_FREEZE_CAN_DBGMCU() (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_CAN1_STOP)) +#define __HAL_UNFREEZE_CAN_DBGMCU() (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_CAN1_STOP)) +#endif /* STM32F042x6 || STM32F072xB */ + + +#define __HAL_FREEZE_TIM1_DBGMCU() (DBGMCU->APB2FZ |= (DBGMCU_APB2_FZ_DBG_TIM1_STOP)) +#define __HAL_UNFREEZE_TIM1_DBGMCU() (DBGMCU->APB2FZ &= ~(DBGMCU_APB2_FZ_DBG_TIM1_STOP)) + +#if defined(STM32F030x8) || defined(STM32F051x8) || \ + defined(STM32F071xB) || defined(STM32F072xB) || \ + defined(STM32F058xx) || defined(STM32F078xx) +#define __HAL_FREEZE_TIM15_DBGMCU() (DBGMCU->APB2FZ |= (DBGMCU_APB2_FZ_DBG_TIM15_STOP)) +#define __HAL_UNFREEZE_TIM15_DBGMCU() (DBGMCU->APB2FZ &= ~(DBGMCU_APB2_FZ_DBG_TIM15_STOP)) +#endif /* STM32F030x8 || STM32F051x8 || */ + /* STM32F071xB || STM32F072xB || */ + /* STM32F058xx || STM32F078xx */ + +#define __HAL_FREEZE_TIM16_DBGMCU() (DBGMCU->APB2FZ |= (DBGMCU_APB2_FZ_DBG_TIM16_STOP)) +#define __HAL_UNFREEZE_TIM16_DBGMCU() (DBGMCU->APB2FZ &= ~(DBGMCU_APB2_FZ_DBG_TIM16_STOP)) + +#define __HAL_FREEZE_TIM17_DBGMCU() (DBGMCU->APB2FZ |= (DBGMCU_APB2_FZ_DBG_TIM17_STOP)) +#define __HAL_UNFREEZE_TIM17_DBGMCU() (DBGMCU->APB2FZ &= ~(DBGMCU_APB2_FZ_DBG_TIM17_STOP)) + +/** @brief Main Flash memory mapped at 0x00000000 + */ +#define __HAL_REMAPMEMORY_FLASH() (SYSCFG->CFGR1 &= ~(SYSCFG_CFGR1_MEM_MODE)) + +/** @brief System Flash memory mapped at 0x00000000 + */ +#define __HAL_REMAPMEMORY_SYSTEMFLASH() do {SYSCFG->CFGR1 &= ~(SYSCFG_CFGR1_MEM_MODE); \ + SYSCFG->CFGR1 |= SYSCFG_CFGR1_MEM_MODE_0; \ + }while(0) + +/** @brief Embedded SRAM mapped at 0x00000000 + */ +#define __HAL_REMAPMEMORY_SRAM() do {SYSCFG->CFGR1 &= ~(SYSCFG_CFGR1_MEM_MODE); \ + SYSCFG->CFGR1 |= (SYSCFG_CFGR1_MEM_MODE_0 | SYSCFG_CFGR1_MEM_MODE_1); \ + }while(0) + +/** @brief DMA remapping enable/disable macros + * @param __DMA_REMAP__: This parameter can be a value of @ref HAL_DMA_Remapping + */ +#define __HAL_REMAPDMA_CHANNEL_ENABLE(__DMA_REMAP__) do {assert_param(IS_HAL_REMAPDMA((__DMA_REMAP__))); \ + SYSCFG->CFGR1 |= (__DMA_REMAP__); \ + }while(0) +#define __HAL_REMAPDMA_CHANNEL_DISABLE(__DMA_REMAP__) do {assert_param(IS_HAL_REMAPDMA((__DMA_REMAP__))); \ + SYSCFG->CFGR1 &= ~(__DMA_REMAP__); \ + }while(0) + +#if defined(STM32F042x6) || defined(STM32F048xx) +/** @brief Pin remapping enable/disable macros + * @param __PIN_REMAP__: This parameter can be a value of @ref HAL_Pin_Remapping + */ +#define __HAL_REMAP_PIN_ENABLE(__PIN_REMAP__) do {assert_param(IS_HAL_REMAP_PIN((__PIN_REMAP__))); \ + SYSCFG->CFGR1 |= (__PIN_REMAP__); \ + }while(0) +#define __HAL_REMAP_PIN_DISABLE(__PIN_REMAP__) do {assert_param(IS_HAL_REMAP_PIN((__DMA_REMAP__))); \ + SYSCFG->CFGR1 &= ~(__PIN_REMAP__); \ + }while(0) +#endif /* STM32F042x6 || STM32F048xx */ + +/** @brief Fast mode Plus driving capability enable/disable macros + * @param __FASTMODEPLUS__: This parameter can be a value of @ref HAL_FastModePlus_I2C + */ +#define __HAL_SYSCFG_FASTMODEPLUS_ENABLE(__FASTMODEPLUS__) do {assert_param(IS_HAL_SYSCFG_FASTMODEPLUS_CONFIG((__FASTMODEPLUS__))); \ + SYSCFG->CFGR1 |= (__FASTMODEPLUS__); \ + }while(0) + +#define __HAL_SYSCFG_FASTMODEPLUS_DISABLE(__FASTMODEPLUS__) do {assert_param(IS_HAL_SYSCFG_FASTMODEPLUS_CONFIG((__FASTMODEPLUS__))); \ + SYSCFG->CFGR1 &= ~(__FASTMODEPLUS__); \ + }while(0) + +/** @brief SYSCFG Break Lockup lock + * Enables and locks the connection of Cortex-M0 LOCKUP (Hardfault) output to TIM1/15/16/17 Break input + * @note The selected configuration is locked and can be unlocked by system reset + */ +#define __HAL_SYSCFG_BREAK_LOCKUP_LOCK() do {SYSCFG->CFGR2 &= ~(SYSCFG_CFGR2_LOCKUP_LOCK); \ + SYSCFG->CFGR2 |= SYSCFG_CFGR2_LOCKUP_LOCK; \ + }while(0) + +#if defined(STM32F031x6) || defined(STM32F042x6) || defined(STM32F048xx) || defined(STM32F051x8) || \ + defined(STM32F071xB) || defined(STM32F072xB) +/** @brief SYSCFG Break PVD lock + * Enables and locks the PVD connection with Timer1/8/15/16/17 Break Input, , as well as the PVDE and PLS[2:0] in the PWR_CR register + * @note The selected configuration is locked and can be unlocked by system reset + */ +#define __HAL_SYSCFG_BREAK_PVD_LOCK() do {SYSCFG->CFGR2 &= ~(SYSCFG_CFGR2_PVD_LOCK); \ + SYSCFG->CFGR2 |= SYSCFG_CFGR2_PVD_LOCK; \ + }while(0) +#endif /* STM32F031x6 || STM32F042x6 || STM32F048xx || STM32F051x8) || */ + /* STM32F071xB || STM32F072xB */ + +/** @brief SYSCFG Break SRAM PARITY lock + * Enables and locks the SRAM_PARITY error signal with Break Input of TIMER1/8/15/16/17 + * @note The selected configuration is locked and can be unlocked by system reset + */ +#define __HAL_SYSCFG_BREAK_SRAMPARITY_LOCK() do {SYSCFG->CFGR2 &= ~(SYSCFG_CFGR2_SRAM_PARITY_LOCK); \ + SYSCFG->CFGR2 |= SYSCFG_CFGR2_SRAM_PARITY_LOCK; \ + }while(0) + +/** + * @brief Parity check on RAM disable macro + * @note Disabling the parity check on RAM locks the configuration bit. + * To re-enable the parity check on RAM perform a system reset. + */ +#define __HAL_SYSCFG_RAM_PARITYCHECK_DISABLE() (SYSCFG->CFGR2 |= SYSCFG_CFGR2_SRAM_PEF) + + +/* Exported functions --------------------------------------------------------*/ + +/* Initialization and de-initialization functions ****************************/ +HAL_StatusTypeDef HAL_Init(void); +HAL_StatusTypeDef HAL_DeInit(void); +void HAL_MspInit(void); +void HAL_MspDeInit(void); +HAL_StatusTypeDef HAL_InitTick (uint32_t TickPriority); + +/* Peripheral Control functions **********************************************/ +void HAL_IncTick(void); +void HAL_Delay(__IO uint32_t Delay); +uint32_t HAL_GetTick(void); +void HAL_SuspendTick(void); +void HAL_ResumeTick(void); +uint32_t HAL_GetHalVersion(void); +uint32_t HAL_GetREVID(void); +uint32_t HAL_GetDEVID(void); + +void HAL_EnableDBGStopMode(void); +void HAL_DisableDBGStopMode(void); +void HAL_EnableDBGStandbyMode(void); +void HAL_DisableDBGStandbyMode(void); + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __STM32F0xx_HAL_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_adc.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_adc.c new file mode 100644 index 0000000000..c0d7057c94 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_adc.c @@ -0,0 +1,1790 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_adc.c + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief This file provides firmware functions to manage the following + * functionalities of the Analog to Digital Convertor (ADC) + * peripheral: + * + Initialization and de-initialization functions + * ++ Initialization and Configuration of ADC + * + Operation functions + * ++ Start, stop, get result of conversions of regular group, + * using 3 possible modes: polling, interruption or DMA. + * + Control functions + * ++ Analog Watchdog configuration + * ++ Channels configuration on regular group + * + State functions + * ++ ADC state machine management + * ++ Interrupts and flags management + * + @verbatim + ============================================================================== + ##### ADC specific features ##### + ============================================================================== + [..] + (#) 12-bit, 10-bit, 8-bit or 6-bit configurable resolution + + (#) Interrupt generation at the end of regular conversion and in case of + analog watchdog or overrun events. + + (#) Single and continuous conversion modes. + + (#) Scan mode for automatic conversion of channel 0 to channel ‘n’. + + (#) Data alignment with in-built data coherency. + + (#) Programmable sampling time. + + (#) ADC conversion group Regular. + + (#) External trigger (timer or EXTI) with configurable polarity. + + (#) DMA request generation for transfer of conversions data of regular group. + + (#) ADC calibration + + (#) ADC supply requirements: 2.4 V to 3.6 V at full speed and down to 1.8 V at + slower speed. + + (#) ADC input range: from Vref– (connected to Vssa) to Vref+ (connected to + Vdda or to an external voltage reference). + + + ##### How to use this driver ##### + ============================================================================== + [..] + + (#) Enable the ADC interface + As prerequisite, into HAL_ADC_MspInit(), ADC clock must be configured + at RCC top level: clock source and clock prescaler. + Two possible clock sources: synchronous clock derived from APB clock + or asynchronous clock derived from ADC dedicated HSI RC oscillator + 14MHz. + Example: + __ADC1_CLK_ENABLE(); (mandatory) + + HI14 enable or let under control of ADC: (optional) + + RCC_OscInitTypeDef RCC_OscInitStructure; + RCC_OscInitStructure.OscillatorType = RCC_OSCILLATORTYPE_HSI14; + RCC_OscInitStructure.HSI14CalibrationValue = RCC_HSI14CALIBRATION_DEFAULT; + RCC_OscInitStructure.HSI14State = RCC_HSI14_ADC_CONTROL; + RCC_OscInitStructure.PLL... (optional if used for system clock) + HAL_RCC_OscConfig(&RCC_OscInitStructure); + + Parameter "HSI14State" must be set either: + - to "...HSI14State = RCC_HSI14_ADC_CONTROL" to let the ADC control + the HSI14 oscillator enable/disable (if not used to supply the main + system clock): feature used if ADC mode LowPowerAutoPowerOff is + enabled. + - to "...HSI14State = RCC_HSI14_ON" to maintain the HSI14 oscillator + always enabled: can be used to supply the main system clock. + + (#) ADC pins configuration + (++) Enable the clock for the ADC GPIOs using the following function: + __GPIOx_CLK_ENABLE(); + (++) Configure these ADC pins in analog mode using HAL_GPIO_Init(); + + (#) Configure the ADC parameters (conversion resolution, data alignment, + continuous mode, ...) using the HAL_ADC_Init() function. + + (#) Activate the ADC peripheral using one of the start functions: + HAL_ADC_Start(), HAL_ADC_Start_IT(), HAL_ADC_Start_DMA(). + + *** Channels to regular group configuration *** + ============================================ + [..] + (+) To configure the ADC regular group features, use + HAL_ADC_Init() and HAL_ADC_ConfigChannel() functions. + (+) To activate the continuous mode, use the HAL_ADC_Init() function. + (+) To read the ADC converted values, use the HAL_ADC_GetValue() function. + + *** DMA for regular configuration *** + ============================================================= + [..] + (+) To enable the DMA mode for regular group, use the + HAL_ADC_Start_DMA() function. + (+) To enable the generation of DMA requests continuously at the end of + the last DMA transfer, use the HAL_ADC_Init() function. + + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @defgroup ADC + * @brief ADC HAL module driver + * @{ + */ + +#ifdef HAL_ADC_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ + /* Fixed timeout values for ADC calibration, enable settling time, disable */ + /* settling time. */ + /* Values defined to be higher than worst cases: low clock frequency, */ + /* maximum prescaler. */ + /* Ex of profile low frequency : Clock source at 0.1 MHz, ADC clock */ + /* prescaler 4, sampling time 7.5 ADC clock cycles, resolution 12 bits. */ + /* Unit: ms */ + #define ADC_ENABLE_TIMEOUT 2 + #define ADC_DISABLE_TIMEOUT 2 + #define ADC_STOP_CONVERSION_TIMEOUT 2 + + /* Delay of 10us fixed to worst case: maximum CPU frequency 180MHz to have */ + /* the minimum number of CPU cycles to fulfill this delay */ + #define ADC_DELAY_10US_MIN_CPU_CYCLES 1800 + +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +static HAL_StatusTypeDef ADC_Enable(ADC_HandleTypeDef* hadc); +static HAL_StatusTypeDef ADC_Disable(ADC_HandleTypeDef* hadc); +static HAL_StatusTypeDef ADC_ConversionStop(ADC_HandleTypeDef* hadc); +static void ADC_DMAConvCplt(DMA_HandleTypeDef *hdma); +static void ADC_DMAHalfConvCplt(DMA_HandleTypeDef *hdma); +static void ADC_DMAError(DMA_HandleTypeDef *hdma); +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup ADC_Private_Functions + * @{ + */ + +/** @defgroup ADC_Group1 Initialization/de-initialization functions + * @brief Initialization and Configuration functions + * +@verbatim + =============================================================================== + ##### Initialization and de-initialization functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Initialize and configure the ADC. + (+) De-initialize the ADC +@endverbatim + * @{ + */ + +/** + * @brief Initializes the ADC peripheral and regular group according to + * parameters specified in structure "ADC_InitTypeDef". + * @note As prerequisite, ADC clock must be configured at RCC top level + * depending on both possible clock sources: APB clock of HSI clock. + * See commented example code below that can be copied and uncommented + * into HAL_ADC_MspInit(). + * @note Possibility to update parameters on the fly: + * This function initializes the ADC MSP (HAL_ADC_MspInit()) only when + * coming from ADC state reset. Following calls to this function can + * be used to reconfigure some parameters of ADC_InitTypeDef + * structure on the fly, without modifiying MSP configuration. If ADC + * MSP has to be modified again, HAL_ADC_DeInit() must be called + * before HAL_ADC_Init(). + * The setting of these parameters is conditioned to ADC state. + * For parameters constraints, see comments of structure + * "ADC_InitTypeDef". + * @note This function configures the ADC within 2 scopes: scope of entire + * ADC and scope of regular group. For parameters details, see comments + * of structure "ADC_InitTypeDef". + * @param hadc: ADC handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_ADC_Init(ADC_HandleTypeDef* hadc) +{ + HAL_StatusTypeDef tmpHALStatus = HAL_OK; + uint32_t tmpCFGR1 = 0; + + /* Check ADC handle */ + if(hadc == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance)); + assert_param(IS_ADC_CLOCKPRESCALER(hadc->Init.ClockPrescaler)); + assert_param(IS_ADC_RESOLUTION(hadc->Init.Resolution)); + assert_param(IS_ADC_DATA_ALIGN(hadc->Init.DataAlign)); + assert_param(IS_ADC_SCAN_MODE(hadc->Init.ScanConvMode)); + assert_param(IS_FUNCTIONAL_STATE(hadc->Init.ContinuousConvMode)); + assert_param(IS_FUNCTIONAL_STATE(hadc->Init.DiscontinuousConvMode)); + assert_param(IS_ADC_EXTTRIG_EDGE(hadc->Init.ExternalTrigConvEdge)); + assert_param(IS_ADC_EXTTRIG(hadc->Init.ExternalTrigConv)); + assert_param(IS_FUNCTIONAL_STATE(hadc->Init.DMAContinuousRequests)); + assert_param(IS_ADC_EOC_SELECTION(hadc->Init.EOCSelection)); + assert_param(IS_ADC_OVERRUN(hadc->Init.Overrun)); + assert_param(IS_FUNCTIONAL_STATE(hadc->Init.LowPowerAutoWait)); + assert_param(IS_FUNCTIONAL_STATE(hadc->Init.LowPowerAutoPowerOff)); + + /* As prerequisite, into HAL_ADC_MspInit(), ADC clock must be configured */ + /* at RCC top level depending on both possible clock sources: */ + /* APB clock or HSI clock. */ + /* For example: */ + /* __ADC1_CLK_ENABLE(); */ + /* __HAL_RCC_HSI14ADC_ENABLE(); */ + + + /* Actions performed only if ADC is coming from state reset: */ + /* - Initialization of ADC MSP */ + /* - ADC voltage regulator enable */ + if (hadc->State == HAL_ADC_STATE_RESET) + { + /* Init the low level hardware */ + HAL_ADC_MspInit(hadc); + + } + + /* Configuration of ADC parameters if previous preliminary actions are */ + /* correctly completed. */ + /* and if there is no conversion on going on regular group (ADC can be */ + /* enabled anyway, in case of call of this function to update a parameter */ + /* on the fly). */ + if ((hadc->State != HAL_ADC_STATE_ERROR) && + (__HAL_ADC_IS_CONVERSION_ONGOING_REGULAR(hadc) == RESET) ) + { + /* Initialize the ADC state */ + hadc->State = HAL_ADC_STATE_BUSY; + + /* Parameters update conditioned to ADC state: */ + /* Parameters that can be updated only when ADC is disabled: */ + /* - ADC clock mode */ + /* - ADC clock prescaler */ + if (__HAL_ADC_IS_ENABLED(hadc) == RESET) + { + /* Some parameters of this register are not reset, since they are set */ + /* by other functions and must be kept in case of usage of this */ + /* function on the fly (update of a parameter of ADC_InitTypeDef */ + /* without needing to reconfigure all other ADC groups/channels */ + /* parameters): */ + /* - internal measurement paths: Vbat, temperature sensor, Vref */ + /* (set into HAL_ADC_ConfigChannel() */ + + /* Reset configuration of ADC configuration register CFGR2: */ + /* - ADC clock mode: CKMODE */ + hadc->Instance->CFGR2 &= ~(ADC_CFGR2_CKMODE); + + /* Configuration of ADC clock mode: clock source AHB or HSI with */ + /* selectable prescaler */ + hadc->Instance->CFGR2 |= hadc->Init.ClockPrescaler; + } + + /* Configuration of ADC: */ + /* - discontinuous mode */ + /* - LowPowerAutoWait mode */ + /* - LowPowerAutoPowerOff mode */ + /* - continuous conversion mode */ + /* - overrun */ + /* - external trigger to start conversion */ + /* - external trigger polarity */ + /* - data alignment */ + /* - resolution */ + /* - scan direction */ + /* - DMA continuous request */ + hadc->Instance->CFGR1 &= ~( ADC_CFGR1_DISCEN | + ADC_CFGR1_AUTOFF | + ADC_CFGR1_AUTDLY | + ADC_CFGR1_CONT | + ADC_CFGR1_OVRMOD | + ADC_CFGR1_EXTSEL | + ADC_CFGR1_EXTEN | + ADC_CFGR1_ALIGN | + ADC_CFGR1_RES | + ADC_CFGR1_SCANDIR | + ADC_CFGR1_DMACFG ); + + tmpCFGR1 |= (__HAL_ADC_CFGR1_AUTOWAIT(hadc->Init.LowPowerAutoWait) | + __HAL_ADC_CFGR1_AUTOOFF(hadc->Init.LowPowerAutoPowerOff) | + __HAL_ADC_CFGR1_CONTINUOUS(hadc->Init.ContinuousConvMode) | + __HAL_ADC_CFGR1_OVERRUN(hadc->Init.Overrun) | + hadc->Init.DataAlign | + hadc->Init.Resolution | + __HAL_ADC_CFGR1_SCANDIR(hadc->Init.ScanConvMode) | + __HAL_ADC_CFGR1_DMACONTREQ(hadc->Init.DMAContinuousRequests) ); + + /* Enable discontinuous mode only if continuous mode is disabled */ + if ((hadc->Init.DiscontinuousConvMode == ENABLE) && + (hadc->Init.ContinuousConvMode == DISABLE) ) + { + /* Enable discontinuous mode of regular group */ + tmpCFGR1 |= ADC_CFGR1_DISCEN; + } + + /* Enable external trigger if trigger selection is different of software */ + /* start. */ + /* Note: This configuration keeps the hardware feature of parameter */ + /* ExternalTrigConvEdge "trigger edge none" equivalent to */ + /* software start. */ + if (hadc->Init.ExternalTrigConv != ADC_SOFTWARE_START) + { + tmpCFGR1 |= ( hadc->Init.ExternalTrigConv | + hadc->Init.ExternalTrigConvEdge ); + } + + /* Update ADC configuration register with previous settings */ + hadc->Instance->CFGR1 |= tmpCFGR1; + + /* Check back if CFGR1 has been effectively configured into ADC register */ + /* to ensure of no potential problem of ADC clocking. */ + /* (check excluding analog watchdog configuration: set into separate */ + /* dedicated function) */ + if ((hadc->Instance->CFGR1 & ~(ADC_CFGR1_AWDCH | ADC_CFGR1_AWDEN | ADC_CFGR1_AWDSGL)) + == tmpCFGR1) + { + /* Set ADC error code to none */ + __HAL_ADC_CLEAR_ERRORCODE(hadc); + + /* Initialize the ADC state */ + hadc->State = HAL_ADC_STATE_READY; + } + else + { + /* Update ADC state machine to error */ + hadc->State = HAL_ADC_STATE_ERROR; + + /* Set ADC error code to ADC IP internal error */ + hadc->ErrorCode |= HAL_ADC_ERROR_INTERNAL; + + tmpHALStatus = HAL_ERROR; + } + + } + else + { + /* Update ADC state machine to error */ + hadc->State = HAL_ADC_STATE_ERROR; + + tmpHALStatus = HAL_ERROR; + } + + + /* Return function status */ + return tmpHALStatus; +} + + +/** + * @brief Deinitialize the ADC peripheral registers to their default reset + * values, with deinitialization of the ADC MSP. + * @note For devices with several ADCs: reset of ADC common registers is done + * only if all ADCs sharing the same common group are disabled. + * If this is not the case, reset of these common parameters reset is + * bypassed without error reporting: it can be the intended behaviour in + * case of reset of a single ADC while the other ADCs sharing the same + * common group is still running. + * @param hadc: ADC handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_ADC_DeInit(ADC_HandleTypeDef* hadc) +{ + HAL_StatusTypeDef tmpHALStatus = HAL_OK; + + /* Check ADC handle */ + if(hadc == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance)); + + /* Change ADC state */ + hadc->State = HAL_ADC_STATE_BUSY; + + /* Stop potential conversion on going, on regular group */ + tmpHALStatus = ADC_ConversionStop(hadc); + + /* Disable ADC peripheral if conversions are effectively stopped */ + if (tmpHALStatus != HAL_ERROR) + { + /* Disable the ADC peripheral */ + tmpHALStatus = ADC_Disable(hadc); + + /* Check if ADC is effectively disabled */ + if (tmpHALStatus != HAL_ERROR) + { + /* Change ADC state */ + hadc->State = HAL_ADC_STATE_READY; + } + } + + + /* Configuration of ADC parameters if previous preliminary actions are */ + /* correctly completed. */ + if (tmpHALStatus != HAL_ERROR) + { + + /* ========== Reset ADC registers ========== */ + /* Reset register IER */ + __HAL_ADC_DISABLE_IT(hadc, (ADC_IT_AWD | ADC_IT_OVR | + ADC_IT_EOS | ADC_IT_EOC | + ADC_IT_EOSMP | ADC_IT_RDY ) ); + + /* Reset register ISR */ + __HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_AWD | ADC_FLAG_OVR | + ADC_FLAG_EOS | ADC_FLAG_EOC | + ADC_FLAG_EOSMP | ADC_FLAG_RDY ) ); + + /* Reset register CR */ + /* Bits ADC_CR_ADCAL, ADC_CR_ADSTP, ADC_CR_ADSTART are in access mode */ + /* "read-set": no direct reset applicable. */ + + /* Reset register CFGR1 */ + hadc->Instance->CFGR1 &= ~(ADC_CFGR1_AWDCH | ADC_CFGR1_AWDEN | ADC_CFGR1_AWDSGL | ADC_CFGR1_DISCEN | + ADC_CFGR1_AUTOFF | ADC_CFGR1_WAIT | ADC_CFGR1_CONT | ADC_CFGR1_OVRMOD | + ADC_CFGR1_EXTEN | ADC_CFGR1_EXTSEL | ADC_CFGR1_ALIGN | ADC_CFGR1_RES | + ADC_CFGR1_SCANDIR | ADC_CFGR1_DMACFG | ADC_CFGR1_DMAEN ); + + /* Reset register CFGR2 */ + /* Note: Update of ADC clock mode is conditioned to ADC state disabled: */ + /* already done above. */ + hadc->Instance->CFGR2 &= ~ADC_CFGR2_CKMODE; + + /* Reset register SMPR */ + hadc->Instance->SMPR &= ~ADC_SMPR_SMP; + + /* Reset register TR1 */ + hadc->Instance->TR &= ~(ADC_TR_HT | ADC_TR_LT); + + /* Reset register CHSELR */ + hadc->Instance->CHSELR &= ~(ADC_CHSELR_CHSEL18 | ADC_CHSELR_CHSEL17 | ADC_CHSELR_CHSEL16 | + ADC_CHSELR_CHSEL15 | ADC_CHSELR_CHSEL14 | ADC_CHSELR_CHSEL13 | ADC_CHSELR_CHSEL12 | + ADC_CHSELR_CHSEL11 | ADC_CHSELR_CHSEL10 | ADC_CHSELR_CHSEL9 | ADC_CHSELR_CHSEL8 | + ADC_CHSELR_CHSEL7 | ADC_CHSELR_CHSEL6 | ADC_CHSELR_CHSEL5 | ADC_CHSELR_CHSEL4 | + ADC_CHSELR_CHSEL3 | ADC_CHSELR_CHSEL2 | ADC_CHSELR_CHSEL1 | ADC_CHSELR_CHSEL0 ); + + /* Reset register DR */ + /* bits in access mode read only, no direct reset applicable*/ + + /* Reset register CCR */ + ADC->CCR &= ~( ADC_CCR_VBATEN | + ADC_CCR_TSEN | + ADC_CCR_VREFEN ); + + /* ========== Hard reset ADC peripheral ========== */ + /* Performs a global reset of the entire ADC peripheral: ADC state is */ + /* forced to a similar state after device power-on. */ + /* If needed, copy-paste and uncomment the following reset code into */ + /* function "void HAL_ADC_MspInit(ADC_HandleTypeDef* hadc)": */ + /* */ + /* __ADC1_FORCE_RESET(); */ + /* __ADC1_RELEASE_RESET(); */ + + /* DeInit the low level hardware */ + HAL_ADC_MspDeInit(hadc); + + /* Set ADC error code to none */ + __HAL_ADC_CLEAR_ERRORCODE(hadc); + + /* Change ADC state */ + hadc->State = HAL_ADC_STATE_RESET; + } + + /* Process unlocked */ + __HAL_UNLOCK(hadc); + + /* Return function status */ + return tmpHALStatus; +} + + +/** + * @brief Initializes the ADC MSP. + * @param hadc: ADC handle + * @retval None + */ +__weak void HAL_ADC_MspInit(ADC_HandleTypeDef* hadc) +{ + /* NOTE : This function should not be modified. When the callback is needed, + function HAL_ADC_MspInit must be implemented in the user file. + */ +} + +/** + * @brief DeInitializes the ADC MSP. + * @param hadc: ADC handle + * @retval None + */ +__weak void HAL_ADC_MspDeInit(ADC_HandleTypeDef* hadc) +{ + /* NOTE : This function should not be modified. When the callback is needed, + function HAL_ADC_MspDeInit must be implemented in the user file. + */ +} + +/** + * @} + */ + +/** @defgroup ADC_Group2 IO operation functions + * @brief IO operation functions + * +@verbatim + =============================================================================== + ##### IO operation functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Start conversion of regular group. + (+) Stop conversion of regular group. + (+) Poll for conversion complete on regular group. + (+) Poll for conversion event. + (+) Get result of regular channel conversion. + (+) Start conversion of regular group and enable interruptions. + (+) Stop conversion of regular group and disable interruptions. + (+) Handle ADC interrupt request + (+) Start conversion of regular group and enable DMA transfer. + (+) Stop conversion of regular group and disable ADC DMA transfer. +@endverbatim + * @{ + */ + +/** + * @brief Enables ADC, starts conversion of regular group. + * Interruptions enabled in this function: None. + * @param hadc: ADC handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_ADC_Start(ADC_HandleTypeDef* hadc) +{ + HAL_StatusTypeDef tmpHALStatus = HAL_OK; + + /* Check the parameters */ + assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance)); + + /* Process locked */ + __HAL_LOCK(hadc); + + /* Enable the ADC peripheral */ + /* If low power mode AutoPowerOff is enabled, power-on/off phases are */ + /* performed automatically by hardware. */ + if (hadc->Init.LowPowerAutoPowerOff != ENABLE) + { + tmpHALStatus = ADC_Enable(hadc); + } + + /* Start conversion if ADC is effectively enabled */ + if (tmpHALStatus != HAL_ERROR) + { + /* State machine update: Change ADC state */ + hadc->State = HAL_ADC_STATE_BUSY_REG; + + /* Set ADC error code to none */ + __HAL_ADC_CLEAR_ERRORCODE(hadc); + + /* Clear regular group conversion flag and overrun flag */ + /* (To ensure of no unknown state from potential previous ADC operations) */ + __HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_EOC | ADC_FLAG_EOS | ADC_FLAG_OVR)); + + /* Enable conversion of regular group. */ + /* If software start has been selected, conversion starts immediately. */ + /* If external trigger has been selected, conversion will start at next */ + /* trigger event. */ + hadc->Instance->CR |= ADC_CR_ADSTART; + } + + /* Process unlocked */ + __HAL_UNLOCK(hadc); + + /* Return function status */ + return tmpHALStatus; +} + +/** + * @brief Stop ADC conversion of regular group, disable ADC peripheral. + * @param hadc: ADC handle + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_ADC_Stop(ADC_HandleTypeDef* hadc) +{ + HAL_StatusTypeDef tmpHALStatus = HAL_OK; + + /* Check the parameters */ + assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance)); + + /* Process locked */ + __HAL_LOCK(hadc); + + /* 1. Stop potential conversion on going, on regular group */ + tmpHALStatus = ADC_ConversionStop(hadc); + + /* Disable ADC peripheral if conversions are effectively stopped */ + if (tmpHALStatus != HAL_ERROR) + { + /* 2. Disable the ADC peripheral */ + tmpHALStatus = ADC_Disable(hadc); + + /* Check if ADC is effectively disabled */ + if (tmpHALStatus != HAL_ERROR) + { + /* Change ADC state */ + hadc->State = HAL_ADC_STATE_READY; + } + } + + /* Process unlocked */ + __HAL_UNLOCK(hadc); + + /* Return function status */ + return tmpHALStatus; +} + +/** + * @brief Wait for regular group conversion to be completed. + * @param hadc: ADC handle + * @param Timeout: Timeout value in millisecond. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_ADC_PollForConversion(ADC_HandleTypeDef* hadc, uint32_t Timeout) +{ + uint32_t tickstart; + uint32_t tmp_Flag_EOC; + + /* Check the parameters */ + assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance)); + + /* If end of conversion selected to end of sequence */ + if (hadc->Init.EOCSelection == EOC_SEQ_CONV) + { + tmp_Flag_EOC = ADC_FLAG_EOS; + } + /* If end of conversion selected to end of each conversion */ + else /* EOC_SINGLE_CONV */ + { + tmp_Flag_EOC = (ADC_FLAG_EOC | ADC_FLAG_EOS); + } + + /* Get timeout */ + tickstart = HAL_GetTick(); + + /* Wait until End of Conversion flag is raised */ + while(HAL_IS_BIT_CLR(hadc->Instance->ISR, tmp_Flag_EOC)) + { + /* Check if timeout is disabled (set to infinite wait) */ + if(Timeout != HAL_MAX_DELAY) + { + if((HAL_GetTick() - tickstart) > Timeout) + { + /* Update ADC state machine to timeout */ + hadc->State = HAL_ADC_STATE_TIMEOUT; + + /* Process unlocked */ + __HAL_UNLOCK(hadc); + + return HAL_ERROR; + } + } + } + + /* Clear end of conversion flag of regular group if low power feature */ + /* "LowPowerAutoWait " is disabled, to not interfere with this feature */ + /* until data register is read using function HAL_ADC_GetValue(). */ + if (hadc->Init.LowPowerAutoWait == DISABLE) + { + /* Clear regular group conversion flag */ + __HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_EOC | ADC_FLAG_EOS)); + } + + /* Update state machine on conversion status if not in error state */ + if(hadc->State != HAL_ADC_STATE_ERROR) + { + /* Change ADC state */ + hadc->State = HAL_ADC_STATE_EOC_REG; + } + + /* Return ADC state */ + return HAL_OK; +} + +/** + * @brief Poll for conversion event. + * @param hadc: ADC handle + * @param EventType: the ADC event type. + * This parameter can be one of the following values: + * @arg AWD_EVENT: ADC Analog watchdog event + * @arg OVR_EVENT: ADC Overrun event + * @param Timeout: Timeout value in millisecond. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_ADC_PollForEvent(ADC_HandleTypeDef* hadc, uint32_t EventType, uint32_t Timeout) +{ + uint32_t tickstart=0; + + /* Check the parameters */ + assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance)); + assert_param(IS_ADC_EVENT_TYPE(EventType)); + + tickstart = HAL_GetTick(); + + /* Check selected event flag */ + while(__HAL_ADC_GET_FLAG(hadc, EventType) == RESET) + { + /* Check if timeout is disabled (set to infinite wait) */ + if(Timeout != HAL_MAX_DELAY) + { + if((HAL_GetTick() - tickstart) > Timeout) + { + /* Update ADC state machine to timeout */ + hadc->State = HAL_ADC_STATE_TIMEOUT; + + /* Process unlocked */ + __HAL_UNLOCK(hadc); + + return HAL_ERROR; + } + } + } + + + switch(EventType) + { + /* Analog watchdog (level out of window) event */ + case AWD_EVENT: + /* Change ADC state */ + hadc->State = HAL_ADC_STATE_AWD; + + /* Clear ADC analog watchdog flag */ + __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_AWD); + break; + + /* Overrun event */ + default: /* Case OVR_EVENT */ + /* If overrun is set to overwrite previous data, overrun event is not */ + /* considered as an error. */ + /* (cf ref manual "Managing conversions without using the DMA and without */ + /* overrun ") */ + if (hadc->Init.Overrun == OVR_DATA_PRESERVED) + { + /* Change ADC state */ + hadc->State = HAL_ADC_STATE_ERROR; + + /* Set ADC error code to overrun */ + hadc->ErrorCode |= HAL_ADC_ERROR_OVR; + } + + /* Clear ADC Overrun flag */ + __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_OVR); + break; + } + + /* Return ADC state */ + return HAL_OK; +} + +/** + * @brief Enables ADC, starts conversion of regular group with interruption. + * Interruptions enabled in this function: EOC (end of conversion), + * overrun. + * Each of these interruptions has its dedicated callback function. + * @param hadc: ADC handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_ADC_Start_IT(ADC_HandleTypeDef* hadc) +{ + HAL_StatusTypeDef tmpHALStatus = HAL_OK; + + /* Check the parameters */ + assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance)); + + /* Process locked */ + __HAL_LOCK(hadc); + + /* Enable the ADC peripheral */ + /* If low power mode AutoPowerOff is enabled, power-on/off phases are */ + /* performed automatically by hardware. */ + if (hadc->Init.LowPowerAutoPowerOff != ENABLE) + { + tmpHALStatus = ADC_Enable(hadc); + } + + /* Start conversion if ADC is effectively enabled */ + if (tmpHALStatus != HAL_ERROR) + { + /* State machine update: Change ADC state */ + hadc->State = HAL_ADC_STATE_BUSY_REG; + + /* Set ADC error code to none */ + __HAL_ADC_CLEAR_ERRORCODE(hadc); + + /* Clear regular group conversion flag and overrun flag */ + /* (To ensure of no unknown state from potential previous ADC operations) */ + __HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_EOC | ADC_FLAG_EOS | ADC_FLAG_OVR)); + + /* Enable ADC end of conversion interrupt */ + /* Enable ADC overrun interrupt */ + switch(hadc->Init.EOCSelection) + { + case EOC_SEQ_CONV: + __HAL_ADC_DISABLE_IT(hadc, ADC_IT_EOC); + __HAL_ADC_ENABLE_IT(hadc, (ADC_IT_EOS | ADC_IT_OVR)); + break; + /* case EOC_SINGLE_CONV */ + default: + __HAL_ADC_ENABLE_IT(hadc, (ADC_IT_EOC | ADC_IT_EOS | ADC_IT_OVR)); + break; + } + + /* Enable conversion of regular group. */ + /* If software start has been selected, conversion starts immediately. */ + /* If external trigger has been selected, conversion will start at next */ + /* trigger event. */ + hadc->Instance->CR |= ADC_CR_ADSTART; + } + + /* Process unlocked */ + __HAL_UNLOCK(hadc); + + /* Return function status */ + return tmpHALStatus; +} + + +/** + * @brief Stop ADC conversion of regular group, disable interruption of + * end-of-conversion, disable ADC peripheral. + * @param hadc: ADC handle + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_ADC_Stop_IT(ADC_HandleTypeDef* hadc) +{ + HAL_StatusTypeDef tmpHALStatus = HAL_OK; + + /* Check the parameters */ + assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance)); + + /* Process locked */ + __HAL_LOCK(hadc); + + /* 1. Stop potential conversion on going, on regular group */ + tmpHALStatus = ADC_ConversionStop(hadc); + + /* Disable ADC peripheral if conversions are effectively stopped */ + if (tmpHALStatus != HAL_ERROR) + { + /* Disable ADC end of conversion interrupt for regular group */ + /* Disable ADC overrun interrupt */ + __HAL_ADC_DISABLE_IT(hadc, (ADC_IT_EOC | ADC_IT_EOS | ADC_IT_OVR)); + + /* 2. Disable the ADC peripheral */ + tmpHALStatus = ADC_Disable(hadc); + + /* Check if ADC is effectively disabled */ + if (tmpHALStatus != HAL_ERROR) + { + /* Change ADC state */ + hadc->State = HAL_ADC_STATE_READY; + } + } + + /* Process unlocked */ + __HAL_UNLOCK(hadc); + + /* Return function status */ + return tmpHALStatus; +} + +/** + * @brief Enables ADC, starts conversion of regular group and transfers result + * through DMA. + * Interruptions enabled in this function: + * overrun, DMA half transfer, DMA transfer complete. + * Each of these interruptions has its dedicated callback function. + * @param hadc: ADC handle + * @param pData: The destination Buffer address. + * @param Length: The length of data to be transferred from ADC peripheral to memory. + * @retval None + */ +HAL_StatusTypeDef HAL_ADC_Start_DMA(ADC_HandleTypeDef* hadc, uint32_t* pData, uint32_t Length) +{ + HAL_StatusTypeDef tmpHALStatus = HAL_OK; + + /* Check the parameters */ + assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance)); + + /* Process locked */ + __HAL_LOCK(hadc); + + /* Enable the ADC peripheral */ + /* If low power mode AutoPowerOff is enabled, power-on/off phases are */ + /* performed automatically by hardware. */ + if (hadc->Init.LowPowerAutoPowerOff != ENABLE) + { + tmpHALStatus = ADC_Enable(hadc); + } + + /* Start conversion if ADC is effectively enabled */ + if (tmpHALStatus != HAL_ERROR) + { + /* State machine update: Change ADC state */ + hadc->State = HAL_ADC_STATE_BUSY_REG; + + /* Set ADC error code to none */ + __HAL_ADC_CLEAR_ERRORCODE(hadc); + + + /* Set the DMA transfer complete callback */ + hadc->DMA_Handle->XferCpltCallback = ADC_DMAConvCplt; + + /* Set the DMA half transfer complete callback */ + hadc->DMA_Handle->XferHalfCpltCallback = ADC_DMAHalfConvCplt; + + /* Set the DMA error callback */ + hadc->DMA_Handle->XferErrorCallback = ADC_DMAError; + + + /* Manage ADC and DMA start: ADC overrun interruption, DMA start, ADC */ + /* start (in case of SW start): */ + + /* Clear regular group conversion flag and overrun flag */ + /* (To ensure of no unknown state from potential previous ADC */ + /* operations) */ + __HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_EOC | ADC_FLAG_EOS | ADC_FLAG_OVR)); + + /* Enable ADC overrun interrupt */ + __HAL_ADC_ENABLE_IT(hadc, ADC_IT_OVR); + + /* Enable ADC DMA mode */ + hadc->Instance->CFGR1 |= ADC_CFGR1_DMAEN; + + /* Start the DMA channel */ + HAL_DMA_Start_IT(hadc->DMA_Handle, (uint32_t)&hadc->Instance->DR, (uint32_t)pData, Length); + + /* Enable conversion of regular group. */ + /* If software start has been selected, conversion starts immediately. */ + /* If external trigger has been selected, conversion will start at next */ + /* trigger event. */ + hadc->Instance->CR |= ADC_CR_ADSTART; + } + + + /* Process unlocked */ + __HAL_UNLOCK(hadc); + + /* Return function status */ + return tmpHALStatus; +} + +/** + * @brief Stop ADC conversion of regular group, disable ADC DMA transfer, disable + * ADC peripheral. + * Each of these interruptions has its dedicated callback function. + * @param hadc: ADC handle + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_ADC_Stop_DMA(ADC_HandleTypeDef* hadc) +{ + HAL_StatusTypeDef tmpHALStatus = HAL_OK; + + /* Check the parameters */ + assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance)); + + /* Process locked */ + __HAL_LOCK(hadc); + + /* 1. Stop potential conversion on going, on regular group */ + tmpHALStatus = ADC_ConversionStop(hadc); + + /* Disable ADC peripheral if conversions are effectively stopped */ + if (tmpHALStatus != HAL_ERROR) + { + /* Disable ADC DMA (ADC DMA configuration ADC_CFGR_DMACFG is kept) */ + hadc->Instance->CFGR1 &= ~ADC_CFGR1_DMAEN; + + /* Disable the DMA channel (in case of DMA in circular mode or stop while */ + /* while DMA transfer is on going) */ + tmpHALStatus = HAL_DMA_Abort(hadc->DMA_Handle); + + /* Check if DMA channel effectively disabled */ + if (tmpHALStatus != HAL_OK) + { + /* Update ADC state machine to error */ + hadc->State = HAL_ADC_STATE_ERROR; + } + + /* Disable ADC overrun interrupt */ + __HAL_ADC_DISABLE_IT(hadc, ADC_IT_OVR); + + /* 2. Disable the ADC peripheral */ + /* Update "tmpHALStatus" only if DMA channel disabling passed, to keep in */ + /* memory a potential failing status. */ + if (tmpHALStatus == HAL_OK) + { + tmpHALStatus = ADC_Disable(hadc); + } + else + { + ADC_Disable(hadc); + } + + /* Check if ADC is effectively disabled */ + if (tmpHALStatus != HAL_OK) + { + /* Change ADC state */ + hadc->State = HAL_ADC_STATE_READY; + } + + } + + /* Process unlocked */ + __HAL_UNLOCK(hadc); + + /* Return function status */ + return tmpHALStatus; +} + +/** + * @brief Get ADC regular group conversion result. + * @param hadc: ADC handle + * @retval Converted value + */ +uint32_t HAL_ADC_GetValue(ADC_HandleTypeDef* hadc) +{ + /* Check the parameters */ + assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance)); + + /* Note: EOC flag is automatically cleared by hardware when reading */ + /* register DR. Additionally, clear flag EOS by software. */ + + /* Clear regular group conversion flag */ + __HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_EOC | ADC_FLAG_EOS) ); + + /* Return ADC converted value */ + return hadc->Instance->DR; +} + +/** + * @brief DMA transfer complete callback. + * @param hdma: pointer to DMA handle. + * @retval None + */ +static void ADC_DMAConvCplt(DMA_HandleTypeDef *hdma) +{ + /* Retrieve ADC handle corresponding to current DMA handle */ + ADC_HandleTypeDef* hadc = ( ADC_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + + /* Update state machine on conversion status if not in error state */ + if(hadc->State != HAL_ADC_STATE_ERROR) + { + /* Change ADC state */ + hadc->State = HAL_ADC_STATE_EOC_REG; + } + + /* Conversion complete callback */ + HAL_ADC_ConvCpltCallback(hadc); +} + +/** + * @brief DMA half transfer complete callback. + * @param hdma: pointer to DMA handle. + * @retval None + */ +static void ADC_DMAHalfConvCplt(DMA_HandleTypeDef *hdma) +{ + /* Retrieve ADC handle corresponding to current DMA handle */ + ADC_HandleTypeDef* hadc = ( ADC_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + + /* Half conversion callback */ + HAL_ADC_ConvHalfCpltCallback(hadc); +} + +/** + * @brief DMA error callback + * @param hdma: pointer to DMA handle. + * @retval None + */ +static void ADC_DMAError(DMA_HandleTypeDef *hdma) +{ + /* Retrieve ADC handle corresponding to current DMA handle */ + ADC_HandleTypeDef* hadc = ( ADC_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + + /* Change ADC state */ + hadc->State = HAL_ADC_STATE_ERROR; + + /* Set ADC error code to DMA error */ + hadc->ErrorCode |= HAL_ADC_ERROR_DMA; + + /* Error callback */ + HAL_ADC_ErrorCallback(hadc); +} + +/** + * @brief Handles ADC interrupt request. + * @param hadc: ADC handle + * @retval None + */ +void HAL_ADC_IRQHandler(ADC_HandleTypeDef* hadc) +{ + /* Check the parameters */ + assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance)); + assert_param(IS_FUNCTIONAL_STATE(hadc->Init.ContinuousConvMode)); + assert_param(IS_ADC_EOC_SELECTION(hadc->Init.EOCSelection)); + + /* ========== Check End of Conversion flag for regular group ========== */ + if( (__HAL_ADC_GET_FLAG(hadc, ADC_FLAG_EOC) && __HAL_ADC_GET_IT_SOURCE(hadc, ADC_IT_EOC)) || + (__HAL_ADC_GET_FLAG(hadc, ADC_FLAG_EOS) && __HAL_ADC_GET_IT_SOURCE(hadc, ADC_IT_EOS)) ) + { + /* Update state machine on conversion status if not in error state */ + if(hadc->State != HAL_ADC_STATE_ERROR) + { + /* Change ADC state */ + hadc->State = HAL_ADC_STATE_EOC_REG; + } + + /* Disable interruption if no further conversion upcoming by regular */ + /* external trigger or by continuous mode, */ + /* and if scan sequence if completed. */ + if(__HAL_ADC_IS_SOFTWARE_START_REGULAR(hadc) && + (hadc->Init.ContinuousConvMode == DISABLE) ) + { + /* If End of Sequence is reached, disable interrupts */ + if( __HAL_ADC_GET_FLAG(hadc, ADC_FLAG_EOS) ) + { + /* Allowed to modify bits ADC_IT_EOC/ADC_IT_EOS only if bit */ + /* ADSTART==0 (no conversion on going) */ + if (__HAL_ADC_IS_CONVERSION_ONGOING_REGULAR(hadc) == RESET) + { + /* Disable ADC end of sequence conversion interrupt */ + /* Note: Overrun interrupt was enabled with EOC interrupt in */ + /* HAL_Start_IT(), but is not disabled here because can be used */ + /* by overrun IRQ process below. */ + __HAL_ADC_DISABLE_IT(hadc, ADC_IT_EOC | ADC_IT_EOS); + } + else + { + /* Change ADC state to error state */ + hadc->State = HAL_ADC_STATE_ERROR; + + /* Set ADC error code to ADC IP internal error */ + hadc->ErrorCode |= HAL_ADC_ERROR_INTERNAL; + } + } + } + + /* Conversion complete callback */ + /* Note: into callback, to determine if conversion has been triggered */ + /* from EOC or EOS, possibility to use: */ + /* " if( __HAL_ADC_GET_FLAG(&hadc, ADC_FLAG_EOS)) " */ + HAL_ADC_ConvCpltCallback(hadc); + + + /* Clear regular group conversion flag */ + /* Note: in case of overrun set to OVR_DATA_PRESERVED, end of conversion */ + /* flags clear induces the release of the preserved data. */ + /* Therefore, if the preserved data value is needed, it must be */ + /* read preliminarily into HAL_ADC_ConvCpltCallback(). */ + __HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_EOC | ADC_FLAG_EOS) ); + } + + /* ========== Check Analog watchdog flags ========== */ + if(__HAL_ADC_GET_FLAG(hadc, ADC_FLAG_AWD) && __HAL_ADC_GET_IT_SOURCE(hadc, ADC_IT_AWD)) + { + /* Change ADC state */ + hadc->State = HAL_ADC_STATE_AWD; + + /* Clear ADC Analog watchdog flag */ + __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_AWD); + + /* Level out of window callback */ + HAL_ADC_LevelOutOfWindowCallback(hadc); + } + + + /* ========== Check Overrun flag ========== */ + if(__HAL_ADC_GET_FLAG(hadc, ADC_FLAG_OVR) && __HAL_ADC_GET_IT_SOURCE(hadc, ADC_IT_OVR)) + { + /* If overrun is set to overwrite previous data (default setting), */ + /* overrun event is not considered as an error. */ + /* (cf ref manual "Managing conversions without using the DMA and without */ + /* overrun ") */ + /* Exception for usage with DMA overrun event always considered as an */ + /* error. */ + if ((hadc->Init.Overrun == OVR_DATA_PRESERVED) || + HAL_IS_BIT_SET(hadc->Instance->CFGR1, ADC_CFGR1_DMAEN) ) + { + /* Change ADC state to error state */ + hadc->State = HAL_ADC_STATE_ERROR; + + /* Set ADC error code to overrun */ + hadc->ErrorCode |= HAL_ADC_ERROR_OVR; + + /* Error callback */ + HAL_ADC_ErrorCallback(hadc); + } + + /* Clear the Overrun flag */ + __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_OVR); + } + +} + + +/** + * @brief Conversion complete callback in non blocking mode + * @param hadc: ADC handle + * @retval None + */ +__weak void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef* hadc) +{ + /* NOTE : This function should not be modified. When the callback is needed, + function HAL_ADC_ConvCpltCallback must be implemented in the user file. + */ +} + +/** + * @brief Conversion DMA half-transfer callback in non blocking mode + * @param hadc: ADC handle + * @retval None + */ +__weak void HAL_ADC_ConvHalfCpltCallback(ADC_HandleTypeDef* hadc) +{ + /* NOTE : This function should not be modified. When the callback is needed, + function HAL_ADC_ConvHalfCpltCallback must be implemented in the user file. + */ +} + +/** + * @brief Analog watchdog callback in non blocking mode. + * @note: In case of several analog watchdog enabled, if needed to know + which one triggered and on which ADCx, check Analog Watchdog flag + ADC_FLAG_AWD1/2/3 into HAL_ADC_LevelOutOfWindowCallback() function. + For example:"if (__HAL_ADC_GET_FLAG(hadc1, ADC_FLAG_AWD1) != RESET)" + * @param hadc: ADC handle + * @retval None + */ +__weak void HAL_ADC_LevelOutOfWindowCallback(ADC_HandleTypeDef* hadc) +{ + /* NOTE : This function should not be modified. When the callback is needed, + function HAL_ADC_LevelOoutOfWindowCallback must be implemented in the user file. + */ +} + +/** + * @brief ADC error callback in non blocking mode + * (ADC conversion with interruption or transfer by DMA) + * @param hadc: ADC handle + * @retval None + */ +__weak void HAL_ADC_ErrorCallback(ADC_HandleTypeDef *hadc) +{ + /* NOTE : This function should not be modified. When the callback is needed, + function HAL_ADC_ErrorCallback must be implemented in the user file. + */ +} + + +/** + * @} + */ + +/** @defgroup ADC_Group3 Peripheral Control functions + * @brief Peripheral Control functions + * +@verbatim + =============================================================================== + ##### Peripheral Control functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Configure channels on regular group + (+) Configure the analog watchdog + +@endverbatim + * @{ + */ + +/** + * @brief Configures the the selected channel to be linked to the regular + * group. + * @note In case of usage of internal measurement channels: + * VrefInt/Vbat/TempSensor. + * Sampling time constraints must be respected (sampling time can be + * adjusted in function of ADC clock frequency and sampling time + * setting). + * Refer to device datasheet for timings values, parameters TS_vrefint, + * TS_vbat, TS_temp (values rough order: 5us to 17us). + * These internal paths can be be disabled using function + * HAL_ADC_DeInit(). + * @note Possibility to update parameters on the fly: + * This function initializes channel into regular group, following + * calls to this function can be used to reconfigure some parameters + * of structure "ADC_ChannelConfTypeDef" on the fly, without reseting + * the ADC. + * The setting of these parameters is conditioned to ADC state. + * For parameters constraints, see comments of structure + * "ADC_ChannelConfTypeDef". + * @param hadc: ADC handle + * @param sConfig: Structure ADC channel for regular group. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_ADC_ConfigChannel(ADC_HandleTypeDef* hadc, ADC_ChannelConfTypeDef* sConfig) +{ + HAL_StatusTypeDef tmpHALStatus = HAL_OK; + + /* Check the parameters */ + assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance)); + assert_param(IS_ADC_CHANNEL(sConfig->Channel)); + assert_param(IS_ADC_RANK(sConfig->Rank)); + assert_param(IS_ADC_SAMPLE_TIME(sConfig->SamplingTime)); + + /* Process locked */ + __HAL_LOCK(hadc); + + /* Parameters update conditioned to ADC state: */ + /* Parameters that can be updated when ADC is disabled or enabled without */ + /* conversion on going on regular group: */ + /* - Channel number */ + /* - Channel sampling time */ + /* - Management of internal measurement channels: Vbat/VrefInt/TempSensor */ + if (__HAL_ADC_IS_CONVERSION_ONGOING_REGULAR(hadc) == RESET) + { + /* Configure channel: depending on rank setting, add it or remove it from */ + /* ADC conversion sequencer. */ + if (sConfig->Rank != ADC_RANK_NONE) + { + /* Regular sequence configuration */ + /* Set the channel selection register from the selected channel */ + hadc->Instance->CHSELR |= __HAL_ADC_CHSELR_CHANNEL(sConfig->Channel); + + /* Channel sampling time configuration */ + /* Modify sampling time if needed (not needed in case of reoccurrence */ + /* for several channels programmed consecutively into the sequencer) */ + if (sConfig->SamplingTime != __HAL_ADC_GET_SAMPLINGTIME(hadc)) + { + /* Channel sampling time configuration */ + /* Clear the old sample time */ + hadc->Instance->SMPR &= ~(ADC_SMPR_SMP); + + /* Set the new sample time */ + hadc->Instance->SMPR |= (sConfig->SamplingTime); + } + + /* Management of internal measurement channels: Vbat/VrefInt/TempSensor */ + /* internal measurement paths enable: If internal channel selected, */ + /* enable dedicated internal buffers and path. */ + /* Note: these internal measurement paths can be disabled using */ + /* HAL_ADC_DeInit() or removing the channel from sequencer with */ + /* channel configuration parameter "Rank". */ + + /* If Channel_16 is selected, enable Temp. sensor measurement path. */ + if (sConfig->Channel == ADC_CHANNEL_TEMPSENSOR) + { + ADC->CCR |= ADC_CCR_TSEN; + } + /* If Channel_17 is selected, enable VBAT measurement path. */ + else if (sConfig->Channel == ADC_CHANNEL_VBAT) + { + ADC->CCR |= ADC_CCR_VBATEN; + } + /* If Channel_18 is selected, enable VREFINT measurement path. */ + else if (sConfig->Channel == ADC_CHANNEL_VREFINT) + { + ADC->CCR |= ADC_CCR_VREFEN; + } + + } + else + { + /* Regular sequence configuration */ + /* Reset the channel selection register from the selected channel */ + hadc->Instance->CHSELR &= ~__HAL_ADC_CHSELR_CHANNEL(sConfig->Channel); + + /* Management of internal measurement channels: Vbat/VrefInt/TempSensor */ + /* internal measurement paths disable: If internal channel selected, */ + /* disable dedicated internal buffers and path. */ + + /* If Channel_16 is selected, disable Temp. sensor measurement path. */ + if (sConfig->Channel == ADC_CHANNEL_TEMPSENSOR) + { + ADC->CCR &= ~ADC_CCR_TSEN; + } + /* If Channel_17 is selected, disable VBAT measurement path. */ + else if (sConfig->Channel == ADC_CHANNEL_VBAT) + { + ADC->CCR &= ~ADC_CCR_VBATEN; + } + /* If Channel_18 is selected, disable VREFINT measurement path. */ + else if (sConfig->Channel == ADC_CHANNEL_VREFINT) + { + ADC->CCR &= ~ADC_CCR_VREFEN; + } + } + + } + + + /* If a conversion is on going on regular group, no update on regular */ + /* channel could be done on neither of the channel configuration structure */ + /* parameters. */ + else + { + /* Update ADC state machine to error */ + hadc->State = HAL_ADC_STATE_ERROR; + + tmpHALStatus = HAL_ERROR; + } + + /* Process unlocked */ + __HAL_UNLOCK(hadc); + + /* Return function status */ + return tmpHALStatus; +} + + +/** + * @brief Configures the analog watchdog. + * @note Possibility to update parameters on the fly: + * This function initializes the selected analog watchdog, following + * calls to this function can be used to reconfigure some parameters + * of structure "ADC_AnalogWDGConfTypeDef" on the fly, without reseting + * the ADC. + * The setting of these parameters is conditioned to ADC state. + * For parameters constraints, see comments of structure + * "ADC_AnalogWDGConfTypeDef". + * @param hadc: ADC handle + * @param AnalogWDGConfig: Structure of ADC analog watchdog configuration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_ADC_AnalogWDGConfig(ADC_HandleTypeDef* hadc, ADC_AnalogWDGConfTypeDef* AnalogWDGConfig) +{ + HAL_StatusTypeDef tmpHALStatus = HAL_OK; + + uint32_t tmpAWDHighThresholdShifted; + uint32_t tmpAWDLowThresholdShifted; + + /* Check the parameters */ + assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance)); + assert_param(IS_ADC_CHANNEL(AnalogWDGConfig->Channel)); + assert_param(IS_FUNCTIONAL_STATE(AnalogWDGConfig->ITMode)); + + /* Verify if threshold is within the selected ADC resolution */ + assert_param(IS_ADC_RANGE(__HAL_ADC_GET_RESOLUTION(hadc), AnalogWDGConfig->HighThreshold)); + assert_param(IS_ADC_RANGE(__HAL_ADC_GET_RESOLUTION(hadc), AnalogWDGConfig->LowThreshold)); + + /* Process locked */ + __HAL_LOCK(hadc); + + /* Parameters update conditioned to ADC state: */ + /* Parameters that can be updated when ADC is disabled or enabled without */ + /* conversion on going on regular group: */ + /* - Analog watchdog channels */ + /* - Analog watchdog thresholds */ + if (__HAL_ADC_IS_CONVERSION_ONGOING_REGULAR(hadc) == RESET) + { + /* Configuration of analog watchdog: */ + /* - Set the analog watchdog enable mode: one or overall group of */ + /* channels. */ + /* - Set the Analog watchdog channel (is not used if watchdog */ + /* mode "all channels": ADC_CFGR_AWD1SGL=0). */ + hadc->Instance->CFGR1 &= ~( ADC_CFGR1_AWDSGL | + ADC_CFGR1_AWDEN | + ADC_CFGR1_AWDCH ); + + hadc->Instance->CFGR1 |= ( AnalogWDGConfig->WatchdogMode | + __HAL_ADC_CFGR_AWDCH(AnalogWDGConfig->Channel) ); + + /* Shift the offset in function of the selected ADC resolution: Thresholds*/ + /* have to be left-aligned on bit 11, the LSB (right bits) are set to 0 */ + tmpAWDHighThresholdShifted = __HAL_ADC_AWD1THRESHOLD_SHIFT_RESOLUTION(hadc, AnalogWDGConfig->HighThreshold); + tmpAWDLowThresholdShifted = __HAL_ADC_AWD1THRESHOLD_SHIFT_RESOLUTION(hadc, AnalogWDGConfig->LowThreshold); + + /* Set the high and low thresholds */ + hadc->Instance->TR &= ~(ADC_TR_HT | ADC_TR_LT); + hadc->Instance->TR |= ( __HAL_ADC_TRX_HIGHTHRESHOLD (tmpAWDHighThresholdShifted) | + tmpAWDLowThresholdShifted ); + + /* Clear the ADC Analog watchdog flag (in case of let enabled by */ + /* previous ADC operations) to be ready to use for HAL_ADC_IRQHandler() */ + /* or HAL_ADC_PollForEvent(). */ + __HAL_ADC_CLEAR_FLAG(hadc, ADC_IT_AWD); + + /* Configure ADC Analog watchdog interrupt */ + if(AnalogWDGConfig->ITMode == ENABLE) + { + /* Enable the ADC Analog watchdog interrupt */ + __HAL_ADC_ENABLE_IT(hadc, ADC_IT_AWD); + } + else + { + /* Disable the ADC Analog watchdog interrupt */ + __HAL_ADC_DISABLE_IT(hadc, ADC_IT_AWD); + } + + } + /* If a conversion is on going on regular group, no update could be done */ + /* on neither of the AWD configuration structure parameters. */ + else + { + /* Update ADC state machine to error */ + hadc->State = HAL_ADC_STATE_ERROR; + + tmpHALStatus = HAL_ERROR; + } + + + /* Process unlocked */ + __HAL_UNLOCK(hadc); + + /* Return function status */ + return tmpHALStatus; +} + + +/** + * @} + */ + + +/** @defgroup ADC_Group4 Peripheral State functions + * @brief Peripheral State functions + * +@verbatim + =============================================================================== + ##### Peripheral State and Errors functions ##### + =============================================================================== + [..] + This subsection provides functions to get in run-time the status of the + peripheral. + (+) Check the ADC state + (+) Check the ADC error code + +@endverbatim + * @{ + */ + +/** + * @brief return the ADC state + * @param hadc: ADC handle + * @retval HAL state + */ +HAL_ADC_StateTypeDef HAL_ADC_GetState(ADC_HandleTypeDef* hadc) +{ + /* Check the parameters */ + assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance)); + + /* Return ADC state */ + return hadc->State; +} + +/** + * @brief Return the ADC error code + * @param hadc: ADC handle + * @retval ADC Error Code + */ +uint32_t HAL_ADC_GetError(ADC_HandleTypeDef *hadc) +{ + return hadc->ErrorCode; +} + +/** + * @} + */ + + +/** + * @brief Enable the selected ADC. + * @note Prerequisite condition to use this function: ADC must be disabled + * and voltage regulator must be enabled (done into HAL_ADC_Init()). + * @param hadc: ADC handle + * @retval HAL status. + */ +static HAL_StatusTypeDef ADC_Enable(ADC_HandleTypeDef* hadc) +{ + uint32_t tickstart = 0; + + /* ADC enable and wait for ADC ready (in case of ADC is disabled or */ + /* enabling phase not yet completed: flag ADC ready not yet set). */ + /* Timeout implemented to not be stuck if ADC cannot be enabled (possible */ + /* causes: ADC clock not running, ...). */ + if (__HAL_ADC_IS_ENABLED(hadc) == RESET) + { + /* Check if conditions to enable the ADC are fulfilled */ + if (__HAL_ADC_ENABLING_CONDITIONS(hadc) == RESET) + { + /* Update ADC state machine to error */ + hadc->State = HAL_ADC_STATE_ERROR; + + /* Set ADC error code to ADC IP internal error */ + hadc->ErrorCode |= HAL_ADC_ERROR_INTERNAL; + + return HAL_ERROR; + } + + /* Enable the ADC peripheral */ + __HAL_ADC_ENABLE(hadc); + + /* Wait for ADC effectively enabled */ + tickstart = HAL_GetTick(); + + while(__HAL_ADC_GET_FLAG(hadc, ADC_FLAG_RDY) == RESET) + { + if((HAL_GetTick() - tickstart) > ADC_ENABLE_TIMEOUT) + { + /* Update ADC state machine to error */ + hadc->State = HAL_ADC_STATE_ERROR; + + /* Set ADC error code to ADC IP internal error */ + hadc->ErrorCode |= HAL_ADC_ERROR_INTERNAL; + + return HAL_ERROR; + } + } + + } + + /* Return HAL status */ + return HAL_OK; +} + +/** + * @brief Disable the selected ADC. + * @note Prerequisite condition to use this function: ADC conversions must be + * stopped. + * @param hadc: ADC handle + * @retval HAL status. + */ +static HAL_StatusTypeDef ADC_Disable(ADC_HandleTypeDef* hadc) +{ + uint32_t tickstart = 0; + + /* Verification if ADC is not already disabled: */ + /* Note: forbidden to disable ADC (set bit ADC_CR_ADDIS) if ADC is already */ + /* disabled. */ + if (__HAL_ADC_IS_ENABLED(hadc) != RESET ) + { + /* Check if conditions to disable the ADC are fulfilled */ + if (__HAL_ADC_DISABLING_CONDITIONS(hadc) != RESET) + { + /* Disable the ADC peripheral */ + __HAL_ADC_DISABLE(hadc); + } + else + { + /* Update ADC state machine to error */ + hadc->State = HAL_ADC_STATE_ERROR; + + /* Set ADC error code to ADC IP internal error */ + hadc->ErrorCode |= HAL_ADC_ERROR_INTERNAL; + + return HAL_ERROR; + } + + /* Wait for ADC effectively disabled */ + tickstart = HAL_GetTick(); + + while(HAL_IS_BIT_SET(hadc->Instance->CR, ADC_CR_ADEN)) + { + if((HAL_GetTick() - tickstart) > ADC_ENABLE_TIMEOUT) + { + /* Update ADC state machine to error */ + hadc->State = HAL_ADC_STATE_ERROR; + + /* Set ADC error code to ADC IP internal error */ + hadc->ErrorCode |= HAL_ADC_ERROR_INTERNAL; + + return HAL_ERROR; + } + } + } + + /* Return HAL status */ + return HAL_OK; +} + + +/** + * @brief Stop ADC conversion. + * @note Prerequisite condition to use this function: ADC conversions must be + * stopped to disable the ADC. + * @param hadc: ADC handle + * @retval HAL status. + */ +static HAL_StatusTypeDef ADC_ConversionStop(ADC_HandleTypeDef* hadc) +{ + uint32_t tickstart = 0; + + /* Check the parameters */ + assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance)); + + /* Verification if ADC is not already stopped on regular group to bypass */ + /* this function if not needed. */ + if (__HAL_ADC_IS_CONVERSION_ONGOING_REGULAR(hadc)) + { + + /* Stop potential conversion on going on regular group */ + /* Software is allowed to set ADSTP only when ADSTART=1 and ADDIS=0 */ + if (HAL_IS_BIT_SET(hadc->Instance->CR, ADC_CR_ADSTART) && + HAL_IS_BIT_CLR(hadc->Instance->CR, ADC_CR_ADDIS) ) + { + /* Stop conversions on regular group */ + hadc->Instance->CR |= ADC_CR_ADSTP; + } + + /* Wait for conversion effectively stopped */ + tickstart = HAL_GetTick(); + + while((hadc->Instance->CR & ADC_CR_ADSTART) != RESET) + { + if((HAL_GetTick() - tickstart) > ADC_STOP_CONVERSION_TIMEOUT) + { + /* Update ADC state machine to error */ + hadc->State = HAL_ADC_STATE_ERROR; + + /* Set ADC error code to ADC IP internal error */ + hadc->ErrorCode |= HAL_ADC_ERROR_INTERNAL; + + return HAL_ERROR; + } + } + + } + + /* Return HAL status */ + return HAL_OK; +} + +/** + * @} + */ + +#endif /* HAL_ADC_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_adc.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_adc.h new file mode 100644 index 0000000000..beae103990 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_adc.h @@ -0,0 +1,927 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_adc.h + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief Header file containing functions prototypes of ADC HAL library. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32F0xx_HAL_ADC_H +#define __STM32F0xx_HAL_ADC_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal_def.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @addtogroup ADC + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ + +/** + * @brief Structure definition of ADC initialization and regular group + * @note The setting of these parameters with function HAL_ADC_Init() is conditioned to ADC state. + * ADC state can be either: + * - For all parameters: ADC disabled (this is the only possible ADC state to modify parameter 'ClockPrescaler') + * - For all parameters except 'ClockPrescaler': ADC enabled without conversion on going on regular group. + * If ADC is not in the appropriate state to modify some parameters, these parameters setting is bypassed + * without error reporting without error reporting (as it can be the expected behaviour in case of intended action to update another parameter (which fulfills the ADC state condition) on the fly). + */ +typedef struct +{ + uint32_t ClockPrescaler; /*!< Select ADC clock source (synchronous clock derived from APB clock or asynchronous clock derived from ADC dedicated HSI RC oscillator) and clock prescaler. + This parameter can be a value of @ref ADC_ClockPrescaler + Note: In case of usage of the ADC dedicated HSI RC oscillator, it must be preliminarily enabled at RCC top level. + Note: This parameter can be modified only if the ADC is disabled */ + uint32_t Resolution; /*!< Configures the ADC resolution. + This parameter can be a value of @ref ADC_Resolution */ + uint32_t DataAlign; /*!< Specifies whether the ADC data alignment is left or right. + This parameter can be a value of @ref ADC_data_align */ + uint32_t ScanConvMode; /*!< Configures the sequencer of regular group. + This parameter can be associated to parameter 'DiscontinuousConvMode' to have main sequence subdivided in successive parts. + Sequencer is automatically enabled if several channels are set (sequencer cannot be disabled, as it can be the case on other STM32 devices): + If only 1 channel is set: Conversion is performed in single mode. + If several channels are set: Conversions are performed in sequence mode (ranks defined by each channel number: channel 0 fixed on rank 0, channel 1 fixed on rank1, ...). + Scan direction can be set to forward (from channel 0 to channel 18) or backward (from channel 18 to channel 0). + This parameter can be a value of @ref ADC_Scan_mode */ + uint32_t EOCSelection; /*!< Specifies what EOC (End Of Conversion) flag is used for conversion by polling and interruption: end of conversion of each rank or complete sequence. + This parameter can be a value of @ref ADC_EOCSelection. */ + uint32_t LowPowerAutoWait; /*!< Selects the dynamic low power Auto Delay: new conversion start only when the previous + conversion has been treated by user software. + This feature automatically adapts the speed of ADC to the speed of the system that reads the data. Moreover, this avoids risk of overrun for low frequency applications. + This parameter can be set to ENABLE or DISABLE. */ + uint32_t LowPowerAutoPowerOff; /*!< Selects the auto-off mode: the ADC automatically powers-off after a conversion and automatically wakes-up when a new conversion is triggered (with startup time between trigger and start of sampling). + This feature can be combined with automatic wait mode (parameter 'LowPowerAutoWait'). + This parameter can be set to ENABLE or DISABLE. + Note: If enabled, this feature also turns off the ADC dedicated 14 MHz RC oscillator (HSI14) */ + uint32_t ContinuousConvMode; /*!< Specifies whether the conversion is performed in single mode (one conversion) or continuous mode for regular group, + after the selected trigger occurred (software start or external trigger). + This parameter can be set to ENABLE or DISABLE. */ + uint32_t DiscontinuousConvMode; /*!< Specifies whether the conversions sequence of regular group is performed in Complete-sequence/Discontinuous-sequence (main sequence subdivided in successive parts). + Discontinuous mode is used only if sequencer is enabled (parameter 'ScanConvMode'). If sequencer is disabled, this parameter is discarded. + Discontinuous mode can be enabled only if continuous mode is disabled. If continuous mode is enabled, this parameter setting is discarded. + This parameter can be set to ENABLE or DISABLE + Note: Number of discontinuous ranks increment is fixed to one-by-one. */ + uint32_t ExternalTrigConv; /*!< Selects the external event used to trigger the conversion start of regular group. + If set to ADC_SOFTWARE_START, external triggers are disabled. + This parameter can be a value of @ref ADC_External_trigger_source_Regular */ + uint32_t ExternalTrigConvEdge; /*!< Selects the external trigger edge of regular group. + If trigger is set to ADC_SOFTWARE_START, this parameter is discarded. + This parameter can be a value of @ref ADC_External_trigger_edge_Regular */ + uint32_t DMAContinuousRequests; /*!< Specifies whether the DMA requests are performed in one shot mode (DMA transfer stop when number of conversions is reached) + or in Continuous mode (DMA transfer unlimited, whatever number of conversions). + Note: In continuous mode, DMA must be configured in circular mode. Otherwise an overrun will be triggered when DMA buffer maximum pointer is reached. + This parameter can be set to ENABLE or DISABLE. */ + uint32_t Overrun; /*!< Select the behaviour in case of overrun: data preserved or overwritten + This parameter has an effect on regular group only, including in DMA mode. + This parameter can be a value of @ref ADC_Overrun */ +}ADC_InitTypeDef; + +/** + * @brief Structure definition of ADC channel for regular group + * @note The setting of these parameters with function HAL_ADC_ConfigChannel() is conditioned to ADC state. + * ADC state can be either: + * - For all parameters: ADC disabled or enabled without conversion on going on regular group. + * If ADC is not in the appropriate state to modify some parameters, these parameters setting is bypassed + * without error reporting (as it can be the expected behaviour in case of intended action to update another parameter (which fulfills the ADC state condition) on the fly). + */ +typedef struct +{ + uint32_t Channel; /*!< Specifies the channel to configure into ADC regular group. + This parameter can be a value of @ref ADC_channels + Note: Depending on devices, some channels may not be available on package pins. Refer to device datasheet for channels availability. */ + uint32_t Rank; /*!< Add or remove the channel from ADC regular group sequencer. + On STM32F0 devices, rank is defined by each channel number (channel 0 fixed on rank 0, channel 1 fixed on rank1, ...). + Despite the channel rank is fixed, this parameter allow an additional possibility: to remove the selected rank (selected channel) from sequencer. + This parameter can be a value of @ref ADC_rank */ + uint32_t SamplingTime; /*!< specifies the sampling time value to be set for the selected channel. + Unit: ADC clock cycles + Conversion time is the addition of sampling time and processing time (12.5 ADC clock cycles at ADC resolution 12 bits, 10.5 cycles at 10 bits, 8.5 cycles at 8 bits, 6.5 cycles at 6 bits). + This parameter can be a value of @ref ADC_sampling_times + Caution: this setting impacts the entire regular group. Therefore, call of HAL_ADCEx_ConfigChannel() to configure a channel can impact the configuration of other channels previously set. + Note: In case of usage of internal measurement channels (VrefInt/Vbat/TempSensor), + sampling time constraints must be respected (sampling time can be adjusted in function of ADC clock frequency and sampling time setting) + Refer to device datasheet for timings values, parameters TS_vrefint, TS_vbat, TS_temp (values rough order: 5us to 17us). */ +}ADC_ChannelConfTypeDef; + +/** + * @brief Structure definition of ADC analog watchdog + * @note The setting of these parameters with function HAL_ADC_AnalogWDGConfig() is conditioned to ADC state. + * ADC state can be either: ADC disabled or ADC enabled without conversion on going on regular group. + */ +typedef struct +{ + uint32_t WatchdogMode; /*!< Configures the ADC analog watchdog mode: single/all/none channels. + This parameter can be a value of @ref ADC_analog_watchdog_mode. */ + uint32_t Channel; /*!< Selects which ADC channel to monitor by analog watchdog. + This parameter has an effect only if parameter 'WatchdogMode' is configured on single channel. Only 1 channel can be monitored. + This parameter can be a value of @ref ADC_channels. */ + uint32_t ITMode; /*!< Specifies whether the analog watchdog is configured in interrupt or polling mode. + This parameter can be set to ENABLE or DISABLE */ + uint32_t HighThreshold; /*!< Configures the ADC analog watchdog High threshold value. + Depending of ADC resolution selected (12, 10, 8 or 6 bits), this parameter must be a number between Min_Data = 0x000 and Max_Data = 0xFFF, 0x3FF, 0xFF or 0x3F respectively. */ + uint32_t LowThreshold; /*!< Configures the ADC analog watchdog High threshold value. + Depending of ADC resolution selected (12, 10, 8 or 6 bits), this parameter must be a number between Min_Data = 0x000 and Max_Data = 0xFFF, 0x3FF, 0xFF or 0x3F respectively. */ +}ADC_AnalogWDGConfTypeDef; + +/** + * @brief HAL ADC state machine: ADC States structure definition + */ +typedef enum +{ + HAL_ADC_STATE_RESET = 0x00, /*!< ADC not yet initialized or disabled */ + HAL_ADC_STATE_READY = 0x01, /*!< ADC peripheral ready for use */ + HAL_ADC_STATE_BUSY = 0x02, /*!< An internal process is ongoing */ + HAL_ADC_STATE_BUSY_REG = 0x12, /*!< Regular conversion is ongoing */ + HAL_ADC_STATE_BUSY_INJ = 0x22, /*!< Not used on STM32F0xx devices (kept for compatibility with other devices featuring an injected group) */ + HAL_ADC_STATE_BUSY_INJ_REG = 0x32, /*!< Not used on STM32F0xx devices (kept for compatibility with other devices featuring an injected group) */ + HAL_ADC_STATE_TIMEOUT = 0x03, /*!< Timeout state */ + HAL_ADC_STATE_ERROR = 0x04, /*!< ADC state error */ + HAL_ADC_STATE_EOC = 0x05, /*!< Conversion is completed */ + HAL_ADC_STATE_EOC_REG = 0x15, /*!< Regular conversion is completed */ + HAL_ADC_STATE_EOC_INJ = 0x25, /*!< Not used on STM32F0xx devices (kept for compatibility with other devices featuring an injected group) */ + HAL_ADC_STATE_EOC_INJ_REG = 0x35, /*!< Not used on STM32F0xx devices (kept for compatibility with other devices featuring an injected group) */ + HAL_ADC_STATE_AWD = 0x06, /*!< ADC state analog watchdog */ + HAL_ADC_STATE_AWD2 = 0x07, /*!< Not used on STM32F0xx devices (kept for compatibility with other devices featuring several AWD) */ + HAL_ADC_STATE_AWD3 = 0x08, /*!< Not used on STM32F0xx devices (kept for compatibility with other devices featuring several AWD) */ +}HAL_ADC_StateTypeDef; + +/** + * @brief ADC handle Structure definition + */ +typedef struct +{ + ADC_TypeDef *Instance; /*!< Register base address */ + + ADC_InitTypeDef Init; /*!< ADC required parameters */ + + __IO uint32_t NbrOfConversionRank ; /*!< ADC conversion rank counter */ + + DMA_HandleTypeDef *DMA_Handle; /*!< Pointer DMA Handler */ + + HAL_LockTypeDef Lock; /*!< ADC locking object */ + + __IO HAL_ADC_StateTypeDef State; /*!< ADC communication state */ + + __IO uint32_t ErrorCode; /*!< ADC Error code */ +}ADC_HandleTypeDef; + +/* Exported constants --------------------------------------------------------*/ + +/** @defgroup ADC_Exported_Constants + * @{ + */ + +/** @defgroup ADC_Error_Code + * @{ + */ +#define HAL_ADC_ERROR_NONE ((uint32_t)0x00) /*!< No error */ +#define HAL_ADC_ERROR_INTERNAL ((uint32_t)0x01) /*!< ADC IP internal error: if problem of clocking, + enable/disable, erroneous state */ +#define HAL_ADC_ERROR_OVR ((uint32_t)0x02) /*!< Overrun error */ +#define HAL_ADC_ERROR_DMA ((uint32_t)0x03) /*!< DMA transfer error */ + +/** + * @} + */ + + +/** @defgroup ADC_ClockPrescaler + * @{ + */ +#define ADC_CLOCK_ASYNC ((uint32_t)0x00000000) /*!< ADC asynchronous clock derived from ADC dedicated HSI */ + +#define ADC_CLOCK_SYNC_PCLK_DIV2 ((uint32_t)ADC_CFGR2_CKMODE_0) /*!< ADC synchronous clock derived from AHB clock divided by a prescaler of 2 */ +#define ADC_CLOCK_SYNC_PCLK_DIV4 ((uint32_t)ADC_CFGR2_CKMODE_1) /*!< ADC synchronous clock derived from AHB clock divided by a prescaler of 4 */ + +#define ADC_CLOCKPRESCALER_PCLK_DIV2 ADC_CLOCK_SYNC_PCLK_DIV2 /* Obsolete naming, kept for compatibility with some other devices */ +#define ADC_CLOCKPRESCALER_PCLK_DIV4 ADC_CLOCK_SYNC_PCLK_DIV4 /* Obsolete naming, kept for compatibility with some other devices */ + +#define IS_ADC_CLOCKPRESCALER(ADC_CLOCK) (((ADC_CLOCK) == ADC_CLOCK_ASYNC) || \ + ((ADC_CLOCK) == ADC_CLOCK_SYNC_PCLK_DIV2) || \ + ((ADC_CLOCK) == ADC_CLOCK_SYNC_PCLK_DIV4) ) + +/** + * @} + */ + +/** @defgroup ADC_Resolution + * @{ + */ +#define ADC_RESOLUTION12b ((uint32_t)0x00000000) /*!< ADC 12-bit resolution */ +#define ADC_RESOLUTION10b ((uint32_t)ADC_CFGR1_RES_0) /*!< ADC 10-bit resolution */ +#define ADC_RESOLUTION8b ((uint32_t)ADC_CFGR1_RES_1) /*!< ADC 8-bit resolution */ +#define ADC_RESOLUTION6b ((uint32_t)ADC_CFGR1_RES) /*!< ADC 6-bit resolution */ + +#define IS_ADC_RESOLUTION(RESOLUTION) (((RESOLUTION) == ADC_RESOLUTION12b) || \ + ((RESOLUTION) == ADC_RESOLUTION10b) || \ + ((RESOLUTION) == ADC_RESOLUTION8b) || \ + ((RESOLUTION) == ADC_RESOLUTION6b) ) +/** + * @} + */ + +/** @defgroup ADC_data_align + * @{ + */ +#define ADC_DATAALIGN_RIGHT ((uint32_t)0x00000000) +#define ADC_DATAALIGN_LEFT ((uint32_t)ADC_CFGR1_ALIGN) + +#define IS_ADC_DATA_ALIGN(ALIGN) (((ALIGN) == ADC_DATAALIGN_RIGHT) || \ + ((ALIGN) == ADC_DATAALIGN_LEFT) ) +/** + * @} + */ + +/** @defgroup ADC_Scan_mode + * @{ + */ +/* Note: Scan mode values must be compatible with other STM32 devices having */ +/* a configurable sequencer. */ +/* Scan direction setting values are defined by taking in account */ +/* already defined values for other STM32 devices: */ +/* ADC_SCAN_DISABLE ((uint32_t)0x00000000) */ +/* ADC_SCAN_ENABLE ((uint32_t)0x00000001) */ +/* Scan direction forward is considered as default setting equivalent */ +/* to scan enable. */ +/* Scan direction backward is considered as additional setting. */ +/* In case of migration from another STM32 device, the user will be */ +/* warned of change of setting choices with assert check. */ +#define ADC_SCAN_DIRECTION_FORWARD ((uint32_t)0x00000001) /*!< Scan direction forward: from channel 0 to channel 18 */ +#define ADC_SCAN_DIRECTION_BACKWARD ((uint32_t)0x00000002) /*!< Scan direction backward: from channel 18 to channel 0 */ + +#define ADC_SCAN_ENABLE ADC_SCAN_DIRECTION_FORWARD /* For compatibility with other STM32 devices */ + +#define IS_ADC_SCAN_MODE(SCAN_MODE) (((SCAN_MODE) == ADC_SCAN_DIRECTION_FORWARD) || \ + ((SCAN_MODE) == ADC_SCAN_DIRECTION_BACKWARD) ) +/** + * @} + */ + +/** @defgroup ADC_External_trigger_edge_Regular + * @{ + */ +#define ADC_EXTERNALTRIGCONVEDGE_NONE ((uint32_t)0x00000000) +#define ADC_EXTERNALTRIGCONVEDGE_RISING ((uint32_t)ADC_CFGR1_EXTEN_0) +#define ADC_EXTERNALTRIGCONVEDGE_FALLING ((uint32_t)ADC_CFGR1_EXTEN_1) +#define ADC_EXTERNALTRIGCONVEDGE_RISINGFALLING ((uint32_t)ADC_CFGR1_EXTEN) + +#define IS_ADC_EXTTRIG_EDGE(EDGE) (((EDGE) == ADC_EXTERNALTRIGCONVEDGE_NONE) || \ + ((EDGE) == ADC_EXTERNALTRIGCONVEDGE_RISING) || \ + ((EDGE) == ADC_EXTERNALTRIGCONVEDGE_FALLING) || \ + ((EDGE) == ADC_EXTERNALTRIGCONVEDGE_RISINGFALLING) ) +/** + * @} + */ + +/** @defgroup ADC_External_trigger_source_Regular + * @{ + */ + +/* List of external triggers with generic trigger name, sorted by trigger */ +/* name: */ + +/* External triggers of regular group for ADC1 */ +#define ADC_EXTERNALTRIGCONV_T1_TRGO ADC1_2_EXTERNALTRIG_T1_TRGO +#define ADC_EXTERNALTRIGCONV_T1_CC4 ADC1_2_EXTERNALTRIG_T1_CC4 +#define ADC_EXTERNALTRIGCONV_T2_TRGO ADC1_2_EXTERNALTRIG_T2_TRGO +#define ADC_EXTERNALTRIGCONV_T3_TRGO ADC1_2_EXTERNALTRIG_T3_TRGO +#define ADC_EXTERNALTRIGCONV_T15_TRGO ADC1_2_EXTERNALTRIG_T15_TRGO +#define ADC_SOFTWARE_START ((uint32_t)0x00000010) + +#define IS_ADC_EXTTRIG(REGTRIG) (((REGTRIG) == ADC_EXTERNALTRIGCONV_T1_TRGO) || \ + ((REGTRIG) == ADC_EXTERNALTRIGCONV_T1_CC4) || \ + ((REGTRIG) == ADC_EXTERNALTRIGCONV_T2_TRGO) || \ + ((REGTRIG) == ADC_EXTERNALTRIGCONV_T3_TRGO) || \ + ((REGTRIG) == ADC_EXTERNALTRIGCONV_T15_TRGO) || \ + ((REGTRIG) == ADC_SOFTWARE_START) ) +/** + * @} + */ + +/** @defgroup ADC_Internal_HAL_driver_Ext_trig_src_Regular + * @{ + */ + +/* List of external triggers of regular group for ADC1: */ +/* (used internally by HAL driver. To not use into HAL structure parameters) */ +#define ADC1_2_EXTERNALTRIG_T1_TRGO ((uint32_t)0x00000000) +#define ADC1_2_EXTERNALTRIG_T1_CC4 ((uint32_t)ADC_CFGR1_EXTSEL_0) +#define ADC1_2_EXTERNALTRIG_T2_TRGO ((uint32_t)ADC_CFGR1_EXTSEL_1) +#define ADC1_2_EXTERNALTRIG_T3_TRGO ((uint32_t)(ADC_CFGR1_EXTSEL_1 | ADC_CFGR1_EXTSEL_0)) +#define ADC1_2_EXTERNALTRIG_T15_TRGO ((uint32_t)ADC_CFGR1_EXTSEL_2) + +/** + * @} + */ + + +/** @defgroup ADC_EOCSelection + * @{ + */ +#define EOC_SINGLE_CONV ((uint32_t) ADC_ISR_EOC) +#define EOC_SEQ_CONV ((uint32_t) ADC_ISR_EOS) +#define EOC_SINGLE_SEQ_CONV ((uint32_t)(ADC_ISR_EOC | ADC_ISR_EOS)) /*!< reserved for future use */ + +#define IS_ADC_EOC_SELECTION(EOC_SELECTION) (((EOC_SELECTION) == EOC_SINGLE_CONV) || \ + ((EOC_SELECTION) == EOC_SEQ_CONV) || \ + ((EOC_SELECTION) == EOC_SINGLE_SEQ_CONV) ) +/** + * @} + */ + +/** @defgroup ADC_Overrun + * @{ + */ +#define OVR_DATA_OVERWRITTEN ((uint32_t)0x00000000) +#define OVR_DATA_PRESERVED ((uint32_t)0x00000001) + +#define IS_ADC_OVERRUN(OVR) (((OVR) == OVR_DATA_PRESERVED) || \ + ((OVR) == OVR_DATA_OVERWRITTEN) ) +/** + * @} + */ + +/** @defgroup ADC_channels + * @{ + */ +/* Note: Depending on devices, some channels may not be available on package */ +/* pins. Refer to device datasheet for channels availability. */ +/* Note: Channels are used by bitfields for setting of channel selection */ +/* (register ADC_CHSELR) and used by number for setting of analog watchdog */ +/* channel (bits AWDCH in register ADC_CFGR1). */ +/* Channels are defined with decimal numbers and converted them to bitfields */ +/* when needed. */ +#define ADC_CHANNEL_0 ((uint32_t) 0x00000000) +#define ADC_CHANNEL_1 ((uint32_t) 0x00000001) +#define ADC_CHANNEL_2 ((uint32_t) 0x00000002) +#define ADC_CHANNEL_3 ((uint32_t) 0x00000003) +#define ADC_CHANNEL_4 ((uint32_t) 0x00000004) +#define ADC_CHANNEL_5 ((uint32_t) 0x00000005) +#define ADC_CHANNEL_6 ((uint32_t) 0x00000006) +#define ADC_CHANNEL_7 ((uint32_t) 0x00000007) +#define ADC_CHANNEL_8 ((uint32_t) 0x00000008) +#define ADC_CHANNEL_9 ((uint32_t) 0x00000009) +#define ADC_CHANNEL_10 ((uint32_t) 0x0000000A) +#define ADC_CHANNEL_11 ((uint32_t) 0x0000000B) +#define ADC_CHANNEL_12 ((uint32_t) 0x0000000C) +#define ADC_CHANNEL_13 ((uint32_t) 0x0000000D) +#define ADC_CHANNEL_14 ((uint32_t) 0x0000000E) +#define ADC_CHANNEL_15 ((uint32_t) 0x0000000F) +#define ADC_CHANNEL_16 ((uint32_t) 0x00000010) +#define ADC_CHANNEL_17 ((uint32_t) 0x00000011) +#define ADC_CHANNEL_18 ((uint32_t) 0x00000012) + +#define ADC_CHANNEL_TEMPSENSOR ADC_CHANNEL_16 +#define ADC_CHANNEL_VREFINT ADC_CHANNEL_17 +#define ADC_CHANNEL_VBAT ADC_CHANNEL_18 + +#define IS_ADC_CHANNEL(CHANNEL) (((CHANNEL) == ADC_CHANNEL_0) || \ + ((CHANNEL) == ADC_CHANNEL_1) || \ + ((CHANNEL) == ADC_CHANNEL_2) || \ + ((CHANNEL) == ADC_CHANNEL_3) || \ + ((CHANNEL) == ADC_CHANNEL_4) || \ + ((CHANNEL) == ADC_CHANNEL_5) || \ + ((CHANNEL) == ADC_CHANNEL_6) || \ + ((CHANNEL) == ADC_CHANNEL_7) || \ + ((CHANNEL) == ADC_CHANNEL_8) || \ + ((CHANNEL) == ADC_CHANNEL_9) || \ + ((CHANNEL) == ADC_CHANNEL_10) || \ + ((CHANNEL) == ADC_CHANNEL_11) || \ + ((CHANNEL) == ADC_CHANNEL_12) || \ + ((CHANNEL) == ADC_CHANNEL_13) || \ + ((CHANNEL) == ADC_CHANNEL_14) || \ + ((CHANNEL) == ADC_CHANNEL_15) || \ + ((CHANNEL) == ADC_CHANNEL_TEMPSENSOR) || \ + ((CHANNEL) == ADC_CHANNEL_VREFINT) || \ + ((CHANNEL) == ADC_CHANNEL_VBAT) ) +/** + * @} + */ + +/** @defgroup ADC_rank + * @{ + */ +#define ADC_RANK_CHANNEL_NUMBER ((uint32_t)0x00001000) /*!< Enable the rank of the selected channels. Rank is defined by each channel number (channel 0 fixed on rank 0, channel 1 fixed on rank1, ...) */ +#define ADC_RANK_NONE ((uint32_t)0x00001001) /*!< Disable the selected rank (selected channel) from sequencer */ + +#define IS_ADC_RANK(WATCHDOG) (((WATCHDOG) == ADC_RANK_CHANNEL_NUMBER) || \ + ((WATCHDOG) == ADC_RANK_NONE) ) +/** + * @} + */ + +/** @defgroup ADC_sampling_times + * @{ + */ +#define ADC_SAMPLETIME_1CYCLE_5 ((uint32_t)0x00000000) /*!< Sampling time 1.5 ADC clock cycle */ +#define ADC_SAMPLETIME_7CYCLES_5 ((uint32_t) ADC_SMPR_SMP_0) /*!< Sampling time 7.5 ADC clock cycles */ +#define ADC_SAMPLETIME_13CYCLES_5 ((uint32_t) ADC_SMPR_SMP_1) /*!< Sampling time 13.5 ADC clock cycles */ +#define ADC_SAMPLETIME_28CYCLES_5 ((uint32_t)(ADC_SMPR_SMP_1 | ADC_SMPR_SMP_0)) /*!< Sampling time 28.5 ADC clock cycles */ +#define ADC_SAMPLETIME_41CYCLES_5 ((uint32_t) ADC_SMPR_SMP_2) /*!< Sampling time 41.5 ADC clock cycles */ +#define ADC_SAMPLETIME_55CYCLES_5 ((uint32_t)(ADC_SMPR_SMP_2 | ADC_SMPR_SMP_0)) /*!< Sampling time 55.5 ADC clock cycles */ +#define ADC_SAMPLETIME_71CYCLES_5 ((uint32_t)(ADC_SMPR_SMP_2 | ADC_SMPR_SMP_1)) /*!< Sampling time 71.5 ADC clock cycles */ +#define ADC_SAMPLETIME_239CYCLES_5 ((uint32_t) ADC_SMPR_SMP) /*!< Sampling time 239.5 ADC clock cycles */ + +#define IS_ADC_SAMPLE_TIME(TIME) (((TIME) == ADC_SAMPLETIME_1CYCLE_5) || \ + ((TIME) == ADC_SAMPLETIME_7CYCLES_5) || \ + ((TIME) == ADC_SAMPLETIME_13CYCLES_5) || \ + ((TIME) == ADC_SAMPLETIME_28CYCLES_5) || \ + ((TIME) == ADC_SAMPLETIME_41CYCLES_5) || \ + ((TIME) == ADC_SAMPLETIME_55CYCLES_5) || \ + ((TIME) == ADC_SAMPLETIME_71CYCLES_5) || \ + ((TIME) == ADC_SAMPLETIME_239CYCLES_5) ) +/** + * @} + */ + +/** @defgroup ADC_analog_watchdog_mode + * @{ + */ +#define ADC_ANALOGWATCHDOG_NONE ((uint32_t) 0x00000000) +#define ADC_ANALOGWATCHDOG_SINGLE_REG ((uint32_t)(ADC_CFGR1_AWDSGL | ADC_CFGR1_AWDEN)) +#define ADC_ANALOGWATCHDOG_ALL_REG ((uint32_t) ADC_CFGR1_AWDEN) + + +#define IS_ADC_ANALOG_WATCHDOG_MODE(WATCHDOG) (((WATCHDOG) == ADC_ANALOGWATCHDOG_NONE) || \ + ((WATCHDOG) == ADC_ANALOGWATCHDOG_SINGLE_REG) || \ + ((WATCHDOG) == ADC_ANALOGWATCHDOG_ALL_REG) ) +/** + * @} + */ + +/** @defgroup ADC_Event_type + * @{ + */ +#define AWD_EVENT ((uint32_t)ADC_FLAG_AWD) /*!< ADC Analog watchdog 1 event */ +#define OVR_EVENT ((uint32_t)ADC_FLAG_OVR) /*!< ADC overrun event */ + +#define IS_ADC_EVENT_TYPE(EVENT) (((EVENT) == AWD_EVENT) || \ + ((EVENT) == OVR_EVENT) ) +/** + * @} + */ + + +/** @defgroup ADC_interrupts_definition + * @{ + */ +#define ADC_IT_AWD ADC_IER_AWDIE /*!< ADC Analog watchdog interrupt source */ +#define ADC_IT_OVR ADC_IER_OVRIE /*!< ADC overrun interrupt source */ +#define ADC_IT_EOS ADC_IER_EOSEQIE /*!< ADC End of Regular sequence of Conversions interrupt source */ +#define ADC_IT_EOC ADC_IER_EOCIE /*!< ADC End of Regular Conversion interrupt source */ +#define ADC_IT_EOSMP ADC_IER_EOSMPIE /*!< ADC End of Sampling interrupt source */ +#define ADC_IT_RDY ADC_IER_ADRDYIE /*!< ADC Ready interrupt source */ + +/* Check of single flag */ +#define IS_ADC_IT(IT) (((IT) == ADC_IT_AWD) || ((IT) == ADC_IT_OVR) || \ + ((IT) == ADC_IT_EOS) || ((IT) == ADC_IT_EOC) || \ + ((IT) == ADC_IT_EOSMP) || ((IT) == ADC_IT_RDY) ) +/** + * @} + */ + +/** @defgroup ADC_flags_definition + * @{ + */ +#define ADC_FLAG_AWD ADC_ISR_AWD /*!< ADC Analog watchdog flag */ +#define ADC_FLAG_OVR ADC_ISR_OVR /*!< ADC overrun flag */ +#define ADC_FLAG_EOS ADC_ISR_EOSEQ /*!< ADC End of Regular sequence of Conversions flag */ +#define ADC_FLAG_EOC ADC_ISR_EOC /*!< ADC End of Regular Conversion flag */ +#define ADC_FLAG_EOSMP ADC_ISR_EOSMP /*!< ADC End of Sampling flag */ +#define ADC_FLAG_RDY ADC_ISR_ADRDY /*!< ADC Ready flag */ + +#define ADC_FLAG_ALL (ADC_FLAG_AWD | ADC_FLAG_OVR | ADC_FLAG_EOS | ADC_FLAG_EOC | \ + ADC_FLAG_EOSMP | ADC_FLAG_RDY ) + +/* Combination of all post-conversion flags bits: EOC/EOS, OVR, AWD */ +#define ADC_FLAG_POSTCONV_ALL (ADC_FLAG_AWD | ADC_FLAG_OVR | ADC_FLAG_EOS | ADC_FLAG_EOC) + +/* Check of single flag */ +#define IS_ADC_FLAG(FLAG) (((FLAG) == ADC_FLAG_AWD) || ((FLAG) == ADC_FLAG_OVR) || \ + ((FLAG) == ADC_FLAG_EOS) || ((FLAG) == ADC_FLAG_EOC) || \ + ((FLAG) == ADC_FLAG_EOSMP) || ((FLAG) == ADC_FLAG_RDY) ) +/** + * @} + */ + +/** @defgroup ADC_range_verification + * in function of ADC resolution selected (12, 10, 8 or 6 bits) + * @{ + */ +#define IS_ADC_RANGE(RESOLUTION, ADC_VALUE) \ + ((((RESOLUTION) == ADC_RESOLUTION12b) && ((ADC_VALUE) <= ((uint32_t)0x0FFF))) || \ + (((RESOLUTION) == ADC_RESOLUTION10b) && ((ADC_VALUE) <= ((uint32_t)0x03FF))) || \ + (((RESOLUTION) == ADC_RESOLUTION8b) && ((ADC_VALUE) <= ((uint32_t)0x00FF))) || \ + (((RESOLUTION) == ADC_RESOLUTION6b) && ((ADC_VALUE) <= ((uint32_t)0x003F))) ) +/** + * @} + */ + +/** @defgroup ADC_regular_rank_verification + * @{ + */ +#define IS_ADC_REGULAR_RANK(RANK) (((RANK) >= ((uint32_t)1)) && ((RANK) <= ((uint32_t)16))) +/** + * @} + */ + + + + +/** + * @} + */ + +/* Exported macros -----------------------------------------------------------*/ + + +/** @defgroup ADC_Exported_Macros + * @{ + */ +/** @brief Reset ADC handle state + * @param __HANDLE__: ADC handle + * @retval None + */ +#define __HAL_ADC_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_ADC_STATE_RESET) + +/** + * @} + */ + +/* Macro for internal HAL driver usage, and possibly can be used into code of */ +/* final user. */ + +/** + * @brief Verification of ADC state: enabled or disabled + * @param __HANDLE__: ADC handle + * @retval SET (ADC enabled) or RESET (ADC disabled) + */ +/* Note: If low power mode AutoPowerOff is enabled, power-on/off phases are */ +/* performed automatically by hardware and flag ADC_FLAG_RDY is not */ +/* set. */ +#define __HAL_ADC_IS_ENABLED(__HANDLE__) \ + (( ((((__HANDLE__)->Instance->CR) & (ADC_CR_ADEN | ADC_CR_ADDIS)) == ADC_CR_ADEN) && \ + (((((__HANDLE__)->Instance->ISR) & ADC_FLAG_RDY) == ADC_FLAG_RDY) || \ + ((((__HANDLE__)->Instance->CFGR1) & ADC_CFGR1_AUTOFF) == ADC_CFGR1_AUTOFF) ) \ + ) ? SET : RESET) + +/** + * @brief Test if conversion trigger of regular group is software start + * or external trigger. + * @param __HANDLE__: ADC handle + * @retval SET (software start) or RESET (external trigger) + */ +#define __HAL_ADC_IS_SOFTWARE_START_REGULAR(__HANDLE__) \ + (((__HANDLE__)->Instance->CFGR1 & ADC_CFGR1_EXTEN) == RESET) + +/** + * @brief Check if no conversion on going on regular group + * @param __HANDLE__: ADC handle + * @retval SET (conversion is on going) or RESET (no conversion is on going) + */ +#define __HAL_ADC_IS_CONVERSION_ONGOING_REGULAR(__HANDLE__) \ + (( (((__HANDLE__)->Instance->CR) & ADC_CR_ADSTART) == RESET \ + ) ? RESET : SET) + +/** + * @brief Returns resolution bits in CFGR1 register: RES[1:0]. + * Returned value is among parameters to @ref ADC_Resolution. + * @param __HANDLE__: ADC handle + * @retval None + */ +#define __HAL_ADC_GET_RESOLUTION(__HANDLE__) (((__HANDLE__)->Instance->CFGR1) & ADC_CFGR1_RES) + +/** + * @brief Returns ADC sample time bits in SMPR register: SMP[2:0]. + * Returned value is among parameters to @ref ADC_Resolution. + * @param __HANDLE__: ADC handle + * @retval None + */ +#define __HAL_ADC_GET_SAMPLINGTIME(__HANDLE__) (((__HANDLE__)->Instance->SMPR) & ADC_SMPR_SMP) + +/** @brief Checks if the specified ADC interrupt source is enabled or disabled. + * @param __HANDLE__: ADC handle + * @param __INTERRUPT__: ADC interrupt source to check + * @retval State ofinterruption (SET or RESET) + */ +#define __HAL_ADC_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) \ + (( ((__HANDLE__)->Instance->IER & (__INTERRUPT__)) == (__INTERRUPT__) \ + )? SET : RESET \ + ) + +/** + * @brief Enable the ADC end of conversion interrupt. + * @param __HANDLE__: ADC handle + * @param __INTERRUPT__: ADC Interrupt + * @retval None + */ +#define __HAL_ADC_ENABLE_IT(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->IER) |= (__INTERRUPT__)) + +/** + * @brief Disable the ADC end of conversion interrupt. + * @param __HANDLE__: ADC handle + * @param __INTERRUPT__: ADC Interrupt + * @retval None + */ +#define __HAL_ADC_DISABLE_IT(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->IER) &= ~(__INTERRUPT__)) + +/** + * @brief Get the selected ADC's flag status. + * @param __HANDLE__: ADC handle + * @param __FLAG__: ADC flag + * @retval None + */ +#define __HAL_ADC_GET_FLAG(__HANDLE__, __FLAG__) ((((__HANDLE__)->Instance->ISR) & (__FLAG__)) == (__FLAG__)) + +/** + * @brief Clear the ADC's pending flags + * @param __HANDLE__: ADC handle + * @param __FLAG__: ADC flag + * @retval None + */ +/* Note: bit cleared bit by writing 1 (writing 0 has no effect on any bit of register ISR) */ +#define __HAL_ADC_CLEAR_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->ISR) = (__FLAG__)) + +/** + * @brief Clear ADC error code (set it to error code: "no error") + * @param __HANDLE__: ADC handle + * @retval None + */ +#define __HAL_ADC_CLEAR_ERRORCODE(__HANDLE__) ((__HANDLE__)->ErrorCode = HAL_ADC_ERROR_NONE) + + +/** + * @brief Configure the channel number into channel selection register + * @param _CHANNEL_: ADC Channel + * @retval None + */ +/* This function converts ADC channels from numbers (see defgroup ADC_channels) + to bitfields, to get the equivalence of CMSIS channels: + ADC_CHANNEL_0 ((uint32_t) ADC_CHSELR_CHSEL0) + ADC_CHANNEL_1 ((uint32_t) ADC_CHSELR_CHSEL1) + ADC_CHANNEL_2 ((uint32_t) ADC_CHSELR_CHSEL2) + ADC_CHANNEL_3 ((uint32_t) ADC_CHSELR_CHSEL3) + ADC_CHANNEL_4 ((uint32_t) ADC_CHSELR_CHSEL4) + ADC_CHANNEL_5 ((uint32_t) ADC_CHSELR_CHSEL5) + ADC_CHANNEL_6 ((uint32_t) ADC_CHSELR_CHSEL6) + ADC_CHANNEL_7 ((uint32_t) ADC_CHSELR_CHSEL7) + ADC_CHANNEL_8 ((uint32_t) ADC_CHSELR_CHSEL8) + ADC_CHANNEL_9 ((uint32_t) ADC_CHSELR_CHSEL9) + ADC_CHANNEL_10 ((uint32_t) ADC_CHSELR_CHSEL10) + ADC_CHANNEL_11 ((uint32_t) ADC_CHSELR_CHSEL11) + ADC_CHANNEL_12 ((uint32_t) ADC_CHSELR_CHSEL12) + ADC_CHANNEL_13 ((uint32_t) ADC_CHSELR_CHSEL13) + ADC_CHANNEL_14 ((uint32_t) ADC_CHSELR_CHSEL14) + ADC_CHANNEL_15 ((uint32_t) ADC_CHSELR_CHSEL15) + ADC_CHANNEL_16 ((uint32_t) ADC_CHSELR_CHSEL16) + ADC_CHANNEL_17 ((uint32_t) ADC_CHSELR_CHSEL17) + ADC_CHANNEL_18 ((uint32_t) ADC_CHSELR_CHSEL18) +*/ +#define __HAL_ADC_CHSELR_CHANNEL(_CHANNEL_) ( 1U << (_CHANNEL_)) + +/** + * @} + */ + +/** @defgroup ADC_Exported_Macro_internal_HAL_driver + * @{ + */ +/* Macro reserved for internal HAL driver usage, not intended to be used in */ +/* code of final user. */ + +/** + * @brief Set the Analog Watchdog 1 channel. + * @param _CHANNEL_: channel to be monitored by Analog Watchdog 1. + * @retval None + */ +#define __HAL_ADC_CFGR_AWDCH(_CHANNEL_) ((_CHANNEL_) << 26) + +/** + * @brief Enable ADC discontinuous conversion mode for regular group + * @param _REG_DISCONTINUOUS_MODE_: Regulat discontinuous mode. + * @retval None + */ +#define __HAL_ADC_CFGR1_REG_DISCCONTINUOUS(_REG_DISCONTINUOUS_MODE_) ((_REG_DISCONTINUOUS_MODE_) << 16) + +/** + * @brief Enable the ADC auto off mode. + * @param _AUTOOFF_: Auto off bit enable or disable. + * @retval None + */ +#define __HAL_ADC_CFGR1_AUTOOFF(_AUTOOFF_) ((_AUTOOFF_) << 15) + +/** + * @brief Enable the ADC auto delay mode. + * @param _AUTOWAIT_: Auto delay bit enable or disable. + * @retval None + */ +#define __HAL_ADC_CFGR1_AUTOWAIT(_AUTOWAIT_) ((_AUTOWAIT_) << 14) + +/** + * @brief Enable ADC continuous conversion mode. + * @param _CONTINUOUS_MODE_: Continuous mode. + * @retval None + */ +#define __HAL_ADC_CFGR1_CONTINUOUS(_CONTINUOUS_MODE_) ((_CONTINUOUS_MODE_) << 13) + +/** + * @brief Enable ADC overrun mode. + * @param _OVERRUN_MODE_: Overrun mode. + * @retval Overun bit setting to be programmed into CFGR register + */ +/* Note: Bit ADC_CFGR1_OVRMOD not used directly in constant */ +/* "OVR_DATA_OVERWRITTEN" to have this case defined to 0x00, to set it as the */ +/* default case to be compliant with other STM32 devices. */ +#define __HAL_ADC_CFGR1_OVERRUN(_OVERRUN_MODE_) \ + ( ( (_OVERRUN_MODE_) != (OVR_DATA_PRESERVED) \ + )? (ADC_CFGR1_OVRMOD) : (0x00000000) \ + ) + +/** + * @brief Enable ADC scan mode to convert multiple ranks with sequencer. + * @param _SCAN_MODE_: Scan conversion mode. + * @retval None + */ +#define __HAL_ADC_CFGR1_SCANDIR(_SCAN_MODE_) \ + ( ( (_SCAN_MODE_) == (ADC_SCAN_DIRECTION_BACKWARD) \ + )? (ADC_CFGR1_SCANDIR) : (0x00000000) \ + ) + +/** + * @brief Enable the ADC DMA continuous request. + * @param _DMACONTREQ_MODE_: DMA continuous request mode. + * @retval None + */ +#define __HAL_ADC_CFGR1_DMACONTREQ(_DMACONTREQ_MODE_) ((_DMACONTREQ_MODE_) << 1) + +/** + * @brief Configure the channel number into offset OFRx register + * @param _CHANNEL_: ADC Channel + * @retval None + */ +#define __HAL_ADC_OFR_CHANNEL(_CHANNEL_) ((_CHANNEL_) << 26) + +/** + * @brief Configure the analog watchdog high threshold into register TR. + * @param _Threshold_: Threshold value + * @retval None + */ +#define __HAL_ADC_TRX_HIGHTHRESHOLD(_Threshold_) ((_Threshold_) << 16) + +/** + * @brief Enable the ADC peripheral + * @param __HANDLE__: ADC handle + * @retval None + */ +#define __HAL_ADC_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= ADC_CR_ADEN) + +/** + * @brief Verification of hardware constraints before ADC can be enabled + * @param __HANDLE__: ADC handle + * @retval SET (ADC can be enabled) or RESET (ADC cannot be enabled) + */ +#define __HAL_ADC_ENABLING_CONDITIONS(__HANDLE__) \ + (( ( ((__HANDLE__)->Instance->CR) & \ + (ADC_CR_ADCAL | ADC_CR_ADSTP | \ + ADC_CR_ADSTART | ADC_CR_ADDIS | ADC_CR_ADEN ) \ + ) == RESET \ + ) ? SET : RESET) + +/** + * @brief Disable the ADC peripheral + * @param __HANDLE__: ADC handle + * @retval None + */ +#define __HAL_ADC_DISABLE(__HANDLE__) \ + do{ \ + (__HANDLE__)->Instance->CR |= ADC_CR_ADDIS; \ + __HAL_ADC_CLEAR_FLAG((__HANDLE__), (ADC_FLAG_EOSMP | ADC_FLAG_RDY)); \ + } while(0) + +/** + * @brief Verification of hardware constraints before ADC can be disabled + * @param __HANDLE__: ADC handle + * @retval SET (ADC can be disabled) or RESET (ADC cannot be disabled) + */ +#define __HAL_ADC_DISABLING_CONDITIONS(__HANDLE__) \ + (( ( ((__HANDLE__)->Instance->CR) & \ + (ADC_CR_ADSTART | ADC_CR_ADEN)) == ADC_CR_ADEN \ + ) ? SET : RESET) + +/** + * @brief Shift the AWD threshold in function of the selected ADC resolution. + * Thresholds have to be left-aligned on bit 11, the LSB (right bits) are set to 0. + * If resolution 12 bits, no shift. + * If resolution 10 bits, shift of 2 ranks on the left. + * If resolution 8 bits, shift of 4 ranks on the left. + * If resolution 6 bits, shift of 6 ranks on the left. + * therefore, shift = (12 - resolution) = 12 - (12- (((RES[1:0]) >> 3)*2)) + * @param __HANDLE__: ADC handle + * @param _Threshold_: Value to be shifted + * @retval None + */ +#define __HAL_ADC_AWD1THRESHOLD_SHIFT_RESOLUTION(__HANDLE__, _Threshold_) \ + ((_Threshold_) << ((((__HANDLE__)->Instance->CFGR1 & ADC_CFGR1_RES) >> 3)*2)) + +/** + * @} + */ + +/* Include ADC HAL Extension module */ +#include "stm32f0xx_hal_adc_ex.h" + +/* Exported functions --------------------------------------------------------*/ +/* Initialization and de-initialization functions **********************************/ +HAL_StatusTypeDef HAL_ADC_Init(ADC_HandleTypeDef* hadc); +HAL_StatusTypeDef HAL_ADC_DeInit(ADC_HandleTypeDef *hadc); +void HAL_ADC_MspInit(ADC_HandleTypeDef* hadc); +void HAL_ADC_MspDeInit(ADC_HandleTypeDef* hadc); + +/* IO operation functions *****************************************************/ +/* Blocking mode: Polling */ +HAL_StatusTypeDef HAL_ADC_Start(ADC_HandleTypeDef* hadc); +HAL_StatusTypeDef HAL_ADC_Stop(ADC_HandleTypeDef* hadc); +HAL_StatusTypeDef HAL_ADC_PollForConversion(ADC_HandleTypeDef* hadc, uint32_t Timeout); +HAL_StatusTypeDef HAL_ADC_PollForEvent(ADC_HandleTypeDef* hadc, uint32_t EventType, uint32_t Timeout); + +/* Non-blocking mode: Interruption */ +HAL_StatusTypeDef HAL_ADC_Start_IT(ADC_HandleTypeDef* hadc); +HAL_StatusTypeDef HAL_ADC_Stop_IT(ADC_HandleTypeDef* hadc); + +/* Non-blocking mode: DMA */ +HAL_StatusTypeDef HAL_ADC_Start_DMA(ADC_HandleTypeDef* hadc, uint32_t* pData, uint32_t Length); +HAL_StatusTypeDef HAL_ADC_Stop_DMA(ADC_HandleTypeDef* hadc); + +/* ADC retrieve conversion value intended to be used with polling or interruption */ +uint32_t HAL_ADC_GetValue(ADC_HandleTypeDef* hadc); + +/* ADC IRQHandler and Callbacks used in non-blocking modes (Interruption and DMA) */ +void HAL_ADC_IRQHandler(ADC_HandleTypeDef* hadc); +void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef* hadc); +void HAL_ADC_ConvHalfCpltCallback(ADC_HandleTypeDef* hadc); +void HAL_ADC_LevelOutOfWindowCallback(ADC_HandleTypeDef* hadc); +void HAL_ADC_ErrorCallback(ADC_HandleTypeDef *hadc); + +/* Peripheral Control functions ***********************************************/ +HAL_StatusTypeDef HAL_ADC_ConfigChannel(ADC_HandleTypeDef* hadc, ADC_ChannelConfTypeDef* sConfig); +HAL_StatusTypeDef HAL_ADC_AnalogWDGConfig(ADC_HandleTypeDef* hadc, ADC_AnalogWDGConfTypeDef* AnalogWDGConfig); + +/* Peripheral State functions *************************************************/ +HAL_ADC_StateTypeDef HAL_ADC_GetState(ADC_HandleTypeDef* hadc); +uint32_t HAL_ADC_GetError(ADC_HandleTypeDef *hadc); + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + + +#endif /* __STM32F0xx_HAL_ADC_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_adc_ex.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_adc_ex.c new file mode 100644 index 0000000000..952ac0f1b4 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_adc_ex.c @@ -0,0 +1,258 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_adc_ex.c + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief This file provides firmware functions to manage the following + * functionalities of the Analog to Digital Convertor (ADC) + * peripheral: + * + Operation functions + * ++ Calibration (ADC automatic self-calibration) + * + @verbatim + ============================================================================== + ##### ADC specific features ##### + ============================================================================== + [..] + (#) 12-bit, 10-bit, 8-bit or 6-bit configurable resolution + + (#) Interrupt generation at the end of regular conversion and in case of + analog watchdog or overrun events. + + (#) Single and continuous conversion modes. + + (#) Scan mode for automatic conversion of channel 0 to channel ‘n’. + + (#) Data alignment with in-built data coherency. + + (#) Programmable sampling time. + + (#) ADC conversion group Regular. + + (#) External trigger (timer or EXTI) with configurable polarity. + + (#) DMA request generation for transfer of conversions data of regular group. + + (#) ADC calibration + + (#) ADC supply requirements: 2.4 V to 3.6 V at full speed and down to 1.8 V at + slower speed. + + (#) ADC input range: from Vref– (connected to Vssa) to Vref+ (connected to + Vdda or to an external voltage reference). + + + ##### How to use this driver ##### + ============================================================================== + [..] + + (#) Enable the ADC interface + As prerequisite, into HAL_ADC_MspInit(), ADC clock must be configured + at RCC top level: clock source and clock prescaler. + Two possible clock sources: synchronous clock derived from APB clock + or asynchronous clock derived from ADC dedicated HSI RC oscillator + 14MHz. + Example: + __ADC1_CLK_ENABLE(); (mandatory) + + HI14 enable or let under control of ADC: (optional) + + RCC_OscInitTypeDef RCC_OscInitStructure; + RCC_OscInitStructure.OscillatorType = RCC_OSCILLATORTYPE_HSI14; + RCC_OscInitStructure.HSI14CalibrationValue = RCC_HSI14CALIBRATION_DEFAULT; + RCC_OscInitStructure.HSI14State = RCC_HSI14_ADC_CONTROL; + RCC_OscInitStructure.PLL... (optional if used for system clock) + HAL_RCC_OscConfig(&RCC_OscInitStructure); + + Parameter "HSI14State" must be set either: + - to "...HSI14State = RCC_HSI14_ADC_CONTROL" to let the ADC control + the HSI14 oscillator enable/disable (if not used to supply the main + system clock): feature used if ADC mode LowPowerAutoPowerOff is + enabled. + - to "...HSI14State = RCC_HSI14_ON" to maintain the HSI14 oscillator + always enabled: can be used to supply the main system clock. + + (#) ADC pins configuration + (++) Enable the clock for the ADC GPIOs using the following function: + __GPIOx_CLK_ENABLE(); + (++) Configure these ADC pins in analog mode using HAL_GPIO_Init(); + + (#) Configure the ADC parameters (conversion resolution, data alignment, + continuous mode, ...) using the HAL_ADC_Init() function. + + (#) Activate the ADC peripheral using one of the start functions: + HAL_ADC_Start(), HAL_ADC_Start_IT(), HAL_ADC_Start_DMA(). + + *** Regular channels group configuration *** + ============================================ + [..] + (+) To configure the ADC regular channels group features, use + HAL_ADC_Init() and HAL_ADC_ConfigChannel() functions. + (+) To activate the continuous mode, use the HAL_ADC_Init() function. + (+) To read the ADC converted values, use the HAL_ADC_GetValue() function. + + *** DMA for Regular channels group features configuration *** + ============================================================= + [..] + (+) To enable the DMA mode for regular channels group, use the + HAL_ADC_Start_DMA() function. + (+) To enable the generation of DMA requests continuously at the end of + the last DMA transfer, use the HAL_ADC_Init() function. + + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @defgroup ADCEx + * @brief ADC HAL module driver + * @{ + */ + +#ifdef HAL_ADC_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ + /* Fixed timeout values for ADC calibration, enable settling time, disable */ + /* settling time. */ + /* Values defined to be higher than worst cases: low clock frequency, */ + /* maximum prescaler. */ + /* Ex of profile low frequency : Clock source at 0.1 MHz, ADC clock */ + /* prescaler 4. */ + /* Unit: ms */ + #define ADC_DISABLE_TIMEOUT 2 + #define ADC_CALIBRATION_TIMEOUT 2 + +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup ADCEx_Private_Functions + * @{ + */ + +/** @defgroup ADCEx_Group1 Extended Initialization/de-initialization functions + * @brief Extended Initialization and Configuration functions + * +@verbatim + =============================================================================== + ##### IO operation functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Perform the ADC calibration. +@endverbatim + * @{ + */ + +/** + * @brief Perform an ADC automatic self-calibration + * Calibration prerequisite: ADC must be disabled (execute this + * function before HAL_ADC_Start() or after HAL_ADC_Stop() ). + * @note Calibration factor can be read after calibration, using function + * HAL_ADC_GetValue() (value on 7 bits: from DR[6;0]). + * @param hadc: ADC handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_ADCEx_Calibration_Start(ADC_HandleTypeDef* hadc) +{ + HAL_StatusTypeDef tmpHALStatus = HAL_OK; + uint32_t tickstart=0; + + /* Check the parameters */ + assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance)); + + /* Process locked */ + __HAL_LOCK(hadc); + + /* Calibration prerequisite: ADC must be disabled. */ + if (__HAL_ADC_IS_ENABLED(hadc) == RESET ) + { + /* Change ADC state */ + hadc->State = HAL_ADC_STATE_READY; + + /* Start ADC calibration */ + hadc->Instance->CR |= ADC_CR_ADCAL; + + tickstart = HAL_GetTick(); + + /* Wait for calibration completion */ + while(HAL_IS_BIT_SET(hadc->Instance->CR, ADC_CR_ADCAL)) + { + if((HAL_GetTick() - tickstart) > ADC_CALIBRATION_TIMEOUT) + { + /* Update ADC state machine to error */ + hadc->State = HAL_ADC_STATE_ERROR; + + /* Process unlocked */ + __HAL_UNLOCK(hadc); + + return HAL_ERROR; + } + } + } + else + { + /* Update ADC state machine to error */ + hadc->State = HAL_ADC_STATE_ERROR; + } + + /* Process unlocked */ + __HAL_UNLOCK(hadc); + + /* Return function status */ + return tmpHALStatus; +} + +/** + * @} + */ + +/** + * @} + */ + +#endif /* HAL_ADC_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_adc_ex.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_adc_ex.h new file mode 100644 index 0000000000..1ac0f87405 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_adc_ex.h @@ -0,0 +1,81 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_adc_ex.h + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief Header file of ADC HAL Extension module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32F0xx_HAL_ADC_EX_H +#define __STM32F0xx_HAL_ADC_EX_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal_def.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @addtogroup ADCEx + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/* Exported constants --------------------------------------------------------*/ +/* Exported macro ------------------------------------------------------------*/ +/* Exported functions --------------------------------------------------------*/ + +/* IO operation functions *****************************************************/ +/* ADC calibration */ +HAL_StatusTypeDef HAL_ADCEx_Calibration_Start(ADC_HandleTypeDef* hadc); + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __STM32F0xx_HAL_ADC_EX_H */ + + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_can.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_can.c new file mode 100644 index 0000000000..1fc25e6e7d --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_can.c @@ -0,0 +1,1380 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_can.c + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief CAN HAL module driver. + * + * This file provides firmware functions to manage the following + * functionalities of the Controller Area Network (CAN) peripheral: + * + Initialization and de-initialization functions + * + IO operation functions + * + Peripheral Control functions + * + Peripheral State and Error functions + * + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + (#) Enable the CAN controller interface clock using + __CAN_CLK_ENABLE(); + + (#) CAN pins configuration + (++) Enable the clock for the CAN GPIOs using the following function: + __GPIOx_CLK_ENABLE(); + (++) Connect and configure the involved CAN pins to AF9 using the + following function HAL_GPIO_Init(); + + (#) Initialise and configure the CAN using HAL_CAN_Init() function. + + (#) Transmit the desired CAN frame using HAL_CAN_Transmit() function. + + (#) Receive a CAN frame using HAL_CAN_Receive() function. + + *** Polling mode IO operation *** + ================================= + [..] + (+) Start the CAN peripheral transmission and wait the end of this operation + using HAL_CAN_Transmit(), at this stage user can specify the value of timeout + according to his end application + (+) Start the CAN peripheral reception and wait the end of this operation + using HAL_CAN_Receive(), at this stage user can specify the value of timeout + according to his end application + + *** Interrupt mode IO operation *** + =================================== + [..] + (+) Start the CAN peripheral transmission using HAL_CAN_Transmit_IT() + (+) Start the CAN peripheral reception using HAL_CAN_Receive_IT() + (+) Use HAL_CAN_IRQHandler() called under the used CAN Interrupt subroutine + (+) At CAN end of transmission HAL_CAN_TxCpltCallback() function is executed and user can + add his own code by customization of function pointer HAL_CAN_TxCpltCallback + (+) In case of CAN Error, HAL_CAN_ErrorCallback() function is executed and user can + add his own code by customization of function pointer HAL_CAN_ErrorCallback + + *** CAN HAL driver macros list *** + ============================================= + [..] + Below the list of most used macros in CAN HAL driver. + + (+) __HAL_CAN_ENABLE_IT: Enable the specified CAN interrupts + (+) __HAL_CAN_DISABLE_IT: Disable the specified CAN interrupts + (+) __HAL_CAN_GET_IT_SOURCE: Check if the specified CAN interrupt source is enabled or disabled + (+) __HAL_CAN_CLEAR_FLAG: Clear the CAN's pending flags + (+) __HAL_CAN_GET_FLAG: Get the selected CAN's flag status + + [..] + (@) You can refer to the CAN HAL driver header file for more useful macros + + @endverbatim + + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @defgroup CAN + * @brief CAN driver modules + * @{ + */ + +#ifdef HAL_CAN_MODULE_ENABLED + +#if defined(STM32F072xB) || defined(STM32F042x6) || defined(STM32F048xx) + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +#define HAL_CAN_DEFAULT_TIMEOUT 10 +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +static HAL_StatusTypeDef CAN_Receive_IT(CAN_HandleTypeDef* hcan, uint8_t FIFONumber); +static HAL_StatusTypeDef CAN_Transmit_IT(CAN_HandleTypeDef* hcan); +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup CAN_Private_Functions + * @{ + */ + +/** @defgroup CAN_Group1 Initialization and de-initialization functions + * @brief Initialization and Configuration functions + * +@verbatim + ============================================================================== + ##### Initialization and de-initialization functions ##### + ============================================================================== + [..] This section provides functions allowing to: + (+) Initialize and configure the CAN. + (+) De-initialize the CAN. + +@endverbatim + * @{ + */ + +/** + * @brief Initializes the CAN peripheral according to the specified + * parameters in the CAN_InitStruct. + * @param hcan: pointer to a CAN_HandleTypeDef structure that contains + * the configuration information for the specified CAN. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_CAN_Init(CAN_HandleTypeDef* hcan) +{ + uint32_t status = CAN_INITSTATUS_FAILED; /* Default init status */ + uint32_t tickstart = 0; + + /* Check CAN handle */ + if(hcan == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_CAN_ALL_INSTANCE(hcan->Instance)); + assert_param(IS_FUNCTIONAL_STATE(hcan->Init.TTCM)); + assert_param(IS_FUNCTIONAL_STATE(hcan->Init.ABOM)); + assert_param(IS_FUNCTIONAL_STATE(hcan->Init.AWUM)); + assert_param(IS_FUNCTIONAL_STATE(hcan->Init.NART)); + assert_param(IS_FUNCTIONAL_STATE(hcan->Init.RFLM)); + assert_param(IS_FUNCTIONAL_STATE(hcan->Init.TXFP)); + assert_param(IS_CAN_MODE(hcan->Init.Mode)); + assert_param(IS_CAN_SJW(hcan->Init.SJW)); + assert_param(IS_CAN_BS1(hcan->Init.BS1)); + assert_param(IS_CAN_BS2(hcan->Init.BS2)); + assert_param(IS_CAN_PRESCALER(hcan->Init.Prescaler)); + + if(hcan->State == HAL_CAN_STATE_RESET) + { + /* Init the low level hardware */ + HAL_CAN_MspInit(hcan); + } + + /* Initialize the CAN state*/ + hcan->State = HAL_CAN_STATE_BUSY; + + /* Exit from sleep mode */ + hcan->Instance->MCR &= (~(uint32_t)CAN_MCR_SLEEP); + + /* Request initialisation */ + hcan->Instance->MCR |= CAN_MCR_INRQ ; + + /* Get tickstart */ + tickstart = HAL_GetTick(); + + /* Wait the acknowledge */ + while((hcan->Instance->MSR & CAN_MSR_INAK) != CAN_MSR_INAK) + { + if((HAL_GetTick() - tickstart) > HAL_CAN_DEFAULT_TIMEOUT) + { + hcan->State= HAL_CAN_STATE_TIMEOUT; + return HAL_TIMEOUT; + } + } + + /* Check acknowledge */ + if ((hcan->Instance->MSR & CAN_MSR_INAK) == CAN_MSR_INAK) + { + /* Set the time triggered communication mode */ + if (hcan->Init.TTCM == ENABLE) + { + hcan->Instance->MCR |= CAN_MCR_TTCM; + } + else + { + hcan->Instance->MCR &= ~(uint32_t)CAN_MCR_TTCM; + } + + /* Set the automatic bus-off management */ + if (hcan->Init.ABOM == ENABLE) + { + hcan->Instance->MCR |= CAN_MCR_ABOM; + } + else + { + hcan->Instance->MCR &= ~(uint32_t)CAN_MCR_ABOM; + } + + /* Set the automatic wake-up mode */ + if (hcan->Init.AWUM == ENABLE) + { + hcan->Instance->MCR |= CAN_MCR_AWUM; + } + else + { + hcan->Instance->MCR &= ~(uint32_t)CAN_MCR_AWUM; + } + + /* Set the no automatic retransmission */ + if (hcan->Init.NART == ENABLE) + { + hcan->Instance->MCR |= CAN_MCR_NART; + } + else + { + hcan->Instance->MCR &= ~(uint32_t)CAN_MCR_NART; + } + + /* Set the receive FIFO locked mode */ + if (hcan->Init.RFLM == ENABLE) + { + hcan->Instance->MCR |= CAN_MCR_RFLM; + } + else + { + hcan->Instance->MCR &= ~(uint32_t)CAN_MCR_RFLM; + } + + /* Set the transmit FIFO priority */ + if (hcan->Init.TXFP == ENABLE) + { + hcan->Instance->MCR |= CAN_MCR_TXFP; + } + else + { + hcan->Instance->MCR &= ~(uint32_t)CAN_MCR_TXFP; + } + + /* Set the bit timing register */ + hcan->Instance->BTR = (uint32_t)((uint32_t)hcan->Init.Mode) | \ + ((uint32_t)hcan->Init.SJW) | \ + ((uint32_t)hcan->Init.BS1) | \ + ((uint32_t)hcan->Init.BS2) | \ + ((uint32_t)hcan->Init.Prescaler - 1); + + /* Request leave initialisation */ + hcan->Instance->MCR &= ~(uint32_t)CAN_MCR_INRQ; + + /* Get timeout */ + tickstart = HAL_GetTick(); + + /* Wait the acknowledge */ + while((hcan->Instance->MSR & CAN_MSR_INAK) == CAN_MSR_INAK) + { + if((HAL_GetTick() - tickstart) > HAL_CAN_DEFAULT_TIMEOUT) + { + hcan->State= HAL_CAN_STATE_TIMEOUT; + return HAL_TIMEOUT; + } + } + + /* Check acknowledged */ + if ((hcan->Instance->MSR & CAN_MSR_INAK) != CAN_MSR_INAK) + { + status = CAN_INITSTATUS_SUCCESS; + } + } + + if(status == CAN_INITSTATUS_SUCCESS) + { + /* Set CAN error code to none */ + hcan->ErrorCode = HAL_CAN_ERROR_NONE; + + /* Initialize the CAN state */ + hcan->State = HAL_CAN_STATE_READY; + + /* Return function status */ + return HAL_OK; + } + else + { + /* Initialize the CAN state */ + hcan->State = HAL_CAN_STATE_ERROR; + + /* Return function status */ + return HAL_ERROR; + } +} + +/** + * @brief Configures the CAN reception filter according to the specified + * parameters in the CAN_FilterInitStruct. + * @param hcan: pointer to a CAN_HandleTypeDef structure that contains + * the configuration information for the specified CAN. + * @param sFilterConfig: pointer to a CAN_FilterConfTypeDef structure that + * contains the filter configuration information. + * @retval None + */ +HAL_StatusTypeDef HAL_CAN_ConfigFilter(CAN_HandleTypeDef* hcan, CAN_FilterConfTypeDef* sFilterConfig) +{ + uint32_t filternbrbitpos = 0; + + /* Check the parameters */ + assert_param(IS_CAN_FILTER_NUMBER(sFilterConfig->FilterNumber)); + assert_param(IS_CAN_FILTER_MODE(sFilterConfig->FilterMode)); + assert_param(IS_CAN_FILTER_SCALE(sFilterConfig->FilterScale)); + assert_param(IS_CAN_FILTER_FIFO(sFilterConfig->FilterFIFOAssignment)); + assert_param(IS_FUNCTIONAL_STATE(sFilterConfig->FilterActivation)); + assert_param(IS_CAN_BANKNUMBER(sFilterConfig->BankNumber)); + + filternbrbitpos = ((uint32_t)1) << sFilterConfig->FilterNumber; + + /* Initialisation mode for the filter */ + hcan->Instance->FMR |= (uint32_t)CAN_FMR_FINIT; + + /* Filter Deactivation */ + hcan->Instance->FA1R &= ~(uint32_t)filternbrbitpos; + + /* Filter Scale */ + if (sFilterConfig->FilterScale == CAN_FILTERSCALE_16BIT) + { + /* 16-bit scale for the filter */ + hcan->Instance->FS1R &= ~(uint32_t)filternbrbitpos; + + /* First 16-bit identifier and First 16-bit mask */ + /* Or First 16-bit identifier and Second 16-bit identifier */ + hcan->Instance->sFilterRegister[sFilterConfig->FilterNumber].FR1 = + ((0x0000FFFF & (uint32_t)sFilterConfig->FilterMaskIdLow) << 16) | + (0x0000FFFF & (uint32_t)sFilterConfig->FilterIdLow); + + /* Second 16-bit identifier and Second 16-bit mask */ + /* Or Third 16-bit identifier and Fourth 16-bit identifier */ + hcan->Instance->sFilterRegister[sFilterConfig->FilterNumber].FR2 = + ((0x0000FFFF & (uint32_t)sFilterConfig->FilterMaskIdHigh) << 16) | + (0x0000FFFF & (uint32_t)sFilterConfig->FilterIdHigh); + } + + if (sFilterConfig->FilterScale == CAN_FILTERSCALE_32BIT) + { + /* 32-bit scale for the filter */ + hcan->Instance->FS1R |= filternbrbitpos; + /* 32-bit identifier or First 32-bit identifier */ + hcan->Instance->sFilterRegister[sFilterConfig->FilterNumber].FR1 = + ((0x0000FFFF & (uint32_t)sFilterConfig->FilterIdHigh) << 16) | + (0x0000FFFF & (uint32_t)sFilterConfig->FilterIdLow); + /* 32-bit mask or Second 32-bit identifier */ + hcan->Instance->sFilterRegister[sFilterConfig->FilterNumber].FR2 = + ((0x0000FFFF & (uint32_t)sFilterConfig->FilterMaskIdHigh) << 16) | + (0x0000FFFF & (uint32_t)sFilterConfig->FilterMaskIdLow); + } + + /* Filter Mode */ + if (sFilterConfig->FilterMode == CAN_FILTERMODE_IDMASK) + { + /*Id/Mask mode for the filter*/ + hcan->Instance->FM1R &= ~(uint32_t)filternbrbitpos; + } + else /* CAN_FilterInitStruct->CAN_FilterMode == CAN_FilterMode_IdList */ + { + /*Identifier list mode for the filter*/ + hcan->Instance->FM1R |= (uint32_t)filternbrbitpos; + } + + /* Filter FIFO assignment */ + if (sFilterConfig->FilterFIFOAssignment == CAN_FILTER_FIFO0) + { + /* FIFO 0 assignation for the filter */ + hcan->Instance->FFA1R &= ~(uint32_t)filternbrbitpos; + } + + if (sFilterConfig->FilterFIFOAssignment == CAN_FILTER_FIFO1) + { + /* FIFO 1 assignation for the filter */ + hcan->Instance->FFA1R |= (uint32_t)filternbrbitpos; + } + + /* Filter activation */ + if (sFilterConfig->FilterActivation == ENABLE) + { + hcan->Instance->FA1R |= filternbrbitpos; + } + + /* Leave the initialisation mode for the filter */ + hcan->Instance->FMR &= ~((uint32_t)CAN_FMR_FINIT); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Deinitializes the CANx peripheral registers to their default reset values. + * @param hcan: pointer to a CAN_HandleTypeDef structure that contains + * the configuration information for the specified CAN. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_CAN_DeInit(CAN_HandleTypeDef* hcan) +{ + /* Check CAN handle */ + if(hcan == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_CAN_ALL_INSTANCE(hcan->Instance)); + + /* Change CAN state */ + hcan->State = HAL_CAN_STATE_BUSY; + + /* DeInit the low level hardware */ + HAL_CAN_MspDeInit(hcan); + + /* Change CAN state */ + hcan->State = HAL_CAN_STATE_RESET; + + /* Release Lock */ + __HAL_UNLOCK(hcan); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Initializes the CAN MSP. + * @param hcan: pointer to a CAN_HandleTypeDef structure that contains + * the configuration information for the specified CAN. + * @retval None + */ +__weak void HAL_CAN_MspInit(CAN_HandleTypeDef* hcan) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_CAN_MspInit could be implemented in the user file + */ +} + +/** + * @brief DeInitializes the CAN MSP. + * @param hcan: pointer to a CAN_HandleTypeDef structure that contains + * the configuration information for the specified CAN. + * @retval None + */ +__weak void HAL_CAN_MspDeInit(CAN_HandleTypeDef* hcan) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_CAN_MspDeInit could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup CAN_Group2 I/O operation functions + * @brief I/O operation functions + * +@verbatim + ============================================================================== + ##### IO operation functions ##### + ============================================================================== + [..] This section provides functions allowing to: + (+) Transmit a CAN frame message. + (+) Receive a CAN frame message. + (+) Enter CAN peripheral in sleep mode. + (+) Wake up the CAN peripheral from sleep mode. + +@endverbatim + * @{ + */ + +/** + * @brief Initiates and transmits a CAN frame message. + * @param hcan: pointer to a CAN_HandleTypeDef structure that contains + * the configuration information for the specified CAN. + * @param Timeout: Timeout duration. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_CAN_Transmit(CAN_HandleTypeDef* hcan, uint32_t Timeout) +{ + uint32_t transmitmailbox = CAN_TXSTATUS_NOMAILBOX; + uint32_t tickstart = 0; + + /* Check the parameters */ + assert_param(IS_CAN_IDTYPE(hcan->pTxMsg->IDE)); + assert_param(IS_CAN_RTR(hcan->pTxMsg->RTR)); + assert_param(IS_CAN_DLC(hcan->pTxMsg->DLC)); + + /* Process locked */ + __HAL_LOCK(hcan); + + if(hcan->State == HAL_CAN_STATE_BUSY_RX) + { + /* Change CAN state */ + hcan->State = HAL_CAN_STATE_BUSY_TX_RX; + } + else + { + /* Change CAN state */ + hcan->State = HAL_CAN_STATE_BUSY_TX; + } + + /* Select one empty transmit mailbox */ + if ((hcan->Instance->TSR&CAN_TSR_TME0) == CAN_TSR_TME0) + { + transmitmailbox = 0; + } + else if ((hcan->Instance->TSR&CAN_TSR_TME1) == CAN_TSR_TME1) + { + transmitmailbox = 1; + } + else if ((hcan->Instance->TSR&CAN_TSR_TME2) == CAN_TSR_TME2) + { + transmitmailbox = 2; + } + + if (transmitmailbox != CAN_TXSTATUS_NOMAILBOX) + { + /* Set up the Id */ + hcan->Instance->sTxMailBox[transmitmailbox].TIR &= CAN_TI0R_TXRQ; + if (hcan->pTxMsg->IDE == CAN_ID_STD) + { + assert_param(IS_CAN_STDID(hcan->pTxMsg->StdId)); + hcan->Instance->sTxMailBox[transmitmailbox].TIR |= ((hcan->pTxMsg->StdId << 21) | \ + hcan->pTxMsg->RTR); + } + else + { + assert_param(IS_CAN_EXTID(hcan->pTxMsg->ExtId)); + hcan->Instance->sTxMailBox[transmitmailbox].TIR |= ((hcan->pTxMsg->ExtId << 3) | \ + hcan->pTxMsg->IDE | \ + hcan->pTxMsg->RTR); + } + + /* Set up the DLC */ + hcan->pTxMsg->DLC &= (uint8_t)0x0000000F; + hcan->Instance->sTxMailBox[transmitmailbox].TDTR &= (uint32_t)0xFFFFFFF0; + hcan->Instance->sTxMailBox[transmitmailbox].TDTR |= hcan->pTxMsg->DLC; + + /* Set up the data field */ + hcan->Instance->sTxMailBox[transmitmailbox].TDLR = (((uint32_t)hcan->pTxMsg->Data[3] << 24) | + ((uint32_t)hcan->pTxMsg->Data[2] << 16) | + ((uint32_t)hcan->pTxMsg->Data[1] << 8) | + ((uint32_t)hcan->pTxMsg->Data[0])); + hcan->Instance->sTxMailBox[transmitmailbox].TDHR = (((uint32_t)hcan->pTxMsg->Data[7] << 24) | + ((uint32_t)hcan->pTxMsg->Data[6] << 16) | + ((uint32_t)hcan->pTxMsg->Data[5] << 8) | + ((uint32_t)hcan->pTxMsg->Data[4])); + /* Request transmission */ + hcan->Instance->sTxMailBox[transmitmailbox].TIR |= CAN_TI0R_TXRQ; + + /* Get timeout */ + tickstart = HAL_GetTick(); + + /* Check End of transmission flag */ + while(!(__HAL_CAN_TRANSMIT_STATUS(hcan, transmitmailbox))) + { + /* Check for the Timeout */ + if(Timeout != HAL_MAX_DELAY) + { + if((HAL_GetTick() - tickstart) > Timeout) + { + hcan->State = HAL_CAN_STATE_TIMEOUT; + /* Process unlocked */ + __HAL_UNLOCK(hcan); + return HAL_TIMEOUT; + } + } + } + if(hcan->State == HAL_CAN_STATE_BUSY_TX_RX) + { + /* Change CAN state */ + hcan->State = HAL_CAN_STATE_BUSY_RX; + } + else + { + /* Change CAN state */ + hcan->State = HAL_CAN_STATE_READY; + } + + /* Process unlocked */ + __HAL_UNLOCK(hcan); + + /* Return function status */ + return HAL_OK; + } + else + { + /* Change CAN state */ + hcan->State = HAL_CAN_STATE_ERROR; + + /* Process unlocked */ + __HAL_UNLOCK(hcan); + + /* Return function status */ + return HAL_ERROR; + } +} + +/** + * @brief Initiates and transmits a CAN frame message. + * @param hcan: pointer to a CAN_HandleTypeDef structure that contains + * the configuration information for the specified CAN. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_CAN_Transmit_IT(CAN_HandleTypeDef* hcan) +{ + uint32_t transmitmailbox = CAN_TXSTATUS_NOMAILBOX; + + /* Check the parameters */ + assert_param(IS_CAN_IDTYPE(hcan->pTxMsg->IDE)); + assert_param(IS_CAN_RTR(hcan->pTxMsg->RTR)); + assert_param(IS_CAN_DLC(hcan->pTxMsg->DLC)); + + if((hcan->State == HAL_CAN_STATE_READY) || (hcan->State == HAL_CAN_STATE_BUSY_RX)) + { + /* Process Locked */ + __HAL_LOCK(hcan); + + /* Select one empty transmit mailbox */ + if((hcan->Instance->TSR&CAN_TSR_TME0) == CAN_TSR_TME0) + { + transmitmailbox = 0; + } + else if((hcan->Instance->TSR&CAN_TSR_TME1) == CAN_TSR_TME1) + { + transmitmailbox = 1; + } + else if((hcan->Instance->TSR&CAN_TSR_TME2) == CAN_TSR_TME2) + { + transmitmailbox = 2; + } + + if(transmitmailbox != CAN_TXSTATUS_NOMAILBOX) + { + /* Set up the Id */ + hcan->Instance->sTxMailBox[transmitmailbox].TIR &= CAN_TI0R_TXRQ; + if(hcan->pTxMsg->IDE == CAN_ID_STD) + { + assert_param(IS_CAN_STDID(hcan->pTxMsg->StdId)); + hcan->Instance->sTxMailBox[transmitmailbox].TIR |= ((hcan->pTxMsg->StdId << 21) | \ + hcan->pTxMsg->RTR); + } + else + { + assert_param(IS_CAN_EXTID(hcan->pTxMsg->ExtId)); + hcan->Instance->sTxMailBox[transmitmailbox].TIR |= ((hcan->pTxMsg->ExtId << 3) | \ + hcan->pTxMsg->IDE | \ + hcan->pTxMsg->RTR); + } + + /* Set up the DLC */ + hcan->pTxMsg->DLC &= (uint8_t)0x0000000F; + hcan->Instance->sTxMailBox[transmitmailbox].TDTR &= (uint32_t)0xFFFFFFF0; + hcan->Instance->sTxMailBox[transmitmailbox].TDTR |= hcan->pTxMsg->DLC; + + /* Set up the data field */ + hcan->Instance->sTxMailBox[transmitmailbox].TDLR = (((uint32_t)hcan->pTxMsg->Data[3] << 24) | + ((uint32_t)hcan->pTxMsg->Data[2] << 16) | + ((uint32_t)hcan->pTxMsg->Data[1] << 8) | + ((uint32_t)hcan->pTxMsg->Data[0])); + hcan->Instance->sTxMailBox[transmitmailbox].TDHR = (((uint32_t)hcan->pTxMsg->Data[7] << 24) | + ((uint32_t)hcan->pTxMsg->Data[6] << 16) | + ((uint32_t)hcan->pTxMsg->Data[5] << 8) | + ((uint32_t)hcan->pTxMsg->Data[4])); + + if(hcan->State == HAL_CAN_STATE_BUSY_RX) + { + /* Change CAN state */ + hcan->State = HAL_CAN_STATE_BUSY_TX_RX; + } + else + { + /* Change CAN state */ + hcan->State = HAL_CAN_STATE_BUSY_TX; + } + + /* Set CAN error code to none */ + hcan->ErrorCode = HAL_CAN_ERROR_NONE; + + /* Process Unlocked */ + __HAL_UNLOCK(hcan); + + /* Enable Error warning Interrupt */ + __HAL_CAN_ENABLE_IT(hcan, CAN_IT_EWG); + + /* Enable Error passive Interrupt */ + __HAL_CAN_ENABLE_IT(hcan, CAN_IT_EPV); + + /* Enable Bus-off Interrupt */ + __HAL_CAN_ENABLE_IT(hcan, CAN_IT_BOF); + + /* Enable Last error code Interrupt */ + __HAL_CAN_ENABLE_IT(hcan, CAN_IT_LEC); + + /* Enable Error Interrupt */ + __HAL_CAN_ENABLE_IT(hcan, CAN_IT_ERR); + + /* Enable Transmit mailbox empty Interrupt */ + __HAL_CAN_ENABLE_IT(hcan, CAN_IT_TME); + + /* Request transmission */ + hcan->Instance->sTxMailBox[transmitmailbox].TIR |= CAN_TI0R_TXRQ; + } + } + else + { + return HAL_BUSY; + } + + return HAL_OK; +} + +/** + * @brief Receives a correct CAN frame. + * @param hcan: pointer to a CAN_HandleTypeDef structure that contains + * the configuration information for the specified CAN. + * @param FIFONumber: FIFO number. + * @param Timeout: Timeout duration. + * @retval HAL status + * @retval None + */ +HAL_StatusTypeDef HAL_CAN_Receive(CAN_HandleTypeDef* hcan, uint8_t FIFONumber, uint32_t Timeout) +{ + uint32_t tickstart = 0; + + /* Check the parameters */ + assert_param(IS_CAN_FIFO(FIFONumber)); + + /* Process locked */ + __HAL_LOCK(hcan); + + if(hcan->State == HAL_CAN_STATE_BUSY_TX) + { + /* Change CAN state */ + hcan->State = HAL_CAN_STATE_BUSY_TX_RX; + } + else + { + /* Change CAN state */ + hcan->State = HAL_CAN_STATE_BUSY_RX; + } + + /* Get timeout */ + tickstart = HAL_GetTick(); + + /* Check pending message */ + while(__HAL_CAN_MSG_PENDING(hcan, FIFONumber) == 0) + { + /* Check for the Timeout */ + if(Timeout != HAL_MAX_DELAY) + { + if((HAL_GetTick() - tickstart) > Timeout) + { + hcan->State = HAL_CAN_STATE_TIMEOUT; + /* Process unlocked */ + __HAL_UNLOCK(hcan); + return HAL_TIMEOUT; + } + } + } + + /* Get the Id */ + hcan->pRxMsg->IDE = (uint8_t)0x04 & hcan->Instance->sFIFOMailBox[FIFONumber].RIR; + if (hcan->pRxMsg->IDE == CAN_ID_STD) + { + hcan->pRxMsg->StdId = (uint32_t)0x000007FF & (hcan->Instance->sFIFOMailBox[FIFONumber].RIR >> 21); + } + else + { + hcan->pRxMsg->ExtId = (uint32_t)0x1FFFFFFF & (hcan->Instance->sFIFOMailBox[FIFONumber].RIR >> 3); + } + + hcan->pRxMsg->RTR = (uint8_t)0x02 & hcan->Instance->sFIFOMailBox[FIFONumber].RIR; + /* Get the DLC */ + hcan->pRxMsg->DLC = (uint8_t)0x0F & hcan->Instance->sFIFOMailBox[FIFONumber].RDTR; + /* Get the FMI */ + hcan->pRxMsg->FMI = (uint8_t)0xFF & (hcan->Instance->sFIFOMailBox[FIFONumber].RDTR >> 8); + /* Get the data field */ + hcan->pRxMsg->Data[0] = (uint8_t)0xFF & hcan->Instance->sFIFOMailBox[FIFONumber].RDLR; + hcan->pRxMsg->Data[1] = (uint8_t)0xFF & (hcan->Instance->sFIFOMailBox[FIFONumber].RDLR >> 8); + hcan->pRxMsg->Data[2] = (uint8_t)0xFF & (hcan->Instance->sFIFOMailBox[FIFONumber].RDLR >> 16); + hcan->pRxMsg->Data[3] = (uint8_t)0xFF & (hcan->Instance->sFIFOMailBox[FIFONumber].RDLR >> 24); + hcan->pRxMsg->Data[4] = (uint8_t)0xFF & hcan->Instance->sFIFOMailBox[FIFONumber].RDHR; + hcan->pRxMsg->Data[5] = (uint8_t)0xFF & (hcan->Instance->sFIFOMailBox[FIFONumber].RDHR >> 8); + hcan->pRxMsg->Data[6] = (uint8_t)0xFF & (hcan->Instance->sFIFOMailBox[FIFONumber].RDHR >> 16); + hcan->pRxMsg->Data[7] = (uint8_t)0xFF & (hcan->Instance->sFIFOMailBox[FIFONumber].RDHR >> 24); + + /* Release the FIFO */ + if(FIFONumber == CAN_FIFO0) + { + /* Release FIFO0 */ + __HAL_CAN_FIFO_RELEASE(hcan, CAN_FIFO0); + } + else /* FIFONumber == CAN_FIFO1 */ + { + /* Release FIFO1 */ + __HAL_CAN_FIFO_RELEASE(hcan, CAN_FIFO1); + } + + if(hcan->State == HAL_CAN_STATE_BUSY_TX_RX) + { + /* Change CAN state */ + hcan->State = HAL_CAN_STATE_BUSY_TX; + } + else + { + /* Change CAN state */ + hcan->State = HAL_CAN_STATE_READY; + } + + /* Process unlocked */ + __HAL_UNLOCK(hcan); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Receives a correct CAN frame. + * @param hcan: pointer to a CAN_HandleTypeDef structure that contains + * the configuration information for the specified CAN. + * @param FIFONumber: FIFO number. + * @retval HAL status + * @retval None + */ +HAL_StatusTypeDef HAL_CAN_Receive_IT(CAN_HandleTypeDef* hcan, uint8_t FIFONumber) +{ + /* Check the parameters */ + assert_param(IS_CAN_FIFO(FIFONumber)); + + if((hcan->State == HAL_CAN_STATE_READY) || (hcan->State == HAL_CAN_STATE_BUSY_TX)) + { + /* Process locked */ + __HAL_LOCK(hcan); + + if(hcan->State == HAL_CAN_STATE_BUSY_TX) + { + /* Change CAN state */ + hcan->State = HAL_CAN_STATE_BUSY_TX_RX; + } + else + { + /* Change CAN state */ + hcan->State = HAL_CAN_STATE_BUSY_RX; + } + + /* Set CAN error code to none */ + hcan->ErrorCode = HAL_CAN_ERROR_NONE; + + /* Enable Error warning Interrupt */ + __HAL_CAN_ENABLE_IT(hcan, CAN_IT_EWG); + + /* Enable Error passive Interrupt */ + __HAL_CAN_ENABLE_IT(hcan, CAN_IT_EPV); + + /* Enable Bus-off Interrupt */ + __HAL_CAN_ENABLE_IT(hcan, CAN_IT_BOF); + + /* Enable Last error code Interrupt */ + __HAL_CAN_ENABLE_IT(hcan, CAN_IT_LEC); + + /* Enable Error Interrupt */ + __HAL_CAN_ENABLE_IT(hcan, CAN_IT_ERR); + + /* Process unlocked */ + __HAL_UNLOCK(hcan); + + if(FIFONumber == CAN_FIFO0) + { + /* Enable FIFO 0 message pending Interrupt */ + __HAL_CAN_ENABLE_IT(hcan, CAN_IT_FMP0); + } + else + { + /* Enable FIFO 1 message pending Interrupt */ + __HAL_CAN_ENABLE_IT(hcan, CAN_IT_FMP1); + } + + } + else + { + return HAL_BUSY; + } + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Enters the Sleep (low power) mode. + * @param hcan: pointer to a CAN_HandleTypeDef structure that contains + * the configuration information for the specified CAN. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_CAN_Sleep(CAN_HandleTypeDef* hcan) +{ + uint32_t tickstart = 0; + + /* Process locked */ + __HAL_LOCK(hcan); + + /* Change CAN state */ + hcan->State = HAL_CAN_STATE_BUSY; + + /* Request Sleep mode */ + hcan->Instance->MCR = (((hcan->Instance->MCR) & (uint32_t)(~(uint32_t)CAN_MCR_INRQ)) | CAN_MCR_SLEEP); + + /* Sleep mode status */ + if ((hcan->Instance->MSR & (CAN_MSR_SLAK|CAN_MSR_INAK)) != CAN_MSR_SLAK) + { + /* Process unlocked */ + __HAL_UNLOCK(hcan); + + /* Return function status */ + return HAL_ERROR; + } + + /* Get timeout */ + tickstart = HAL_GetTick(); + + /* Wait the acknowledge */ + while((hcan->Instance->MSR & (CAN_MSR_SLAK|CAN_MSR_INAK)) != CAN_MSR_SLAK) + { + if((HAL_GetTick() - tickstart) > HAL_CAN_DEFAULT_TIMEOUT) + { + hcan->State = HAL_CAN_STATE_TIMEOUT; + /* Process unlocked */ + __HAL_UNLOCK(hcan); + return HAL_TIMEOUT; + } + } + + /* Change CAN state */ + hcan->State = HAL_CAN_STATE_READY; + + /* Process unlocked */ + __HAL_UNLOCK(hcan); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Wakes up the CAN peripheral from sleep mode, after that the CAN peripheral + * is in the normal mode. + * @param hcan: pointer to a CAN_HandleTypeDef structure that contains + * the configuration information for the specified CAN. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_CAN_WakeUp(CAN_HandleTypeDef* hcan) +{ + uint32_t tickstart = 0; + + /* Process locked */ + __HAL_LOCK(hcan); + + /* Change CAN state */ + hcan->State = HAL_CAN_STATE_BUSY; + + /* Wake up request */ + hcan->Instance->MCR &= ~(uint32_t)CAN_MCR_SLEEP; + + /* Get timeout */ + tickstart = HAL_GetTick(); + + /* Sleep mode status */ + while((hcan->Instance->MSR & CAN_MSR_SLAK) == CAN_MSR_SLAK) + { + if((HAL_GetTick() - tickstart) > HAL_CAN_DEFAULT_TIMEOUT) + { + hcan->State= HAL_CAN_STATE_TIMEOUT; + /* Process unlocked */ + __HAL_UNLOCK(hcan); + return HAL_TIMEOUT; + } + } + if((hcan->Instance->MSR & CAN_MSR_SLAK) == CAN_MSR_SLAK) + { + /* Process unlocked */ + __HAL_UNLOCK(hcan); + + /* Return function status */ + return HAL_ERROR; + } + + /* Change CAN state */ + hcan->State = HAL_CAN_STATE_READY; + + /* Process unlocked */ + __HAL_UNLOCK(hcan); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Handles CAN interrupt request + * @param hcan: pointer to a CAN_HandleTypeDef structure that contains + * the configuration information for the specified CAN. + * @retval None + */ +void HAL_CAN_IRQHandler(CAN_HandleTypeDef* hcan) +{ + /* Check End of transmission flag */ + if(__HAL_CAN_GET_IT_SOURCE(hcan, CAN_IT_TME)) + { + if((__HAL_CAN_TRANSMIT_STATUS(hcan, CAN_TXMAILBOX_0)) || + (__HAL_CAN_TRANSMIT_STATUS(hcan, CAN_TXMAILBOX_1)) || + (__HAL_CAN_TRANSMIT_STATUS(hcan, CAN_TXMAILBOX_2))) + { + /* Call transmit function */ + CAN_Transmit_IT(hcan); + } + } + + /* Check End of reception flag for FIFO0 */ + if((__HAL_CAN_GET_IT_SOURCE(hcan, CAN_IT_FMP0)) && + (__HAL_CAN_MSG_PENDING(hcan, CAN_FIFO0) != 0)) + { + /* Call receive function */ + CAN_Receive_IT(hcan, CAN_FIFO0); + } + + /* Check End of reception flag for FIFO1 */ + if((__HAL_CAN_GET_IT_SOURCE(hcan, CAN_IT_FMP1)) && + (__HAL_CAN_MSG_PENDING(hcan, CAN_FIFO1) != 0)) + { + /* Call receive function */ + CAN_Receive_IT(hcan, CAN_FIFO1); + } + + /* Check Error Warning Flag */ + if((__HAL_CAN_GET_FLAG(hcan, CAN_FLAG_EWG)) && + (__HAL_CAN_GET_IT_SOURCE(hcan, CAN_IT_EWG)) && + (__HAL_CAN_GET_IT_SOURCE(hcan, CAN_IT_ERR))) + { + /* Set CAN error code to EWG error */ + hcan->ErrorCode |= HAL_CAN_ERROR_EWG; + /* Clear Error Warning Flag */ + __HAL_CAN_CLEAR_FLAG(hcan, CAN_FLAG_EWG); + } + + /* Check Error Passive Flag */ + if((__HAL_CAN_GET_FLAG(hcan, CAN_FLAG_EPV)) && + (__HAL_CAN_GET_IT_SOURCE(hcan, CAN_IT_EPV)) && + (__HAL_CAN_GET_IT_SOURCE(hcan, CAN_IT_ERR))) + { + /* Set CAN error code to EPV error */ + hcan->ErrorCode |= HAL_CAN_ERROR_EPV; + /* Clear Error Passive Flag */ + __HAL_CAN_CLEAR_FLAG(hcan, CAN_FLAG_EPV); + } + + /* Check Bus-Off Flag */ + if((__HAL_CAN_GET_FLAG(hcan, CAN_FLAG_BOF)) && + (__HAL_CAN_GET_IT_SOURCE(hcan, CAN_IT_BOF)) && + (__HAL_CAN_GET_IT_SOURCE(hcan, CAN_IT_ERR))) + { + /* Set CAN error code to BOF error */ + hcan->ErrorCode |= HAL_CAN_ERROR_BOF; + /* Clear Bus-Off Flag */ + __HAL_CAN_CLEAR_FLAG(hcan, CAN_FLAG_BOF); + } + + /* Check Last error code Flag */ + if((!HAL_IS_BIT_CLR(hcan->Instance->ESR, CAN_ESR_LEC)) && + (__HAL_CAN_GET_IT_SOURCE(hcan, CAN_IT_LEC)) && + (__HAL_CAN_GET_IT_SOURCE(hcan, CAN_IT_ERR))) + { + switch(hcan->Instance->ESR & CAN_ESR_LEC) + { + case(CAN_ESR_LEC_0): + /* Set CAN error code to STF error */ + hcan->ErrorCode |= HAL_CAN_ERROR_STF; + break; + case(CAN_ESR_LEC_1): + /* Set CAN error code to FOR error */ + hcan->ErrorCode |= HAL_CAN_ERROR_FOR; + break; + case(CAN_ESR_LEC_1 | CAN_ESR_LEC_0): + /* Set CAN error code to ACK error */ + hcan->ErrorCode |= HAL_CAN_ERROR_ACK; + break; + case(CAN_ESR_LEC_2): + /* Set CAN error code to BR error */ + hcan->ErrorCode |= HAL_CAN_ERROR_BR; + break; + case(CAN_ESR_LEC_2 | CAN_ESR_LEC_0): + /* Set CAN error code to BD error */ + hcan->ErrorCode |= HAL_CAN_ERROR_BD; + break; + case(CAN_ESR_LEC_2 | CAN_ESR_LEC_1): + /* Set CAN error code to CRC error */ + hcan->ErrorCode |= HAL_CAN_ERROR_CRC; + break; + default: + break; + } + + /* Clear Last error code Flag */ + hcan->Instance->ESR &= ~(CAN_ESR_LEC); + } + + /* Call the Error call Back in case of Errors */ + if(hcan->ErrorCode != HAL_CAN_ERROR_NONE) + { + /* Set the CAN state ready to be able to start again the process */ + hcan->State = HAL_CAN_STATE_READY; + /* Call Error callback function */ + HAL_CAN_ErrorCallback(hcan); + } +} + +/** + * @brief Transmission complete callback in non blocking mode + * @param hcan: pointer to a CAN_HandleTypeDef structure that contains + * the configuration information for the specified CAN. + * @retval None + */ +__weak void HAL_CAN_TxCpltCallback(CAN_HandleTypeDef* hcan) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_CAN_TxCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Transmission complete callback in non blocking mode + * @param hcan: pointer to a CAN_HandleTypeDef structure that contains + * the configuration information for the specified CAN. + * @retval None + */ +__weak void HAL_CAN_RxCpltCallback(CAN_HandleTypeDef* hcan) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_CAN_RxCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Error CAN callback. + * @param hcan: pointer to a CAN_HandleTypeDef structure that contains + * the configuration information for the specified CAN. + * @retval None + */ +__weak void HAL_CAN_ErrorCallback(CAN_HandleTypeDef *hcan) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_CAN_ErrorCallback could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup CAN_Group3 Peripheral State and Error functions + * @brief CAN Peripheral State functions + * +@verbatim + ============================================================================== + ##### Peripheral State and Error functions ##### + ============================================================================== + [..] + This subsection provides functions allowing to : + (+) Check the CAN state. + (+) Check CAN Errors detected during interrupt process + +@endverbatim + * @{ + */ + +/** + * @brief return the CAN state + * @param hcan: pointer to a CAN_HandleTypeDef structure that contains + * the configuration information for the specified CAN. + * @retval HAL state + */ +HAL_CAN_StateTypeDef HAL_CAN_GetState(CAN_HandleTypeDef* hcan) +{ + /* Return CAN state */ + return hcan->State; +} + +/** + * @brief Return the CAN error code + * @param hcan: pointer to a CAN_HandleTypeDef structure that contains + * the configuration information for the specified CAN. + * @retval CAN Error Code + */ +uint32_t HAL_CAN_GetError(CAN_HandleTypeDef *hcan) +{ + return hcan->ErrorCode; +} + +/** + * @} + */ + +/** + * @brief Initiates and transmits a CAN frame message. + * @param hcan: pointer to a CAN_HandleTypeDef structure that contains + * the configuration information for the specified CAN. + * @retval HAL status + */ +static HAL_StatusTypeDef CAN_Transmit_IT(CAN_HandleTypeDef* hcan) +{ + /* Disable Transmit mailbox empty Interrupt */ + __HAL_CAN_DISABLE_IT(hcan, CAN_IT_TME); + + if(hcan->State == HAL_CAN_STATE_BUSY_TX) + { + /* Disable Error warning Interrupt */ + __HAL_CAN_DISABLE_IT(hcan, CAN_IT_EWG); + + /* Disable Error passive Interrupt */ + __HAL_CAN_DISABLE_IT(hcan, CAN_IT_EPV); + + /* Disable Bus-off Interrupt */ + __HAL_CAN_DISABLE_IT(hcan, CAN_IT_BOF); + + /* Disable Last error code Interrupt */ + __HAL_CAN_DISABLE_IT(hcan, CAN_IT_LEC); + + /* Disable Error Interrupt */ + __HAL_CAN_DISABLE_IT(hcan, CAN_IT_ERR); + } + + if(hcan->State == HAL_CAN_STATE_BUSY_TX_RX) + { + /* Change CAN state */ + hcan->State = HAL_CAN_STATE_BUSY_RX; + } + else + { + /* Change CAN state */ + hcan->State = HAL_CAN_STATE_READY; + } + + /* Transmission complete callback */ + HAL_CAN_TxCpltCallback(hcan); + + return HAL_OK; +} + +/** + * @brief Receives a correct CAN frame. + * @param hcan: Pointer to a CAN_HandleTypeDef structure that contains + * the configuration information for the specified CAN. + * @param FIFONumber: Specify the FIFO number + * @retval HAL status + * @retval None + */ +static HAL_StatusTypeDef CAN_Receive_IT(CAN_HandleTypeDef* hcan, uint8_t FIFONumber) +{ + /* Get the Id */ + hcan->pRxMsg->IDE = (uint8_t)0x04 & hcan->Instance->sFIFOMailBox[FIFONumber].RIR; + if (hcan->pRxMsg->IDE == CAN_ID_STD) + { + hcan->pRxMsg->StdId = (uint32_t)0x000007FF & (hcan->Instance->sFIFOMailBox[FIFONumber].RIR >> 21); + } + else + { + hcan->pRxMsg->ExtId = (uint32_t)0x1FFFFFFF & (hcan->Instance->sFIFOMailBox[FIFONumber].RIR >> 3); + } + + hcan->pRxMsg->RTR = (uint8_t)0x02 & hcan->Instance->sFIFOMailBox[FIFONumber].RIR; + /* Get the DLC */ + hcan->pRxMsg->DLC = (uint8_t)0x0F & hcan->Instance->sFIFOMailBox[FIFONumber].RDTR; + /* Get the FMI */ + hcan->pRxMsg->FMI = (uint8_t)0xFF & (hcan->Instance->sFIFOMailBox[FIFONumber].RDTR >> 8); + /* Get the data field */ + hcan->pRxMsg->Data[0] = (uint8_t)0xFF & hcan->Instance->sFIFOMailBox[FIFONumber].RDLR; + hcan->pRxMsg->Data[1] = (uint8_t)0xFF & (hcan->Instance->sFIFOMailBox[FIFONumber].RDLR >> 8); + hcan->pRxMsg->Data[2] = (uint8_t)0xFF & (hcan->Instance->sFIFOMailBox[FIFONumber].RDLR >> 16); + hcan->pRxMsg->Data[3] = (uint8_t)0xFF & (hcan->Instance->sFIFOMailBox[FIFONumber].RDLR >> 24); + hcan->pRxMsg->Data[4] = (uint8_t)0xFF & hcan->Instance->sFIFOMailBox[FIFONumber].RDHR; + hcan->pRxMsg->Data[5] = (uint8_t)0xFF & (hcan->Instance->sFIFOMailBox[FIFONumber].RDHR >> 8); + hcan->pRxMsg->Data[6] = (uint8_t)0xFF & (hcan->Instance->sFIFOMailBox[FIFONumber].RDHR >> 16); + hcan->pRxMsg->Data[7] = (uint8_t)0xFF & (hcan->Instance->sFIFOMailBox[FIFONumber].RDHR >> 24); + /* Release the FIFO */ + /* Release FIFO0 */ + if (FIFONumber == CAN_FIFO0) + { + __HAL_CAN_FIFO_RELEASE(hcan, CAN_FIFO0); + + /* Disable FIFO 0 message pending Interrupt */ + __HAL_CAN_DISABLE_IT(hcan, CAN_IT_FMP0); + } + /* Release FIFO1 */ + else /* FIFONumber == CAN_FIFO1 */ + { + __HAL_CAN_FIFO_RELEASE(hcan, CAN_FIFO1); + + /* Disable FIFO 1 message pending Interrupt */ + __HAL_CAN_DISABLE_IT(hcan, CAN_IT_FMP1); + } + + if(hcan->State == HAL_CAN_STATE_BUSY_RX) + { + /* Disable Error warning Interrupt */ + __HAL_CAN_DISABLE_IT(hcan, CAN_IT_EWG); + + /* Disable Error passive Interrupt */ + __HAL_CAN_DISABLE_IT(hcan, CAN_IT_EPV); + + /* Disable Bus-off Interrupt */ + __HAL_CAN_DISABLE_IT(hcan, CAN_IT_BOF); + + /* Disable Last error code Interrupt */ + __HAL_CAN_DISABLE_IT(hcan, CAN_IT_LEC); + + /* Disable Error Interrupt */ + __HAL_CAN_DISABLE_IT(hcan, CAN_IT_ERR); + } + + if(hcan->State == HAL_CAN_STATE_BUSY_TX_RX) + { + /* Disable CAN state */ + hcan->State = HAL_CAN_STATE_BUSY_TX; + } + else + { + /* Change CAN state */ + hcan->State = HAL_CAN_STATE_READY; + } + + /* Receive complete callback */ + HAL_CAN_RxCpltCallback(hcan); + + /* Return function status */ + return HAL_OK; +} + +/** + * @} + */ +#endif /* defined(STM32F072xB) || defined(STM32F042x6) || defined(STM32F048xx) */ + +#endif /* HAL_CAN_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_can.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_can.h new file mode 100644 index 0000000000..0a3bb94fb9 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_can.h @@ -0,0 +1,779 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_can.h + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief Header file of CAN HAL module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32F0xx_HAL_CAN_H +#define __STM32F0xx_HAL_CAN_H + +#ifdef __cplusplus + extern "C" { +#endif + +#if defined(STM32F072xB) || defined(STM32F042x6) || defined(STM32F048xx) + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal_def.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @addtogroup CAN + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ + +/** + * @brief HAL State structures definition + */ +typedef enum +{ + HAL_CAN_STATE_RESET = 0x00, /*!< CAN not yet initialized or disabled */ + HAL_CAN_STATE_READY = 0x01, /*!< CAN initialized and ready for use */ + HAL_CAN_STATE_BUSY = 0x02, /*!< CAN process is ongoing */ + HAL_CAN_STATE_BUSY_TX = 0x12, /*!< CAN process is ongoing */ + HAL_CAN_STATE_BUSY_RX = 0x22, /*!< CAN process is ongoing */ + HAL_CAN_STATE_BUSY_TX_RX = 0x32, /*!< CAN process is ongoing */ + HAL_CAN_STATE_TIMEOUT = 0x03, /*!< CAN in Timeout state */ + HAL_CAN_STATE_ERROR = 0x04 /*!< CAN error state */ + +}HAL_CAN_StateTypeDef; + +/** + * @brief HAL CAN Error Code structure definition + */ +typedef enum +{ + HAL_CAN_ERROR_NONE = 0x00, /*!< No error */ + HAL_CAN_ERROR_EWG = 0x01, /*!< EWG error */ + HAL_CAN_ERROR_EPV = 0x02, /*!< EPV error */ + HAL_CAN_ERROR_BOF = 0x04, /*!< BOF error */ + HAL_CAN_ERROR_STF = 0x08, /*!< Stuff error */ + HAL_CAN_ERROR_FOR = 0x10, /*!< Form error */ + HAL_CAN_ERROR_ACK = 0x20, /*!< Acknowledgment error */ + HAL_CAN_ERROR_BR = 0x40, /*!< Bit recessive */ + HAL_CAN_ERROR_BD = 0x80, /*!< LEC dominant */ + HAL_CAN_ERROR_CRC = 0x100 /*!< LEC transfer error */ +}HAL_CAN_ErrorTypeDef; + +/** + * @brief CAN init structure definition + */ +typedef struct +{ + uint32_t Prescaler; /*!< Specifies the length of a time quantum. + This parameter must be a number between Min_Data = 1 and Max_Data = 1024. */ + + uint32_t Mode; /*!< Specifies the CAN operating mode. + This parameter can be a value of @ref CAN_operating_mode */ + + uint32_t SJW; /*!< Specifies the maximum number of time quanta + the CAN hardware is allowed to lengthen or + shorten a bit to perform resynchronization. + This parameter can be a value of @ref CAN_synchronisation_jump_width */ + + uint32_t BS1; /*!< Specifies the number of time quanta in Bit Segment 1. + This parameter can be a value of @ref CAN_time_quantum_in_bit_segment_1 */ + + uint32_t BS2; /*!< Specifies the number of time quanta in Bit Segment 2. + This parameter can be a value of @ref CAN_time_quantum_in_bit_segment_2 */ + + uint32_t TTCM; /*!< Enable or disable the time triggered communication mode. + This parameter can be set to ENABLE or DISABLE. */ + + uint32_t ABOM; /*!< Enable or disable the automatic bus-off management. + This parameter can be set to ENABLE or DISABLE. */ + + uint32_t AWUM; /*!< Enable or disable the automatic wake-up mode. + This parameter can be set to ENABLE or DISABLE. */ + + uint32_t NART; /*!< Enable or disable the non-automatic retransmission mode. + This parameter can be set to ENABLE or DISABLE. */ + + uint32_t RFLM; /*!< Enable or disable the Receive FIFO Locked mode. + This parameter can be set to ENABLE or DISABLE. */ + + uint32_t TXFP; /*!< Enable or disable the transmit FIFO priority. + This parameter can be set to ENABLE or DISABLE. */ +}CAN_InitTypeDef; + +/** + * @brief CAN filter configuration structure definition + */ +typedef struct +{ + uint32_t FilterIdHigh; /*!< Specifies the filter identification number (MSBs for a 32-bit + configuration, first one for a 16-bit configuration). + This parameter must be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF. */ + + uint32_t FilterIdLow; /*!< Specifies the filter identification number (LSBs for a 32-bit + configuration, second one for a 16-bit configuration). + This parameter must be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF. */ + + uint32_t FilterMaskIdHigh; /*!< Specifies the filter mask number or identification number, + according to the mode (MSBs for a 32-bit configuration, + first one for a 16-bit configuration). + This parameter must be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF. */ + + uint32_t FilterMaskIdLow; /*!< Specifies the filter mask number or identification number, + according to the mode (LSBs for a 32-bit configuration, + second one for a 16-bit configuration). + This parameter must be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF. */ + + uint32_t FilterFIFOAssignment; /*!< Specifies the FIFO (0 or 1) which will be assigned to the filter. + This parameter can be a value of @ref CAN_filter_FIFO */ + + uint32_t FilterNumber; /*!< Specifies the filter which will be initialized. + This parameter must be a number between Min_Data = 0 and Max_Data = 27. */ + + uint32_t FilterMode; /*!< Specifies the filter mode to be initialized. + This parameter can be a value of @ref CAN_filter_mode */ + + uint32_t FilterScale; /*!< Specifies the filter scale. + This parameter can be a value of @ref CAN_filter_scale */ + + uint32_t FilterActivation; /*!< Enable or disable the filter. + This parameter can be set to ENABLE or DISABLE. */ + + uint32_t BankNumber; /*!< Select the start slave bank filter + This parameter must be a number between Min_Data = 0 and Max_Data = 28. */ + +}CAN_FilterConfTypeDef; + +/** + * @brief CAN Tx message structure definition + */ +typedef struct +{ + uint32_t StdId; /*!< Specifies the standard identifier. + This parameter must be a number between Min_Data = 0 and Max_Data = 0x7FF. */ + + uint32_t ExtId; /*!< Specifies the extended identifier. + This parameter must be a number between Min_Data = 0 and Max_Data = 0x1FFFFFFF. */ + + uint32_t IDE; /*!< Specifies the type of identifier for the message that will be transmitted. + This parameter can be a value of @ref CAN_identifier_type */ + + uint32_t RTR; /*!< Specifies the type of frame for the message that will be transmitted. + This parameter can be a value of @ref CAN_remote_transmission_request */ + + uint32_t DLC; /*!< Specifies the length of the frame that will be transmitted. + This parameter must be a number between Min_Data = 0 and Max_Data = 8. */ + + uint32_t Data[8]; /*!< Contains the data to be transmitted. + This parameter must be a number between Min_Data = 0 and Max_Data = 0xFF. */ + +}CanTxMsgTypeDef; + +/** + * @brief CAN Rx message structure definition + */ +typedef struct +{ + uint32_t StdId; /*!< Specifies the standard identifier. + This parameter must be a number between Min_Data = 0 and Max_Data = 0x7FF. */ + + uint32_t ExtId; /*!< Specifies the extended identifier. + This parameter must be a number between Min_Data = 0 and Max_Data = 0x1FFFFFFF. */ + + uint32_t IDE; /*!< Specifies the type of identifier for the message that will be received. + This parameter can be a value of @ref CAN_identifier_type */ + + uint32_t RTR; /*!< Specifies the type of frame for the received message. + This parameter can be a value of @ref CAN_remote_transmission_request */ + + uint32_t DLC; /*!< Specifies the length of the frame that will be received. + This parameter must be a number between Min_Data = 0 and Max_Data = 8. */ + + uint32_t Data[8]; /*!< Contains the data to be received. + This parameter must be a number between Min_Data = 0 and Max_Data = 0xFF. */ + + uint32_t FMI; /*!< Specifies the index of the filter the message stored in the mailbox passes through. + This parameter must be a number between Min_Data = 0 and Max_Data = 0xFF. */ + + uint32_t FIFONumber; /*!< Specifies the receive FIFO number. + This parameter can be CAN_FIFO0 or CAN_FIFO1 */ + +}CanRxMsgTypeDef; + +/** + * @brief CAN handle Structure definition + */ +typedef struct +{ + CAN_TypeDef *Instance; /*!< Register base address */ + + CAN_InitTypeDef Init; /*!< CAN required parameters */ + + CanTxMsgTypeDef* pTxMsg; /*!< Pointer to transmit structure */ + + CanRxMsgTypeDef* pRxMsg; /*!< Pointer to reception structure */ + + HAL_LockTypeDef Lock; /*!< CAN locking object */ + + __IO HAL_CAN_StateTypeDef State; /*!< CAN communication state */ + + __IO HAL_CAN_ErrorTypeDef ErrorCode; /*!< CAN Error code */ + +}CAN_HandleTypeDef; + +/* Exported constants --------------------------------------------------------*/ + +/** @defgroup CAN_Exported_Constants + * @{ + */ + +/** @defgroup CAN_InitStatus + * @{ + */ +#define CAN_INITSTATUS_FAILED ((uint32_t)0x00000000) /*!< CAN initialization failed */ +#define CAN_INITSTATUS_SUCCESS ((uint32_t)0x00000001) /*!< CAN initialization OK */ +/** + * @} + */ + +/** @defgroup CAN_operating_mode + * @{ + */ +#define CAN_MODE_NORMAL ((uint32_t)0x00000000) /*!< Normal mode */ +#define CAN_MODE_LOOPBACK ((uint32_t)CAN_BTR_LBKM) /*!< Loopback mode */ +#define CAN_MODE_SILENT ((uint32_t)CAN_BTR_SILM) /*!< Silent mode */ +#define CAN_MODE_SILENT_LOOPBACK ((uint32_t)(CAN_BTR_LBKM | CAN_BTR_SILM)) /*!< Loopback combined with silent mode */ + +#define IS_CAN_MODE(MODE) (((MODE) == CAN_MODE_NORMAL) || \ + ((MODE) == CAN_MODE_LOOPBACK)|| \ + ((MODE) == CAN_MODE_SILENT) || \ + ((MODE) == CAN_MODE_SILENT_LOOPBACK)) +/** + * @} + */ + + +/** @defgroup CAN_synchronisation_jump_width + * @{ + */ +#define CAN_SJW_1TQ ((uint32_t)0x00000000) /*!< 1 time quantum */ +#define CAN_SJW_2TQ ((uint32_t)CAN_BTR_SJW_0) /*!< 2 time quantum */ +#define CAN_SJW_3TQ ((uint32_t)CAN_BTR_SJW_1) /*!< 3 time quantum */ +#define CAN_SJW_4TQ ((uint32_t)CAN_BTR_SJW) /*!< 4 time quantum */ + +#define IS_CAN_SJW(SJW) (((SJW) == CAN_SJW_1TQ) || ((SJW) == CAN_SJW_2TQ)|| \ + ((SJW) == CAN_SJW_3TQ) || ((SJW) == CAN_SJW_4TQ)) +/** + * @} + */ + +/** @defgroup CAN_time_quantum_in_bit_segment_1 + * @{ + */ +#define CAN_BS1_1TQ ((uint32_t)0x00000000) /*!< 1 time quantum */ +#define CAN_BS1_2TQ ((uint32_t)CAN_BTR_TS1_0) /*!< 2 time quantum */ +#define CAN_BS1_3TQ ((uint32_t)CAN_BTR_TS1_1) /*!< 3 time quantum */ +#define CAN_BS1_4TQ ((uint32_t)(CAN_BTR_TS1_1 | CAN_BTR_TS1_0)) /*!< 4 time quantum */ +#define CAN_BS1_5TQ ((uint32_t)CAN_BTR_TS1_2) /*!< 5 time quantum */ +#define CAN_BS1_6TQ ((uint32_t)(CAN_BTR_TS1_2 | CAN_BTR_TS1_0)) /*!< 6 time quantum */ +#define CAN_BS1_7TQ ((uint32_t)(CAN_BTR_TS1_2 | CAN_BTR_TS1_1)) /*!< 7 time quantum */ +#define CAN_BS1_8TQ ((uint32_t)(CAN_BTR_TS1_2 | CAN_BTR_TS1_1 | CAN_BTR_TS1_0)) /*!< 8 time quantum */ +#define CAN_BS1_9TQ ((uint32_t)CAN_BTR_TS1_3) /*!< 9 time quantum */ +#define CAN_BS1_10TQ ((uint32_t)(CAN_BTR_TS1_3 | CAN_BTR_TS1_0)) /*!< 10 time quantum */ +#define CAN_BS1_11TQ ((uint32_t)(CAN_BTR_TS1_3 | CAN_BTR_TS1_1)) /*!< 11 time quantum */ +#define CAN_BS1_12TQ ((uint32_t)(CAN_BTR_TS1_3 | CAN_BTR_TS1_1 | CAN_BTR_TS1_0)) /*!< 12 time quantum */ +#define CAN_BS1_13TQ ((uint32_t)(CAN_BTR_TS1_3 | CAN_BTR_TS1_2)) /*!< 13 time quantum */ +#define CAN_BS1_14TQ ((uint32_t)(CAN_BTR_TS1_3 | CAN_BTR_TS1_2 | CAN_BTR_TS1_0)) /*!< 14 time quantum */ +#define CAN_BS1_15TQ ((uint32_t)(CAN_BTR_TS1_3 | CAN_BTR_TS1_2 | CAN_BTR_TS1_1)) /*!< 15 time quantum */ +#define CAN_BS1_16TQ ((uint32_t)CAN_BTR_TS1) /*!< 16 time quantum */ + +#define IS_CAN_BS1(BS1) ((BS1) <= CAN_BS1_16TQ) +/** + * @} + */ + +/** @defgroup CAN_time_quantum_in_bit_segment_2 + * @{ + */ +#define CAN_BS2_1TQ ((uint32_t)0x00000000) /*!< 1 time quantum */ +#define CAN_BS2_2TQ ((uint32_t)CAN_BTR_TS2_0) /*!< 2 time quantum */ +#define CAN_BS2_3TQ ((uint32_t)CAN_BTR_TS2_1) /*!< 3 time quantum */ +#define CAN_BS2_4TQ ((uint32_t)(CAN_BTR_TS2_1 | CAN_BTR_TS2_0)) /*!< 4 time quantum */ +#define CAN_BS2_5TQ ((uint32_t)CAN_BTR_TS2_2) /*!< 5 time quantum */ +#define CAN_BS2_6TQ ((uint32_t)(CAN_BTR_TS2_2 | CAN_BTR_TS2_0)) /*!< 6 time quantum */ +#define CAN_BS2_7TQ ((uint32_t)(CAN_BTR_TS2_2 | CAN_BTR_TS2_1)) /*!< 7 time quantum */ +#define CAN_BS2_8TQ ((uint32_t)CAN_BTR_TS2) /*!< 8 time quantum */ + +#define IS_CAN_BS2(BS2) ((BS2) <= CAN_BS2_8TQ) +/** + * @} + */ + +/** @defgroup CAN_clock_prescaler + * @{ + */ +#define IS_CAN_PRESCALER(PRESCALER) (((PRESCALER) >= 1) && ((PRESCALER) <= 1024)) +/** + * @} + */ + +/** @defgroup CAN_filter_number + * @{ + */ +#define IS_CAN_FILTER_NUMBER(NUMBER) ((NUMBER) <= 27) +/** + * @} + */ + +/** @defgroup CAN_filter_mode + * @{ + */ +#define CAN_FILTERMODE_IDMASK ((uint8_t)0x00) /*!< Identifier mask mode */ +#define CAN_FILTERMODE_IDLIST ((uint8_t)0x01) /*!< Identifier list mode */ + +#define IS_CAN_FILTER_MODE(MODE) (((MODE) == CAN_FILTERMODE_IDMASK) || \ + ((MODE) == CAN_FILTERMODE_IDLIST)) +/** + * @} + */ + +/** @defgroup CAN_filter_scale + * @{ + */ +#define CAN_FILTERSCALE_16BIT ((uint8_t)0x00) /*!< Two 16-bit filters */ +#define CAN_FILTERSCALE_32BIT ((uint8_t)0x01) /*!< One 32-bit filter */ + +#define IS_CAN_FILTER_SCALE(SCALE) (((SCALE) == CAN_FILTERSCALE_16BIT) || \ + ((SCALE) == CAN_FILTERSCALE_32BIT)) +/** + * @} + */ + +/** @defgroup CAN_filter_FIFO + * @{ + */ +#define CAN_FILTER_FIFO0 ((uint8_t)0x00) /*!< Filter FIFO 0 assignment for filter x */ +#define CAN_FILTER_FIFO1 ((uint8_t)0x01) /*!< Filter FIFO 1 assignment for filter x */ + +#define IS_CAN_FILTER_FIFO(FIFO) (((FIFO) == CAN_FILTER_FIFO0) || \ + ((FIFO) == CAN_FILTER_FIFO1)) + +/* Legacy defines */ +#define CAN_FilterFIFO0 CAN_FILTER_FIFO0 +#define CAN_FilterFIFO1 CAN_FILTER_FIFO1 +/** + * @} + */ + +/** @defgroup CAN_Start_bank_filter_for_slave_CAN + * @{ + */ +#define IS_CAN_BANKNUMBER(BANKNUMBER) ((BANKNUMBER) <= 28) +/** + * @} + */ + +/** @defgroup CAN_Tx + * @{ + */ +#define IS_CAN_TRANSMITMAILBOX(TRANSMITMAILBOX) ((TRANSMITMAILBOX) <= ((uint8_t)0x02)) +#define IS_CAN_STDID(STDID) ((STDID) <= ((uint32_t)0x7FF)) +#define IS_CAN_EXTID(EXTID) ((EXTID) <= ((uint32_t)0x1FFFFFFF)) +#define IS_CAN_DLC(DLC) ((DLC) <= ((uint8_t)0x08)) +/** + * @} + */ + +/** @defgroup CAN_identifier_type + * @{ + */ +#define CAN_ID_STD ((uint32_t)0x00000000) /*!< Standard Id */ +#define CAN_ID_EXT ((uint32_t)0x00000004) /*!< Extended Id */ +#define IS_CAN_IDTYPE(IDTYPE) (((IDTYPE) == CAN_ID_STD) || \ + ((IDTYPE) == CAN_ID_EXT)) +/** + * @} + */ + +/** @defgroup CAN_remote_transmission_request + * @{ + */ +#define CAN_RTR_DATA ((uint32_t)0x00000000) /*!< Data frame */ +#define CAN_RTR_REMOTE ((uint32_t)0x00000002) /*!< Remote frame */ +#define IS_CAN_RTR(RTR) (((RTR) == CAN_RTR_DATA) || ((RTR) == CAN_RTR_REMOTE)) + +/** + * @} + */ + +/** @defgroup CAN_transmit_constants + * @{ + */ +#define CAN_TXSTATUS_FAILED ((uint8_t)0x00) /*!< CAN transmission failed */ +#define CAN_TXSTATUS_OK ((uint8_t)0x01) /*!< CAN transmission succeeded */ +#define CAN_TXSTATUS_PENDING ((uint8_t)0x02) /*!< CAN transmission pending */ +#define CAN_TXSTATUS_NOMAILBOX ((uint8_t)0x04) /*!< CAN cell did not provide CAN_TxStatus_NoMailBox */ + +/** + * @} + */ + +/** @defgroup CAN_receive_FIFO_number_constants + * @{ + */ +#define CAN_FIFO0 ((uint8_t)0x00) /*!< CAN FIFO 0 used to receive */ +#define CAN_FIFO1 ((uint8_t)0x01) /*!< CAN FIFO 1 used to receive */ + +#define IS_CAN_FIFO(FIFO) (((FIFO) == CAN_FIFO0) || ((FIFO) == CAN_FIFO1)) +/** + * @} + */ + +/** @defgroup CAN_flags + * @{ + */ +/* If the flag is 0x3XXXXXXX, it means that it can be used with CAN_GetFlagStatus() + and CAN_ClearFlag() functions. */ +/* If the flag is 0x1XXXXXXX, it means that it can only be used with + CAN_GetFlagStatus() function. */ + +/* Transmit Flags */ +#define CAN_FLAG_RQCP0 ((uint32_t)0x00000500) /*!< Request MailBox0 flag */ +#define CAN_FLAG_RQCP1 ((uint32_t)0x00000508) /*!< Request MailBox1 flag */ +#define CAN_FLAG_RQCP2 ((uint32_t)0x00000510) /*!< Request MailBox2 flag */ +#define CAN_FLAG_TXOK0 ((uint32_t)0x00000501) /*!< Transmission OK MailBox0 flag */ +#define CAN_FLAG_TXOK1 ((uint32_t)0x00000509) /*!< Transmission OK MailBox1 flag */ +#define CAN_FLAG_TXOK2 ((uint32_t)0x00000511) /*!< Transmission OK MailBox2 flag */ +#define CAN_FLAG_TME0 ((uint32_t)0x0000051A) /*!< Transmit mailbox 0 empty flag */ +#define CAN_FLAG_TME1 ((uint32_t)0x0000051B) /*!< Transmit mailbox 0 empty flag */ +#define CAN_FLAG_TME2 ((uint32_t)0x0000051C) /*!< Transmit mailbox 0 empty flag */ + +/* Receive Flags */ +#define CAN_FLAG_FF0 ((uint32_t)0x00000203) /*!< FIFO 0 Full flag */ +#define CAN_FLAG_FOV0 ((uint32_t)0x00000204) /*!< FIFO 0 Overrun flag */ + +#define CAN_FLAG_FF1 ((uint32_t)0x00000403) /*!< FIFO 1 Full flag */ +#define CAN_FLAG_FOV1 ((uint32_t)0x00000404) /*!< FIFO 1 Overrun flag */ + +/* Operating Mode Flags */ +#define CAN_FLAG_WKU ((uint32_t)0x00000103) /*!< Wake up flag */ +#define CAN_FLAG_SLAK ((uint32_t)0x00000101) /*!< Sleep acknowledge flag */ +#define CAN_FLAG_SLAKI ((uint32_t)0x00000104) /*!< Sleep acknowledge flag */ +/* @note When SLAK interrupt is disabled (SLKIE=0), no polling on SLAKI is possible. + In this case the SLAK bit can be polled.*/ + +/* Error Flags */ +#define CAN_FLAG_EWG ((uint32_t)0x00000300) /*!< Error warning flag */ +#define CAN_FLAG_EPV ((uint32_t)0x00000301) /*!< Error passive flag */ +#define CAN_FLAG_BOF ((uint32_t)0x00000302) /*!< Bus-Off flag */ + +#define IS_CAN_GET_FLAG(FLAG) (((FLAG) == CAN_FLAG_RQCP2) || ((FLAG) == CAN_FLAG_BOF) || \ + ((FLAG) == CAN_FLAG_EPV) || ((FLAG) == CAN_FLAG_EWG) || \ + ((FLAG) == CAN_FLAG_WKU) || ((FLAG) == CAN_FLAG_FOV0) || \ + ((FLAG) == CAN_FLAG_FF0) || ((FLAG) == CAN_FLAG_SLAK) || \ + ((FLAG) == CAN_FLAG_FOV1) || ((FLAG) == CAN_FLAG_FF1) || \ + ((FLAG) == CAN_FLAG_RQCP1) || ((FLAG) == CAN_FLAG_RQCP0)) + + +#define IS_CAN_CLEAR_FLAG(FLAG)(((FLAG) == CAN_FLAG_RQCP2) || ((FLAG) == CAN_FLAG_RQCP1) || \ + ((FLAG) == CAN_FLAG_RQCP0) || ((FLAG) == CAN_FLAG_FF0) || \ + ((FLAG) == CAN_FLAG_FOV0) || ((FLAG) == CAN_FLAG_FF1) || \ + ((FLAG) == CAN_FLAG_FOV1) || ((FLAG) == CAN_FLAG_WKU)) +/** + * @} + */ + + +/** @defgroup CAN_interrupts + * @{ + */ +#define CAN_IT_TME ((uint32_t)CAN_IER_TMEIE) /*!< Transmit mailbox empty interrupt */ + +/* Receive Interrupts */ +#define CAN_IT_FMP0 ((uint32_t)CAN_IER_FMPIE0) /*!< FIFO 0 message pending interrupt */ +#define CAN_IT_FF0 ((uint32_t)CAN_IER_FFIE0) /*!< FIFO 0 full interrupt */ +#define CAN_IT_FOV0 ((uint32_t)CAN_IER_FOVIE0) /*!< FIFO 0 overrun interrupt */ +#define CAN_IT_FMP1 ((uint32_t)CAN_IER_FMPIE1) /*!< FIFO 1 message pending interrupt */ +#define CAN_IT_FF1 ((uint32_t)CAN_IER_FFIE1) /*!< FIFO 1 full interrupt */ +#define CAN_IT_FOV1 ((uint32_t)CAN_IER_FOVIE1) /*!< FIFO 1 overrun interrupt */ + +/* Operating Mode Interrupts */ +#define CAN_IT_WKU ((uint32_t)CAN_IER_WKUIE) /*!< Wake-up interrupt */ +#define CAN_IT_SLK ((uint32_t)CAN_IER_SLKIE) /*!< Sleep acknowledge interrupt */ + +/* Error Interrupts */ +#define CAN_IT_EWG ((uint32_t)CAN_IER_EWGIE) /*!< Error warning interrupt */ +#define CAN_IT_EPV ((uint32_t)CAN_IER_EPVIE) /*!< Error passive interrupt */ +#define CAN_IT_BOF ((uint32_t)CAN_IER_BOFIE) /*!< Bus-off interrupt */ +#define CAN_IT_LEC ((uint32_t)CAN_IER_LECIE) /*!< Last error code interrupt */ +#define CAN_IT_ERR ((uint32_t)CAN_IER_ERRIE) /*!< Error Interrupt */ + +/* Flags named as Interrupts : kept only for FW compatibility */ +#define CAN_IT_RQCP0 CAN_IT_TME +#define CAN_IT_RQCP1 CAN_IT_TME +#define CAN_IT_RQCP2 CAN_IT_TME + +#define IS_CAN_IT(IT) (((IT) == CAN_IT_TME) || ((IT) == CAN_IT_FMP0) ||\ + ((IT) == CAN_IT_FF0) || ((IT) == CAN_IT_FOV0) ||\ + ((IT) == CAN_IT_FMP1) || ((IT) == CAN_IT_FF1) ||\ + ((IT) == CAN_IT_FOV1) || ((IT) == CAN_IT_EWG) ||\ + ((IT) == CAN_IT_EPV) || ((IT) == CAN_IT_BOF) ||\ + ((IT) == CAN_IT_LEC) || ((IT) == CAN_IT_ERR) ||\ + ((IT) == CAN_IT_WKU) || ((IT) == CAN_IT_SLK)) + +#define IS_CAN_CLEAR_IT(IT) (((IT) == CAN_IT_TME) || ((IT) == CAN_IT_FF0) ||\ + ((IT) == CAN_IT_FOV0)|| ((IT) == CAN_IT_FF1) ||\ + ((IT) == CAN_IT_FOV1)|| ((IT) == CAN_IT_EWG) ||\ + ((IT) == CAN_IT_EPV) || ((IT) == CAN_IT_BOF) ||\ + ((IT) == CAN_IT_LEC) || ((IT) == CAN_IT_ERR) ||\ + ((IT) == CAN_IT_WKU) || ((IT) == CAN_IT_SLK)) +/** + * @} + */ + +/* Time out for INAK bit */ +#define INAK_TIMEOUT ((uint32_t)0x00FFFFFF) +/* Time out for SLAK bit */ +#define SLAK_TIMEOUT ((uint32_t)0x00FFFFFF) + +/* Mailboxes definition */ +#define CAN_TXMAILBOX_0 ((uint8_t)0x00) +#define CAN_TXMAILBOX_1 ((uint8_t)0x01) +#define CAN_TXMAILBOX_2 ((uint8_t)0x02) + +/** + * @} + */ + +/* Exported macros -----------------------------------------------------------*/ + +/** @brief Reset CAN handle state + * @param __HANDLE__: CAN handle. + * @retval None + */ +#define __HAL_CAN_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_CAN_STATE_RESET) + +/** + * @brief Enable the specified CAN interrupts. + * @param __HANDLE__: CAN handle. + * @param __INTERRUPT__: CAN Interrupt + * @retval None + */ +#define __HAL_CAN_ENABLE_IT(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->IER) |= (__INTERRUPT__)) + +/** + * @brief Disable the specified CAN interrupts. + * @param __HANDLE__: CAN handle. + * @param __INTERRUPT__: CAN Interrupt + * @retval None + */ +#define __HAL_CAN_DISABLE_IT(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->IER) &= ~(__INTERRUPT__)) + +/** + * @brief Return the number of pending received messages. + * @param __HANDLE__: CAN handle. + * @param __FIFONUMBER__: Receive FIFO number, CAN_FIFO0 or CAN_FIFO1. + * @retval The number of pending message. + */ +#define __HAL_CAN_MSG_PENDING(__HANDLE__, __FIFONUMBER__) (((__FIFONUMBER__) == CAN_FIFO0)? \ +((uint8_t)((__HANDLE__)->Instance->RF0R&(uint32_t)0x03)) : ((uint8_t)((__HANDLE__)->Instance->RF1R&(uint32_t)0x03))) + +/** @brief Check whether the specified CAN flag is set or not. + * @param __HANDLE__: CAN handle. + * @param __FLAG__: specifies the flag to check. + * This parameter can be one of the following values: + * @arg CAN_TSR_RQCP0: Request MailBox0 Flag + * @arg CAN_TSR_RQCP1: Request MailBox1 Flag + * @arg CAN_TSR_RQCP2: Request MailBox2 Flag + * @arg CAN_FLAG_TXOK0: Transmission OK MailBox0 Flag + * @arg CAN_FLAG_TXOK1: Transmission OK MailBox1 Flag + * @arg CAN_FLAG_TXOK2: Transmission OK MailBox2 Flag + * @arg CAN_FLAG_TME0: Transmit mailbox 0 empty Flag + * @arg CAN_FLAG_TME1: Transmit mailbox 1 empty Flag + * @arg CAN_FLAG_TME2: Transmit mailbox 2 empty Flag + * @arg CAN_FLAG_FMP0: FIFO 0 Message Pending Flag + * @arg CAN_FLAG_FF0: FIFO 0 Full Flag + * @arg CAN_FLAG_FOV0: FIFO 0 Overrun Flag + * @arg CAN_FLAG_FMP1: FIFO 1 Message Pending Flag + * @arg CAN_FLAG_FF1: FIFO 1 Full Flag + * @arg CAN_FLAG_FOV1: FIFO 1 Overrun Flag + * @arg CAN_FLAG_WKU: Wake up Flag + * @arg CAN_FLAG_SLAK: Sleep acknowledge Flag + * @arg CAN_FLAG_SLAKI: Sleep acknowledge Flag + * @arg CAN_FLAG_EWG: Error Warning Flag + * @arg CAN_FLAG_EPV: Error Passive Flag + * @arg CAN_FLAG_BOF: Bus-Off Flag + * @retval The new state of __FLAG__ (TRUE or FALSE). + */ +#define CAN_FLAG_MASK ((uint32_t)0x000000FF) +#define __HAL_CAN_GET_FLAG(__HANDLE__, __FLAG__) \ +((((__FLAG__) >> 8) == 5)? ((((__HANDLE__)->Instance->TSR) & (1 << ((__FLAG__) & CAN_FLAG_MASK))) == (1 << ((__FLAG__) & CAN_FLAG_MASK))): \ + (((__FLAG__) >> 8) == 2)? ((((__HANDLE__)->Instance->RF0R) & (1 << ((__FLAG__) & CAN_FLAG_MASK))) == (1 << ((__FLAG__) & CAN_FLAG_MASK))): \ + (((__FLAG__) >> 8) == 4)? ((((__HANDLE__)->Instance->RF1R) & (1 << ((__FLAG__) & CAN_FLAG_MASK))) == (1 << ((__FLAG__) & CAN_FLAG_MASK))): \ + (((__FLAG__) >> 8) == 1)? ((((__HANDLE__)->Instance->MSR) & (1 << ((__FLAG__) & CAN_FLAG_MASK))) == (1 << ((__FLAG__) & CAN_FLAG_MASK))): \ + ((((__HANDLE__)->Instance->ESR) & (1 << ((__FLAG__) & CAN_FLAG_MASK))) == (1 << ((__FLAG__) & CAN_FLAG_MASK)))) + +/** @brief Clear the specified CAN pending flag. + * @param __HANDLE__: CAN handle. + * @param __FLAG__: specifies the flag to check. + * This parameter can be one of the following values: + * @arg CAN_TSR_RQCP0: Request MailBox0 Flag + * @arg CAN_TSR_RQCP1: Request MailBox1 Flag + * @arg CAN_TSR_RQCP2: Request MailBox2 Flag + * @arg CAN_FLAG_TXOK0: Transmission OK MailBox0 Flag + * @arg CAN_FLAG_TXOK1: Transmission OK MailBox1 Flag + * @arg CAN_FLAG_TXOK2: Transmission OK MailBox2 Flag + * @arg CAN_FLAG_TME0: Transmit mailbox 0 empty Flag + * @arg CAN_FLAG_TME1: Transmit mailbox 1 empty Flag + * @arg CAN_FLAG_TME2: Transmit mailbox 2 empty Flag + * @arg CAN_FLAG_FMP0: FIFO 0 Message Pending Flag + * @arg CAN_FLAG_FF0: FIFO 0 Full Flag + * @arg CAN_FLAG_FOV0: FIFO 0 Overrun Flag + * @arg CAN_FLAG_FMP1: FIFO 1 Message Pending Flag + * @arg CAN_FLAG_FF1: FIFO 1 Full Flag + * @arg CAN_FLAG_FOV1: FIFO 1 Overrun Flag + * @arg CAN_FLAG_WKU: Wake up Flag + * @arg CAN_FLAG_SLAKI: Sleep acknowledge Flag + * @arg CAN_FLAG_EWG: Error Warning Flag + * @arg CAN_FLAG_EPV: Error Passive Flag + * @arg CAN_FLAG_BOF: Bus-Off Flag + * @retval The new state of __FLAG__ (TRUE or FALSE). + */ +#define __HAL_CAN_CLEAR_FLAG(__HANDLE__, __FLAG__) \ +((((__FLAG__) >> 8U) == 5)? (((__HANDLE__)->Instance->TSR) &= ~(1U << ((__FLAG__) & CAN_FLAG_MASK))): \ + (((__FLAG__) >> 8U) == 2)? (((__HANDLE__)->Instance->RF0R) &= ~(1U << ((__FLAG__) & CAN_FLAG_MASK))): \ + (((__FLAG__) >> 8U) == 4)? (((__HANDLE__)->Instance->RF1R) &= ~(1U << ((__FLAG__) & CAN_FLAG_MASK))): \ + (((__FLAG__) >> 8U) == 1)? (((__HANDLE__)->Instance->MSR) &= ~(1U << ((__FLAG__) & CAN_FLAG_MASK))): \ + (((__HANDLE__)->Instance->ESR) &= ~(1U << ((__FLAG__) & CAN_FLAG_MASK)))) + +/** @brief Check if the specified CAN interrupt source is enabled or disabled. + * @param __HANDLE__: CAN handle. + * @param __INTERRUPT__: specifies the CAN interrupt source to check. + * This parameter can be one of the following values: + * @arg CAN_IT_TME: Transmit mailbox empty interrupt enable + * @arg CAN_IT_FMP0: FIFO0 message pending interrupt enablev + * @arg CAN_IT_FMP1: FIFO1 message pending interrupt enable + * @retval The new state of __IT__ (TRUE or FALSE). + */ +#define __HAL_CAN_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((((__HANDLE__)->Instance->IER & (__INTERRUPT__)) == (__INTERRUPT__)) ? SET : RESET) + +/** + * @brief Check the transmission status of a CAN Frame. + * @param __HANDLE__: CAN handle. + * @param __TRANSMITMAILBOX__: the number of the mailbox that is used for transmission. + * @retval The new status of transmission (TRUE or FALSE). + */ +#define __HAL_CAN_TRANSMIT_STATUS(__HANDLE__, __TRANSMITMAILBOX__)\ +(((__TRANSMITMAILBOX__) == CAN_TXMAILBOX_0)? ((((__HANDLE__)->Instance->TSR) & (CAN_TSR_RQCP0 | CAN_TSR_TXOK0 | CAN_TSR_TME0)) == (CAN_TSR_RQCP0 | CAN_TSR_TXOK0 | CAN_TSR_TME0)) :\ + ((__TRANSMITMAILBOX__) == CAN_TXMAILBOX_1)? ((((__HANDLE__)->Instance->TSR) & (CAN_TSR_RQCP1 | CAN_TSR_TXOK1 | CAN_TSR_TME1)) == (CAN_TSR_RQCP1 | CAN_TSR_TXOK1 | CAN_TSR_TME1)) :\ + ((((__HANDLE__)->Instance->TSR) & (CAN_TSR_RQCP2 | CAN_TSR_TXOK2 | CAN_TSR_TME2)) == (CAN_TSR_RQCP2 | CAN_TSR_TXOK2 | CAN_TSR_TME2))) + + + +/** + * @brief Release the specified receive FIFO. + * @param __HANDLE__: CAN handle. + * @param __FIFONUMBER__: Receive FIFO number, CAN_FIFO0 or CAN_FIFO1. + * @retval None + */ +#define __HAL_CAN_FIFO_RELEASE(__HANDLE__, __FIFONUMBER__) (((__FIFONUMBER__) == CAN_FIFO0)? \ +((__HANDLE__)->Instance->RF0R |= CAN_RF0R_RFOM0) : ((__HANDLE__)->Instance->RF1R |= CAN_RF1R_RFOM1)) + +/** + * @brief Cancel a transmit request. + * @param __HANDLE__: CAN handle. + * @param __TRANSMITMAILBOX__: the number of the mailbox that is used for transmission. + * @retval None + */ +#define __HAL_CAN_CANCEL_TRANSMIT(__HANDLE__, __TRANSMITMAILBOX__)\ +(((__TRANSMITMAILBOX__) == CAN_TXMAILBOX_0)? ((__HANDLE__)->Instance->TSR |= CAN_TSR_ABRQ0) :\ + ((__TRANSMITMAILBOX__) == CAN_TXMAILBOX_1)? ((__HANDLE__)->Instance->TSR |= CAN_TSR_ABRQ1) :\ + ((__HANDLE__)->Instance->TSR |= CAN_TSR_ABRQ2)) + +/** + * @brief Enable or disable the DBG Freeze for CAN. + * @param __HANDLE__: CAN handle. + * @param __NEWSTATE__: new state of the CAN peripheral. + * This parameter can be: ENABLE (CAN reception/transmission is frozen + * during debug. Reception FIFOs can still be accessed/controlled normally) + * or DISABLE (CAN is working during debug). + * @retval None + */ +#define __HAL_CAN_DBG_FREEZE(__HANDLE__, __NEWSTATE__) (((__NEWSTATE__) == ENABLE)? \ +((__HANDLE__)->Instance->MCR |= CAN_MCR_DBF) : ((__HANDLE__)->Instance->MCR &= ~CAN_MCR_DBF)) + +/* Exported functions --------------------------------------------------------*/ + +/* Initialization and de-initialization functions *****************************/ +HAL_StatusTypeDef HAL_CAN_Init(CAN_HandleTypeDef* hcan); +HAL_StatusTypeDef HAL_CAN_ConfigFilter(CAN_HandleTypeDef* hcan, CAN_FilterConfTypeDef* sFilterConfig); +HAL_StatusTypeDef HAL_CAN_DeInit(CAN_HandleTypeDef* hcan); +void HAL_CAN_MspInit(CAN_HandleTypeDef* hcan); +void HAL_CAN_MspDeInit(CAN_HandleTypeDef* hcan); + +/* IO operation functions *****************************************************/ +HAL_StatusTypeDef HAL_CAN_Transmit(CAN_HandleTypeDef *hcan, uint32_t Timeout); +HAL_StatusTypeDef HAL_CAN_Transmit_IT(CAN_HandleTypeDef *hcan); +HAL_StatusTypeDef HAL_CAN_Receive(CAN_HandleTypeDef *hcan, uint8_t FIFONumber, uint32_t Timeout); +HAL_StatusTypeDef HAL_CAN_Receive_IT(CAN_HandleTypeDef *hcan, uint8_t FIFONumber); +HAL_StatusTypeDef HAL_CAN_Sleep(CAN_HandleTypeDef *hcan); +HAL_StatusTypeDef HAL_CAN_WakeUp(CAN_HandleTypeDef *hcan); + +/* Peripheral State and Error functions ***************************************/ +void HAL_CAN_IRQHandler(CAN_HandleTypeDef* hcan); +uint32_t HAL_CAN_GetError(CAN_HandleTypeDef *hcan); +HAL_CAN_StateTypeDef HAL_CAN_GetState(CAN_HandleTypeDef* hcan); + +void HAL_CAN_TxCpltCallback(CAN_HandleTypeDef* hcan); +void HAL_CAN_RxCpltCallback(CAN_HandleTypeDef* hcan); +void HAL_CAN_ErrorCallback(CAN_HandleTypeDef *hcan); + +/** + * @} + */ + +/** + * @} + */ + +#endif /* STM32F072xB || STM32F042x6 || STM32F048xx */ + +#ifdef __cplusplus +} +#endif + +#endif /* __STM32F0xx_HAL_CAN_H */ + + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_cec.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_cec.c new file mode 100644 index 0000000000..1ad3a29381 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_cec.c @@ -0,0 +1,1108 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_cec.c + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief CEC HAL module driver. + * + * This file provides firmware functions to manage the following + * functionalities of the High Definition Multimedia Interface + * Consumer Electronics Control Peripheral (CEC). + * + Initialization and de-initialization function + * + IO operation function + * + Peripheral Control function + * + * + @verbatim + =============================================================================== + ##### How to use this driver ##### + =============================================================================== + [..] + The CEC HAL driver can be used as follows: + + (#) Declare a CEC_HandleTypeDef handle structure. + (#) Initialize the CEC low level resources by implementing the HAL_CEC_MspInit ()API: + (##) Enable the CEC interface clock. + (##) CEC pins configuration: + (+) Enable the clock for the CEC GPIOs. + (+) Configure these CEC pins as alternate function pull-up. + (##) NVIC configuration if you need to use interrupt process (HAL_CEC_Transmit_IT() + and HAL_CEC_Receive_IT() APIs): + (+) Configure the CEC interrupt priority. + (+) Enable the NVIC CEC IRQ handle. + (@) The specific CEC interrupts (Transmission complete interrupt, + RXNE interrupt and Error Interrupts) will be managed using the macros + __HAL_CEC_ENABLE_IT() and __HAL_CEC_DISABLE_IT() inside the transmit + and receive process. + + (#) Program the Signal Free Time (SFT) and SFT option, Tolerance, reception stop in + in case of Bit Rising Error, Error-Bit generation conditions, device logical + address and Listen mode in the hcec Init structure. + + (#) Initialize the CEC registers by calling the HAL_CEC_Init() API. + + (@) This API (HAL_CEC_Init()) configures also the low level Hardware GPIO, CLOCK, CORTEX...etc) + by calling the customed HAL_CEC_MspInit() API. + + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @defgroup CEC + * @brief HAL CEC module driver + * @{ + */ +#ifdef HAL_CEC_MODULE_ENABLED + +#if defined(STM32F042x6) || defined(STM32F048xx) ||\ + defined(STM32F051x8) || defined(STM32F058xx) ||\ + defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +#define CEC_CFGR_FIELDS (CEC_CFGR_SFT | CEC_CFGR_RXTOL | CEC_CFGR_BRESTP \ + | CEC_CFGR_BREGEN | CEC_CFGR_LBPEGEN | CEC_CFGR_SFTOPT \ + | CEC_CFGR_BRDNOGEN | CEC_CFGR_OAR | CEC_CFGR_LSTN) +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +static HAL_StatusTypeDef CEC_Transmit_IT(CEC_HandleTypeDef *hcec); +static HAL_StatusTypeDef CEC_Receive_IT(CEC_HandleTypeDef *hcec); +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup CEC_Private_Functions + * @{ + */ + +/** @defgroup HAL_CEC_Group1 Initialization/de-initialization function + * @brief Initialization and Configuration functions + * +@verbatim +=============================================================================== + ##### Initialization and Configuration functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to initialize the CEC + (+) The following parameters need to be configured: + (++) SignalFreeTime + (++) Tolerance + (++) BRERxStop (RX stopped or not upon Bit Rising Error) + (++) BREErrorBitGen (Error-Bit generation in case of Bit Rising Error) + (++) LBPEErrorBitGen (Error-Bit generation in case of Long Bit Period Error) + (++) BroadcastMsgNoErrorBitGen (Error-bit generation in case of broadcast message error) + (++) SignalFreeTimeOption (SFT Timer start definition) + (++) OwnAddress (CEC device address) + (++) ListenMode + +@endverbatim + * @{ + */ + +/** + * @brief Initializes the CEC mode according to the specified + * parameters in the CEC_InitTypeDef and creates the associated handle . + * @param hcec: CEC handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_CEC_Init(CEC_HandleTypeDef *hcec) +{ + uint32_t tmpreg = 0x0; + + /* Check the CEC handle allocation */ + if(hcec == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_CEC_SIGNALFREETIME(hcec->Init.SignalFreeTime)); + assert_param(IS_CEC_TOLERANCE(hcec->Init.Tolerance)); + assert_param(IS_CEC_BRERXSTOP(hcec->Init.BRERxStop)); + assert_param(IS_CEC_BREERRORBITGEN(hcec->Init.BREErrorBitGen)); + assert_param(IS_CEC_LBPEERRORBITGEN(hcec->Init.LBPEErrorBitGen)); + assert_param(IS_CEC_BROADCASTERROR_NO_ERRORBIT_GENERATION(hcec->Init.BroadcastMsgNoErrorBitGen)); + assert_param(IS_CEC_SFTOP(hcec->Init.SignalFreeTimeOption)); + assert_param(IS_CEC_OAR_ADDRESS(hcec->Init.OwnAddress)); + assert_param(IS_CEC_LISTENING_MODE(hcec->Init.ListenMode)); + assert_param(IS_CEC_ADDRESS(hcec->Init.InitiatorAddress)); + + + if(hcec->State == HAL_CEC_STATE_RESET) + { + /* Init the low level hardware : GPIO, CLOCK */ + HAL_CEC_MspInit(hcec); + } + + hcec->State = HAL_CEC_STATE_BUSY; + + /* Disable the Peripheral */ + __HAL_CEC_DISABLE(hcec); + + tmpreg = hcec->Init.SignalFreeTime; + tmpreg |= hcec->Init.Tolerance; + tmpreg |= hcec->Init.BRERxStop; + tmpreg |= hcec->Init.BREErrorBitGen; + tmpreg |= hcec->Init.LBPEErrorBitGen; + tmpreg |= hcec->Init.BroadcastMsgNoErrorBitGen; + tmpreg |= hcec->Init.SignalFreeTimeOption; + tmpreg |= (hcec->Init.OwnAddress << CEC_CFGR_OAR_LSB_POS); + tmpreg |= hcec->Init.ListenMode; + + /* Write to CEC Control Register */ + MODIFY_REG(hcec->Instance->CFGR, CEC_CFGR_FIELDS, tmpreg); + + /* Enable the Peripheral */ + __HAL_CEC_ENABLE(hcec); + + hcec->State = HAL_CEC_STATE_READY; + + return HAL_OK; +} + + + +/** + * @brief DeInitializes the CEC peripheral + * @param hcec: CEC handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_CEC_DeInit(CEC_HandleTypeDef *hcec) +{ + /* Check the CEC handle allocation */ + if(hcec == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_CEC_ALL_INSTANCE(hcec->Instance)); + + hcec->State = HAL_CEC_STATE_BUSY; + + /* DeInit the low level hardware */ + HAL_CEC_MspDeInit(hcec); + /* Disable the Peripheral */ + __HAL_CEC_DISABLE(hcec); + + hcec->ErrorCode = HAL_CEC_ERROR_NONE; + hcec->State = HAL_CEC_STATE_RESET; + + /* Process Unlock */ + __HAL_UNLOCK(hcec); + + return HAL_OK; +} + +/** + * @brief CEC MSP Init + * @param hcec: CEC handle + * @retval None + */ + __weak void HAL_CEC_MspInit(CEC_HandleTypeDef *hcec) +{ + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_CEC_MspInit can be implemented in the user file + */ +} + +/** + * @brief CEC MSP DeInit + * @param hcec: CEC handle + * @retval None + */ + __weak void HAL_CEC_MspDeInit(CEC_HandleTypeDef *hcec) +{ + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_CEC_MspDeInit can be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup HAL_CEC_Group2 IO operation function + * @brief CEC Transmit/Receive functions + * +@verbatim + =============================================================================== + ##### I/O operation function ##### + =============================================================================== + This subsection provides a set of functions allowing to manage the CEC data transfers. + + (#) The CEC handle must contain the initiator (TX side) and the destination (RX side) + logical addresses (4-bit long addresses, 0xF for broadcast messages destination) + + (#) There are two mode of transfer: + (+) Blocking mode: The communication is performed in polling mode. + The HAL status of all data processing is returned by the same function + after finishing transfer. + (+) No-Blocking mode: The communication is performed using Interrupts. + These API's return the HAL status. + The end of the data processing will be indicated through the + dedicated CEC IRQ when using Interrupt mode. + The HAL_CEC_TxCpltCallback(), HAL_CEC_RxCpltCallback() user callbacks + will be executed respectivelly at the end of the transmit or Receive process + The HAL_CEC_ErrorCallback()user callback will be executed when a communication + error is detected + + (#) Blocking mode API's are : + (+) HAL_CEC_Transmit() + (+) HAL_CEC_Receive() + + (#) Non-Blocking mode API's with Interrupt are : + (+) HAL_CEC_Transmit_IT() + (+) HAL_CEC_Receive_IT() + (+) HAL_CEC_IRQHandler() + + (#) A set of Transfer Complete Callbacks are provided in No_Blocking mode: + (+) HAL_CEC_TxCpltCallback() + (+) HAL_CEC_RxCpltCallback() + (+) HAL_CEC_ErrorCallback() + +@endverbatim + * @{ + */ + +/** + * @brief Send data in blocking mode + * @param hcec: CEC handle + * @param DestinationAddress: destination logical address + * @param pData: pointer to input byte data buffer + * @param Size: amount of data to be sent in bytes (without counting the header). + * 0 means only the header is sent (ping operation). + * Maximum TX size is 15 bytes (1 opcode and up to 14 operands). + * @param Timeout: Timeout duration. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_CEC_Transmit(CEC_HandleTypeDef *hcec, uint8_t DestinationAddress, uint8_t *pData, uint32_t Size, uint32_t Timeout) +{ + uint8_t temp = 0; + uint32_t tempisr = 0; + uint32_t tickstart = 0; + + if((hcec->State == HAL_CEC_STATE_READY) && (__HAL_CEC_GET_TRANSMISSION_START_FLAG(hcec) == RESET)) + { + hcec->ErrorCode = HAL_CEC_ERROR_NONE; + if((pData == NULL ) && (Size > 0)) + { + hcec->State = HAL_CEC_STATE_ERROR; + return HAL_ERROR; + } + + assert_param(IS_CEC_ADDRESS(DestinationAddress)); + assert_param(IS_CEC_MSGSIZE(Size)); + + /* Process Locked */ + __HAL_LOCK(hcec); + + hcec->State = HAL_CEC_STATE_BUSY_TX; + + hcec->TxXferCount = Size; + + /* case no data to be sent, sender is only pinging the system */ + if (Size == 0) + { + /* Set TX End of Message (TXEOM) bit, must be set before writing data to TXDR */ + __HAL_CEC_LAST_BYTE_TX_SET(hcec); + } + + /* send header block */ + temp = ((uint32_t)hcec->Init.InitiatorAddress << CEC_INITIATOR_LSB_POS) | DestinationAddress; + hcec->Instance->TXDR = temp; + /* Set TX Start of Message (TXSOM) bit */ + __HAL_CEC_FIRST_BYTE_TX_SET(hcec); + + while (hcec->TxXferCount > 0) + { + hcec->TxXferCount--; + + tickstart = HAL_GetTick(); + while(HAL_IS_BIT_CLR(hcec->Instance->ISR, CEC_ISR_TXBR)) + { + if(Timeout != HAL_MAX_DELAY) + { + if((HAL_GetTick() - tickstart) > Timeout) + { + hcec->State = HAL_CEC_STATE_TIMEOUT; + /* Process Unlocked */ + __HAL_UNLOCK(hcec); + return HAL_TIMEOUT; + } + } + + /* check whether error occured while waiting for TXBR to be set: + * has Tx underrun occurred ? + * has Tx error occurred ? + * has Tx Missing Acknowledge error occurred ? + * has Arbitration Loss error occurred ? */ + tempisr = hcec->Instance->ISR; + if ((tempisr & (CEC_ISR_TXUDR|CEC_ISR_TXERR|CEC_ISR_TXACKE|CEC_ISR_ARBLST)) != 0) + { + /* copy ISR for error handling purposes */ + hcec->ErrorCode = tempisr; + /* clear all error flags by default */ + __HAL_CEC_CLEAR_FLAG(hcec, (CEC_ISR_TXUDR|CEC_ISR_TXERR|CEC_ISR_TXACKE|CEC_ISR_ARBLST)); + hcec->State = HAL_CEC_STATE_ERROR; + __HAL_UNLOCK(hcec); + return HAL_ERROR; + } + } + /* TXBR to clear BEFORE writing TXDR register */ + __HAL_CEC_CLEAR_FLAG(hcec,CEC_ISR_TXBR); + if (hcec->TxXferCount == 0) + { + /* if last byte transmission, set TX End of Message (TXEOM) bit */ + __HAL_CEC_LAST_BYTE_TX_SET(hcec); + } + hcec->Instance->TXDR = *pData++; + + /* error check after TX byte write up */ + tempisr = hcec->Instance->ISR; + if ((tempisr & (CEC_ISR_TXUDR|CEC_ISR_TXERR|CEC_ISR_TXACKE|CEC_ISR_ARBLST)) != 0) + { + /* copy ISR for error handling purposes */ + hcec->ErrorCode = tempisr; + /* clear all error flags by default */ + __HAL_CEC_CLEAR_FLAG(hcec, (CEC_ISR_TXUDR|CEC_ISR_TXERR|CEC_ISR_TXACKE|CEC_ISR_ARBLST)); + hcec->State = HAL_CEC_STATE_ERROR; + __HAL_UNLOCK(hcec); + return HAL_ERROR; + } + } /* end while (while (hcec->TxXferCount > 0)) */ + + + /* if no error up to this point, check that transmission is + * complete, that is wait until TXEOM is reset */ + tickstart = HAL_GetTick(); + + while (HAL_IS_BIT_SET(hcec->Instance->CR, CEC_CR_TXEOM)) + { + if(Timeout != HAL_MAX_DELAY) + { + if((HAL_GetTick() - tickstart) > Timeout) + { + hcec->State = HAL_CEC_STATE_ERROR; + __HAL_UNLOCK(hcec); + return HAL_TIMEOUT; + } + } + } + + /* Final error check once all bytes have been transmitted */ + tempisr = hcec->Instance->ISR; + if ((tempisr & (CEC_ISR_TXUDR|CEC_ISR_TXERR|CEC_ISR_TXACKE)) != 0) + { + /* copy ISR for error handling purposes */ + hcec->ErrorCode = tempisr; + /* clear all error flags by default */ + __HAL_CEC_CLEAR_FLAG(hcec, (CEC_ISR_TXUDR|CEC_ISR_TXERR|CEC_ISR_TXACKE)); + hcec->State = HAL_CEC_STATE_ERROR; + __HAL_UNLOCK(hcec); + return HAL_ERROR; + } + + hcec->State = HAL_CEC_STATE_READY; + __HAL_UNLOCK(hcec); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive data in blocking mode. Must be invoked when RXBR has been set. + * @param hcec: CEC handle + * @param pData: pointer to received data buffer. + * @param Timeout: Timeout duration. + * Note that the received data size is not known beforehand, the latter is known + * when the reception is complete and is stored in hcec->RxXferSize. + * hcec->RxXferSize is the sum of opcodes + operands (0 to 14 operands max). + * If only a header is received, hcec->RxXferSize = 0 + * @retval HAL status + */ +HAL_StatusTypeDef HAL_CEC_Receive(CEC_HandleTypeDef *hcec, uint8_t *pData, uint32_t Timeout) +{ + uint32_t temp; + uint32_t tickstart = 0; + + if (hcec->State == HAL_CEC_STATE_READY) + { + hcec->ErrorCode = HAL_CEC_ERROR_NONE; + if (pData == NULL ) + { + hcec->State = HAL_CEC_STATE_ERROR; + return HAL_ERROR; + } + + hcec->RxXferSize = 0; + /* Process Locked */ + __HAL_LOCK(hcec); + + + /* Rx loop until CEC_ISR_RXEND is set */ + while (HAL_IS_BIT_CLR(hcec->Instance->ISR, CEC_ISR_RXEND)) + { + tickstart = HAL_GetTick(); + /* Wait for next byte to be received */ + while (HAL_IS_BIT_CLR(hcec->Instance->ISR, CEC_ISR_RXBR)) + { + if(Timeout != HAL_MAX_DELAY) + { + if((HAL_GetTick() - tickstart) > Timeout) + { + hcec->State = HAL_CEC_STATE_TIMEOUT; + __HAL_UNLOCK(hcec); + return HAL_TIMEOUT; + } + } + /* any error so far ? + * has Rx Missing Acknowledge occurred ? + * has Rx Long Bit Period error occurred ? + * has Rx Short Bit Period error occurred ? + * has Rx Bit Rising error occurred ? + * has Rx Overrun error occurred ? */ + temp = (uint32_t) (hcec->Instance->ISR); + if ((temp & (CEC_ISR_RXACKE|CEC_ISR_LBPE|CEC_ISR_SBPE|CEC_ISR_BRE|CEC_ISR_RXOVR)) != 0) + { + /* copy ISR for error handling purposes */ + hcec->ErrorCode = temp; + /* clear all error flags by default */ + __HAL_CEC_CLEAR_FLAG(hcec, (CEC_ISR_RXACKE|CEC_ISR_LBPE|CEC_ISR_SBPE|CEC_ISR_BRE|CEC_ISR_RXOVR)); + hcec->State = HAL_CEC_STATE_ERROR; + __HAL_UNLOCK(hcec); + return HAL_ERROR; + } + } /* while (HAL_IS_BIT_CLR(hcec->Instance->ISR, CEC_ISR_RXBR)) */ + + + /* read received data */ + *pData++ = hcec->Instance->RXDR; + temp = (uint32_t) (hcec->Instance->ISR); + /* end of message ? */ + if ((temp & CEC_ISR_RXEND) != 0) + { + assert_param(IS_CEC_MSGSIZE(hcec->RxXferSize)); + __HAL_CEC_CLEAR_FLAG(hcec,CEC_ISR_RXEND); + hcec->State = HAL_CEC_STATE_READY; + __HAL_UNLOCK(hcec); + return HAL_OK; + } + + /* clear Rx-Byte Received flag */ + __HAL_CEC_CLEAR_FLAG(hcec,CEC_ISR_RXBR); + /* increment payload byte counter */ + hcec->RxXferSize++; + } /* while (HAL_IS_BIT_CLR(hcec->Instance->ISR, CEC_ISR_RXEND)) */ + + /* if the instructions below are executed, it means RXEND was set when RXBR was + * set for the first time: + * the code within the "while (HAL_IS_BIT_CLR(hcec->Instance->ISR, CEC_ISR_RXEND))" + * loop has not been executed and this means a single byte has been sent */ + *pData++ = hcec->Instance->RXDR; + /* only one header is received: RxXferSize is set to 0 (no operand, no opcode) */ + hcec->RxXferSize = 0; + __HAL_CEC_CLEAR_FLAG(hcec,CEC_ISR_RXEND); + + hcec->State = HAL_CEC_STATE_READY; + __HAL_UNLOCK(hcec); + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + + +/** + * @brief Send data in interrupt mode + * @param hcec: CEC handle + * @param DestinationAddress: destination logical address + * @param pData: pointer to input byte data buffer + * @param Size: amount of data to be sent in bytes (without counting the header). + * 0 means only the header is sent (ping operation). + * Maximum TX size is 15 bytes (1 opcode and up to 14 operands). + * @retval HAL status + */ +HAL_StatusTypeDef HAL_CEC_Transmit_IT(CEC_HandleTypeDef *hcec, uint8_t DestinationAddress, uint8_t *pData, uint32_t Size) +{ + uint8_t temp = 0; + /* if the IP isn't already busy and if there is no previous transmission + already pending due to arbitration lost */ + if (((hcec->State == HAL_CEC_STATE_READY) || (hcec->State == HAL_CEC_STATE_STANDBY_RX)) + && (__HAL_CEC_GET_TRANSMISSION_START_FLAG(hcec) == RESET)) + { + if((pData == NULL ) && (Size > 0)) + { + hcec->State = HAL_CEC_STATE_ERROR; + return HAL_ERROR; + } + + assert_param(IS_CEC_ADDRESS(DestinationAddress)); + assert_param(IS_CEC_MSGSIZE(Size)); + + /* Process Locked */ + __HAL_LOCK(hcec); + hcec->pTxBuffPtr = pData; + hcec->State = HAL_CEC_STATE_BUSY_TX; + hcec->ErrorCode = HAL_CEC_ERROR_NONE; + + /* Disable Peripheral to write CEC_IER register */ + __HAL_CEC_DISABLE(hcec); + + /* Enable the following two CEC Transmission interrupts as + * well as the following CEC Transmission Errors interrupts: + * Tx Byte Request IT + * End of Transmission IT + * Tx Missing Acknowledge IT + * Tx-Error IT + * Tx-Buffer Underrun IT + * Tx arbitration lost */ + __HAL_CEC_ENABLE_IT(hcec, CEC_IER_TXBRIE|CEC_IER_TXENDIE|CEC_IER_TX_ALL_ERR); + + /* Enable the Peripheral */ + __HAL_CEC_ENABLE(hcec); + + /* initialize the number of bytes to send, + * 0 means only one header is sent (ping operation) */ + hcec->TxXferCount = Size; + + /* Process Unlocked */ + __HAL_UNLOCK(hcec); + + /* in case of no payload (Size = 0), sender is only pinging the system; + * Set TX End of Message (TXEOM) bit, must be set before writing data to TXDR */ + if (Size == 0) + { + __HAL_CEC_LAST_BYTE_TX_SET(hcec); + } + + /* send header block */ + temp = ((uint32_t)hcec->Init.InitiatorAddress << CEC_INITIATOR_LSB_POS) | DestinationAddress; + hcec->Instance->TXDR = temp; + /* Set TX Start of Message (TXSOM) bit */ + __HAL_CEC_FIRST_BYTE_TX_SET(hcec); + + return HAL_OK; + } + /* if the IP is already busy or if there is a previous transmission + already pending due to arbitration loss */ + else if ((hcec->State == HAL_CEC_STATE_BUSY_TX) + || (__HAL_CEC_GET_TRANSMISSION_START_FLAG(hcec) != RESET)) + { + __HAL_LOCK(hcec); + /* set state to BUSY TX, in case it wasn't set already (case + * of transmission new attempt after arbitration loss) */ + if (hcec->State != HAL_CEC_STATE_BUSY_TX) + { + hcec->State = HAL_CEC_STATE_BUSY_TX; + } + + /* if all data have been sent */ + if(hcec->TxXferCount == 0) + { + /* Disable Peripheral to write CEC_IER register */ + __HAL_CEC_DISABLE(hcec); + + /* Disable the CEC Transmission Interrupts */ + __HAL_CEC_DISABLE_IT(hcec, CEC_IER_TXBRIE|CEC_IER_TXENDIE); + /* Disable the CEC Transmission Error Interrupts */ + __HAL_CEC_DISABLE_IT(hcec, CEC_IER_TX_ALL_ERR); + + /* Enable the Peripheral */ + __HAL_CEC_ENABLE(hcec); + + __HAL_CEC_CLEAR_FLAG(hcec,CEC_ISR_TXBR|CEC_ISR_TXEND); + + hcec->State = HAL_CEC_STATE_READY; + /* Call the Process Unlocked before calling the Tx call back API to give the possibility to + start again the Transmission under the Tx call back API */ + __HAL_UNLOCK(hcec); + + HAL_CEC_TxCpltCallback(hcec); + + return HAL_OK; + } + else + { + if (hcec->TxXferCount == 1) + { + /* if this is the last byte transmission, set TX End of Message (TXEOM) bit */ + __HAL_CEC_LAST_BYTE_TX_SET(hcec); + } + /* clear Tx-Byte request flag */ + __HAL_CEC_CLEAR_FLAG(hcec,CEC_ISR_TXBR); + hcec->Instance->TXDR = *hcec->pTxBuffPtr++; + hcec->TxXferCount--; + + /* Process Unlocked */ + __HAL_UNLOCK(hcec); + + return HAL_OK; + } + } + else + { + return HAL_BUSY; + } +} + + +/** + * @brief Receive data in interrupt mode. + * @param hcec: CEC handle + * @param pData: pointer to received data buffer. + * Note that the received data size is not known beforehand, the latter is known + * when the reception is complete and is stored in hcec->RxXferSize. + * hcec->RxXferSize is the sum of opcodes + operands (0 to 14 operands max). + * If only a header is received, hcec->RxXferSize = 0 + * @retval HAL status + */ +HAL_StatusTypeDef HAL_CEC_Receive_IT(CEC_HandleTypeDef *hcec, uint8_t *pData) +{ + if(hcec->State == HAL_CEC_STATE_READY) + { + if(pData == NULL ) + { + hcec->State = HAL_CEC_STATE_ERROR; + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(hcec); + hcec->RxXferSize = 0; + hcec->pRxBuffPtr = pData; + hcec->ErrorCode = HAL_CEC_ERROR_NONE; + /* the IP is moving to a ready to receive state */ + hcec->State = HAL_CEC_STATE_STANDBY_RX; + + /* Disable Peripheral to write CEC_IER register */ + __HAL_CEC_DISABLE(hcec); + + /* Enable the following CEC Reception Error Interrupts: + * Rx overrun + * Rx bit rising error + * Rx short bit period error + * Rx long bit period error + * Rx missing acknowledge */ + __HAL_CEC_ENABLE_IT(hcec, CEC_IER_RX_ALL_ERR); + + /* Process Unlocked */ + __HAL_UNLOCK(hcec); + + /* Enable the following two CEC Reception interrupts: + * Rx Byte Received IT + * End of Reception IT */ + __HAL_CEC_ENABLE_IT(hcec, CEC_IER_RXBRIE|CEC_IER_RXENDIE); + + __HAL_CEC_ENABLE(hcec); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + + + +/** + * @brief This function handles CEC interrupt requests. + * @param hcec: CEC handle + * @retval None + */ +void HAL_CEC_IRQHandler(CEC_HandleTypeDef *hcec) +{ + /* save interrupts register for further error or interrupts handling purposes */ + hcec->ErrorCode = hcec->Instance->ISR; + /* CEC TX missing acknowledge error interrupt occurred -------------------------------------*/ + if((__HAL_CEC_GET_IT(hcec, CEC_ISR_TXACKE) != RESET) && (__HAL_CEC_GET_IT_SOURCE(hcec, CEC_IER_TXACKEIE) != RESET)) + { + __HAL_CEC_CLEAR_FLAG(hcec, CEC_ISR_TXACKE); + hcec->State = HAL_CEC_STATE_ERROR; + } + + /* CEC transmit error interrupt occured --------------------------------------*/ + if((__HAL_CEC_GET_IT(hcec, CEC_ISR_TXERR) != RESET) && (__HAL_CEC_GET_IT_SOURCE(hcec, CEC_IER_TXERRIE) != RESET)) + { + __HAL_CEC_CLEAR_FLAG(hcec, CEC_ISR_TXERR); + hcec->State = HAL_CEC_STATE_ERROR; + } + + /* CEC TX underrun error interrupt occured --------------------------------------*/ + if((__HAL_CEC_GET_IT(hcec, CEC_ISR_TXUDR) != RESET) && (__HAL_CEC_GET_IT_SOURCE(hcec, CEC_IER_TXUDRIE) != RESET)) + { + __HAL_CEC_CLEAR_FLAG(hcec, CEC_ISR_TXUDR); + hcec->State = HAL_CEC_STATE_ERROR; + } + + /* CEC TX arbitration error interrupt occured --------------------------------------*/ + if((__HAL_CEC_GET_IT(hcec, CEC_ISR_ARBLST) != RESET) && (__HAL_CEC_GET_IT_SOURCE(hcec, CEC_IER_ARBLSTIE) != RESET)) + { + __HAL_CEC_CLEAR_FLAG(hcec, CEC_ISR_ARBLST); + hcec->State = HAL_CEC_STATE_ERROR; + } + + /* CEC RX overrun error interrupt occured --------------------------------------*/ + if((__HAL_CEC_GET_IT(hcec, CEC_ISR_RXOVR) != RESET) && (__HAL_CEC_GET_IT_SOURCE(hcec, CEC_IER_RXOVRIE) != RESET)) + { + __HAL_CEC_CLEAR_FLAG(hcec, CEC_ISR_RXOVR); + hcec->State = HAL_CEC_STATE_ERROR; + } + + /* CEC RX bit rising error interrupt occured --------------------------------------*/ + if((__HAL_CEC_GET_IT(hcec, CEC_ISR_BRE) != RESET) && (__HAL_CEC_GET_IT_SOURCE(hcec, CEC_IER_BREIE) != RESET)) + { + __HAL_CEC_CLEAR_FLAG(hcec, CEC_ISR_BRE); + hcec->State = HAL_CEC_STATE_ERROR; + } + + /* CEC RX short bit period error interrupt occured --------------------------------------*/ + if((__HAL_CEC_GET_IT(hcec, CEC_ISR_SBPE) != RESET) && (__HAL_CEC_GET_IT_SOURCE(hcec, CEC_IER_SBPEIE) != RESET)) + { + __HAL_CEC_CLEAR_FLAG(hcec, CEC_ISR_SBPE); + hcec->State = HAL_CEC_STATE_ERROR; + } + + /* CEC RX long bit period error interrupt occured --------------------------------------*/ + if((__HAL_CEC_GET_IT(hcec, CEC_ISR_LBPE) != RESET) && (__HAL_CEC_GET_IT_SOURCE(hcec, CEC_IER_LBPEIE) != RESET)) + { + __HAL_CEC_CLEAR_FLAG(hcec, CEC_ISR_LBPE); + hcec->State = HAL_CEC_STATE_ERROR; + } + + /* CEC RX missing acknowledge error interrupt occured --------------------------------------*/ + if((__HAL_CEC_GET_IT(hcec, CEC_ISR_RXACKE) != RESET) && (__HAL_CEC_GET_IT_SOURCE(hcec, CEC_IER_RXACKEIE) != RESET)) + { + __HAL_CEC_CLEAR_FLAG(hcec, CEC_ISR_RXACKE); + hcec->State = HAL_CEC_STATE_ERROR; + } + + if ((hcec->ErrorCode & CEC_ISR_ALL_ERROR) != 0) + { + HAL_CEC_ErrorCallback(hcec); + } + + /* CEC RX byte received interrupt ---------------------------------------------------*/ + if((__HAL_CEC_GET_IT(hcec, CEC_ISR_RXBR) != RESET) && (__HAL_CEC_GET_IT_SOURCE(hcec, CEC_IER_RXBRIE) != RESET)) + { + /* RXBR IT is cleared during HAL_CEC_Transmit_IT processing */ + CEC_Receive_IT(hcec); + } + + /* CEC RX end received interrupt ---------------------------------------------------*/ + if((__HAL_CEC_GET_IT(hcec, CEC_ISR_RXEND) != RESET) && (__HAL_CEC_GET_IT_SOURCE(hcec, CEC_IER_RXENDIE) != RESET)) + { + /* RXBR IT is cleared during HAL_CEC_Transmit_IT processing */ + CEC_Receive_IT(hcec); + } + + + /* CEC TX byte request interrupt ------------------------------------------------*/ + if((__HAL_CEC_GET_IT(hcec, CEC_ISR_TXBR) != RESET) &&(__HAL_CEC_GET_IT_SOURCE(hcec, CEC_IER_TXBRIE) != RESET)) + { + /* TXBR IT is cleared during HAL_CEC_Transmit_IT processing */ + CEC_Transmit_IT(hcec); + } + + /* CEC TX end interrupt ------------------------------------------------*/ + if((__HAL_CEC_GET_IT(hcec, CEC_ISR_TXEND) != RESET) &&(__HAL_CEC_GET_IT_SOURCE(hcec, CEC_IER_TXENDIE) != RESET)) + { + /* TXEND IT is cleared during HAL_CEC_Transmit_IT processing */ + CEC_Transmit_IT(hcec); + } + +} + + +/** + * @brief Tx Transfer completed callback + * @param hcec: CEC handle + * @retval None + */ + __weak void HAL_CEC_TxCpltCallback(CEC_HandleTypeDef *hcec) +{ + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_CEC_TxCpltCallback can be implemented in the user file + */ +} + +/** + * @brief Rx Transfer completed callback + * @param hcec: CEC handle + * @retval None + */ +__weak void HAL_CEC_RxCpltCallback(CEC_HandleTypeDef *hcec) +{ + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_CEC_TxCpltCallback can be implemented in the user file + */ +} + +/** + * @brief CEC error callbacks + * @param hcec: CEC handle + * @retval None + */ + __weak void HAL_CEC_ErrorCallback(CEC_HandleTypeDef *hcec) +{ + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_CEC_ErrorCallback can be implemented in the user file + */ +} + + +/** + * @brief Send data in interrupt mode + * @param hcec: CEC handle. + * Function called under interruption only, once + * interruptions have been enabled by HAL_CEC_Transmit_IT() + * @retval HAL status + */ +static HAL_StatusTypeDef CEC_Transmit_IT(CEC_HandleTypeDef *hcec) +{ + /* if the IP is already busy or if there is a previous transmission + already pending due to arbitration loss */ + if ((hcec->State == HAL_CEC_STATE_BUSY_TX) + || (__HAL_CEC_GET_TRANSMISSION_START_FLAG(hcec) != RESET)) + { + __HAL_LOCK(hcec); + /* set state to BUSY TX, in case it wasn't set already (case + * of transmission new attempt after arbitration loss) */ + if (hcec->State != HAL_CEC_STATE_BUSY_TX) + { + hcec->State = HAL_CEC_STATE_BUSY_TX; + } + + /* if all data have been sent */ + if(hcec->TxXferCount == 0) + { + /* Disable Peripheral to write CEC_IER register */ + __HAL_CEC_DISABLE(hcec); + + /* Disable the CEC Transmission Interrupts */ + __HAL_CEC_DISABLE_IT(hcec, CEC_IER_TXBRIE|CEC_IER_TXENDIE); + /* Disable the CEC Transmission Error Interrupts */ + __HAL_CEC_DISABLE_IT(hcec, CEC_IER_TX_ALL_ERR); + + /* Enable the Peripheral */ + __HAL_CEC_ENABLE(hcec); + + __HAL_CEC_CLEAR_FLAG(hcec,CEC_ISR_TXBR|CEC_ISR_TXEND); + + hcec->State = HAL_CEC_STATE_READY; + /* Call the Process Unlocked before calling the Tx call back API to give the possibility to + start again the Transmission under the Tx call back API */ + __HAL_UNLOCK(hcec); + + HAL_CEC_TxCpltCallback(hcec); + + return HAL_OK; + } + else + { + if (hcec->TxXferCount == 1) + { + /* if this is the last byte transmission, set TX End of Message (TXEOM) bit */ + __HAL_CEC_LAST_BYTE_TX_SET(hcec); + } + /* clear Tx-Byte request flag */ + __HAL_CEC_CLEAR_FLAG(hcec,CEC_ISR_TXBR); + hcec->Instance->TXDR = *hcec->pTxBuffPtr++; + hcec->TxXferCount--; + + /* Process Unlocked */ + __HAL_UNLOCK(hcec); + + return HAL_OK; + } + } + else + { + return HAL_BUSY; + } +} + + +/** + * @brief Receive data in interrupt mode. + * @param hcec: CEC handle. + * Function called under interruption only, once + * interruptions have been enabled by HAL_CEC_Receive_IT() + * @retval HAL status + */ +static HAL_StatusTypeDef CEC_Receive_IT(CEC_HandleTypeDef *hcec) +{ + uint32_t tempisr; + + /* Three different conditions are tested to carry out the RX IT processing: + * - the IP is in reception stand-by (the IP state is HAL_CEC_STATE_STANDBY_RX) and + * the reception of the first byte is starting + * - a message reception is already on-going (the IP state is HAL_CEC_STATE_BUSY_RX) + * and a new byte is being received + * - a transmission has just been started (the IP state is HAL_CEC_STATE_BUSY_TX) + * but has been interrupted by a new message reception or discarded due to + * arbitration loss: the reception of the first or higher priority message + * (the arbitration winner) is starting */ + if ((hcec->State == HAL_CEC_STATE_STANDBY_RX) + || (hcec->State == HAL_CEC_STATE_BUSY_RX) + || (hcec->State == HAL_CEC_STATE_BUSY_TX)) + { + /* reception is starting */ + hcec->State = HAL_CEC_STATE_BUSY_RX; + tempisr = (uint32_t) (hcec->Instance->ISR); + if ((tempisr & CEC_ISR_RXBR) != 0) + { + /* Process Locked */ + __HAL_LOCK(hcec); + /* read received byte */ + *hcec->pRxBuffPtr++ = hcec->Instance->RXDR; + /* if last byte has been received */ + if ((tempisr & CEC_ISR_RXEND) != 0) + { + /* clear IT */ + __HAL_CEC_CLEAR_FLAG(hcec,CEC_ISR_RXBR|CEC_ISR_RXEND); + /* RX interrupts are not disabled at this point. + * Indeed, to disable the IT, the IP must be disabled first + * which resets the TXSOM flag. In case of arbitration loss, + * this leads to a transmission abort. + * Therefore, RX interruptions disabling if so required, + * is done in HAL_CEC_RxCpltCallback */ + + /* IP state is moved to READY. + * If the IP must remain in standby mode to listen + * any new message, it is up to HAL_CEC_RxCpltCallback + * to move it again to HAL_CEC_STATE_STANDBY_RX */ + hcec->State = HAL_CEC_STATE_READY; + + /* Call the Process Unlocked before calling the Rx call back API */ + __HAL_UNLOCK(hcec); + HAL_CEC_RxCpltCallback(hcec); + + return HAL_OK; + } + __HAL_CEC_CLEAR_FLAG(hcec, CEC_ISR_RXBR); + + hcec->RxXferSize++; + /* Process Unlocked */ + __HAL_UNLOCK(hcec); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } + } + else + { + return HAL_BUSY; + } +} + + + +/** + * @} + */ + +/** @defgroup HAL_CEC_Group3 Peripheral Control function + * @brief CEC control functions + * +@verbatim + =============================================================================== + ##### Peripheral Control function ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to control the CEC. + (+) HAL_CEC_GetState() API can be helpful to check in run-time the state of the CEC peripheral. +@endverbatim + * @{ + */ + + + + + +/** + * @brief return the CEC state + * @param hcec: CEC handle + * @retval HAL state + */ +HAL_CEC_StateTypeDef HAL_CEC_GetState(CEC_HandleTypeDef *hcec) +{ + return hcec->State; +} + +/** +* @brief Return the CEC error code +* @param hcec : pointer to a CEC_HandleTypeDef structure that contains + * the configuration information for the specified CEC. +* @retval CEC Error Code +*/ +uint32_t HAL_CEC_GetError(CEC_HandleTypeDef *hcec) +{ + return hcec->ErrorCode; +} + +/** + * @} + */ + +/** + * @} + */ + +#endif /* defined(STM32F042x6) || defined(STM32F048xx) || defined(STM32F051x8) || defined(STM32F058xx) || */ + /* defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx)*/ + +#endif /* HAL_CEC_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_cec.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_cec.h new file mode 100644 index 0000000000..20c64d39f4 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_cec.h @@ -0,0 +1,566 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_cec.h + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief Header file of CEC HAL module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32F0xx_HAL_CEC_H +#define __STM32F0xx_HAL_CEC_H + +#ifdef __cplusplus + extern "C" { +#endif + +#if defined(STM32F042x6) || defined(STM32F048xx) ||\ + defined(STM32F051x8) || defined(STM32F058xx) ||\ + defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal_def.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @addtogroup CEC + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ + +/** + * @brief CEC Init Structure definition + */ +typedef struct +{ + uint32_t SignalFreeTime; /*!< Set SFT field, specifies the Signal Free Time. + It can be one of @ref CEC_Signal_Free_Time + and belongs to the set {0,...,7} where + 0x0 is the default configuration + else means 0.5 + (SignalFreeTime - 1) nominal data bit periods */ + + uint32_t Tolerance; /*!< Set RXTOL bit, specifies the tolerance accepted on the received waveforms, + it can be a value of @ref CEC_Tolerance : it is either CEC_STANDARD_TOLERANCE + or CEC_EXTENDED_TOLERANCE */ + + uint32_t BRERxStop; /*!< Set BRESTP bit @ref CEC_BRERxStop : specifies whether or not a Bit Rising Error stops the reception. + CEC_NO_RX_STOP_ON_BRE: reception is not stopped. + CEC_RX_STOP_ON_BRE: reception is stopped. */ + + uint32_t BREErrorBitGen; /*!< Set BREGEN bit @ref CEC_BREErrorBitGen : specifies whether or not an Error-Bit is generated on the + CEC line upon Bit Rising Error detection. + CEC_BRE_ERRORBIT_NO_GENERATION: no error-bit generation. + CEC_BRE_ERRORBIT_GENERATION: error-bit generation if BRESTP is set. */ + + uint32_t LBPEErrorBitGen; /*!< Set LBPEGEN bit @ref CEC_LBPEErrorBitGen : specifies whether or not an Error-Bit is generated on the + CEC line upon Long Bit Period Error detection. + CEC_LBPE_ERRORBIT_NO_GENERATION: no error-bit generation. + CEC_LBPE_ERRORBIT_GENERATION: error-bit generation. */ + + uint32_t BroadcastMsgNoErrorBitGen; /*!< Set BRDNOGEN bit @ref CEC_BroadCastMsgErrorBitGen : allows to avoid an Error-Bit generation on the CEC line + upon an error detected on a broadcast message. + + It supersedes BREGEN and LBPEGEN bits for a broadcast message error handling. It can take two values: + + 1) CEC_BROADCASTERROR_ERRORBIT_GENERATION. + a) BRE detection: error-bit generation on the CEC line if BRESTP=CEC_RX_STOP_ON_BRE + and BREGEN=CEC_BRE_ERRORBIT_NO_GENERATION. + b) LBPE detection: error-bit generation on the CEC line + if LBPGEN=CEC_LBPE_ERRORBIT_NO_GENERATION. + + 2) CEC_BROADCASTERROR_NO_ERRORBIT_GENERATION. + no error-bit generation in case neither a) nor b) are satisfied. Additionally, + there is no error-bit generation in case of Short Bit Period Error detection in + a broadcast message while LSTN bit is set. */ + + uint32_t SignalFreeTimeOption; /*!< Set SFTOP bit @ref CEC_SFT_Option : specifies when SFT timer starts. + CEC_SFT_START_ON_TXSOM SFT: timer starts when TXSOM is set by software. + CEC_SFT_START_ON_TX_RX_END: SFT timer starts automatically at the end of message transmission/reception. */ + + uint32_t OwnAddress; /*!< Set OAR field, specifies CEC device address within a 15-bit long field */ + + uint32_t ListenMode; /*!< Set LSTN bit @ref CEC_Listening_Mode : specifies device listening mode. It can take two values: + + CEC_REDUCED_LISTENING_MODE: CEC peripheral receives only message addressed to its + own address (OAR). Messages addressed to different destination are ignored. + Broadcast messages are always received. + + CEC_FULL_LISTENING_MODE: CEC peripheral receives messages addressed to its own + address (OAR) with positive acknowledge. Messages addressed to different destination + are received, but without interfering with the CEC bus: no acknowledge sent. */ + + uint8_t InitiatorAddress; /* Initiator address (source logical address, sent in each header) */ + +}CEC_InitTypeDef; + +/** + * @brief HAL CEC State structures definition + */ +typedef enum +{ + HAL_CEC_STATE_RESET = 0x00, /*!< Peripheral Reset state */ + HAL_CEC_STATE_READY = 0x01, /*!< Peripheral Initialized and ready for use */ + HAL_CEC_STATE_BUSY = 0x02, /*!< an internal process is ongoing */ + HAL_CEC_STATE_BUSY_TX = 0x03, /*!< Data Transmission process is ongoing */ + HAL_CEC_STATE_BUSY_RX = 0x04, /*!< Data Reception process is ongoing */ + HAL_CEC_STATE_STANDBY_RX = 0x05, /*!< IP ready to receive, doesn't prevent IP to transmit */ + HAL_CEC_STATE_TIMEOUT = 0x06, /*!< Timeout state */ + HAL_CEC_STATE_ERROR = 0x07 /*!< State Error */ +}HAL_CEC_StateTypeDef; + +/** + * @brief HAL Error structures definition + */ +typedef enum +{ + HAL_CEC_ERROR_NONE = (uint32_t) 0x0, /*!< no error */ + HAL_CEC_ERROR_RXOVR = CEC_ISR_RXOVR, /*!< CEC Rx-Overrun */ + HAL_CEC_ERROR_BRE = CEC_ISR_BRE, /*!< CEC Rx Bit Rising Error */ + HAL_CEC_ERROR_SBPE = CEC_ISR_SBPE, /*!< CEC Rx Short Bit period Error */ + HAL_CEC_ERROR_LBPE = CEC_ISR_LBPE, /*!< CEC Rx Long Bit period Error */ + HAL_CEC_ERROR_RXACKE = CEC_ISR_RXACKE, /*!< CEC Rx Missing Acknowledge */ + HAL_CEC_ERROR_ARBLST = CEC_ISR_ARBLST, /*!< CEC Arbitration Lost */ + HAL_CEC_ERROR_TXUDR = CEC_ISR_TXUDR, /*!< CEC Tx-Buffer Underrun */ + HAL_CEC_ERROR_TXERR = CEC_ISR_TXERR, /*!< CEC Tx-Error */ + HAL_CEC_ERROR_TXACKE = CEC_ISR_TXACKE /*!< CEC Tx Missing Acknowledge */ +} +HAL_CEC_ErrorTypeDef; + +/** + * @brief CEC handle Structure definition + */ +typedef struct +{ + CEC_TypeDef *Instance; /* CEC registers base address */ + + CEC_InitTypeDef Init; /* CEC communication parameters */ + + uint8_t *pTxBuffPtr; /* Pointer to CEC Tx transfer Buffer */ + + uint16_t TxXferCount; /* CEC Tx Transfer Counter */ + + uint8_t *pRxBuffPtr; /* Pointer to CEC Rx transfer Buffer */ + + uint16_t RxXferSize; /* CEC Rx Transfer size, 0: header received only */ + + uint32_t ErrorCode; /* For errors handling purposes, copy of ISR register + in case error is reported */ + + HAL_LockTypeDef Lock; /* Locking object */ + + HAL_CEC_StateTypeDef State; /* CEC communication state */ + +}CEC_HandleTypeDef; + + + +/* Exported constants --------------------------------------------------------*/ +/** @defgroup CEC_Exported_Constants + * @{ + */ + +/** @defgroup CEC_Signal_Free_Time Signal Free Time setting parameter + * @{ + */ +#define CEC_DEFAULT_SFT ((uint32_t)0x00000000) +#define CEC_0_5_BITPERIOD_SFT ((uint32_t)0x00000001) +#define CEC_1_5_BITPERIOD_SFT ((uint32_t)0x00000002) +#define CEC_2_5_BITPERIOD_SFT ((uint32_t)0x00000003) +#define CEC_3_5_BITPERIOD_SFT ((uint32_t)0x00000004) +#define CEC_4_5_BITPERIOD_SFT ((uint32_t)0x00000005) +#define CEC_5_5_BITPERIOD_SFT ((uint32_t)0x00000006) +#define CEC_6_5_BITPERIOD_SFT ((uint32_t)0x00000007) +#define IS_CEC_SIGNALFREETIME(SFT) ((SFT) <= CEC_CFGR_SFT) +/** + * @} + */ + +/** @defgroup CEC_Tolerance Receiver Tolerance + * @{ + */ +#define CEC_STANDARD_TOLERANCE ((uint32_t)0x00000000) +#define CEC_EXTENDED_TOLERANCE ((uint32_t)CEC_CFGR_RXTOL) +#define IS_CEC_TOLERANCE(RXTOL) (((RXTOL) == CEC_STANDARD_TOLERANCE) || \ + ((RXTOL) == CEC_EXTENDED_TOLERANCE)) +/** + * @} + */ + +/** @defgroup CEC_BRERxStop Reception Stop on Error + * @{ + */ +#define CEC_NO_RX_STOP_ON_BRE ((uint32_t)0x00000000) +#define CEC_RX_STOP_ON_BRE ((uint32_t)CEC_CFGR_BRESTP) +#define IS_CEC_BRERXSTOP(BRERXSTOP) (((BRERXSTOP) == CEC_NO_RX_STOP_ON_BRE) || \ + ((BRERXSTOP) == CEC_RX_STOP_ON_BRE)) +/** + * @} + */ + +/** @defgroup CEC_BREErrorBitGen Error Bit Generation if Bit Rise Error reported + * @{ + */ +#define CEC_BRE_ERRORBIT_NO_GENERATION ((uint32_t)0x00000000) +#define CEC_BRE_ERRORBIT_GENERATION ((uint32_t)CEC_CFGR_BREGEN) +#define IS_CEC_BREERRORBITGEN(ERRORBITGEN) (((ERRORBITGEN) == CEC_BRE_ERRORBIT_NO_GENERATION) || \ + ((ERRORBITGEN) == CEC_BRE_ERRORBIT_GENERATION)) +/** + * @} + */ + +/** @defgroup CEC_LBPEErrorBitGen Error Bit Generation if Long Bit Period Error reported + * @{ + */ +#define CEC_LBPE_ERRORBIT_NO_GENERATION ((uint32_t)0x00000000) +#define CEC_LBPE_ERRORBIT_GENERATION ((uint32_t)CEC_CFGR_LBPEGEN) +#define IS_CEC_LBPEERRORBITGEN(ERRORBITGEN) (((ERRORBITGEN) == CEC_LBPE_ERRORBIT_NO_GENERATION) || \ + ((ERRORBITGEN) == CEC_LBPE_ERRORBIT_GENERATION)) +/** + * @} + */ + +/** @defgroup CEC_BroadCastMsgErrorBitGen Error Bit Generation on Broadcast message + * @{ + */ +#define CEC_BROADCASTERROR_ERRORBIT_GENERATION ((uint32_t)0x00000000) +#define CEC_BROADCASTERROR_NO_ERRORBIT_GENERATION ((uint32_t)CEC_CFGR_BRDNOGEN) +#define IS_CEC_BROADCASTERROR_NO_ERRORBIT_GENERATION(ERRORBITGEN) (((ERRORBITGEN) == CEC_BROADCASTERROR_ERRORBIT_GENERATION) || \ + ((ERRORBITGEN) == CEC_BROADCASTERROR_NO_ERRORBIT_GENERATION)) +/** + * @} + */ + +/** @defgroup CEC_SFT_Option Signal Free Time start option + * @{ + */ +#define CEC_SFT_START_ON_TXSOM ((uint32_t)0x00000000) +#define CEC_SFT_START_ON_TX_RX_END ((uint32_t)CEC_CFGR_SFTOPT) +#define IS_CEC_SFTOP(SFTOP) (((SFTOP) == CEC_SFT_START_ON_TXSOM) || \ + ((SFTOP) == CEC_SFT_START_ON_TX_RX_END)) +/** + * @} + */ + +/** @defgroup CEC_Listening_Mode Listening mode option + * @{ + */ +#define CEC_REDUCED_LISTENING_MODE ((uint32_t)0x00000000) +#define CEC_FULL_LISTENING_MODE ((uint32_t)CEC_CFGR_LSTN) +#define IS_CEC_LISTENING_MODE(MODE) (((MODE) == CEC_REDUCED_LISTENING_MODE) || \ + ((MODE) == CEC_FULL_LISTENING_MODE)) +/** + * @} + */ + +/** @defgroup CEC_ALL_ERROR all RX or TX errors flags in CEC ISR register + * @{ + */ +#define CEC_ISR_ALL_ERROR ((uint32_t)CEC_ISR_RXOVR|CEC_ISR_BRE|CEC_ISR_SBPE|CEC_ISR_LBPE|CEC_ISR_RXACKE|\ + CEC_ISR_ARBLST|CEC_ISR_TXUDR|CEC_ISR_TXERR|CEC_ISR_TXACKE) +/** + * @} + */ + +/** @defgroup CEC_IER_ALL_RX all RX errors interrupts enabling flag + * @{ + */ +#define CEC_IER_RX_ALL_ERR ((uint32_t)CEC_IER_RXACKEIE|CEC_IER_LBPEIE|CEC_IER_SBPEIE|CEC_IER_BREIE|CEC_IER_RXOVRIE) +/** + * @} + */ + +/** @defgroup CEC_IER_ALL_TX all TX errors interrupts enabling flag + * @{ + */ +#define CEC_IER_TX_ALL_ERR ((uint32_t)CEC_IER_TXACKEIE|CEC_IER_TXERRIE|CEC_IER_TXUDRIE|CEC_IER_ARBLSTIE) +/** + * @} + */ + +/** @defgroup CEC_OAR_Position Device Own Address position in CEC CFGR register + * @{ + */ +#define CEC_CFGR_OAR_LSB_POS ((uint32_t) 16) +/** + * @} + */ + +/** @defgroup CEC_Initiator_Position Initiator logical address position in message header + * @{ + */ +#define CEC_INITIATOR_LSB_POS ((uint32_t) 4) +/** + * @} + */ + +/** + * @} + */ + +/* Exported macros -----------------------------------------------------------*/ +/** @defgroup CEC_Exported_Macros + * @{ + */ + +/** @brief Reset CEC handle state + * @param __HANDLE__: CEC handle. + * @retval None + */ +#define __HAL_CEC_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_CEC_STATE_RESET) + +/** @brief Checks whether or not the specified CEC interrupt flag is set. + * @param __HANDLE__: specifies the CEC Handle. + * @param __INTERRUPT__: specifies the interrupt to check. + * This parameter can be one of the following values: + * @arg CEC_ISR_RXBR : Rx-Byte Received + * @arg CEC_ISR_RXEND : End of Reception + * @arg CEC_ISR_RXOVR : Rx Overrun + * @arg CEC_ISR_BRE : Rx Bit Rising Error + * @arg CEC_ISR_SBPE : Rx Short Bit Period Error + * @arg CEC_ISR_LBPE : Rx Long Bit Period Error + * @arg CEC_ISR_RXACKE : Rx Missing Acknowledge + * @arg CEC_ISR_ARBLST : Arbitration lost + * @arg CEC_ISR_TXBR : Tx-Byte Request + * @arg CEC_ISR_TXEND : End of Transmission + * @arg CEC_ISR_TXUDR : Tx-buffer Underrun + * @arg CEC_ISR_TXERR : Tx Error + * @arg CEC_ISR_TXACKE : Tx Missing Acknowledge + * @retval ITStatus + */ +#define __HAL_CEC_GET_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->ISR & (__INTERRUPT__)) + +/** @brief Clears the interrupt or status flag when raised (write at 1) + * @param __HANDLE__: specifies the CEC Handle. + * @param __FLAG__: specifies the interrupt/status flag to clear. + * This parameter can be one of the following values: + * @arg CEC_ISR_RXBR : Rx-Byte Received + * @arg CEC_ISR_RXEND : End of Reception + * @arg CEC_ISR_RXOVR : Rx Overrun + * @arg CEC_ISR_BRE : Rx Bit Rising Error + * @arg CEC_ISR_SBPE : Rx Short Bit Period Error + * @arg CEC_ISR_LBPE : Rx Long Bit Period Error + * @arg CEC_ISR_RXACKE : Rx Missing Acknowledge + * @arg CEC_ISR_ARBLST : Arbitration lost + * @arg CEC_ISR_TXBR : Tx-Byte Request + * @arg CEC_ISR_TXEND : End of Transmission + * @arg CEC_ISR_TXUDR : Tx-buffer Underrun + * @arg CEC_ISR_TXERR : Tx Error + * @arg CEC_ISR_TXACKE : Tx Missing Acknowledge + * @retval none + */ +#define __HAL_CEC_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->ISR |= (__FLAG__)) + +/** @brief Enables the specified CEC interrupt. + * @param __HANDLE__: specifies the CEC Handle. + * @param __INTERRUPT__: specifies the CEC interrupt to enable. + * This parameter can be one of the following values: + * @arg CEC_IER_RXBRIE : Rx-Byte Received IT Enable + * @arg CEC_IER_RXENDIE : End Of Reception IT Enable + * @arg CEC_IER_RXOVRIE : Rx-Overrun IT Enable + * @arg CEC_IER_BREIE : Rx Bit Rising Error IT Enable + * @arg CEC_IER_SBPEIE : Rx Short Bit period Error IT Enable + * @arg CEC_IER_LBPEIE : Rx Long Bit period Error IT Enable + * @arg CEC_IER_RXACKEIE : Rx Missing Acknowledge IT Enable + * @arg CEC_IER_ARBLSTIE : Arbitration Lost IT Enable + * @arg CEC_IER_TXBRIE : Tx Byte Request IT Enable + * @arg CEC_IER_TXENDIE : End of Transmission IT Enable + * @arg CEC_IER_TXUDRIE : Tx-Buffer Underrun IT Enable + * @arg CEC_IER_TXERRIE : Tx-Error IT Enable + * @arg CEC_IER_TXACKEIE : Tx Missing Acknowledge IT Enable + * @retval none + */ +#define __HAL_CEC_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->IER |= (__INTERRUPT__)) + +/** @brief Disables the specified CEC interrupt. + * @param __HANDLE__: specifies the CEC Handle. + * @param __INTERRUPT__: specifies the CEC interrupt to disable. + * This parameter can be one of the following values: + * @arg CEC_IER_RXBRIE : Rx-Byte Received IT Enable + * @arg CEC_IER_RXENDIE : End Of Reception IT Enable + * @arg CEC_IER_RXOVRIE : Rx-Overrun IT Enable + * @arg CEC_IER_BREIE : Rx Bit Rising Error IT Enable + * @arg CEC_IER_SBPEIE : Rx Short Bit period Error IT Enable + * @arg CEC_IER_LBPEIE : Rx Long Bit period Error IT Enable + * @arg CEC_IER_RXACKEIE : Rx Missing Acknowledge IT Enable + * @arg CEC_IER_ARBLSTIE : Arbitration Lost IT Enable + * @arg CEC_IER_TXBRIE : Tx Byte Request IT Enable + * @arg CEC_IER_TXENDIE : End of Transmission IT Enable + * @arg CEC_IER_TXUDRIE : Tx-Buffer Underrun IT Enable + * @arg CEC_IER_TXERRIE : Tx-Error IT Enable + * @arg CEC_IER_TXACKEIE : Tx Missing Acknowledge IT Enable + * @retval none + */ +#define __HAL_CEC_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->IER &= (~(__INTERRUPT__))) + +/** @brief Checks whether or not the specified CEC interrupt is enabled. + * @param __HANDLE__: specifies the CEC Handle. + * @param __INTERRUPT__: specifies the CEC interrupt to check. + * This parameter can be one of the following values: + * @arg CEC_IER_RXBRIE : Rx-Byte Received IT Enable + * @arg CEC_IER_RXENDIE : End Of Reception IT Enable + * @arg CEC_IER_RXOVRIE : Rx-Overrun IT Enable + * @arg CEC_IER_BREIE : Rx Bit Rising Error IT Enable + * @arg CEC_IER_SBPEIE : Rx Short Bit period Error IT Enable + * @arg CEC_IER_LBPEIE : Rx Long Bit period Error IT Enable + * @arg CEC_IER_RXACKEIE : Rx Missing Acknowledge IT Enable + * @arg CEC_IER_ARBLSTIE : Arbitration Lost IT Enable + * @arg CEC_IER_TXBRIE : Tx Byte Request IT Enable + * @arg CEC_IER_TXENDIE : End of Transmission IT Enable + * @arg CEC_IER_TXUDRIE : Tx-Buffer Underrun IT Enable + * @arg CEC_IER_TXERRIE : Tx-Error IT Enable + * @arg CEC_IER_TXACKEIE : Tx Missing Acknowledge IT Enable + * @retval FlagStatus + */ +#define __HAL_CEC_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->IER & (__INTERRUPT__)) + +/** @brief Enables the CEC device + * @param __HANDLE__: specifies the CEC Handle. + * @retval none + */ +#define __HAL_CEC_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= CEC_CR_CECEN) + +/** @brief Disables the CEC device + * @param __HANDLE__: specifies the CEC Handle. + * @retval none + */ +#define __HAL_CEC_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~CEC_CR_CECEN) + +/** @brief Set Transmission Start flag + * @param __HANDLE__: specifies the CEC Handle. + * @retval none + */ +#define __HAL_CEC_FIRST_BYTE_TX_SET(__HANDLE__) ((__HANDLE__)->Instance->CR |= CEC_CR_TXSOM) + +/** @brief Set Transmission End flag + * @param __HANDLE__: specifies the CEC Handle. + * @retval none + * If the CEC message consists of only one byte, TXEOM must be set before of TXSOM. + */ +#define __HAL_CEC_LAST_BYTE_TX_SET(__HANDLE__) ((__HANDLE__)->Instance->CR |= CEC_CR_TXEOM) + +/** @brief Get Transmission Start flag + * @param __HANDLE__: specifies the CEC Handle. + * @retval FlagStatus + */ +#define __HAL_CEC_GET_TRANSMISSION_START_FLAG(__HANDLE__) ((__HANDLE__)->Instance->CR & CEC_CR_TXSOM) + +/** @brief Get Transmission End flag + * @param __HANDLE__: specifies the CEC Handle. + * @retval FlagStatus + */ +#define __HAL_CEC_GET_TRANSMISSION_END_FLAG(__HANDLE__) ((__HANDLE__)->Instance->CR & CEC_CR_TXEOM) + +/** @brief Clear OAR register + * @param __HANDLE__: specifies the CEC Handle. + * @retval none + */ +#define __HAL_CEC_CLEAR_OAR(__HANDLE__) CLEAR_BIT((__HANDLE__)->Instance->CFGR, CEC_CFGR_OAR) + +/** @brief Set OAR register (without resetting previously set address in case of multi-address mode) + * To reset OAR, __HAL_CEC_CLEAR_OAR() needs to be called beforehand + * @param __HANDLE__: specifies the CEC Handle. + * @param __ADDRESS__: Own Address value (CEC logical address is identified by bit position) + * @retval none + */ +#define __HAL_CEC_SET_OAR(__HANDLE__,__ADDRESS__) SET_BIT((__HANDLE__)->Instance->CFGR, (__ADDRESS__)<< CEC_CFGR_OAR_LSB_POS) + +/** @brief Check CEC device Own Address Register (OAR) setting. + * OAR address is written in a 15-bit field within CEC_CFGR register. + * @param __ADDRESS__: CEC own address. + * @retval Test result (TRUE or FALSE). + */ +#define IS_CEC_OAR_ADDRESS(__ADDRESS__) ((__ADDRESS__) <= 0x07FFF) + +/** @brief Check CEC initiator or destination logical address setting. + * Initiator and destination addresses are coded over 4 bits. + * @param __ADDRESS__: CEC initiator or logical address. + * @retval Test result (TRUE or FALSE). + */ +#define IS_CEC_ADDRESS(__ADDRESS__) ((__ADDRESS__) <= 0xF) + +/** @brief Check CEC message size. + * The message size is the payload size: without counting the header, + * it varies from 0 byte (ping operation, one header only, no payload) to + * 15 bytes (1 opcode and up to 14 operands following the header). + * @param __SIZE__: CEC message size. + * @retval Test result (TRUE or FALSE). + */ +#define IS_CEC_MSGSIZE(__SIZE__) ((__SIZE__) <= 0xF) + +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/* Initialization and de-initialization functions ****************************/ +HAL_StatusTypeDef HAL_CEC_Init(CEC_HandleTypeDef *hcec); +HAL_StatusTypeDef HAL_CEC_DeInit(CEC_HandleTypeDef *hcec); +void HAL_CEC_MspInit(CEC_HandleTypeDef *hcec); +void HAL_CEC_MspDeInit(CEC_HandleTypeDef *hcec); + + +/* I/O operation functions ***************************************************/ +HAL_StatusTypeDef HAL_CEC_Transmit(CEC_HandleTypeDef *hcec, uint8_t DestinationAddress, uint8_t *pData, uint32_t Size, uint32_t Timeout); +HAL_StatusTypeDef HAL_CEC_Receive(CEC_HandleTypeDef *hcec, uint8_t *pData, uint32_t Timeout); +HAL_StatusTypeDef HAL_CEC_Transmit_IT(CEC_HandleTypeDef *hcec, uint8_t DestinationAddress, uint8_t *pData, uint32_t Size); +HAL_StatusTypeDef HAL_CEC_Receive_IT(CEC_HandleTypeDef *hcec, uint8_t *pData); +void HAL_CEC_IRQHandler(CEC_HandleTypeDef *hcec); +void HAL_CEC_TxCpltCallback(CEC_HandleTypeDef *hcec); +void HAL_CEC_RxCpltCallback(CEC_HandleTypeDef *hcec); +void HAL_CEC_ErrorCallback(CEC_HandleTypeDef *hcec); + + +/* Peripheral State functions ************************************************/ +HAL_CEC_StateTypeDef HAL_CEC_GetState(CEC_HandleTypeDef *hcec); +uint32_t HAL_CEC_GetError(CEC_HandleTypeDef *hcec); + +/** + * @} + */ + +/** + * @} + */ + +#endif /* defined(STM32F042x6) || defined(STM32F048xx) || */ + /* defined(STM32F051x8) || defined(STM32F058xx) || */ + /* defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx)*/ +#ifdef __cplusplus +} +#endif + +#endif /* __STM32F0xx_HAL_CEC_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_comp.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_comp.c new file mode 100644 index 0000000000..85e4c0210f --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_comp.c @@ -0,0 +1,689 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_comp.c + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief COMP HAL module driver. + * + * This file provides firmware functions to manage the following + * functionalities of the COMP peripheral: + * + Initialization/de-initialization functions + * + I/O operation functions + * + Peripheral Control functions + * + Peripheral State functions + * + @verbatim +================================================================================ + ##### COMP Peripheral features ##### +================================================================================ + + [..] + The STM32F0xx device family integrates up to 2 analog comparators COMP1 and COMP2: + (#) The non inverting input and inverting input can be set to GPIO pins + as shown in table1. COMP Inputs below. + + (#) The COMP output is available using HAL_COMP_GetOutputLevel() + and can be set on GPIO pins. Refer to table 2. COMP Outputs below. + + (#) The COMP output can be redirected to embedded timers (TIM1, TIM2 and TIM3) + Refer to table 3. COMP Outputs redirection to embedded timers below. + + (#) The comparators COMP1 and COMP2 can be combined in window mode. + + (#) The comparators have interrupt capability with wake-up + from Sleep and Stop modes (through the EXTI controller): + (++) COMP1 is internally connected to EXTI Line 21 + (++) COMP2 is internally connected to EXTI Line 22 + From the corresponding IRQ handler, the right interrupt source can be retrieved with the + macro __HAL_COMP_EXTI_GET_FLAG(). Possible values are: + (++) COMP_EXTI_LINE_COMP1_EVENT + (++) COMP_EXTI_LINE_COMP2_EVENT + + +[..] Table 1. COMP Inputs for the STM32F05x and STM32F07x devices + +--------------------------------------------------+ + | | | COMP1 | COMP2 | + |-----------------|----------------|---------------| + | | 1/4 VREFINT | OK | OK | + | | 1/2 VREFINT | OK | OK | + | | 3/4 VREFINT | OK | OK | + | Inverting Input | VREFINT | OK | OK | + | | DAC1 OUT (PA4) | OK | OK | + | | DAC2 OUT (PA5) | OK | OK | + | | IO1 | PA0 | PA2 | + |-----------------|----------------|-------|-------| + | Non Inverting | | PA1 | PA3 | + | Input | | | | + +--------------------------------------------------+ + + [..] Table 2. COMP Outputs for the STM32F05x and STM32F07x devices + +---------------+ + | COMP1 | COMP2 | + |-------|-------| + | PA0 | PA2 | + | PA6 | PA7 | + | PA11 | PA12 | + +---------------+ + + [..] Table 3. COMP Outputs redirection to embedded timers for the STM32F05x and STM32F07x devices + +---------------------------------+ + | COMP1 | COMP2 | + |----------------|----------------| + | TIM1 BKIN | TIM1 BKIN | + | | | + | TIM1 OCREFCLR | TIM1 OCREFCLR | + | | | + | TIM1 IC1 | TIM1 IC1 | + | | | + | TIM2 IC4 | TIM2 IC4 | + | | | + | TIM2 OCREFCLR | TIM2 OCREFCLR | + | | | + | TIM3 IC1 | TIM3 IC1 | + | | | + | TIM3 OCREFCLR | TIM3 OCREFCLR | + +---------------------------------+ + + ##### How to use this driver ##### +================================================================================ + [..] + This driver provides functions to configure and program the Comparators of STM32F05x and STM32F07x devices. + + To use the comparator, perform the following steps: + + (#) Fill in the HAL_COMP_MspInit() to + (++) Configure the comparator input in analog mode using HAL_GPIO_Init() + (++) Configure the comparator output in alternate function mode using HAL_GPIO_Init() to map the comparator + output to the GPIO pin + (++) If required enable the COMP interrupt by configuring and enabling EXTI line in Interrupt mode and + selecting the desired sensitivity level using HAL_GPIO_Init() function. After that enable the comparator + interrupt vector using HAL_NVIC_EnableIRQ() function. + + (#) Configure the comparator using HAL_COMP_Init() function: + (++) Select the inverting input + (++) Select the output polarity + (++) Select the output redirection + (++) Select the hysteresis level + (++) Select the power mode + (++) Select the event/interrupt mode + + (#) Enable the comparator using HAL_COMP_Start() function or HAL_COMP_Start_IT() function for interrupt mode + + (#) Read the comparator output level with HAL_COMP_GetOutputLevel() + + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +#if defined(STM32F051x8) || defined(STM32F058xx) || \ + defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @defgroup COMP + * @brief COMP HAL module driver + * @{ + */ + +#ifdef HAL_COMP_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* CSR register reset value */ +#define COMP_CSR_RESET_VALUE ((uint32_t)0x00000000) +/* CSR register Mask */ +#define COMP_CSR_UPDATE_PARAMETERS_MASK ((uint32_t)0x00003FFE) +/* CSR COMPx Shift */ +#define COMP_CSR_COMP1_SHIFT ((uint32_t)0) +#define COMP_CSR_COMP2_SHIFT ((uint32_t)16) + +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup COMP_Private_Functions + * @{ + */ + +/** @defgroup HAL_COMP_Group1 Initialization/de-initialization functions + * @brief Initialization and Configuration functions + * +@verbatim + =============================================================================== + ##### Initialization/de-initialization functions ##### + =============================================================================== + [..] This section provides functions to initialize and de-initialize comparators + +@endverbatim + * @{ + */ + +/** + * @brief Initializes the COMP according to the specified + * parameters in the COMP_InitTypeDef and create the associated handle. + * @note If the selected comparator is locked, initialization can't be performed. + * To unlock the configuration, perform a system reset. + * @param hcomp: COMP handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_COMP_Init(COMP_HandleTypeDef *hcomp) +{ + HAL_StatusTypeDef status = HAL_OK; + uint32_t tmpreg = 0; + + /* Check the COMP handle allocation and lock status */ + if((hcomp == NULL) || (hcomp->State & COMP_STATE_BIT_LOCK)) + { + status = HAL_ERROR; + } + else + { + /* Check the parameter */ + assert_param(IS_COMP_ALL_INSTANCE(hcomp->Instance)); + assert_param(IS_COMP_INVERTINGINPUT(hcomp->Init.InvertingInput)); + assert_param(IS_COMP_OUTPUT(hcomp->Init.Output)); + assert_param(IS_COMP_OUTPUTPOL(hcomp->Init.OutputPol)); + assert_param(IS_COMP_HYSTERESIS(hcomp->Init.Hysteresis)); + assert_param(IS_COMP_MODE(hcomp->Init.Mode)); + + if(hcomp->Init.WindowMode != COMP_WINDOWMODE_DISABLED) + { + assert_param(IS_COMP_WINDOWMODE_INSTANCE(hcomp->Instance)); + } + + if(hcomp->State == HAL_COMP_STATE_RESET) + { + /* Init SYSCFG and the low level hardware to access comparators */ + __SYSCFG_CLK_ENABLE(); + + HAL_COMP_MspInit(hcomp); + } + + /* Set COMP parameters */ + /* Set COMPxINSEL bits according to hcomp->Init.InvertingInput value */ + /* Set COMPxOUTSEL bits according to hcomp->Init.Output value */ + /* Set COMPxPOL bit according to hcomp->Init.OutputPol value */ + /* Set COMPxHYST bits according to hcomp->Init.Hysteresis value */ + /* Set COMPxMODE bits according to hcomp->Init.Mode value */ + if(hcomp->Instance == COMP1) + { + tmpreg = hcomp->Instance->CSR; + tmpreg = (tmpreg & ~COMP_CSR_UPDATE_PARAMETERS_MASK); + tmpreg = tmpreg | hcomp->Init.InvertingInput | \ + hcomp->Init.Output | \ + hcomp->Init.OutputPol | \ + hcomp->Init.Hysteresis | \ + hcomp->Init.Mode; + hcomp->Instance->CSR = tmpreg; + } + else + { + tmpreg = (COMP->CSR); + tmpreg = (tmpreg & ~(COMP_CSR_UPDATE_PARAMETERS_MASK<Init.InvertingInput | \ + hcomp->Init.Output | \ + hcomp->Init.OutputPol | \ + hcomp->Init.Hysteresis | \ + hcomp->Init.Mode) << COMP_CSR_COMP2_SHIFT) | \ + hcomp->Init.WindowMode); + COMP->CSR = tmpreg; + } + + /* Initialize the COMP state*/ + if(hcomp->State == HAL_COMP_STATE_RESET) + { + hcomp->State = HAL_COMP_STATE_READY; + } + } + + return status; +} + +/** + * @brief DeInitializes the COMP peripheral + * @note Deinitialization can't be performed if the COMP configuration is locked. + * To unlock the configuration, perform a system reset. + * @param hcomp: COMP handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_COMP_DeInit(COMP_HandleTypeDef *hcomp) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check the COMP handle allocation and lock status */ + if((hcomp == NULL) || (hcomp->State & COMP_STATE_BIT_LOCK)) + { + status = HAL_ERROR; + } + else + { + /* Check the parameter */ + assert_param(IS_COMP_ALL_INSTANCE(hcomp->Instance)); + + /* Set COMP_CSR register to reset value for the corresponding COMP instance */ + if(hcomp->Instance == COMP1) + { + MODIFY_REG(hcomp->Instance->CSR, + (COMP_CSR_UPDATE_PARAMETERS_MASK), + (COMP_CSR_RESET_VALUE)); + } + else + { + MODIFY_REG(COMP->CSR, + (COMP_CSR_UPDATE_PARAMETERS_MASK << COMP_CSR_COMP2_SHIFT), + (COMP_CSR_RESET_VALUE)); + } + + /* DeInit the low level hardware: SYSCFG, GPIO, CLOCK and NVIC */ + HAL_COMP_MspDeInit(hcomp); + + hcomp->State = HAL_COMP_STATE_RESET; + } + + return status; +} + +/** + * @brief Initializes the COMP MSP. + * @param hcomp: COMP handle + * @retval None + */ +__weak void HAL_COMP_MspInit(COMP_HandleTypeDef *hcomp) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_COMP_MspInit could be implenetd in the user file + */ +} + +/** + * @brief DeInitializes COMP MSP. + * @param hcomp: COMP handle + * @retval None + */ +__weak void HAL_COMP_MspDeInit(COMP_HandleTypeDef *hcomp) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_COMP_MspDeInit could be implenetd in the user file + */ +} + +/** + * @} + */ + +/** @defgroup HAL_COMP_Group2 I/O operation functions + * @brief Data transfers functions + * +@verbatim + =============================================================================== + ##### IO operation functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to manage the COMP data + transfers. + +@endverbatim + * @{ + */ + +/** + * @brief Start the comparator + * @param hcomp: COMP handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_COMP_Start(COMP_HandleTypeDef *hcomp) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check the COMP handle allocation and lock status */ + if((hcomp == NULL) || (hcomp->State & COMP_STATE_BIT_LOCK)) + { + status = HAL_ERROR; + } + else + { + /* Check the parameter */ + assert_param(IS_COMP_ALL_INSTANCE(hcomp->Instance)); + + if(hcomp->State == HAL_COMP_STATE_READY) + { + /* Enable the selected comparator */ + if(hcomp->Instance == COMP1) + { + SET_BIT(hcomp->Instance->CSR, (COMP_CSR_COMP1EN)); + } + else + { + SET_BIT(COMP->CSR, (COMP_CSR_COMP1EN << COMP_CSR_COMP2_SHIFT)); + } + hcomp->State = HAL_COMP_STATE_BUSY; + } + else + { + status = HAL_ERROR; + } + } + + return status; +} + +/** + * @brief Stop the comparator + * @param hcomp: COMP handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_COMP_Stop(COMP_HandleTypeDef *hcomp) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check the COMP handle allocation and lock status */ + if((hcomp == NULL) || (hcomp->State & COMP_STATE_BIT_LOCK)) + { + status = HAL_ERROR; + } + else + { + /* Check the parameter */ + assert_param(IS_COMP_ALL_INSTANCE(hcomp->Instance)); + + if(hcomp->State == HAL_COMP_STATE_BUSY) + { + /* Disable the selected comparator */ + if(hcomp->Instance == COMP1) + { + CLEAR_BIT(hcomp->Instance->CSR, (COMP_CSR_COMP1EN )); + } + else + { + CLEAR_BIT(COMP->CSR, (COMP_CSR_COMP1EN << COMP_CSR_COMP2_SHIFT)); + } + hcomp->State = HAL_COMP_STATE_READY; + } + else + { + status = HAL_ERROR; + } + } + + return status; +} + +/** + * @brief Enables the interrupt and starts the comparator + * @param hcomp: COMP handle + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_COMP_Start_IT(COMP_HandleTypeDef *hcomp) +{ + HAL_StatusTypeDef status = HAL_OK; + uint32_t extiline = 0; + + status = HAL_COMP_Start(hcomp); + if(status == HAL_OK) + { + /* Check the Exti Line output configuration */ + extiline = __HAL_COMP_GET_EXTI_LINE(hcomp->Instance); + /* Configure the rising edge */ + if(hcomp->Init.TriggerMode & COMP_TRIGGERMODE_IT_RISING) + { + __HAL_COMP_EXTI_RISING_IT_ENABLE(extiline); + } + else + { + __HAL_COMP_EXTI_RISING_IT_DISABLE(extiline); + } + /* Configure the falling edge */ + if(hcomp->Init.TriggerMode & COMP_TRIGGERMODE_IT_FALLING) + { + __HAL_COMP_EXTI_FALLING_IT_ENABLE(extiline); + } + else + { + __HAL_COMP_EXTI_FALLING_IT_DISABLE(extiline); + } + /* Enable Exti interrupt mode */ + __HAL_COMP_EXTI_ENABLE_IT(extiline); + /* Clear COMP Exti pending bit */ + __HAL_COMP_EXTI_CLEAR_FLAG(extiline); + } + + return status; +} + +/** + * @brief Disable the interrupt and Stop the comparator + * @param hcomp: COMP handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_COMP_Stop_IT(COMP_HandleTypeDef *hcomp) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Disable the Exti Line interrupt mode */ + __HAL_COMP_EXTI_DISABLE_IT(__HAL_COMP_GET_EXTI_LINE(hcomp->Instance)); + + status = HAL_COMP_Stop(hcomp); + + return status; +} + +/** + * @brief Comparator IRQ Handler + * @param hcomp: COMP handle + * @retval HAL status + */ +void HAL_COMP_IRQHandler(COMP_HandleTypeDef *hcomp) +{ + uint32_t extiline = __HAL_COMP_GET_EXTI_LINE(hcomp->Instance); + + /* Check COMP Exti flag */ + if(__HAL_COMP_EXTI_GET_FLAG(extiline) != RESET) + { + /* Clear COMP Exti pending bit */ + __HAL_COMP_EXTI_CLEAR_FLAG(extiline); + + /* COMP trigger user callback */ + HAL_COMP_TriggerCallback(hcomp); + } +} + +/** + * @} + */ + +/** @defgroup HAL_COMP_Group3 Peripheral Control functions + * @brief management functions + * +@verbatim + =============================================================================== + ##### Peripheral Control functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to control the COMP data + transfers. + +@endverbatim + * @{ + */ + +/** + * @brief Lock the selected comparator configuration. + * @param hcomp: COMP handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_COMP_Lock(COMP_HandleTypeDef *hcomp) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check the COMP handle allocation and lock status */ + if((hcomp == NULL) || (hcomp->State & COMP_STATE_BIT_LOCK)) + { + status = HAL_ERROR; + } + else + { + /* Check the parameter */ + assert_param(IS_COMP_ALL_INSTANCE(hcomp->Instance)); + + /* Set lock flag */ + hcomp->State |= COMP_STATE_BIT_LOCK; + + /* Set the lock bit corresponding to selected comparator */ + if(hcomp->Instance == COMP1) + { + SET_BIT(hcomp->Instance->CSR, (COMP_CSR_COMP1LOCK )); + } + else + { + SET_BIT(COMP->CSR, (COMP_CSR_COMP1LOCK << COMP_CSR_COMP2_SHIFT)); + } + } + + return status; +} + +/** + * @brief Return the output level (high or low) of the selected comparator. + * The output level depends on the selected polarity. + * If the polarity is not inverted: + * - Comparator output is low when the non-inverting input is at a lower + * voltage than the inverting input + * - Comparator output is high when the non-inverting input is at a higher + * voltage than the inverting input + * If the polarity is inverted: + * - Comparator output is high when the non-inverting input is at a lower + * voltage than the inverting input + * - Comparator output is low when the non-inverting input is at a higher + * voltage than the inverting input + * @param hcomp: COMP handle + * @retval Returns the selected comparator output level: COMP_OUTPUTLEVEL_LOW or COMP_OUTPUTLEVEL_HIGH. + * + */ +uint32_t HAL_COMP_GetOutputLevel(COMP_HandleTypeDef *hcomp) +{ + uint32_t level=0; + + /* Check the parameter */ + assert_param(IS_COMP_ALL_INSTANCE(hcomp->Instance)); + + if(hcomp->Instance == COMP1) + { + level = READ_BIT(hcomp->Instance->CSR, (COMP_CSR_COMP1OUT )); + } + else + { + level = READ_BIT(COMP->CSR, (COMP_CSR_COMP1OUT << COMP_CSR_COMP2_SHIFT)); + } + + if(level != 0) + { + return(COMP_OUTPUTLEVEL_HIGH); + } + return(COMP_OUTPUTLEVEL_LOW); +} + +/** + * @brief Comparator callback. + * @param hcomp: COMP handle + * @retval None + */ +__weak void HAL_COMP_TriggerCallback(COMP_HandleTypeDef *hcomp) +{ + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_COMP_TriggerCallback should be implemented in the user file + */ +} + + +/** + * @} + */ + +/** @defgroup HAL_COMP_Group4 Peripheral State functions + * @brief Peripheral State functions + * +@verbatim + =============================================================================== + ##### Peripheral State functions ##### + =============================================================================== + [..] + This subsection permit to get in run-time the status of the peripheral + and the data flow. + +@endverbatim + * @{ + */ + +/** + * @brief Return the COMP state + * @param hcomp : COMP handle + * @retval HAL state + */ +HAL_COMP_StateTypeDef HAL_COMP_GetState(COMP_HandleTypeDef *hcomp) +{ + /* Check the COMP handle allocation */ + if(hcomp == NULL) + { + return HAL_COMP_STATE_RESET; + } + + /* Check the parameter */ + assert_param(IS_COMP_ALL_INSTANCE(hcomp->Instance)); + + return hcomp->State; +} +/** + * @} + */ + +/** + * @} + */ + +#endif /* HAL_COMP_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + +#endif /* STM32F051x8 || STM32F058xx || */ + /* STM32F071xB || STM32F072xB || STM32F078xx */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_comp.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_comp.h new file mode 100644 index 0000000000..b0efb14af9 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_comp.h @@ -0,0 +1,409 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_comp.h + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief Header file of COMP HAL module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32F0xx_HAL_COMP_H +#define __STM32F0xx_HAL_COMP_H + +#ifdef __cplusplus + extern "C" { +#endif + +#if defined(STM32F051x8) || defined(STM32F058xx) || \ + defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal_def.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @addtogroup COMP + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ + +/** + * @brief COMP Init structure definition + */ + +typedef struct +{ + + uint32_t InvertingInput; /*!< Selects the inverting input of the comparator. + This parameter can be a value of @ref COMP_InvertingInput */ + + uint32_t Output; /*!< Selects the output redirection of the comparator. + This parameter can be a value of @ref COMP_Output */ + + uint32_t OutputPol; /*!< Selects the output polarity of the comparator. + This parameter can be a value of @ref COMP_OutputPolarity */ + + uint32_t Hysteresis; /*!< Selects the hysteresis voltage of the comparator. + This parameter can be a value of @ref COMP_Hysteresis */ + + uint32_t Mode; /*!< Selects the operating comsumption mode of the comparator + to adjust the speed/consumption. + This parameter can be a value of @ref COMP_Mode */ + + uint32_t WindowMode; /*!< Selects the window mode of the comparator 1 & 2. + This parameter can be a value of @ref COMP_WindowMode */ + + uint32_t TriggerMode; /*!< Selects the trigger mode of the comparator (interrupt mode). + This parameter can be a value of @ref COMP_TriggerMode */ + +}COMP_InitTypeDef; + +/** + * @brief HAL State structures definition + */ +typedef enum +{ + HAL_COMP_STATE_RESET = 0x00, /*!< COMP not yet initialized or disabled */ + HAL_COMP_STATE_READY = 0x01, /*!< COMP initialized and ready for use */ + HAL_COMP_STATE_READY_LOCKED = 0x11, /*!< COMP initialized but the configuration is locked */ + HAL_COMP_STATE_BUSY = 0x02, /*!< COMP is running */ + HAL_COMP_STATE_BUSY_LOCKED = 0x12 /*!< COMP is running and the configuration is locked */ +}HAL_COMP_StateTypeDef; + + +/** + * @brief PPP Handle Structure definition + */ +typedef struct +{ + COMP_TypeDef *Instance; /*!< Register base address */ + COMP_InitTypeDef Init; /*!< COMP required parameters */ + HAL_LockTypeDef Lock; /*!< Locking object */ + __IO HAL_COMP_StateTypeDef State; /*!< COMP communication state */ + +}COMP_HandleTypeDef; + +/* Exported constants --------------------------------------------------------*/ +/** @defgroup COMP_Exported_Constants + * @{ + */ + +/** @defgroup COMP_OutputPolarity + * @{ + */ +#define COMP_OUTPUTPOL_NONINVERTED ((uint32_t)0x00000000) /*!< COMP output on GPIO isn't inverted */ +#define COMP_OUTPUTPOL_INVERTED COMP_CSR_COMP1POL /*!< COMP output on GPIO is inverted */ + +#define IS_COMP_OUTPUTPOL(POL) (((POL) == COMP_OUTPUTPOL_NONINVERTED) || \ + ((POL) == COMP_OUTPUTPOL_INVERTED)) +/** + * @} + */ + +/** @defgroup COMP_Hysteresis + * @{ + */ +#define COMP_HYSTERESIS_NONE ((uint32_t)0x00000000) /*!< No hysteresis */ +#define COMP_HYSTERESIS_LOW COMP_CSR_COMP1HYST_0 /*!< Hysteresis level low */ +#define COMP_HYSTERESIS_MEDIUM COMP_CSR_COMP1HYST_1 /*!< Hysteresis level medium */ +#define COMP_HYSTERESIS_HIGH COMP_CSR_COMP1HYST /*!< Hysteresis level high */ + +#define IS_COMP_HYSTERESIS(HYSTERESIS) (((HYSTERESIS) == COMP_HYSTERESIS_NONE) || \ + ((HYSTERESIS) == COMP_HYSTERESIS_LOW) || \ + ((HYSTERESIS) == COMP_HYSTERESIS_MEDIUM) || \ + ((HYSTERESIS) == COMP_HYSTERESIS_HIGH)) +/** + * @} + */ + +/** @defgroup COMP_Mode + * @{ + */ +/* Please refer to the electrical characteristics in the device datasheet for + the power consumption values */ +#define COMP_MODE_HIGHSPEED ((uint32_t)0x00000000) /*!< High Speed */ +#define COMP_MODE_MEDIUMSPEED COMP_CSR_COMP1MODE_0 /*!< Medium Speed */ +#define COMP_MODE_LOWPOWER COMP_CSR_COMP1MODE_1 /*!< Low power mode */ +#define COMP_MODE_ULTRALOWPOWER COMP_CSR_COMP1MODE /*!< Ultra-low power mode */ + +#define IS_COMP_MODE(MODE) (((MODE) == COMP_MODE_HIGHSPEED) || \ + ((MODE) == COMP_MODE_MEDIUMSPEED) || \ + ((MODE) == COMP_MODE_LOWPOWER) || \ + ((MODE) == COMP_MODE_ULTRALOWPOWER)) + +/** + * @} + */ + +/** @defgroup COMP_InvertingInput + * @{ + */ + +#define COMP_INVERTINGINPUT_1_4VREFINT ((uint32_t)0x00000000) /*!< 1/4 VREFINT connected to comparator inverting input */ +#define COMP_INVERTINGINPUT_1_2VREFINT COMP_CSR_COMP1INSEL_0 /*!< 1/2 VREFINT connected to comparator inverting input */ +#define COMP_INVERTINGINPUT_3_4VREFINT COMP_CSR_COMP1INSEL_1 /*!< 3/4 VREFINT connected to comparator inverting input */ +#define COMP_INVERTINGINPUT_VREFINT (COMP_CSR_COMP1INSEL_1|COMP_CSR_COMP1INSEL_0) /*!< VREFINT connected to comparator inverting input */ +#define COMP_INVERTINGINPUT_DAC1 COMP_CSR_COMP1INSEL_2 /*!< DAC_OUT1 (PA4) connected to comparator inverting input */ +#define COMP_INVERTINGINPUT_DAC1SWITCHCLOSED (COMP_CSR_COMP1INSEL_2|COMP_CSR_COMP1SW1) /*!< DAC_OUT1 (PA4) connected to comparator inverting input + and close switch (PA0 for COMP1 only) */ +#define COMP_INVERTINGINPUT_DAC2 (COMP_CSR_COMP1INSEL_2|COMP_CSR_COMP1INSEL_0) /*!< DAC_OUT2 (PA5) connected to comparator inverting input */ +#define COMP_INVERTINGINPUT_IO1 (COMP_CSR_COMP1INSEL_2|COMP_CSR_COMP1INSEL_1) /*!< IO (PA0 for COMP1 and PA2 for COMP2) connected to comparator inverting input */ + +#define IS_COMP_INVERTINGINPUT(INPUT) (((INPUT) == COMP_INVERTINGINPUT_1_4VREFINT) || \ + ((INPUT) == COMP_INVERTINGINPUT_1_2VREFINT) || \ + ((INPUT) == COMP_INVERTINGINPUT_3_4VREFINT) || \ + ((INPUT) == COMP_INVERTINGINPUT_VREFINT) || \ + ((INPUT) == COMP_INVERTINGINPUT_DAC1) || \ + ((INPUT) == COMP_INVERTINGINPUT_DAC1SWITCHCLOSED) || \ + ((INPUT) == COMP_INVERTINGINPUT_DAC2) || \ + ((INPUT) == COMP_INVERTINGINPUT_IO1)) +/** + * @} + */ + +/** @defgroup COMP_Output + * @{ + */ + +/* Output Redirection common for COMP1 and COMP2 */ +#define COMP_OUTPUT_NONE ((uint32_t)0x00000000) /*!< COMP output isn't connected to other peripherals */ +#define COMP_OUTPUT_TIM1BKIN COMP_CSR_COMP1OUTSEL_0 /*!< COMP output connected to TIM1 Break Input (BKIN) */ +#define COMP_OUTPUT_TIM1IC1 COMP_CSR_COMP1OUTSEL_1 /*!< COMP output connected to TIM1 Input Capture 1 */ +#define COMP_OUTPUT_TIM1OCREFCLR (COMP_CSR_COMP1OUTSEL_1|COMP_CSR_COMP1OUTSEL_0) /*!< COMP output connected to TIM1 OCREF Clear */ +#define COMP_OUTPUT_TIM2IC4 COMP_CSR_COMP1OUTSEL_2 /*!< COMP output connected to TIM2 Input Capture 4 */ +#define COMP_OUTPUT_TIM2OCREFCLR (COMP_CSR_COMP1OUTSEL_2|COMP_CSR_COMP1OUTSEL_0) /*!< COMP output connected to TIM2 OCREF Clear */ +#define COMP_OUTPUT_TIM3IC1 (COMP_CSR_COMP1OUTSEL_2|COMP_CSR_COMP1OUTSEL_1) /*!< COMP output connected to TIM3 Input Capture 1 */ +#define COMP_OUTPUT_TIM3OCREFCLR COMP_CSR_COMP1OUTSEL /*!< COMP output connected to TIM3 OCREF Clear */ + +#define IS_COMP_OUTPUT(OUTPUT) (((OUTPUT) == COMP_OUTPUT_NONE) || \ + ((OUTPUT) == COMP_OUTPUT_TIM1BKIN) || \ + ((OUTPUT) == COMP_OUTPUT_TIM1IC1) || \ + ((OUTPUT) == COMP_OUTPUT_TIM1OCREFCLR) || \ + ((OUTPUT) == COMP_OUTPUT_TIM2IC4) || \ + ((OUTPUT) == COMP_OUTPUT_TIM2OCREFCLR) || \ + ((OUTPUT) == COMP_OUTPUT_TIM3IC1) || \ + ((OUTPUT) == COMP_OUTPUT_TIM3OCREFCLR)) + +/** + * @} + */ + +/** @defgroup COMP_OutputLevel + * @{ + */ +/* When output polarity is not inverted, comparator output is low when + the non-inverting input is at a lower voltage than the inverting input*/ +#define COMP_OUTPUTLEVEL_LOW ((uint32_t)0x00000000) +/* When output polarity is not inverted, comparator output is high when + the non-inverting input is at a higher voltage than the inverting input */ +#define COMP_OUTPUTLEVEL_HIGH COMP_CSR_COMP1OUT +/** + * @} + */ + +/** @defgroup COMP_TriggerMode + * @{ + */ +#define COMP_TRIGGERMODE_NONE ((uint32_t)0x00000000) /*!< No External Interrupt trigger detection */ +#define COMP_TRIGGERMODE_IT_RISING ((uint32_t)0x00000001) /*!< External Interrupt Mode with Rising edge trigger detection */ +#define COMP_TRIGGERMODE_IT_FALLING ((uint32_t)0x00000002) /*!< External Interrupt Mode with Falling edge trigger detection */ +#define COMP_TRIGGERMODE_IT_RISING_FALLING ((uint32_t)0x00000003) /*!< External Interrupt Mode with Rising/Falling edge trigger detection */ + +#define IS_COMP_TRIGGERMODE(MODE) (((MODE) == COMP_TRIGGERMODE_NONE) || \ + ((MODE) == COMP_TRIGGERMODE_IT_RISING) || \ + ((MODE) == COMP_TRIGGERMODE_IT_FALLING) || \ + ((MODE) == COMP_TRIGGERMODE_IT_RISING_FALLING)) +/** + * @} + */ + +/** @defgroup COMP_WindowMode + * @{ + */ +#define COMP_WINDOWMODE_DISABLED ((uint32_t)0x00000000) /*!< Window mode disabled */ +#define COMP_WINDOWMODE_ENABLED COMP_CSR_WNDWEN /*!< Window mode enabled: non inverting input of comparator 2 + is connected to the non inverting input of comparator 1 (PA1) */ + +#define IS_COMP_WINDOWMODE(WINDOWMODE) (((WINDOWMODE) == COMP_WINDOWMODE_DISABLED) || \ + ((WINDOWMODE) == COMP_WINDOWMODE_ENABLED)) +/** + * @} + */ + +/** @defgroup COMP_ExtiLineEvent + * Elements values convention: XXXX0000 + * - XXXX : Interrupt mask in the EMR/IMR/RTSR/FTSR register + * @{ + */ +#define COMP_EXTI_LINE_COMP1_EVENT ((uint32_t)0x00200000) /*!< External interrupt line 21 Connected to COMP1 */ +#define COMP_EXTI_LINE_COMP2_EVENT ((uint32_t)0x00400000) /*!< External interrupt line 22 Connected to COMP2 */ + +/** + * @} + */ + +#define COMP_LOCK_DISABLE ((uint32_t)0x00000000) +#define COMP_LOCK_ENABLE COMP_CSR_COMP1LOCK + +#define COMP_STATE_BIT_LOCK ((uint32_t)0x10) + +/** + * @} + */ + +/* Exported macros -----------------------------------------------------------*/ + +/** @brief Reset COMP handle state + * @param __HANDLE__: COMP handle. + * @retval None + */ +#define __HAL_COMP_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_COMP_STATE_RESET) + +/** + * @brief Checks whether the specified EXTI line flag is set or not. + * @param __FLAG__: specifies the COMP Exti sources to be checked. + * This parameter can be a value of @ref COMP_ExtiLineEvent + * @retval The state of __FLAG__ (SET or RESET). + */ +#define __HAL_COMP_EXTI_GET_FLAG(__FLAG__) (EXTI->PR & (__FLAG__)) + +/** + * @brief Clear the COMP Exti flags. + * @param __FLAG__: specifies the COMP Exti sources to be cleared. + * This parameter can be a value of @ref COMP_ExtiLineEvent + * @retval None. + */ +#define __HAL_COMP_EXTI_CLEAR_FLAG(__FLAG__) (EXTI->PR |= (__FLAG__)) + +/** + * @brief Enable the COMP Exti Line. + * @param __EXTILINE__: specifies the COMP Exti sources to be enabled. + * This parameter can be a value of @ref COMP_ExtiLineEvent + * @retval None. + */ +#define __HAL_COMP_EXTI_ENABLE_IT(__EXTILINE__) (EXTI->IMR |= (__EXTILINE__)) + +/** + * @brief Disable the COMP Exti Line. + * @param __EXTILINE__: specifies the COMP Exti sources to be disabled. + * This parameter can be a value of @ref COMP_ExtiLineEvent + * @retval None. + */ +#define __HAL_COMP_EXTI_DISABLE_IT(__EXTILINE__) (EXTI->IMR &= ~(__EXTILINE__)) + +/** + * @brief Enable the Exti Line rising edge trigger. + * @param __EXTILINE__: specifies the COMP Exti sources to be enabled. + * This parameter can be a value of @ref COMP_ExtiLineEvent + * @retval None. + */ +#define __HAL_COMP_EXTI_RISING_IT_ENABLE(__EXTILINE__) (EXTI->RTSR |= (__EXTILINE__)) + +/** + * @brief Disable the Exti Line rising edge trigger. + * @param __EXTILINE__: specifies the COMP Exti sources to be disabled. + * This parameter can be a value of @ref COMP_ExtiLineEvent + * @retval None. + */ +#define __HAL_COMP_EXTI_RISING_IT_DISABLE(__EXTILINE__) (EXTI->RTSR &= ~(__EXTILINE__)) + +/** + * @brief Enable the Exti Line falling edge trigger. + * @param __EXTILINE__: specifies the COMP Exti sources to be enabled. + * This parameter can be a value of @ref COMP_ExtiLineEvent + * @retval None. + */ +#define __HAL_COMP_EXTI_FALLING_IT_ENABLE(__EXTILINE__) (EXTI->FTSR |= (__EXTILINE__)) + +/** + * @brief Disable the Exti Line falling edge trigger. + * @param __EXTILINE__: specifies the COMP Exti sources to be disabled. + * This parameter can be a value of @ref COMP_ExtiLineEvent + * @retval None. + */ +#define __HAL_COMP_EXTI_FALLING_IT_DISABLE(__EXTILINE__) (EXTI->FTSR &= ~(__EXTILINE__)) + +/** + * @brief Get the specified EXTI line for a comparator instance + * @param __INSTANCE__: specifies the COMP instance. + * @retval value of @ref COMP_ExtiLineEvent + */ +#define __HAL_COMP_GET_EXTI_LINE(__INSTANCE__) (((__INSTANCE__) == COMP1) ? COMP_EXTI_LINE_COMP1_EVENT : \ + COMP_EXTI_LINE_COMP2_EVENT) + + +/* Exported functions --------------------------------------------------------*/ + +/* Initialization and de-initialization functions ****************************/ +HAL_StatusTypeDef HAL_COMP_Init(COMP_HandleTypeDef *hcomp); +HAL_StatusTypeDef HAL_COMP_DeInit (COMP_HandleTypeDef *hcomp); +void HAL_COMP_MspInit(COMP_HandleTypeDef *hcomp); +void HAL_COMP_MspDeInit(COMP_HandleTypeDef *hcomp); + +/* IO operation functions *****************************************************/ +HAL_StatusTypeDef HAL_COMP_Start(COMP_HandleTypeDef *hcomp); +HAL_StatusTypeDef HAL_COMP_Stop(COMP_HandleTypeDef *hcomp); +HAL_StatusTypeDef HAL_COMP_Start_IT(COMP_HandleTypeDef *hcomp); +HAL_StatusTypeDef HAL_COMP_Stop_IT(COMP_HandleTypeDef *hcomp); +void HAL_COMP_IRQHandler(COMP_HandleTypeDef *hcomp); + +/* Peripheral Control functions ***********************************************/ +HAL_StatusTypeDef HAL_COMP_Lock(COMP_HandleTypeDef *hcomp); +uint32_t HAL_COMP_GetOutputLevel(COMP_HandleTypeDef *hcomp); + +/* Callback in Interrupt mode */ +void HAL_COMP_TriggerCallback(COMP_HandleTypeDef *hcomp); + +/* Peripheral State and Error functions ***************************************/ +HAL_COMP_StateTypeDef HAL_COMP_GetState(COMP_HandleTypeDef *hcomp); + +/** + * @} + */ + +/** + * @} + */ + +#endif /* STM32F051x8 || STM32F058xx || */ + /* STM32F071xB || STM32F072xB || STM32F078xx */ + +#ifdef __cplusplus +} +#endif + +#endif /* __STM32F0xx_HAL_COMP_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_conf.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_conf.h new file mode 100644 index 0000000000..7457f754a3 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_conf.h @@ -0,0 +1,306 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_conf.h + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief HAL configuration file. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32F0xx_HAL_CONF_H +#define __STM32F0xx_HAL_CONF_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Exported types ------------------------------------------------------------*/ +/* Exported constants --------------------------------------------------------*/ + +/* ########################## Module Selection ############################## */ +/** + * @brief This is the list of modules to be used in the HAL driver + */ +#define HAL_MODULE_ENABLED +#define HAL_ADC_MODULE_ENABLED +#define HAL_CAN_MODULE_ENABLED +#define HAL_CEC_MODULE_ENABLED +#define HAL_COMP_MODULE_ENABLED +#define HAL_CORTEX_MODULE_ENABLED +#define HAL_CRC_MODULE_ENABLED +#define HAL_DAC_MODULE_ENABLED +#define HAL_DMA_MODULE_ENABLED +#define HAL_FLASH_MODULE_ENABLED +#define HAL_GPIO_MODULE_ENABLED +#define HAL_I2C_MODULE_ENABLED +#define HAL_I2S_MODULE_ENABLED +#define HAL_IRDA_MODULE_ENABLED +#define HAL_IWDG_MODULE_ENABLED +#define HAL_PCD_MODULE_ENABLED +#define HAL_PWR_MODULE_ENABLED +#define HAL_RCC_MODULE_ENABLED +#define HAL_RTC_MODULE_ENABLED +#define HAL_SMARTCARD_MODULE_ENABLED +#define HAL_SMBUS_MODULE_ENABLED +#define HAL_SPI_MODULE_ENABLED +#define HAL_TIM_MODULE_ENABLED +#define HAL_TSC_MODULE_ENABLED +#define HAL_UART_MODULE_ENABLED +#define HAL_USART_MODULE_ENABLED +#define HAL_WWDG_MODULE_ENABLED + +/* ######################### Oscillator Values adaptation ################### */ +/** + * @brief Adjust the value of External High Speed oscillator (HSE) used in your application. + * This value is used by the RCC HAL module to compute the system frequency + * (when HSE is used as system clock source, directly or through the PLL). + */ +#if !defined (HSE_VALUE) + #define HSE_VALUE ((uint32_t)8000000) /*!< Value of the External oscillator in Hz */ +#endif /* HSE_VALUE */ + +/** + * @brief In the following line adjust the External High Speed oscillator (HSE) Startup + * Timeout value + */ +#if !defined (HSE_STARTUP_TIMEOUT) + #define HSE_STARTUP_TIMEOUT ((uint32_t)100) /*!< Time out for HSE start up, in ms */ +#endif /* HSE_STARTUP_TIMEOUT */ + +/** + * @brief Internal High Speed oscillator (HSI) value. + * This value is used by the RCC HAL module to compute the system frequency + * (when HSI is used as system clock source, directly or through the PLL). + */ +#if !defined (HSI_VALUE) + #define HSI_VALUE ((uint32_t)8000000) /*!< Value of the Internal oscillator in Hz*/ +#endif /* HSI_VALUE */ + +/** + * @brief In the following line adjust the Internal High Speed oscillator (HSI) Startup + * Timeout value + */ +#if !defined (HSI_STARTUP_TIMEOUT) + #define HSI_STARTUP_TIMEOUT ((uint32_t)5000) /*!< Time out for HSI start up */ +#endif /* HSI_STARTUP_TIMEOUT */ + +/** + * @brief Internal High Speed oscillator for ADC (HSI14) value. + */ +#if !defined (HSI14_VALUE) +#define HSI14_VALUE ((uint32_t)14000000) /*!< Value of the Internal High Speed oscillator for ADC in Hz. + The real value may vary depending on the variations + in voltage and temperature. */ +#endif /* HSI14_VALUE */ + +/** + * @brief Internal High Speed oscillator for USB (HSI48) value. + */ +#if !defined (HSI48_VALUE) +#define HSI48_VALUE ((uint32_t)48000000) /*!< Value of the Internal High Speed oscillator for USB in Hz. + The real value may vary depending on the variations + in voltage and temperature. */ +#endif /* HSI48_VALUE */ + +/** + * @brief Internal Low Speed oscillator (LSI) value. + */ +#if !defined (LSI_VALUE) + #define LSI_VALUE ((uint32_t)40000) +#endif /* LSI_VALUE */ /*!< Value of the Internal Low Speed oscillator in Hz + The real value may vary depending on the variations + in voltage and temperature. */ +/** + * @brief External Low Speed oscillator (LSI) value. + */ +#if !defined (LSE_VALUE) + #define LSE_VALUE ((uint32_t)32768) /*!< Value of the External Low Speed oscillator in Hz */ +#endif /* LSE_VALUE */ + + +/* Tip: To avoid modifying this file each time you need to use different HSE, + === you can define the HSE value in your toolchain compiler preprocessor. */ + +/* ########################### System Configuration ######################### */ +/** + * @brief This is the HAL system configuration section + */ +#define VDD_VALUE ((uint32_t)3300) /*!< Value of VDD in mv */ +#define TICK_INT_PRIORITY ((uint32_t)(1<<__NVIC_PRIO_BITS) - 1) /*!< tick interrupt priority (lowest by default) */ + /* Warning: Must be set to higher priority for HAL_Delay() */ + /* and HAL_GetTick() usage under interrupt context */ +#define USE_RTOS 0 +#define PREFETCH_ENABLE 1 +#define INSTRUCTION_CACHE_ENABLE 0 +#define DATA_CACHE_ENABLE 0 + +/* ########################## Assert Selection ############################## */ +/** + * @brief Uncomment the line below to expanse the "assert_param" macro in the + * HAL drivers code + */ +/*#define USE_FULL_ASSERT 1*/ + +/* Includes ------------------------------------------------------------------*/ +/** + * @brief Include module's header file + */ + +#ifdef HAL_RCC_MODULE_ENABLED + #include "stm32f0xx_hal_rcc.h" +#endif /* HAL_RCC_MODULE_ENABLED */ + +#ifdef HAL_GPIO_MODULE_ENABLED + #include "stm32f0xx_hal_gpio.h" +#endif /* HAL_GPIO_MODULE_ENABLED */ + +#ifdef HAL_DMA_MODULE_ENABLED + #include "stm32f0xx_hal_dma.h" +#endif /* HAL_DMA_MODULE_ENABLED */ + +#ifdef HAL_CORTEX_MODULE_ENABLED + #include "stm32f0xx_hal_cortex.h" +#endif /* HAL_CORTEX_MODULE_ENABLED */ + +#ifdef HAL_ADC_MODULE_ENABLED + #include "stm32f0xx_hal_adc.h" +#endif /* HAL_ADC_MODULE_ENABLED */ + +#ifdef HAL_CAN_MODULE_ENABLED + #include "stm32f0xx_hal_can.h" +#endif /* HAL_CAN_MODULE_ENABLED */ + +#ifdef HAL_CEC_MODULE_ENABLED + #include "stm32f0xx_hal_cec.h" +#endif /* HAL_CEC_MODULE_ENABLED */ + +#ifdef HAL_COMP_MODULE_ENABLED + #include "stm32f0xx_hal_comp.h" +#endif /* HAL_COMP_MODULE_ENABLED */ + +#ifdef HAL_CRC_MODULE_ENABLED + #include "stm32f0xx_hal_crc.h" +#endif /* HAL_CRC_MODULE_ENABLED */ + +#ifdef HAL_DAC_MODULE_ENABLED + #include "stm32f0xx_hal_dac.h" +#endif /* HAL_DAC_MODULE_ENABLED */ + +#ifdef HAL_FLASH_MODULE_ENABLED + #include "stm32f0xx_hal_flash.h" +#endif /* HAL_FLASH_MODULE_ENABLED */ + +#ifdef HAL_I2C_MODULE_ENABLED + #include "stm32f0xx_hal_i2c.h" +#endif /* HAL_I2C_MODULE_ENABLED */ + +#ifdef HAL_I2S_MODULE_ENABLED + #include "stm32f0xx_hal_i2s.h" +#endif /* HAL_I2S_MODULE_ENABLED */ + +#ifdef HAL_IRDA_MODULE_ENABLED + #include "stm32f0xx_hal_irda.h" +#endif /* HAL_IRDA_MODULE_ENABLED */ + +#ifdef HAL_IWDG_MODULE_ENABLED + #include "stm32f0xx_hal_iwdg.h" +#endif /* HAL_IWDG_MODULE_ENABLED */ + +#ifdef HAL_PCD_MODULE_ENABLED + #include "stm32f0xx_hal_pcd.h" +#endif /* HAL_PCD_MODULE_ENABLED */ + +#ifdef HAL_PWR_MODULE_ENABLED + #include "stm32f0xx_hal_pwr.h" +#endif /* HAL_PWR_MODULE_ENABLED */ + +#ifdef HAL_RTC_MODULE_ENABLED + #include "stm32f0xx_hal_rtc.h" +#endif /* HAL_RTC_MODULE_ENABLED */ + +#ifdef HAL_SMARTCARD_MODULE_ENABLED + #include "stm32f0xx_hal_smartcard.h" +#endif /* HAL_SMARTCARD_MODULE_ENABLED */ + +#ifdef HAL_SMBUS_MODULE_ENABLED + #include "stm32f0xx_hal_smbus.h" +#endif /* HAL_SMBUS_MODULE_ENABLED */ + +#ifdef HAL_SPI_MODULE_ENABLED + #include "stm32f0xx_hal_spi.h" +#endif /* HAL_SPI_MODULE_ENABLED */ + +#ifdef HAL_TIM_MODULE_ENABLED + #include "stm32f0xx_hal_tim.h" +#endif /* HAL_TIM_MODULE_ENABLED */ + +#ifdef HAL_TSC_MODULE_ENABLED + #include "stm32f0xx_hal_tsc.h" +#endif /* HAL_TSC_MODULE_ENABLED */ + +#ifdef HAL_UART_MODULE_ENABLED + #include "stm32f0xx_hal_uart.h" +#endif /* HAL_UART_MODULE_ENABLED */ + +#ifdef HAL_USART_MODULE_ENABLED + #include "stm32f0xx_hal_usart.h" +#endif /* HAL_USART_MODULE_ENABLED */ + +#ifdef HAL_WWDG_MODULE_ENABLED + #include "stm32f0xx_hal_wwdg.h" +#endif /* HAL_WWDG_MODULE_ENABLED */ + +/* Exported macro ------------------------------------------------------------*/ +#ifdef USE_FULL_ASSERT +/** + * @brief The assert_param macro is used for function's parameters check. + * @param expr: If expr is false, it calls assert_failed function + * which reports the name of the source file and the source + * line number of the call that failed. + * If expr is true, it returns no value. + * @retval None + */ + #define assert_param(expr) ((expr) ? (void)0 : assert_failed((uint8_t *)__FILE__, __LINE__)) +/* Exported functions ------------------------------------------------------- */ + void assert_failed(uint8_t* file, uint32_t line); +#else + #define assert_param(expr) ((void)0) +#endif /* USE_FULL_ASSERT */ + +#ifdef __cplusplus +} +#endif + +#endif /* __STM32F0xx_HAL_CONF_H */ + + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_cortex.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_cortex.c new file mode 100644 index 0000000000..c7b99e32d6 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_cortex.c @@ -0,0 +1,345 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_cortex.c + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief CORTEX HAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the CORTEX: + * + Initialization and de-initialization functions + * + Peripheral Control functions + * + * @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + + [..] + *** How to configure Interrupts using CORTEX HAL driver *** + =========================================================== + [..] + This section provides functions allowing to configure the NVIC interrupts (IRQ). + The Cortex-M0 exceptions are managed by CMSIS functions. + (#) Enable and Configure the priority of the selected IRQ Channels. + The priority can be 0..3. + + -@- Lower priority values gives higher priority. + -@- Priority Order: + (#@) Lowest priority. + (#@) Lowest hardware priority (IRQn position). + + (#) Configure the priority of the selected IRQ Channels using HAL_NVIC_SetPriority() + + (#) Enable the selected IRQ Channels using HAL_NVIC_EnableIRQ() + + + [..] + *** How to configure Systick using CORTEX HAL driver *** + ======================================================== + [..] + Setup SysTick Timer for time base + + (+) The HAL_SYSTICK_Config()function calls the SysTick_Config() function which + is a CMSIS function that: + (++) Configures the SysTick Reload register with value passed as function parameter. + (++) Configures the SysTick IRQ priority to the lowest value (0x03). + (++) Resets the SysTick Counter register. + (++) Configures the SysTick Counter clock source to be Core Clock Source (HCLK). + (++) Enables the SysTick Interrupt. + (++) Starts the SysTick Counter. + + (+) You can change the SysTick Clock source to be HCLK_Div8 by calling the macro + __HAL_CORTEX_SYSTICKCLK_CONFIG(SYSTICK_CLKSOURCE_HCLK_DIV8) just after the + HAL_SYSTICK_Config() function call. The __HAL_CORTEX_SYSTICKCLK_CONFIG() macro is defined + inside the stm32f0xx_hal_cortex.h file. + + (+) You can change the SysTick IRQ priority by calling the + HAL_NVIC_SetPriority(SysTick_IRQn,...) function just after the HAL_SYSTICK_Config() function + call. The HAL_NVIC_SetPriority() call the NVIC_SetPriority() function which is a CMSIS function. + + (+) To adjust the SysTick time base, use the following formula: + + Reload Value = SysTick Counter Clock (Hz) x Desired Time base (s) + (++) Reload Value is the parameter to be passed for HAL_SYSTICK_Config() function + (++) Reload Value should not exceed 0xFFFFFF + + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @defgroup CORTEX + * @brief CORTEX HAL module driver + * @{ + */ + +#ifdef HAL_CORTEX_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup CORTEX_Private_Functions + * @{ + */ + + +/** @defgroup CORTEX_Group1 Initialization and de-initialization functions + * @brief Initialization and Configuration functions + * +@verbatim + ============================================================================== + ##### Initialization and de-initialization functions ##### + ============================================================================== + [..] + This section provides the CORTEX HAL driver functions allowing to configure Interrupts + Systick functionalities + +@endverbatim + * @{ + */ + +/** + * @brief Sets the priority of an interrupt. + * @param IRQn: External interrupt number . + * This parameter can be an enumerator of IRQn_Type enumeration + * (For the complete STM32 Devices IRQ Channels list, please refer to stm32l0xx.h file) + * @param PreemptPriority: The pre-emption priority for the IRQn channel. + * This parameter can be a value between 0 and 3. + * A lower priority value indicates a higher priority + * @param SubPriority: The subpriority level for the IRQ channel. + * with stm32f0xx devices, this parameter is a dummy value and it is ignored, because + * no subpriority supported in Cortex M0 based products. + * @retval None + */ +void HAL_NVIC_SetPriority(IRQn_Type IRQn, uint32_t PreemptPriority, uint32_t SubPriority) +{ + /* Check the parameters */ + assert_param(IS_NVIC_PREEMPTION_PRIORITY(PreemptPriority)); + NVIC_SetPriority(IRQn,PreemptPriority); +} + +/** + * @brief Enables a device specific interrupt in the NVIC interrupt controller. + * @note To configure interrupts priority correctly, the NVIC_PriorityGroupConfig() + * function should be called before. + * @param IRQn External interrupt number + * This parameter can be an enumerator of IRQn_Type enumeration + * (For the complete STM32 Devices IRQ Channels list, please refer to the appropriate CMSIS device file (stm32f0xxxx.h)) + * @retval None + */ +void HAL_NVIC_EnableIRQ(IRQn_Type IRQn) +{ + /* Enable interrupt */ + NVIC_EnableIRQ(IRQn); +} + +/** + * @brief Disables a device specific interrupt in the NVIC interrupt controller. + * @param IRQn External interrupt number + * This parameter can be an enumerator of IRQn_Type enumeration + * (For the complete STM32 Devices IRQ Channels list, please refer to the appropriate CMSIS device file (stm32f0xxxx.h)) + * @retval None + */ +void HAL_NVIC_DisableIRQ(IRQn_Type IRQn) +{ + /* Disable interrupt */ + NVIC_DisableIRQ(IRQn); +} + +/** + * @brief Initiates a system reset request to reset the MCU. + * @param None + * @retval None + */ +void HAL_NVIC_SystemReset(void) +{ + /* System Reset */ + NVIC_SystemReset(); +} + +/** + * @brief Initializes the System Timer and its interrupt, and starts the System Tick Timer. + * Counter is in free running mode to generate periodic interrupts. + * @param TicksNumb: Specifies the ticks Number of ticks between two interrupts. + * @retval status: - 0 Function succeeded. + * - 1 Function failed. + */ +uint32_t HAL_SYSTICK_Config(uint32_t TicksNumb) +{ + return SysTick_Config(TicksNumb); +} +/** + * @} + */ + +/** @defgroup CORTEX_Group2 Peripheral Control functions + * @brief Cortex control functions + * +@verbatim + ============================================================================== + ##### Peripheral Control functions ##### + ============================================================================== + [..] + This subsection provides a set of functions allowing to control the CORTEX + (NVIC, SYSTICK) functionalities. + + +@endverbatim + * @{ + */ + + +/** + * @brief Gets the priority of an interrupt. + * @param IRQn: External interrupt number + * This parameter can be an enumerator of IRQn_Type enumeration + * (For the complete STM32 Devices IRQ Channels list, please refer to the appropriate CMSIS device file (stm32f0xxxx.h)) + * @retval None + */ +uint32_t HAL_NVIC_GetPriority(IRQn_Type IRQn) +{ + /* Get priority for Cortex-M system or device specific interrupts */ + return NVIC_GetPriority(IRQn); +} + +/** + * @brief Sets Pending bit of an external interrupt. + * @param IRQn External interrupt number + * This parameter can be an enumerator of IRQn_Type enumeration + * (For the complete STM32 Devices IRQ Channels list, please refer to the appropriate CMSIS device file (stm32f0xxxx.h)) + * @retval None + */ +void HAL_NVIC_SetPendingIRQ(IRQn_Type IRQn) +{ + /* Set interrupt pending */ + NVIC_SetPendingIRQ(IRQn); +} + +/** + * @brief Gets Pending Interrupt (reads the pending register in the NVIC + * and returns the pending bit for the specified interrupt). + * @param IRQn External interrupt number + * This parameter can be an enumerator of IRQn_Type enumeration + * (For the complete STM32 Devices IRQ Channels list, please refer to the appropriate CMSIS device file (stm32f0xxxx.h)) + * @retval status: - 0 Interrupt status is not pending. + * - 1 Interrupt status is pending. + */ +uint32_t HAL_NVIC_GetPendingIRQ(IRQn_Type IRQn) +{ + /* Return 1 if pending else 0 */ + return NVIC_GetPendingIRQ(IRQn); +} + +/** + * @brief Clears the pending bit of an external interrupt. + * @param IRQn External interrupt number + * This parameter can be an enumerator of IRQn_Type enumeration + * (For the complete STM32 Devices IRQ Channels list, please refer to the appropriate CMSIS device file (stm32f0xxxx.h)) + * @retval None + */ +void HAL_NVIC_ClearPendingIRQ(IRQn_Type IRQn) +{ + /* Clear pending interrupt */ + NVIC_ClearPendingIRQ(IRQn); +} + +/** + * @brief Configures the SysTick clock source. + * @param CLKSource: specifies the SysTick clock source. + * This parameter can be one of the following values: + * @arg SYSTICK_CLKSOURCE_HCLK_DIV8: AHB clock divided by 8 selected as SysTick clock source. + * @arg SYSTICK_CLKSOURCE_HCLK: AHB clock selected as SysTick clock source. + * @retval None + */ +void HAL_SYSTICK_CLKSourceConfig(uint32_t CLKSource) +{ + /* Check the parameters */ + assert_param(IS_SYSTICK_CLKSOURCE(CLKSource)); + if (CLKSource == SYSTICK_CLKSOURCE_HCLK) + { + SysTick->CTRL |= SYSTICK_CLKSOURCE_HCLK; + } + else + { + SysTick->CTRL &= ~SYSTICK_CLKSOURCE_HCLK; + } +} + +/** + * @brief This function handles SYSTICK interrupt request. + * @param None + * @retval None + */ +void HAL_SYSTICK_IRQHandler(void) +{ + HAL_SYSTICK_Callback(); +} + +/** + * @brief SYSTICK callback. + * @param None + * @retval None + */ +__weak void HAL_SYSTICK_Callback(void) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_SYSTICK_Callback could be implemented in the user file + */ +} + +/** + * @} + */ + +/** + * @} + */ + +#endif /* HAL_CORTEX_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_cortex.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_cortex.h new file mode 100644 index 0000000000..21fe4ec913 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_cortex.h @@ -0,0 +1,132 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_cortex.h + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief Header file of CORTEX HAL module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32F0xx_HAL_CORTEX_H +#define __STM32F0xx_HAL_CORTEX_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal_def.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @addtogroup CORTEX + * @{ + */ +/* Exported types ------------------------------------------------------------*/ +/* Exported constants --------------------------------------------------------*/ + +/** @defgroup CORTEX_Exported_Constants + * @{ + */ + + +#define IS_NVIC_PREEMPTION_PRIORITY(PRIORITY) ((PRIORITY) < 0x4) + +/** @defgroup CORTEX_SysTick_clock_source + * @{ + */ +#define SYSTICK_CLKSOURCE_HCLK_DIV8 ((uint32_t)0x00000000) +#define SYSTICK_CLKSOURCE_HCLK ((uint32_t)0x00000004) +#define IS_SYSTICK_CLKSOURCE(SOURCE) (((SOURCE) == SYSTICK_CLKSOURCE_HCLK) || \ + ((SOURCE) == SYSTICK_CLKSOURCE_HCLK_DIV8)) +/** + * @} + */ + +/* Exported Macros -----------------------------------------------------------*/ + +/** @brief Configures the SysTick clock source. + * @param __CLKSRC__: specifies the SysTick clock source. + * This parameter can be one of the following values: + * @arg SYSTICK_CLKSOURCE_HCLK_DIV8: AHB clock divided by 8 selected as SysTick clock source. + * @arg SYSTICK_CLKSOURCE_HCLK: AHB clock selected as SysTick clock source. + * @retval None + */ +#define __HAL_CORTEX_SYSTICKCLK_CONFIG(__CLKSRC__) \ + do { \ + if ((__CLKSRC__) == SYSTICK_CLKSOURCE_HCLK) \ + { \ + SysTick->CTRL |= SYSTICK_CLKSOURCE_HCLK; \ + } \ + else \ + SysTick->CTRL &= ~SYSTICK_CLKSOURCE_HCLK; \ + } while(0) + +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/* Initialization and de-initialization functions *******************************/ +void HAL_NVIC_SetPriority(IRQn_Type IRQn,uint32_t PreemptPriority, uint32_t SubPriority); +void HAL_NVIC_EnableIRQ(IRQn_Type IRQn); +void HAL_NVIC_DisableIRQ(IRQn_Type IRQn); +void HAL_NVIC_SystemReset(void); +uint32_t HAL_SYSTICK_Config(uint32_t TicksNumb); + +/* Peripheral Control functions *************************************************/ +uint32_t HAL_NVIC_GetPriority(IRQn_Type IRQn); +uint32_t HAL_NVIC_GetPendingIRQ(IRQn_Type IRQn); +void HAL_NVIC_SetPendingIRQ(IRQn_Type IRQn); +void HAL_NVIC_ClearPendingIRQ(IRQn_Type IRQn); +void HAL_SYSTICK_CLKSourceConfig(uint32_t CLKSource); +void HAL_SYSTICK_IRQHandler(void); +void HAL_SYSTICK_Callback(void); + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __STM32F0xx_HAL_CORTEX_H */ + + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_crc.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_crc.c new file mode 100644 index 0000000000..7aa46a610f --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_crc.c @@ -0,0 +1,493 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_crc.c + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief CRC HAL module driver. + * + * This file provides firmware functions to manage the following + * functionalities of the CRC peripheral: + * + Initialization and de-initialization functions + * + Peripheral Control functions + * + Peripheral State functions + * + @verbatim + =============================================================================== + ##### How to use this driver ##### + =============================================================================== + [..] + (+) Enable CRC AHB clock using __CRC_CLK_ENABLE(); + (+) Initialize CRC calculator + - specify generating polynomial (IP default or non-default one) + - specify initialization value (IP default or non-default one) + - specify input data format + - specify input or output data inversion mode if any + (+) Use HAL_CRC_Accumulate() function to compute the CRC value of the + input data buffer starting with the previously computed CRC as + initialization value + (+) Use HAL_CRC_Calculate() function to compute the CRC value of the + input data buffer starting with the defined initialization value + (default or non-default) to initiate CRC calculation + + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @defgroup CRC + * @brief CRC HAL module driver. + * @{ + */ + +#ifdef HAL_CRC_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ +static uint32_t CRC_Handle_8(CRC_HandleTypeDef *hcrc, uint8_t pBuffer[], uint32_t BufferLength); +static uint32_t CRC_Handle_16(CRC_HandleTypeDef *hcrc, uint16_t pBuffer[], uint32_t BufferLength); +/** @defgroup CRC_Private_Functions + * @{ + */ + +/** @defgroup HAL_CRC_Group1 Initialization/de-initialization functions + * @brief Initialization and Configuration functions. + * +@verbatim + =============================================================================== + ##### Initialization/de-initialization functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Initialize the CRC according to the specified parameters + in the CRC_InitTypeDef and create the associated handle + (+) DeInitialize the CRC peripheral + (+) Initialize the CRC MSP + (+) DeInitialize CRC MSP + +@endverbatim + * @{ + */ + +/** + * @brief Initializes the CRC according to the specified + * parameters in the CRC_InitTypeDef and creates the associated handle. + * @param hcrc: CRC handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_CRC_Init(CRC_HandleTypeDef *hcrc) +{ + /* Check the CRC handle allocation */ + if(hcrc == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_CRC_ALL_INSTANCE(hcrc->Instance)); + + if(hcrc->State == HAL_CRC_STATE_RESET) + { + /* Init the low level hardware */ + HAL_CRC_MspInit(hcrc); + } + + hcrc->State = HAL_CRC_STATE_BUSY; + + /* Extended initialization: if programmable polynomial feature is + applicable to device, set default or non-default generating + polynomial according to hcrc->Init parameters. + If feature is non-applicable to device in use, HAL_CRCEx_Init straight + away reports HAL_OK. */ + if (HAL_CRCEx_Init(hcrc) != HAL_OK) + { + return HAL_ERROR; + } + + /* check whether or not non-default CRC initial value has been + * picked up by user */ + assert_param(IS_DEFAULT_INIT_VALUE(hcrc->Init.DefaultInitValueUse)); + if (hcrc->Init.DefaultInitValueUse == DEFAULT_INIT_VALUE_ENABLE) + { + WRITE_REG(hcrc->Instance->INIT, DEFAULT_CRC_INITVALUE); + } + else + { + WRITE_REG(hcrc->Instance->INIT, hcrc->Init.InitValue); + } + + + /* set input data inversion mode */ + assert_param(IS_CRC_INPUTDATA_INVERSION_MODE(hcrc->Init.InputDataInversionMode)); + MODIFY_REG(hcrc->Instance->CR, CRC_CR_REV_IN, hcrc->Init.InputDataInversionMode); + + /* set output data inversion mode */ + assert_param(IS_CRC_OUTPUTDATA_INVERSION_MODE(hcrc->Init.OutputDataInversionMode)); + MODIFY_REG(hcrc->Instance->CR, CRC_CR_REV_OUT, hcrc->Init.OutputDataInversionMode); + + /* makes sure the input data format (bytes, halfwords or words stream) + * is properly specified by user */ + assert_param(IS_CRC_INPUTDATA_FORMAT(hcrc->InputDataFormat)); + + /* Change CRC peripheral state */ + hcrc->State = HAL_CRC_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief DeInitializes the CRC peripheral. + * @param hcrc: CRC handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_CRC_DeInit(CRC_HandleTypeDef *hcrc) +{ + /* Check the CRC handle allocation */ + if(hcrc == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_CRC_ALL_INSTANCE(hcrc->Instance)); + + /* Check the CRC peripheral state */ + if(hcrc->State == HAL_CRC_STATE_BUSY) + { + return HAL_BUSY; + } + + /* Change CRC peripheral state */ + hcrc->State = HAL_CRC_STATE_BUSY; + + /* DeInit the low level hardware */ + HAL_CRC_MspDeInit(hcrc); + + /* Change CRC peripheral state */ + hcrc->State = HAL_CRC_STATE_RESET; + + /* Process unlocked */ + __HAL_UNLOCK(hcrc); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Initializes the CRC MSP. + * @param hcrc: CRC handle + * @retval None + */ +__weak void HAL_CRC_MspInit(CRC_HandleTypeDef *hcrc) +{ + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_CRC_MspInit can be implemented in the user file + */ +} + +/** + * @brief DeInitializes the CRC MSP. + * @param hcrc: CRC handle + * @retval None + */ +__weak void HAL_CRC_MspDeInit(CRC_HandleTypeDef *hcrc) +{ + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_CRC_MspDeInit can be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup HAL_CRC_Group2 Peripheral Control functions + * @brief management functions. + * +@verbatim + =============================================================================== + ##### Peripheral Control functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Compute the 7, 8, 16 or 32-bit CRC value of an 8, 16 or 32-bit data buffer + using combination of the previous CRC value and the new one. + + or + + (+) Compute the 7, 8, 16 or 32-bit CRC value of an 8, 16 or 32-bit data buffer + independently of the previous CRC value. + +@endverbatim + * @{ + */ + +/** + * @brief Compute the 7, 8, 16 or 32-bit CRC value of an 8, 16 or 32-bit data buffer + * starting with the previously computed CRC as initialization value. + * @param hcrc: CRC handle + * @param pBuffer: pointer to the input data buffer, exact input data format is + * provided by hcrc->InputDataFormat. + * @param BufferLength: input data buffer length + * @retval uint32_t CRC (returned value LSBs for CRC shorter than 32 bits) + */ +uint32_t HAL_CRC_Accumulate(CRC_HandleTypeDef *hcrc, uint32_t pBuffer[], uint32_t BufferLength) +{ + uint32_t index = 0; /* CRC input data buffer index */ + uint32_t temp = 0; /* CRC output (read from hcrc->Instance->DR register) */ + + /* Process locked */ + __HAL_LOCK(hcrc); + + /* Change CRC peripheral state */ + hcrc->State = HAL_CRC_STATE_BUSY; + + switch (hcrc->InputDataFormat) + { + case CRC_INPUTDATA_FORMAT_WORDS: + /* Enter Data to the CRC calculator */ + for(index = 0; index < BufferLength; index++) + { + hcrc->Instance->DR = pBuffer[index]; + } + temp = hcrc->Instance->DR; + break; + + case CRC_INPUTDATA_FORMAT_BYTES: + temp = CRC_Handle_8(hcrc, (uint8_t*)pBuffer, BufferLength); + break; + + case CRC_INPUTDATA_FORMAT_HALFWORDS: + temp = CRC_Handle_16(hcrc, (uint16_t*)pBuffer, BufferLength); + break; + + default: + break; + } + + /* Change CRC peripheral state */ + hcrc->State = HAL_CRC_STATE_READY; + + /* Process unlocked */ + __HAL_UNLOCK(hcrc); + + /* Return the CRC computed value */ + return temp; +} + + +/** + * @brief Compute the 7, 8, 16 or 32-bit CRC value of an 8, 16 or 32-bit data buffer + * starting with hcrc->Instance->INIT as initialization value. + * @param hcrc: CRC handle + * @param pBuffer: pointer to the input data buffer, exact input data format is + * provided by hcrc->InputDataFormat. + * @param BufferLength: input data buffer length + * @retval uint32_t CRC (returned value LSBs for CRC shorter than 32 bits) + */ +uint32_t HAL_CRC_Calculate(CRC_HandleTypeDef *hcrc, uint32_t pBuffer[], uint32_t BufferLength) +{ + uint32_t index = 0; /* CRC input data buffer index */ + uint32_t temp = 0; /* CRC output (read from hcrc->Instance->DR register) */ + + /* Process locked */ + __HAL_LOCK(hcrc); + + /* Change CRC peripheral state */ + hcrc->State = HAL_CRC_STATE_BUSY; + + /* Reset CRC Calculation Unit (hcrc->Instance->INIT is + * written in hcrc->Instance->DR) */ + __HAL_CRC_DR_RESET(hcrc); + + switch (hcrc->InputDataFormat) + { + case CRC_INPUTDATA_FORMAT_WORDS: + /* Enter 32-bit input data to the CRC calculator */ + for(index = 0; index < BufferLength; index++) + { + hcrc->Instance->DR = pBuffer[index]; + } + temp = hcrc->Instance->DR; + break; + + case CRC_INPUTDATA_FORMAT_BYTES: + /* Specific 8-bit input data handling */ + temp = CRC_Handle_8(hcrc, (uint8_t*)pBuffer, BufferLength); + break; + + case CRC_INPUTDATA_FORMAT_HALFWORDS: + /* Specific 16-bit input data handling */ + temp = CRC_Handle_16(hcrc, (uint16_t*)pBuffer, BufferLength); + break; + + default: + break; + } + + /* Change CRC peripheral state */ + hcrc->State = HAL_CRC_STATE_READY; + + /* Process unlocked */ + __HAL_UNLOCK(hcrc); + + /* Return the CRC computed value */ + return temp; +} + + + +/** + * @brief Enter 8-bit input data to the CRC calculator. + * Specific data handling to optimize processing time. + * @param hcrc: CRC handle + * @param pBuffer: pointer to the input data buffer + * @param BufferLength: input data buffer length + * @retval uint32_t CRC (returned value LSBs for CRC shorter than 32 bits) + */ +static uint32_t CRC_Handle_8(CRC_HandleTypeDef *hcrc, uint8_t pBuffer[], uint32_t BufferLength) +{ + uint32_t i = 0; /* input data buffer index */ + + /* Processing time optimization: 4 bytes are entered in a row with a single word write, + * last bytes must be carefully fed to the CRC calculator to ensure a correct type + * handling by the IP */ + for(i = 0; i < (BufferLength/4); i++) + { + hcrc->Instance->DR = ((uint32_t)pBuffer[4*i]<<24) | ((uint32_t)pBuffer[4*i+1]<<16) | ((uint32_t)pBuffer[4*i+2]<<8) | (uint32_t)pBuffer[4*i+3]; + } + /* last bytes specific handling */ + if ((BufferLength%4) != 0) + { + if (BufferLength%4 == 1) + { + *(uint8_t*) (&hcrc->Instance->DR) = pBuffer[4*i]; + } + if (BufferLength%4 == 2) + { + *(uint16_t*) (&hcrc->Instance->DR) = ((uint16_t)pBuffer[4*i]<<8) | (uint16_t)pBuffer[4*i+1]; + } + if (BufferLength%4 == 3) + { + *(uint16_t*) (&hcrc->Instance->DR) = ((uint16_t)pBuffer[4*i]<<8) | (uint16_t)pBuffer[4*i+1]; + *(uint8_t*) (&hcrc->Instance->DR) = pBuffer[4*i+2]; + } + } + + /* Return the CRC computed value */ + return hcrc->Instance->DR; +} + + + +/** + * @brief Enter 16-bit input data to the CRC calculator. + * Specific data handling to optimize processing time. + * @param hcrc: CRC handle + * @param pBuffer: pointer to the input data buffer + * @param BufferLength: input data buffer length + * @retval uint32_t CRC (returned value LSBs for CRC shorter than 32 bits) + */ +static uint32_t CRC_Handle_16(CRC_HandleTypeDef *hcrc, uint16_t pBuffer[], uint32_t BufferLength) +{ + uint32_t i = 0; /* input data buffer index */ + + /* Processing time optimization: 2 HalfWords are entered in a row with a single word write, + * in case of odd length, last HalfWord must be carefully fed to the CRC calculator to ensure + * a correct type handling by the IP */ + for(i = 0; i < (BufferLength/2); i++) + { + hcrc->Instance->DR = (pBuffer[2*i]<<16) | pBuffer[2*i+1]; + } + if ((BufferLength%2) != 0) + { + *(uint16_t*) (&hcrc->Instance->DR) = pBuffer[2*i]; + } + + /* Return the CRC computed value */ + return hcrc->Instance->DR; +} + +/** + * @} + */ + +/** @defgroup HAL_CRC_Group3 Peripheral State functions + * @brief Peripheral State functions. + * +@verbatim + =============================================================================== + ##### Peripheral State functions ##### + =============================================================================== + [..] + This subsection permits to get in run-time the status of the peripheral + and the data flow. + +@endverbatim + * @{ + */ + +/** + * @brief Returns the CRC state. + * @param hcrc: CRC handle + * @retval HAL state + */ +HAL_CRC_StateTypeDef HAL_CRC_GetState(CRC_HandleTypeDef *hcrc) +{ + return hcrc->State; +} + +/** + * @} + */ + +/** + * @} + */ + +#endif /* HAL_CRC_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_crc.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_crc.h new file mode 100644 index 0000000000..bf5a7925b4 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_crc.h @@ -0,0 +1,270 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_crc.h + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief Header file of CRC HAL module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32F0xx_HAL_CRC_H +#define __STM32F0xx_HAL_CRC_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal_def.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @addtogroup CRC + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ + +/** + * @brief CRC HAL State Structure definition + */ +typedef enum +{ + HAL_CRC_STATE_RESET = 0x00, /*!< CRC not yet initialized or disabled */ + HAL_CRC_STATE_READY = 0x01, /*!< CRC initialized and ready for use */ + HAL_CRC_STATE_BUSY = 0x02, /*!< CRC internal process is ongoing */ + HAL_CRC_STATE_TIMEOUT = 0x03, /*!< CRC timeout state */ + HAL_CRC_STATE_ERROR = 0x04 /*!< CRC error state */ +}HAL_CRC_StateTypeDef; + + +/** + * @brief CRC Init Structure definition + */ +typedef struct +{ + uint8_t DefaultPolynomialUse; /*!< This parameter is a value of @ref CRC_Default_Polynomial and indicates if default polynomial is used. + If set to DEFAULT_POLYNOMIAL_ENABLE, resort to default + X^32 + X^26 + X^23 + X^22 + X^16 + X^12 + X^11 + X^10 +X^8 + X^7 + X^5 + X^4 + X^2+ X +1. + In that case, there is no need to set GeneratingPolynomial field. + If otherwise set to DEFAULT_POLYNOMIAL_DISABLE, GeneratingPolynomial and CRCLength fields must be set */ + + uint8_t DefaultInitValueUse; /*!< This parameter is a value of @ref CRC_Default_InitValue_Use and indicates if default init value is used. + If set to DEFAULT_INIT_VALUE_ENABLE, resort to default + 0xFFFFFFFF value. In that case, there is no need to set InitValue field. + If otherwise set to DEFAULT_INIT_VALUE_DISABLE, InitValue field must be set */ + + uint32_t GeneratingPolynomial; /*!< Set CRC generating polynomial. 7, 8, 16 or 32-bit long value for a polynomial degree + respectively equal to 7, 8, 16 or 32. This field is written in normal representation, + e.g., for a polynomial of degree 7, X^7 + X^6 + X^5 + X^2 + 1 is written 0x65. + No need to specify it if DefaultPolynomialUse is set to DEFAULT_POLYNOMIAL_ENABLE */ + + uint32_t CRCLength; /*!< This parameter is a value of @ref CRCEx_Polynomial_Size_Definitions and indicates CRC length. + Value can be either one of + CRC_POLYLENGTH_32B (32-bit CRC) + CRC_POLYLENGTH_16B (16-bit CRC) + CRC_POLYLENGTH_8B (8-bit CRC) + CRC_POLYLENGTH_7B (7-bit CRC) */ + + uint32_t InitValue; /*!< Init value to initiate CRC computation. No need to specify it if DefaultInitValueUse + is set to DEFAULT_INIT_VALUE_ENABLE */ + + uint32_t InputDataInversionMode; /*!< This parameter is a value of @ref CRCEx_Input_Data_Inversion and specifies input data inversion mode. + Can be either one of the following values + CRC_INPUTDATA_INVERSION_NONE no input data inversion + CRC_INPUTDATA_INVERSION_BYTE byte-wise inversion, 0x1A2B3C4D becomes 0x58D43CB2 + CRC_INPUTDATA_INVERSION_HALFWORD halfword-wise inversion, 0x1A2B3C4D becomes 0xD458B23C + CRC_INPUTDATA_INVERSION_WORD word-wise inversion, 0x1A2B3C4D becomes 0xB23CD458 */ + + uint32_t OutputDataInversionMode; /*!< This parameter is a value of @ref CRCEx_Output_Data_Inversion and specifies output data (i.e. CRC) inversion mode. + Can be either + CRC_OUTPUTDATA_INVERSION_DISABLED no CRC inversion, or + CRC_OUTPUTDATA_INVERSION_ENABLED CRC 0x11223344 is converted into 0x22CC4488 */ +}CRC_InitTypeDef; + + +/** + * @brief CRC Handle Structure definition + */ +typedef struct +{ + CRC_TypeDef *Instance; /*!< Register base address */ + + CRC_InitTypeDef Init; /*!< CRC configuration parameters */ + + HAL_LockTypeDef Lock; /*!< CRC Locking object */ + + __IO HAL_CRC_StateTypeDef State; /*!< CRC communication state */ + + uint32_t InputDataFormat; /*!< This parameter is a value of @ref CRC_Input_Buffer_Format and specifies input data format. + Can be either + CRC_INPUTDATA_FORMAT_BYTES input data is a stream of bytes (8-bit data) + CRC_INPUTDATA_FORMAT_HALFWORDS input data is a stream of half-words (16-bit data) + CRC_INPUTDATA_FORMAT_WORDS input data is a stream of words (32-bits data) + Note that constant CRC_INPUT_FORMAT_UNDEFINED is defined but an initialization error + must occur if InputBufferFormat is not one of the three values listed above */ +}CRC_HandleTypeDef; + +/* Exported constants --------------------------------------------------------*/ + +/** @defgroup CRC_Default_Polynomial_Value Default CRC generating polynomial + * @{ + */ +#define DEFAULT_CRC32_POLY 0x04C11DB7 + +/** + * @} + */ + +/** @defgroup CRC_Default_InitValue Default CRC computation initialization value + * @{ + */ +#define DEFAULT_CRC_INITVALUE 0xFFFFFFFF + +/** + * @} + */ + +/** @defgroup CRC_Default_Polynomial Indicates whether or not default polynomial is used + * @{ + */ +#define DEFAULT_POLYNOMIAL_ENABLE ((uint8_t)0x00) +#define DEFAULT_POLYNOMIAL_DISABLE ((uint8_t)0x01) + +#define IS_DEFAULT_POLYNOMIAL(DEFAULT) (((DEFAULT) == DEFAULT_POLYNOMIAL_ENABLE) || \ + ((DEFAULT) == DEFAULT_POLYNOMIAL_DISABLE)) + +/** + * @} + */ + +/** @defgroup CRC_Default_InitValue_Use Indicates whether or not default init value is used + * @{ + */ +#define DEFAULT_INIT_VALUE_ENABLE ((uint8_t)0x00) +#define DEFAULT_INIT_VALUE_DISABLE ((uint8_t)0x01) + +#define IS_DEFAULT_INIT_VALUE(VALUE) (((VALUE) == DEFAULT_INIT_VALUE_ENABLE) || \ + ((VALUE) == DEFAULT_INIT_VALUE_DISABLE)) +/** + * @} + */ + +/** @defgroup CRC_Input_Buffer_Format Input Buffer Format + * @{ + */ +/* WARNING: CRC_INPUT_FORMAT_UNDEFINED is created for reference purposes but + * an error is triggered in HAL_CRC_Init() if InputDataFormat field is set + * to CRC_INPUT_FORMAT_UNDEFINED: the format MUST be defined by the user for + * the CRC APIs to provide a correct result */ +#define CRC_INPUTDATA_FORMAT_UNDEFINED ((uint32_t)0x00000000) +#define CRC_INPUTDATA_FORMAT_BYTES ((uint32_t)0x00000001) +#define CRC_INPUTDATA_FORMAT_HALFWORDS ((uint32_t)0x00000002) +#define CRC_INPUTDATA_FORMAT_WORDS ((uint32_t)0x00000003) + +#define IS_CRC_INPUTDATA_FORMAT(FORMAT) (((FORMAT) == CRC_INPUTDATA_FORMAT_BYTES) || \ + ((FORMAT) == CRC_INPUTDATA_FORMAT_HALFWORDS) || \ + ((FORMAT) == CRC_INPUTDATA_FORMAT_WORDS)) +/** + * @} + */ + +/* Exported macros -----------------------------------------------------------*/ + +/** @defgroup CRC_Exported_Macros + * @{ + */ + +/** @brief Reset CRC handle state + * @param __HANDLE__: CRC handle. + * @retval None + */ +#define __HAL_CRC_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_CRC_STATE_RESET) + +/** + * @brief Reset CRC Data Register. + * @param __HANDLE__: CRC handle + * @retval None. + */ +#define __HAL_CRC_DR_RESET(__HANDLE__) ((__HANDLE__)->Instance->CR |= CRC_CR_RESET) + +/** + * @brief Set CRC INIT non-default value + * @param __HANDLE__ : CRC handle + * @param __INIT__ : 32-bit initial value + * @retval None. + */ +#define __HAL_CRC_INITIALCRCVALUE_CONFIG(__HANDLE__, __INIT__) ((__HANDLE__)->Instance->INIT = (__INIT__)) + +/** + * @} + */ + + +/* Include CRC HAL Extension module */ +#include "stm32f0xx_hal_crc_ex.h" + +/* Exported functions --------------------------------------------------------*/ + +/* Initialization and de-initialization functions ****************************/ +HAL_StatusTypeDef HAL_CRC_Init(CRC_HandleTypeDef *hcrc); +HAL_StatusTypeDef HAL_CRC_DeInit (CRC_HandleTypeDef *hcrc); +void HAL_CRC_MspInit(CRC_HandleTypeDef *hcrc); +void HAL_CRC_MspDeInit(CRC_HandleTypeDef *hcrc); +/* Aliases for inter STM32 series compatibility */ +#define HAL_CRC_Input_Data_Reverse HAL_CRCEx_Input_Data_Reverse +#define HAL_CRC_Output_Data_Reverse HAL_CRCEx_Output_Data_Reverse + +/* Peripheral Control functions ***********************************************/ +uint32_t HAL_CRC_Accumulate(CRC_HandleTypeDef *hcrc, uint32_t pBuffer[], uint32_t BufferLength); +uint32_t HAL_CRC_Calculate(CRC_HandleTypeDef *hcrc, uint32_t pBuffer[], uint32_t BufferLength); + +/* Peripheral State and Error functions ***************************************/ +HAL_CRC_StateTypeDef HAL_CRC_GetState(CRC_HandleTypeDef *hcrc); + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __STM32F0xx_HAL_CRC_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_crc_ex.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_crc_ex.c new file mode 100644 index 0000000000..ad3600de47 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_crc_ex.c @@ -0,0 +1,276 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_crc_ex.c + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief Extended CRC HAL module driver. + * + * This file provides firmware functions to manage the following + * functionalities of the CRC peripheral: + * + Extended initialization functions + * + @verbatim +================================================================================ + ##### ##### +================================================================================ + + + ##### How to use this driver ##### +================================================================================ + [..] + (+) Extended initialization + (+) Set or not user-defined generating + polynomial other than default one + + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @defgroup CRCEx + * @brief CRC Extended HAL module driver + * @{ + */ + +#ifdef HAL_CRC_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup CRCEx_Private_Functions + * @{ + */ + +/** @defgroup CRCEx_Group1 Extended Initialization/de-initialization functions + * @brief Extended Initialization and Configuration functions. + * +@verbatim + =============================================================================== + ##### Initialization/de-initialization function ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Initialize the CRC generating polynomial: if programmable polynomial + feature is applicable to device, set default or non-default generating + polynomial according to hcrc->Init.DefaultPolynomialUse parameter. + If feature is non-applicable to device in use, HAL_CRCEx_Init straight + away reports HAL_OK. + (+) Set the generating polynomial + +@endverbatim + * @{ + */ + + +/** + * @brief Extended initialization to set generating polynomial + * @param hcrc: CRC handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_CRCEx_Init(CRC_HandleTypeDef *hcrc) +{ +#if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) + /* check whether or not non-default generating polynomial has been + * picked up by user */ + assert_param(IS_DEFAULT_POLYNOMIAL(hcrc->Init.DefaultPolynomialUse)); + if (hcrc->Init.DefaultPolynomialUse == DEFAULT_POLYNOMIAL_ENABLE) + { + /* initialize IP with default generating polynomial */ + WRITE_REG(hcrc->Instance->POL, DEFAULT_CRC32_POLY); + MODIFY_REG(hcrc->Instance->CR, CRC_CR_POLYSIZE, CRC_POLYLENGTH_32B); + } + else + { + /* initialize CRC IP with generating polynomial defined by user */ + if (HAL_CRCEx_Polynomial_Set(hcrc, hcrc->Init.GeneratingPolynomial, hcrc->Init.CRCLength) != HAL_OK) + { + return HAL_ERROR; + } + } +#endif /* defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) */ + + return HAL_OK; +} + +/** + * @brief Set the Reverse Input data mode. + * @param hcrc: CRC handle + * @param InputReverseMode: Input Data inversion mode + * This parameter can be one of the following values: + * @arg CRC_INPUTDATA_NOINVERSION: no change in bit order (default value) + * @arg CRC_INPUTDATA_INVERSION_BYTE: Byte-wise bit reversal + * @arg CRC_INPUTDATA_INVERSION_HALFWORD: HalfWord-wise bit reversal + * @arg CRC_INPUTDATA_INVERSION_WORD: Word-wise bit reversal + * @retval HAL status + */ +HAL_StatusTypeDef HAL_CRCEx_Input_Data_Reverse(CRC_HandleTypeDef *hcrc, uint32_t InputReverseMode) +{ + /* Check the parameters */ + assert_param(IS_CRC_INPUTDATA_INVERSION_MODE(InputReverseMode)); + + /* Change CRC peripheral state */ + hcrc->State = HAL_CRC_STATE_BUSY; + + /* set input data inversion mode */ + MODIFY_REG(hcrc->Instance->CR, CRC_CR_REV_IN, InputReverseMode); + /* Change CRC peripheral state */ + hcrc->State = HAL_CRC_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Set the Reverse Output data mode. + * @param hcrc: CRC handle + * @param OutputReverseMode: Output Data inversion mode + * This parameter can be one of the following values: + * @arg CRC_OUTPUTDATA_INVERSION_DISABLED: no CRC inversion (default value) + * @arg CRC_OUTPUTDATA_INVERSION_ENABLED: bit-level inversion (e.g for a 8-bit CRC: 0xB5 becomes 0xAD) + * @retval HAL status + */ +HAL_StatusTypeDef HAL_CRCEx_Output_Data_Reverse(CRC_HandleTypeDef *hcrc, uint32_t OutputReverseMode) +{ + /* Check the parameters */ + assert_param(IS_CRC_OUTPUTDATA_INVERSION_MODE(OutputReverseMode)); + + /* Change CRC peripheral state */ + hcrc->State = HAL_CRC_STATE_BUSY; + + /* set output data inversion mode */ + MODIFY_REG(hcrc->Instance->CR, CRC_CR_REV_OUT, OutputReverseMode); + + /* Change CRC peripheral state */ + hcrc->State = HAL_CRC_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +#if defined (STM32F071xB) || defined (STM32F072xB) || defined (STM32F078xx) +/** + * @brief Initializes the CRC polynomial if different from default one. + * @param hcrc: CRC handle + * @param Pol: CRC generating polynomial (7, 8, 16 or 32-bit long) + * This parameter is written in normal representation, e.g. + * for a polynomial of degree 7, X^7 + X^6 + X^5 + X^2 + 1 is written 0x65 + * for a polynomial of degree 16, X^16 + X^12 + X^5 + 1 is written 0x1021 + * @param PolyLength: CRC polynomial length + * This parameter can be one of the following values: + * @arg CRC_POLYLENGTH_7B: 7-bit long CRC (generating polynomial of degree 7) + * @arg CRC_POLYLENGTH_8B: 8-bit long CRC (generating polynomial of degree 8) + * @arg CRC_POLYLENGTH_16B: 16-bit long CRC (generating polynomial of degree 16) + * @arg CRC_POLYLENGTH_32B: 32-bit long CRC (generating polynomial of degree 32) + * @retval HAL status + */ +HAL_StatusTypeDef HAL_CRCEx_Polynomial_Set(CRC_HandleTypeDef *hcrc, uint32_t Pol, uint32_t PolyLength) +{ + uint32_t msb = 31; /* polynomial degree is 32 at most, so msb is initialized to max value */ + + /* Check the parameters */ + assert_param(IS_CRC_POL_LENGTH(PolyLength)); + + /* check polynomial definition vs polynomial size: + * polynomial length must be aligned with polynomial + * definition. HAL_ERROR is reported if Pol degree is + * larger than that indicated by PolyLength. + * Look for MSB position: msb will contain the degree of + * the second to the largest polynomial member. E.g., for + * X^7 + X^6 + X^5 + X^2 + 1, msb = 6. */ + while (((Pol & (0x1 << msb)) == 0) && (msb-- > 0)); + + switch (PolyLength) + { + case CRC_POLYLENGTH_7B: + if (msb >= HAL_CRC_LENGTH_7B) + { + return HAL_ERROR; + } + break; + case CRC_POLYLENGTH_8B: + if (msb >= HAL_CRC_LENGTH_8B) + { + return HAL_ERROR; + } + break; + case CRC_POLYLENGTH_16B: + if (msb >= HAL_CRC_LENGTH_16B) + { + return HAL_ERROR; + } + break; + case CRC_POLYLENGTH_32B: + /* no polynomial definition vs. polynomial length issue possible */ + break; + default: + break; + } + + /* set generating polynomial */ + WRITE_REG(hcrc->Instance->POL, Pol); + + /* set generating polynomial size */ + MODIFY_REG(hcrc->Instance->CR, CRC_CR_POLYSIZE, PolyLength); + + /* Return function status */ + return HAL_OK; +} +#endif /* #if defined (STM32F071xB) || defined (STM32F072xB) || defined (STM32F078xx) */ + +/** + * @} + */ + + +/** + * @} + */ + + +#endif /* HAL_CRC_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_crc_ex.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_crc_ex.h new file mode 100644 index 0000000000..fa0fab6afc --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_crc_ex.h @@ -0,0 +1,177 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_crc_ex.h + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief Header file of CRC HAL extension module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32F0xx_HAL_CRC_EX_H +#define __STM32F0xx_HAL_CRC_EX_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal_def.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @addtogroup CRCEx + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/* Exported constants --------------------------------------------------------*/ + +/** @defgroup CRCEx_Input_Data_Inversion Input Data Inversion Modes + * @{ + */ +#define CRC_INPUTDATA_INVERSION_NONE ((uint32_t)0x00000000) +#define CRC_INPUTDATA_INVERSION_BYTE ((uint32_t)CRC_CR_REV_IN_0) +#define CRC_INPUTDATA_INVERSION_HALFWORD ((uint32_t)CRC_CR_REV_IN_1) +#define CRC_INPUTDATA_INVERSION_WORD ((uint32_t)CRC_CR_REV_IN) + +#define IS_CRC_INPUTDATA_INVERSION_MODE(MODE) (((MODE) == CRC_INPUTDATA_INVERSION_NONE) || \ + ((MODE) == CRC_INPUTDATA_INVERSION_BYTE) || \ + ((MODE) == CRC_INPUTDATA_INVERSION_HALFWORD) || \ + ((MODE) == CRC_INPUTDATA_INVERSION_WORD)) +/** + * @} + */ + +/** @defgroup CRCEx_Output_Data_Inversion Output Data Inversion Modes + * @{ + */ +#define CRC_OUTPUTDATA_INVERSION_DISABLED ((uint32_t)0x00000000) +#define CRC_OUTPUTDATA_INVERSION_ENABLED ((uint32_t)CRC_CR_REV_OUT) + +#define IS_CRC_OUTPUTDATA_INVERSION_MODE(MODE) (((MODE) == CRC_OUTPUTDATA_INVERSION_DISABLED) || \ + ((MODE) == CRC_OUTPUTDATA_INVERSION_ENABLED)) +/** + * @} + */ + +#if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) +/** @defgroup CRCEx_Polynomial_Sizes Polynomial sizes to configure the IP + * @{ + */ +#define CRC_POLYLENGTH_32B ((uint32_t)0x00000000) +#define CRC_POLYLENGTH_16B ((uint32_t)CRC_CR_POLYSIZE_0) +#define CRC_POLYLENGTH_8B ((uint32_t)CRC_CR_POLYSIZE_1) +#define CRC_POLYLENGTH_7B ((uint32_t)CRC_CR_POLYSIZE) +#define IS_CRC_POL_LENGTH(LENGTH) (((LENGTH) == CRC_POLYLENGTH_32B) || \ + ((LENGTH) == CRC_POLYLENGTH_16B) || \ + ((LENGTH) == CRC_POLYLENGTH_8B) || \ + ((LENGTH) == CRC_POLYLENGTH_7B)) +/** + * @} + */ + +/** @defgroup CRCEx_Polynomial_Size_Definitions CRC polynomial possible sizes actual definitions + * @{ + */ +#define HAL_CRC_LENGTH_32B 32 +#define HAL_CRC_LENGTH_16B 16 +#define HAL_CRC_LENGTH_8B 8 +#define HAL_CRC_LENGTH_7B 7 +/** + * @} + */ +#endif /* defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) */ + +/* Exported macro ------------------------------------------------------------*/ + +/** @defgroup CRCEx_Exported_Macros + * @{ + */ + +/** + * @brief Set CRC output reversal + * @param __HANDLE__ : CRC handle + * @retval None. + */ +#define __HAL_CRC_OUTPUTREVERSAL_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= CRC_CR_REV_OUT) + +/** + * @brief Unset CRC output reversal + * @param __HANDLE__ : CRC handle + * @retval None. + */ +#define __HAL_CRC_OUTPUTREVERSAL_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~(CRC_CR_REV_OUT)) + +#if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) +/** + * @brief Set CRC non-default polynomial + * @param __HANDLE__ : CRC handle + * @param __POLYNOMIAL__: 7, 8, 16 or 32-bit polynomial + * @retval None. + */ +#define __HAL_CRC_POLYNOMIAL_CONFIG(__HANDLE__, __POLYNOMIAL__) ((__HANDLE__)->Instance->POL = (__POLYNOMIAL__)) +#endif /* defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) */ +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/* Initialization and de-initialization functions ****************************/ +HAL_StatusTypeDef HAL_CRCEx_Init(CRC_HandleTypeDef *hcrc); +HAL_StatusTypeDef HAL_CRCEx_Input_Data_Reverse(CRC_HandleTypeDef *hcrc, uint32_t InputReverseMode); +HAL_StatusTypeDef HAL_CRCEx_Output_Data_Reverse(CRC_HandleTypeDef *hcrc, uint32_t OutputReverseMode); + +#if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) +HAL_StatusTypeDef HAL_CRCEx_Polynomial_Set(CRC_HandleTypeDef *hcrc, uint32_t Pol, uint32_t PolyLength); +#endif /* defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) */ + +/* Peripheral Control functions ***********************************************/ +/* Peripheral State and Error functions ***************************************/ + + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __STM32F0xx_HAL_CRC_EX_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_dac.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_dac.c new file mode 100644 index 0000000000..325c045dab --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_dac.c @@ -0,0 +1,682 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_dac.c + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief DAC HAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the Digital to Analog Converter (DAC) peripheral: + * + Initialization and de-initialization functions + * + IO operation functions + * + Peripheral Control functions + * + Peripheral State and Errors functions + * + * + @verbatim + ============================================================================== + ##### DAC Peripheral features ##### + ============================================================================== + [..] + *** DAC Channels *** + ==================== + [..] + STM32F0 devices integrates no, one or two 12-bit Digital Analog Converters. + STM32F05x devices have one converter (channel1) + STM32F07x & STM32F09x devices have two converters (i.e. channel1 & channel2) + + When 2 converters are present (i.e. channel1 & channel2) they + can be used independently or simultaneously (dual mode): + (#) DAC channel1 with DAC_OUT1 (PA4) as output + (#) DAC channel2 with DAC_OUT2 (PA5) as output + + *** DAC Triggers *** + ==================== + [..] + Digital to Analog conversion can be non-triggered using DAC_Trigger_None + and DAC_OUT1/DAC_OUT2 is available once writing to DHRx register. + [..] + Digital to Analog conversion can be triggered by: + (#) External event: EXTI Line 9 (any GPIOx_Pin9) using DAC_Trigger_Ext_IT9. + The used pin (GPIOx_Pin9) must be configured in input mode. + + (#) Timers TRGO: TIM2, TIM3, TIM6, and TIM15 + (DAC_Trigger_T2_TRGO, DAC_Trigger_T3_TRGO...) + + (#) Software using DAC_Trigger_Software + + *** DAC Buffer mode feature *** + =============================== + [..] + Each DAC channel integrates an output buffer that can be used to + reduce the output impedance, and to drive external loads directly + without having to add an external operational amplifier. + To enable, the output buffer use + sConfig.DAC_OutputBuffer = DAC_OutputBuffer_Enable; + [..] + (@) Refer to the device datasheet for more details about output + impedance value with and without output buffer. + + *** DAC wave generation feature *** + =================================== + [..] + Both DAC channels can be used to generate + (#) Noise wave + (#) Triangle wave + + *** DAC data format *** + ======================= + [..] + The DAC data format can be: + (#) 8-bit right alignment using DAC_ALIGN_8B_R + (#) 12-bit left alignment using DAC_ALIGN_12B_L + (#) 12-bit right alignment using DAC_ALIGN_12B_R + + *** DAC data value to voltage correspondence *** + ================================================ + [..] + The analog output voltage on each DAC channel pin is determined + by the following equation: + DAC_OUTx = VREF+ * DOR / 4095 + with DOR is the Data Output Register + VEF+ is the input voltage reference (refer to the device datasheet) + e.g. To set DAC_OUT1 to 0.7V, use + Assuming that VREF+ = 3.3V, DAC_OUT1 = (3.3 * 868) / 4095 = 0.7V + + *** DMA requests *** + ===================== + [..] + A DMA1 request can be generated when an external trigger (but not + a software trigger) occurs if DMA1 requests are enabled using + HAL_DAC_Start_DMA() + [..] + DMA1 requests are mapped as following: + (#) DAC channel1 : mapped on DMA1 channel3 which must be + already configured + (#) DAC channel2 : mapped on DMA1 channel4 which must be + already configured + + -@- For Dual mode and specific signal (Triangle and noise) generation please + refer to Extension Features Driver description + STM32F0 devices with one channel (one converting capability) does not + support Dual mode and specific signal (Triangle and noise) generation. + + ##### How to use this driver ##### + ============================================================================== + [..] + (+) DAC APB clock must be enabled to get write access to DAC + registers using HAL_DAC_Init() + (+) Configure DAC_OUTx (DAC_OUT1: PA4, DAC_OUT2: PA5) in analog mode. + (+) Configure the DAC channel using HAL_DAC_ConfigChannel() function. + (+) Enable the DAC channel using HAL_DAC_Start() or HAL_DAC_Start_DMA functions + + *** Polling mode IO operation *** + ================================= + [..] + (+) Start the DAC peripheral using HAL_DAC_Start() + (+) To read the DAC last data output value value, use the HAL_DAC_GetValue() function. + (+) Stop the DAC peripheral using HAL_DAC_Stop() + + *** DMA mode IO operation *** + ============================== + [..] + (+) Start the DAC peripheral using HAL_DAC_Start_DMA(), at this stage the user specify the length + of data to be transfered at each end of conversion + (+) At The end of data transfer HAL_DAC_ConvCpltCallbackCh1()or HAL_DAC_ConvCpltCallbackCh2() + function is executed and user can add his own code by customization of function pointer + HAL_DAC_ConvCpltCallbackCh1 or HAL_DAC_ConvCpltCallbackCh2 + (+) In case of transfer Error, HAL_DAC_ErrorCallbackCh1() function is executed and user can + add his own code by customization of function pointer HAL_DAC_ErrorCallbackCh1 + (+) Stop the DAC peripheral using HAL_DAC_Stop_DMA() + + *** DAC HAL driver macros list *** + ============================================= + [..] + Below the list of most used macros in DAC HAL driver. + + (+) __HAL_DAC_ENABLE : Enable the DAC peripheral + (+) __HAL_DAC_DISABLE : Disable the DAC peripheral + (+) __HAL_DAC_CLEAR_FLAG: Clear the DAC's pending flags + (+) __HAL_DAC_GET_FLAG: Get the selected DAC's flag status + + [..] + (@) You can refer to the DAC HAL driver header file for more useful macros + + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @defgroup DAC + * @brief DAC driver modules + * @{ + */ + +#ifdef HAL_DAC_MODULE_ENABLED + +#if defined(STM32F051x8) || defined(STM32F058xx) || \ + defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ + +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup DAC_Private_Functions + * @{ + */ + +/** @defgroup DAC_Group1 Initialization and de-initialization functions + * @brief Initialization and Configuration functions + * +@verbatim + ============================================================================== + ##### Initialization and de-initialization functions ##### + ============================================================================== + [..] This section provides functions allowing to: + (+) Initialize and configure the DAC. + (+) De-initialize the DAC. + +@endverbatim + * @{ + */ + +/** + * @brief Initializes the DAC peripheral according to the specified parameters + * in the DAC_InitStruct. + * @param hdac: pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_DAC_Init(DAC_HandleTypeDef* hdac) +{ + /* Check DAC handle */ + if(hdac == NULL) + { + return HAL_ERROR; + } + /* Check the parameters */ + assert_param(IS_DAC_ALL_INSTANCE(hdac->Instance)); + + if(hdac->State == HAL_DAC_STATE_RESET) + { + /* Init the low level hardware */ + HAL_DAC_MspInit(hdac); + } + + /* Initialize the DAC state*/ + hdac->State = HAL_DAC_STATE_BUSY; + + /* Set DAC error code to none */ + hdac->ErrorCode = HAL_DAC_ERROR_NONE; + + /* Initialize the DAC state*/ + hdac->State = HAL_DAC_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Deinitializes the DAC peripheral registers to their default reset values. + * @param hdac: pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_DAC_DeInit(DAC_HandleTypeDef* hdac) +{ + /* Check DAC handle */ + if(hdac == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_DAC_ALL_INSTANCE(hdac->Instance)); + + /* Change DAC state */ + hdac->State = HAL_DAC_STATE_BUSY; + + /* DeInit the low level hardware */ + HAL_DAC_MspDeInit(hdac); + + /* Set DAC error code to none */ + hdac->ErrorCode = HAL_DAC_ERROR_NONE; + + /* Change DAC state */ + hdac->State = HAL_DAC_STATE_RESET; + + /* Release Lock */ + __HAL_UNLOCK(hdac); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Initializes the DAC MSP. + * @param hdac: pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @retval None + */ +__weak void HAL_DAC_MspInit(DAC_HandleTypeDef* hdac) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_DAC_MspInit could be implemented in the user file + */ +} + +/** + * @brief DeInitializes the DAC MSP. + * @param hdac: pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @retval None + */ +__weak void HAL_DAC_MspDeInit(DAC_HandleTypeDef* hdac) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_DAC_MspDeInit could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup DAC_Group2 IO operation functions + * @brief IO operation functions + * +@verbatim + ============================================================================== + ##### IO operation functions ##### + ============================================================================== + [..] This section provides functions allowing to: + (+) Start conversion. + (+) Stop conversion. + (+) Start conversion and enable DMA transfer. + (+) Stop conversion and disable DMA transfer. + (+) Get result of conversion. + +@endverbatim + * @{ + */ + +/** + * @brief Enables DAC and starts conversion of channel. + * @param hdac: pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @param Channel: The selected DAC channel. + * This parameter can be one of the following values: + * @arg DAC_CHANNEL_1: DAC Channel1 selected + * @arg DAC_CHANNEL_2: DAC Channel2 selected + * @retval HAL status + */ +__weak HAL_StatusTypeDef HAL_DAC_Start(DAC_HandleTypeDef* hdac, uint32_t Channel) +{ + /* Note : This function is defined into this file for library reference. */ + /* Function content is located into file stm32f0xx_hal_dac_ex.c */ + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Disables DAC and stop conversion of channel. + * @param hdac: pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @param Channel: The selected DAC channel. + * This parameter can be one of the following values: + * @arg DAC_CHANNEL_1: DAC Channel1 selected + * @arg DAC_CHANNEL_2: DAC Channel2 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_DAC_Stop(DAC_HandleTypeDef* hdac, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_DAC_CHANNEL(Channel)); + + /* Disable the Peripheral */ + __HAL_DAC_DISABLE(hdac, Channel); + + /* Change DAC state */ + hdac->State = HAL_DAC_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Enables DAC and starts conversion of channel. + * @param hdac: pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @param Channel: The selected DAC channel. + * This parameter can be one of the following values: + * @arg DAC_CHANNEL_1: DAC Channel1 selected + * @arg DAC_CHANNEL_2: DAC Channel2 selected + * @param pData: The destination peripheral Buffer address. + * @param Length: The length of data to be transferred from memory to DAC peripheral + * @param Alignment: Specifies the data alignment for DAC channel. + * This parameter can be one of the following values: + * @arg DAC_ALIGN_8B_R: 8bit right data alignment selected + * @arg DAC_ALIGN_12B_L: 12bit left data alignment selected + * @arg DAC_ALIGN_12B_R: 12bit right data alignment selected + * @retval HAL status + */ +__weak HAL_StatusTypeDef HAL_DAC_Start_DMA(DAC_HandleTypeDef* hdac, uint32_t Channel, uint32_t* pData, uint32_t Length, uint32_t Alignment) +{ + /* Note : This function is defined into this file for library reference. */ + /* Function content is located into file stm32f0xx_hal_dac_ex.c */ + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Disables DAC and stop conversion of channel. + * @param hdac: pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @param Channel: The selected DAC channel. + * This parameter can be one of the following values: + * @arg DAC_CHANNEL_1: DAC Channel1 selected + * @arg DAC_CHANNEL_2: DAC Channel2 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_DAC_Stop_DMA(DAC_HandleTypeDef* hdac, uint32_t Channel) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check the parameters */ + assert_param(IS_DAC_CHANNEL(Channel)); + + /* Disable the selected DAC channel DMA request */ + hdac->Instance->CR &= ~(DAC_CR_DMAEN1 << Channel); + + /* Disable the Peripharal */ + __HAL_DAC_DISABLE(hdac, Channel); + + /* Disable the DMA Channel */ + /* Channel1 is used */ + if (Channel == DAC_CHANNEL_1) + { + status = HAL_DMA_Abort(hdac->DMA_Handle1); + } + else /* Channel2 is used for */ + { + status = HAL_DMA_Abort(hdac->DMA_Handle2); + } + + + /* Change DAC state */ + hdac->State = HAL_DAC_STATE_READY; + + /* Return function status */ + return status; +} + +/** + * @brief Conversion complete callback in non blocking mode for Channel1 + * @param hdac: pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @retval None + */ +__weak void HAL_DAC_ConvCpltCallbackCh1(DAC_HandleTypeDef* hdac) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_DAC_ConvCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Conversion half DMA transfer callback in non blocking mode for Channel1 + * @param hdac: pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @retval None + */ +__weak void HAL_DAC_ConvHalfCpltCallbackCh1(DAC_HandleTypeDef* hdac) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_DAC_ConvHalfCpltCallbackCh1 could be implemented in the user file + */ +} + +/** + * @brief Error DAC callback for Channel1. + * @param hdac: pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @retval None + */ +__weak void HAL_DAC_ErrorCallbackCh1(DAC_HandleTypeDef *hdac) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_DAC_ErrorCallback could be implemented in the user file + */ +} + +/** + * @brief DMA underrun DAC callback for channel1. + * @param hdac: pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @retval None + */ +__weak void HAL_DAC_DMAUnderrunCallbackCh1(DAC_HandleTypeDef *hdac) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_DAC_DMAUnderrunCallbackCh1 could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup DAC_Group3 Peripheral Control functions + * @brief Peripheral Control functions + * +@verbatim + ============================================================================== + ##### Peripheral Control functions ##### + ============================================================================== + [..] This section provides functions allowing to: + (+) Configure channels. + (+) Set the specified data holding register value for DAC channel. + +@endverbatim + * @{ + */ + +/** + * @brief Configures the selected DAC channel. + * @param hdac: pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @param sConfig: DAC configuration structure. + * @param Channel: The selected DAC channel. + * This parameter can be one of the following values: + * @arg DAC_CHANNEL_1: DAC Channel1 selected + * @arg DAC_CHANNEL_2: DAC Channel2 selected + * @retval HAL status + */ +__weak HAL_StatusTypeDef HAL_DAC_ConfigChannel(DAC_HandleTypeDef* hdac, DAC_ChannelConfTypeDef* sConfig, uint32_t Channel) +{ + /* Note : This function is defined into this file for library reference. */ + /* Function content is located into file stm32f0xx_hal_dac_ex.c */ + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Set the specified data holding register value for DAC channel. + * @param hdac: pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @param Channel: The selected DAC channel. + * This parameter can be one of the following values: + * @arg DAC_CHANNEL_1: DAC Channel1 selected + * @arg DAC_CHANNEL_2: DAC Channel2 selected + * @param Alignment: Specifies the data alignment. + * This parameter can be one of the following values: + * @arg DAC_ALIGN_8B_R: 8bit right data alignment selected + * @arg DAC_ALIGN_12B_L: 12bit left data alignment selected + * @arg DAC_ALIGN_12B_R: 12bit right data alignment selected + * @param Data: Data to be loaded in the selected data holding register. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_DAC_SetValue(DAC_HandleTypeDef* hdac, uint32_t Channel, uint32_t Alignment, uint32_t Data) +{ + __IO uint32_t tmp = 0; + + /* Check the parameters */ + assert_param(IS_DAC_CHANNEL(Channel)); + assert_param(IS_DAC_ALIGN(Alignment)); + assert_param(IS_DAC_DATA(Data)); + + tmp = (uint32_t)hdac->Instance; + if(Channel == DAC_CHANNEL_1) + { + tmp += __HAL_DHR12R1_ALIGNEMENT(Alignment); + } + else + { + tmp += __HAL_DHR12R2_ALIGNEMENT(Alignment); + } + + /* Set the DAC channel1 selected data holding register */ + *(__IO uint32_t *) tmp = Data; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Returns the last data output value of the selected DAC channel. + * @param hdac: pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @param Channel: The selected DAC channel. + * This parameter can be one of the following values: + * @arg DAC_CHANNEL_1: DAC Channel1 selected + * @arg DAC_CHANNEL_2: DAC Channel2 selected + * @retval The selected DAC channel data output value. + */ +__weak uint32_t HAL_DAC_GetValue(DAC_HandleTypeDef* hdac, uint32_t Channel) +{ + /* Note : This function is defined into this file for library reference. */ + /* Function content is located into file stm32f0xx_hal_dac_ex.c */ + + /* Return value */ + return 0; +} + +/** + * @} + */ + +/** @defgroup DAC_Group4 Peripheral State and Errors functions + * @brief Peripheral State and Errors functions + * +@verbatim + ============================================================================== + ##### Peripheral State and Errors functions ##### + ============================================================================== + [..] + This subsection provides functions allowing to + (+) Check the DAC state. + (+) Check the DAC Errors. + +@endverbatim + * @{ + */ + +/** + * @brief return the DAC state + * @param hdac: pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @retval HAL state + */ +HAL_DAC_StateTypeDef HAL_DAC_GetState(DAC_HandleTypeDef* hdac) +{ + /* Return DAC state */ + return hdac->State; +} + + +/** + * @brief Return the DAC error code + * @param hdac: pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @retval DAC Error Code + */ +uint32_t HAL_DAC_GetError(DAC_HandleTypeDef *hdac) +{ + return hdac->ErrorCode; +} + +/** + * @brief Handles DAC interrupt request + * @param hdac: pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @retval None + */ +__weak void HAL_DAC_IRQHandler(DAC_HandleTypeDef* hdac) +{ + /* Note : This function is defined into this file for library reference. */ + /* Function content is located into file stm32f0xx_hal_dac_ex.c */ +} + +/** + * @} + */ + + +/** + * @} + */ +#endif /* STM32F051x8 || STM32F058xx || */ + /* STM32F071xB || STM32F072xB || STM32F078xx */ + +#endif /* HAL_DAC_MODULE_ENABLED */ + +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_dac.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_dac.h new file mode 100644 index 0000000000..92125352f4 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_dac.h @@ -0,0 +1,265 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_dac.h + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief Header file of DAC HAL module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32F0xx_HAL_DAC_H +#define __STM32F0xx_HAL_DAC_H + +#ifdef __cplusplus + extern "C" { +#endif + +#if defined(STM32F051x8) || defined(STM32F058xx) || \ + defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal_def.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @addtogroup DAC + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ + +/** + * @brief HAL State structures definition + */ +typedef enum +{ + HAL_DAC_STATE_RESET = 0x00, /*!< DAC not yet initialized or disabled */ + HAL_DAC_STATE_READY = 0x01, /*!< DAC initialized and ready for use */ + HAL_DAC_STATE_BUSY = 0x02, /*!< DAC internal processing is ongoing */ + HAL_DAC_STATE_TIMEOUT = 0x03, /*!< DAC timeout state */ + HAL_DAC_STATE_ERROR = 0x04 /*!< DAC error state */ + +}HAL_DAC_StateTypeDef; + +/** + * @brief DAC handle Structure definition + */ +typedef struct +{ + DAC_TypeDef *Instance; /*!< Register base address */ + + __IO HAL_DAC_StateTypeDef State; /*!< DAC communication state */ + + HAL_LockTypeDef Lock; /*!< DAC locking object */ + + DMA_HandleTypeDef *DMA_Handle1; /*!< Pointer DMA handler for channel 1 */ + + DMA_HandleTypeDef *DMA_Handle2; /*!< Pointer DMA handler for channel 2 */ + + __IO uint32_t ErrorCode; /*!< DAC Error code */ + +}DAC_HandleTypeDef; + +/** + * @brief DAC Configuration regular Channel structure definition + */ +typedef struct +{ + uint32_t DAC_Trigger; /*!< Specifies the external trigger for the selected DAC channel. + This parameter can be a value of @ref DAC_trigger_selection */ + + uint32_t DAC_OutputBuffer; /*!< Specifies whether the DAC channel output buffer is enabled or disabled. + This parameter can be a value of @ref DAC_output_buffer */ + +}DAC_ChannelConfTypeDef; + +/* Exported constants --------------------------------------------------------*/ + +/** @defgroup DAC_Error_Code + * @{ + */ +#define HAL_DAC_ERROR_NONE 0x00 /*!< No error */ +#define HAL_DAC_ERROR_DMAUNDERRUNCH1 0x01 /*!< DAC channel1 DAM underrun error */ +#define HAL_DAC_ERROR_DMAUNDERRUNCH2 0x02 /*!< DAC channel2 DAM underrun error */ +#define HAL_DAC_ERROR_DMA 0x04 /*!< DMA error */ +/** + * @} + */ + +/** @defgroup DAC_output_buffer + * @{ + */ +#define DAC_OUTPUTBUFFER_ENABLE ((uint32_t)0x00000000) +#define DAC_OUTPUTBUFFER_DISABLE ((uint32_t)DAC_CR_BOFF1) + +#define IS_DAC_OUTPUT_BUFFER_STATE(STATE) (((STATE) == DAC_OUTPUTBUFFER_ENABLE) || \ + ((STATE) == DAC_OUTPUTBUFFER_DISABLE)) +/** + * @} + */ + +/** @defgroup DAC_data_alignement + * @{ + */ +#define DAC_ALIGN_12B_R ((uint32_t)0x00000000) +#define DAC_ALIGN_12B_L ((uint32_t)0x00000004) +#define DAC_ALIGN_8B_R ((uint32_t)0x00000008) + +#define IS_DAC_ALIGN(ALIGN) (((ALIGN) == DAC_ALIGN_12B_R) || \ + ((ALIGN) == DAC_ALIGN_12B_L) || \ + ((ALIGN) == DAC_ALIGN_8B_R)) +/** + * @} + */ + +/** @defgroup DAC_data + * @{ + */ +#define IS_DAC_DATA(DATA) ((DATA) <= 0xFFF0) +/** + * @} + */ + +/** @defgroup DAC_flags_definition + * @{ + */ +#define DAC_FLAG_DMAUDR1 ((uint32_t)DAC_SR_DMAUDR1) +#define DAC_FLAG_DMAUDR2 ((uint32_t)DAC_SR_DMAUDR2) + +#define IS_DAC_FLAG(FLAG) (((FLAG) == DAC_FLAG_DMAUDR1) || \ + ((FLAG) == DAC_FLAG_DMAUDR2)) +/** + * @} + */ + +/** @defgroup DAC_IT_definition + * @{ + */ +#define DAC_IT_DMAUDR1 ((uint32_t)DAC_SR_DMAUDR1) +#define DAC_IT_DMAUDR2 ((uint32_t)DAC_SR_DMAUDR2) + +#define IS_DAC_IT(IT) (((IT) == DAC_IT_DMAUDR1) || \ + ((IT) == DAC_IT_DMAUDR2)) + +/** + * @} + */ + +/* Exported macros -----------------------------------------------------------*/ + +/** @brief Reset DAC handle state + * @param __HANDLE__: DAC handle. + * @retval None + */ +#define __HAL_DAC_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_DAC_STATE_RESET) + +/* Enable the DAC peripheral */ +#define __HAL_DAC_ENABLE(__HANDLE__, __DAC_Channel__) \ +((__HANDLE__)->Instance->CR |= (DAC_CR_EN1 << (__DAC_Channel__))) + +/* Disable the DAC peripheral */ +#define __HAL_DAC_DISABLE(__HANDLE__, __DAC_Channel__) \ +((__HANDLE__)->Instance->CR &= ~(DAC_CR_EN1 << (__DAC_Channel__))) + +/* Set DHR12R1 alignment */ +#define __HAL_DHR12R1_ALIGNEMENT(__ALIGNEMENT__) (((uint32_t)0x00000008) + (__ALIGNEMENT__)) + +/* Set DHR12R2 alignment */ +#define __HAL_DHR12R2_ALIGNEMENT(__ALIGNEMENT__) (((uint32_t)0x00000014) + (__ALIGNEMENT__)) + +/* Set DHR12RD alignment */ +#define __HAL_DHR12RD_ALIGNEMENT(__ALIGNEMENT__) (((uint32_t)0x00000020) + (__ALIGNEMENT__)) + +/* Enable the DAC interrupt */ +#define __HAL_DAC_ENABLE_IT(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->CR) |= (__INTERRUPT__)) + +/* Disable the DAC interrupt */ +#define __HAL_DAC_DISABLE_IT(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->CR) &= ~(__INTERRUPT__)) + +/* Get the selected DAC's flag status */ +#define __HAL_DAC_GET_FLAG(__HANDLE__, __FLAG__) ((((__HANDLE__)->Instance->SR) & (__FLAG__)) == (__FLAG__)) + +/* Clear the DAC's flag */ +#define __HAL_DAC_CLEAR_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->SR) |= (__FLAG__)) + +/* Include DAC HAL Extension module */ +#include "stm32f0xx_hal_dac_ex.h" + +/* Exported functions --------------------------------------------------------*/ +/* Initialization and de-initialization functions *****************************/ +HAL_StatusTypeDef HAL_DAC_Init(DAC_HandleTypeDef* hdac); +HAL_StatusTypeDef HAL_DAC_DeInit(DAC_HandleTypeDef* hdac); +void HAL_DAC_MspInit(DAC_HandleTypeDef* hdac); +void HAL_DAC_MspDeInit(DAC_HandleTypeDef* hdac); + +/* IO operation functions *****************************************************/ +HAL_StatusTypeDef HAL_DAC_Start(DAC_HandleTypeDef* hdac, uint32_t Channel); +HAL_StatusTypeDef HAL_DAC_Stop(DAC_HandleTypeDef* hdac, uint32_t Channel); +HAL_StatusTypeDef HAL_DAC_Start_DMA(DAC_HandleTypeDef* hdac, uint32_t Channel, uint32_t* pData, uint32_t Length, uint32_t Alignment); +HAL_StatusTypeDef HAL_DAC_Stop_DMA(DAC_HandleTypeDef* hdac, uint32_t Channel); + +/* Peripheral Control functions ***********************************************/ +HAL_StatusTypeDef HAL_DAC_ConfigChannel(DAC_HandleTypeDef* hdac, DAC_ChannelConfTypeDef* sConfig, uint32_t Channel); +HAL_StatusTypeDef HAL_DAC_SetValue(DAC_HandleTypeDef* hdac, uint32_t Channel, uint32_t Alignment, uint32_t Data); +uint32_t HAL_DAC_GetValue(DAC_HandleTypeDef* hdac, uint32_t Channel); + +/* Peripheral State and Error functions ***************************************/ +HAL_DAC_StateTypeDef HAL_DAC_GetState(DAC_HandleTypeDef* hdac); +void HAL_DAC_IRQHandler(DAC_HandleTypeDef* hdac); +uint32_t HAL_DAC_GetError(DAC_HandleTypeDef *hdac); + +void HAL_DAC_ConvCpltCallbackCh1(DAC_HandleTypeDef* hdac); +void HAL_DAC_ConvHalfCpltCallbackCh1(DAC_HandleTypeDef* hdac); +void HAL_DAC_ErrorCallbackCh1(DAC_HandleTypeDef *hdac); +void HAL_DAC_DMAUnderrunCallbackCh1(DAC_HandleTypeDef *hdac); + +#endif /* */ + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif /* STM32F051x8 || STM32F058xx || */ + /* STM32F071xB || STM32F072xB || STM32F078xx */ + + +#endif /*__STM32F0xx_HAL_DAC_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_dac_ex.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_dac_ex.c new file mode 100644 index 0000000000..f5747b3acd --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_dac_ex.c @@ -0,0 +1,1038 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_dac_ex.c + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief DAC HAL module driver. + * This file provides firmware functions to manage the following + * functionalities of DAC extension peripheral: + * + Extended features functions + * + * + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + (+) When Dual mode is enabled (i.e DAC Channel1 and Channel2 are used simultaneously) : + Use HAL_DACEx_DualGetValue() to get digital data to be converted and use + HAL_DACEx_DualSetValue() to set digital value to converted simultaneously in Channel 1 and Channel 2. + (+) Use HAL_DACEx_TriangleWaveGenerate() to generate Triangle signal. + (+) Use HAL_DACEx_NoiseWaveGenerate() to generate Noise signal. + + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @defgroup DACEx + * @brief DAC driver modules + * @{ + */ + +#ifdef HAL_DAC_MODULE_ENABLED + +#if defined(STM32F051x8) || defined(STM32F058xx) || \ + defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ + +static void DAC_DMAConvCpltCh1(DMA_HandleTypeDef *hdma); +static void DAC_DMAErrorCh1(DMA_HandleTypeDef *hdma); +static void DAC_DMAHalfConvCpltCh1(DMA_HandleTypeDef *hdma); + +/** @defgroup DACEx_Private_Functions + * @{ + */ + +/** @defgroup DACEx_Group1 Extended features functions + * @brief Extended features functions + * +@verbatim + ============================================================================== + ##### Extended features functions ##### + ============================================================================== + [..] This section provides functions allowing to: + (+) Start conversion. + (+) Stop conversion. + (+) Start conversion and enable DMA transfer. + (+) Stop conversion and disable DMA transfer. + (+) Get result of conversion. + (+) Get result of dual mode conversion. + +@endverbatim + * @{ + */ + +#endif /* STM32F051x8 STM32F058xx */ + /* STM32F071xB STM32F072xB STM32F078xx */ + +#if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) + +/** + * @brief Configures the selected DAC channel. + * @param hdac: pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @param sConfig: DAC configuration structure. + * @param Channel: The selected DAC channel. + * This parameter can be one of the following values: + * @arg DAC_CHANNEL_1: DAC Channel1 selected + * @arg DAC_CHANNEL_2: DAC Channel2 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_DAC_ConfigChannel(DAC_HandleTypeDef* hdac, DAC_ChannelConfTypeDef* sConfig, uint32_t Channel) +{ + uint32_t tmpreg1 = 0, tmpreg2 = 0; + + /* Check the DAC parameters */ + assert_param(IS_DAC_TRIGGER(sConfig->DAC_Trigger)); + assert_param(IS_DAC_OUTPUT_BUFFER_STATE(sConfig->DAC_OutputBuffer)); + assert_param(IS_DAC_TRIGGER(sConfig->DAC_Trigger)); + assert_param(IS_DAC_CHANNEL(Channel)); + + /* Process locked */ + __HAL_LOCK(hdac); + + /* Change DAC state */ + hdac->State = HAL_DAC_STATE_BUSY; + + /* Get the DAC CR value */ + tmpreg1 = DAC->CR; + /* Clear BOFFx, TENx, TSELx, WAVEx and MAMPx bits */ + tmpreg1 &= ~(((uint32_t)(DAC_CR_MAMP1 | DAC_CR_WAVE1 | DAC_CR_TSEL1 | DAC_CR_TEN1 | DAC_CR_BOFF1)) << Channel); + /* Configure for the selected DAC channel: buffer output, trigger */ + /* Set TSELx and TENx bits according to DAC_Trigger value */ + /* Set BOFFx bit according to DAC_OutputBuffer value */ + tmpreg2 = (sConfig->DAC_Trigger | sConfig->DAC_OutputBuffer); + /* Calculate CR register value depending on DAC_Channel */ + tmpreg1 |= tmpreg2 << Channel; + /* Write to DAC CR */ + DAC->CR = tmpreg1; + /* Disable wave generation */ + DAC->CR &= ~(DAC_CR_WAVE1 << Channel); + + /* Change DAC state */ + hdac->State = HAL_DAC_STATE_READY; + + /* Process unlocked */ + __HAL_UNLOCK(hdac); + + /* Return function status */ + return HAL_OK; +} + +#endif /* STM32F071xB STM32F072xB STM32F078xx */ + +#if defined (STM32F051x8) || defined (STM32F058xx) + +/** + * @brief Configures the selected DAC channel. + * @param hdac: pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @param sConfig: DAC configuration structure. + * @param Channel: The selected DAC channel. + * This parameter can be one of the following values: + * @arg DAC_CHANNEL_1: DAC Channel1 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_DAC_ConfigChannel(DAC_HandleTypeDef* hdac, DAC_ChannelConfTypeDef* sConfig, uint32_t Channel) +{ + uint32_t tmpreg1 = 0, tmpreg2 = 0; + + /* Check the DAC parameters */ + assert_param(IS_DAC_TRIGGER(sConfig->DAC_Trigger)); + assert_param(IS_DAC_OUTPUT_BUFFER_STATE(sConfig->DAC_OutputBuffer)); + assert_param(IS_DAC_TRIGGER(sConfig->DAC_Trigger)); + assert_param(IS_DAC_CHANNEL(Channel)); + + /* Process locked */ + __HAL_LOCK(hdac); + + /* Change DAC state */ + hdac->State = HAL_DAC_STATE_BUSY; + + /* Get the DAC CR value */ + tmpreg1 = DAC->CR; + /* Clear BOFFx, TENx, TSELx, WAVEx and MAMPx bits */ + // tmpreg1 &= ~(((uint32_t)(DAC_CR_MAMP1 | DAC_CR_WAVE1 | DAC_CR_TSEL1 | DAC_CR_TEN1 | DAC_CR_BOFF1)) << Channel); + tmpreg1 &= ~(((uint32_t)(DAC_CR_TSEL1 | DAC_CR_TEN1 | DAC_CR_BOFF1)) << Channel); + /* Configure for the selected DAC channel: buffer output, trigger */ + /* Set TSELx and TENx bits according to DAC_Trigger value */ + /* Set BOFFx bit according to DAC_OutputBuffer value */ + tmpreg2 = (sConfig->DAC_Trigger | sConfig->DAC_OutputBuffer); + /* Calculate CR register value depending on DAC_Channel */ + tmpreg1 |= tmpreg2 << Channel; + /* Write to DAC CR */ + DAC->CR = tmpreg1; + /* Disable wave generation */ + // DAC->CR &= ~(DAC_CR_WAVE1 << Channel); + + /* Change DAC state */ + hdac->State = HAL_DAC_STATE_READY; + + /* Process unlocked */ + __HAL_UNLOCK(hdac); + + /* Return function status */ + return HAL_OK; +} + +#endif /* STM32F051x8 STM32F058xx */ + +#if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) +/* DAC 1 has 2 channels 1 & 2 */ + +/** + * @brief Returns the last data output value of the selected DAC channel. + * @param hdac: pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @param Channel: The selected DAC channel. + * This parameter can be one of the following values: + * @arg DAC_CHANNEL_1: DAC Channel1 selected + * @arg DAC_CHANNEL_2: DAC Channel2 selected + * @retval The selected DAC channel data output value. + */ +uint32_t HAL_DAC_GetValue(DAC_HandleTypeDef* hdac, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_DAC_CHANNEL(Channel)); + + /* Returns the DAC channel data output register value */ + if(Channel == DAC_CHANNEL_1) + { + return hdac->Instance->DOR1; + } + else + { + return hdac->Instance->DOR2; + } +} + +#endif /* STM32F071xB STM32F072xB STM32F078xx */ + +#if defined (STM32F051x8) || defined (STM32F058xx) + +/* DAC 1 has 1 channels */ + +/** + * @brief Returns the last data output value of the selected DAC channel. + * @param hdac: pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @param Channel: The selected DAC channel. + * This parameter can be one of the following values: + * @arg DAC_CHANNEL_1: DAC Channel1 selected + * @retval The selected DAC channel data output value. + */ +uint32_t HAL_DAC_GetValue(DAC_HandleTypeDef* hdac, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_DAC_CHANNEL(Channel)); + + /* Returns the DAC channel data output register value */ + return hdac->Instance->DOR1; +} + + + +#endif /* STM32F051x8 STM32F058xx */ + +#if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) + +/** + * @brief Enables DAC and starts conversion of channel. + * @param hdac: pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @param Channel: The selected DAC channel. + * This parameter can be one of the following values: + * @arg DAC_CHANNEL_1: DAC Channel1 selected + * @arg DAC_CHANNEL_2: DAC Channel2 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_DAC_Start(DAC_HandleTypeDef* hdac, uint32_t Channel) +{ + uint32_t tmp1 = 0, tmp2 = 0; + + /* Check the parameters */ + assert_param(IS_DAC_CHANNEL(Channel)); + + /* Process locked */ + __HAL_LOCK(hdac); + + /* Change DAC state */ + hdac->State = HAL_DAC_STATE_BUSY; + + /* Enable the Peripharal */ + __HAL_DAC_ENABLE(hdac, Channel); + + if(Channel == DAC_CHANNEL_1) + { + tmp1 = hdac->Instance->CR & DAC_CR_TEN1; + tmp2 = hdac->Instance->CR & DAC_CR_TSEL1; + /* Check if software trigger enabled */ + if((tmp1 == DAC_CR_TEN1) && (tmp2 == DAC_CR_TSEL1)) + { + /* Enable the selected DAC software conversion */ + hdac->Instance->SWTRIGR |= (uint32_t)DAC_SWTRIGR_SWTRIG1; + } + } + else + { + tmp1 = hdac->Instance->CR & DAC_CR_TEN2; + tmp2 = hdac->Instance->CR & DAC_CR_TSEL2; + /* Check if software trigger enabled */ + if((tmp1 == DAC_CR_TEN2) && (tmp2 == DAC_CR_TSEL2)) + { + /* Enable the selected DAC software conversion*/ + hdac->Instance->SWTRIGR |= (uint32_t)DAC_SWTRIGR_SWTRIG2; + } + } + + /* Change DAC state */ + hdac->State = HAL_DAC_STATE_READY; + + /* Process unlocked */ + __HAL_UNLOCK(hdac); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Enables DAC and starts conversion of channel. + * @param hdac: pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @param Channel: The selected DAC channel. + * This parameter can be one of the following values: + * @arg DAC_CHANNEL_1: DAC Channel1 selected + * @arg DAC_CHANNEL_2: DAC Channel2 selected + * @param pData: The destination peripheral Buffer address. + * @param Length: The length of data to be transferred from memory to DAC peripheral + * @param Alignment: Specifies the data alignment for DAC channel. + * This parameter can be one of the following values: + * @arg DAC_ALIGN_8B_R: 8bit right data alignment selected + * @arg DAC_ALIGN_12B_L: 12bit left data alignment selected + * @arg DAC_ALIGN_12B_R: 12bit right data alignment selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_DAC_Start_DMA(DAC_HandleTypeDef* hdac, uint32_t Channel, uint32_t* pData, uint32_t Length, uint32_t Alignment) +{ + uint32_t tmpreg = 0; + + /* Check the parameters */ + assert_param(IS_DAC_CHANNEL(Channel)); + assert_param(IS_DAC_ALIGN(Alignment)); + + /* Process locked */ + __HAL_LOCK(hdac); + + /* Change DAC state */ + hdac->State = HAL_DAC_STATE_BUSY; + + if(Channel == DAC_CHANNEL_1) + { + /* Set the DMA transfer complete callback for channel1 */ + hdac->DMA_Handle1->XferCpltCallback = DAC_DMAConvCpltCh1; + + /* Set the DMA half transfer complete callback for channel1 */ + hdac->DMA_Handle1->XferHalfCpltCallback = DAC_DMAHalfConvCpltCh1; + + /* Set the DMA error callback for channel1 */ + hdac->DMA_Handle1->XferErrorCallback = DAC_DMAErrorCh1; + + /* Enable the selected DAC channel1 DMA request */ + hdac->Instance->CR |= DAC_CR_DMAEN1; + + /* Case of use of channel 1 */ + switch(Alignment) + { + case DAC_ALIGN_12B_R: + /* Get DHR12R1 address */ + tmpreg = (uint32_t)&hdac->Instance->DHR12R1; + break; + case DAC_ALIGN_12B_L: + /* Get DHR12L1 address */ + tmpreg = (uint32_t)&hdac->Instance->DHR12L1; + break; + case DAC_ALIGN_8B_R: + /* Get DHR8R1 address */ + tmpreg = (uint32_t)&hdac->Instance->DHR8R1; + break; + default: + break; + } + } + else + { + /* Set the DMA transfer complete callback for channel2 */ + hdac->DMA_Handle2->XferCpltCallback = DAC_DMAConvCpltCh2; + + /* Set the DMA half transfer complete callback for channel2 */ + hdac->DMA_Handle2->XferHalfCpltCallback = DAC_DMAHalfConvCpltCh2; + + /* Set the DMA error callback for channel2 */ + hdac->DMA_Handle2->XferErrorCallback = DAC_DMAErrorCh2; + + /* Enable the selected DAC channel2 DMA request */ + hdac->Instance->CR |= DAC_CR_DMAEN2; + + /* Case of use of channel 2 */ + switch(Alignment) + { + case DAC_ALIGN_12B_R: + /* Get DHR12R2 address */ + tmpreg = (uint32_t)&hdac->Instance->DHR12R2; + break; + case DAC_ALIGN_12B_L: + /* Get DHR12L2 address */ + tmpreg = (uint32_t)&hdac->Instance->DHR12L2; + break; + case DAC_ALIGN_8B_R: + /* Get DHR8R2 address */ + tmpreg = (uint32_t)&hdac->Instance->DHR8R2; + break; + default: + break; + } + } + + /* Enable the DMA channel */ + if(Channel == DAC_CHANNEL_1) + { + /* Enable the DAC DMA underrun interrupt */ + __HAL_DAC_ENABLE_IT(hdac, DAC_IT_DMAUDR1); + + /* Enable the DMA channel */ + HAL_DMA_Start_IT(hdac->DMA_Handle1, (uint32_t)pData, tmpreg, Length); + } + else + { + /* Enable the DAC DMA underrun interrupt */ + __HAL_DAC_ENABLE_IT(hdac, DAC_IT_DMAUDR2); + + /* Enable the DMA channel */ + HAL_DMA_Start_IT(hdac->DMA_Handle2, (uint32_t)pData, tmpreg, Length); + } + + /* Enable the Peripharal */ + __HAL_DAC_ENABLE(hdac, Channel); + + /* Process Unlocked */ + __HAL_UNLOCK(hdac); + + /* Return function status */ + return HAL_OK; +} + + + +#endif /* STM32F071xB STM32F072xB STM32F078xx */ + +#if defined (STM32F051x8) || defined (STM32F058xx) + +HAL_StatusTypeDef HAL_DAC_Start(DAC_HandleTypeDef* hdac, uint32_t Channel) +{ + uint32_t tmp1 = 0, tmp2 = 0; + + /* Check the parameters */ + assert_param(IS_DAC_CHANNEL(Channel)); + + /* Process locked */ + __HAL_LOCK(hdac); + + /* Change DAC state */ + hdac->State = HAL_DAC_STATE_BUSY; + + /* Enable the Peripharal */ + __HAL_DAC_ENABLE(hdac, Channel); + + if(Channel == DAC_CHANNEL_1) + { + tmp1 = hdac->Instance->CR & DAC_CR_TEN1; + tmp2 = hdac->Instance->CR & DAC_CR_TSEL1; + /* Check if software trigger enabled */ + if((tmp1 == DAC_CR_TEN1) && (tmp2 == DAC_CR_TSEL1)) + { + /* Enable the selected DAC software conversion */ + hdac->Instance->SWTRIGR |= (uint32_t)DAC_SWTRIGR_SWTRIG1; + } + } + + /* Change DAC state */ + hdac->State = HAL_DAC_STATE_READY; + + /* Process unlocked */ + __HAL_UNLOCK(hdac); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Enables DAC and starts conversion of channel. + * @param hdac: pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @param Channel: The selected DAC channel. + * This parameter can be one of the following values: + * @arg DAC_CHANNEL_1: DAC Channel1 selected + * @param pData: The destination peripheral Buffer address. + * @param Length: The length of data to be transferred from memory to DAC peripheral + * @param Alignment: Specifies the data alignment for DAC channel. + * This parameter can be one of the following values: + * @arg DAC_ALIGN_8B_R: 8bit right data alignment selected + * @arg DAC_ALIGN_12B_L: 12bit left data alignment selected + * @arg DAC_ALIGN_12B_R: 12bit right data alignment selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_DAC_Start_DMA(DAC_HandleTypeDef* hdac, uint32_t Channel, uint32_t* pData, uint32_t Length, uint32_t Alignment) +{ + uint32_t tmpreg = 0; + + /* Check the parameters */ + assert_param(IS_DAC_CHANNEL(Channel)); + assert_param(IS_DAC_ALIGN(Alignment)); + + /* Process locked */ + __HAL_LOCK(hdac); + + /* Change DAC state */ + hdac->State = HAL_DAC_STATE_BUSY; + + /* Set the DMA transfer complete callback for channel1 */ + hdac->DMA_Handle1->XferCpltCallback = DAC_DMAConvCpltCh1; + + /* Set the DMA half transfer complete callback for channel1 */ + hdac->DMA_Handle1->XferHalfCpltCallback = DAC_DMAHalfConvCpltCh1; + + /* Set the DMA error callback for channel1 */ + hdac->DMA_Handle1->XferErrorCallback = DAC_DMAErrorCh1; + + /* Enable the selected DAC channel1 DMA request */ + hdac->Instance->CR |= DAC_CR_DMAEN1; + + /* Case of use of channel 1 */ + switch(Alignment) + { + case DAC_ALIGN_12B_R: + /* Get DHR12R1 address */ + tmpreg = (uint32_t)&hdac->Instance->DHR12R1; + break; + case DAC_ALIGN_12B_L: + /* Get DHR12L1 address */ + tmpreg = (uint32_t)&hdac->Instance->DHR12L1; + break; + case DAC_ALIGN_8B_R: + /* Get DHR8R1 address */ + tmpreg = (uint32_t)&hdac->Instance->DHR8R1; + break; + default: + break; + } + + /* Enable the DMA channel */ + /* Enable the DAC DMA underrun interrupt */ + __HAL_DAC_ENABLE_IT(hdac, DAC_IT_DMAUDR1); + + /* Enable the DMA channel */ + HAL_DMA_Start_IT(hdac->DMA_Handle1, (uint32_t)pData, tmpreg, Length); + + /* Enable the DAC DMA underrun interrupt */ + __HAL_DAC_ENABLE_IT(hdac, DAC_IT_DMAUDR1); + + /* Enable the DMA channel */ + HAL_DMA_Start_IT(hdac->DMA_Handle1, (uint32_t)pData, tmpreg, Length); + + /* Enable the Peripharal */ + __HAL_DAC_ENABLE(hdac, Channel); + + /* Process Unlocked */ + __HAL_UNLOCK(hdac); + + /* Return function status */ + return HAL_OK; +} + +#endif /* STM32F051x8 STM32F058xx */ + +#if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) +/* DAC channel 2 is available on top of DAC channel 1 */ + +/** + * @brief Handles DAC interrupt request + * @param hdac: pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @retval None + */ +void HAL_DAC_IRQHandler(DAC_HandleTypeDef* hdac) +{ + /* Check Overrun flag */ + if(__HAL_DAC_GET_FLAG(hdac, DAC_FLAG_DMAUDR1)) + { + /* Change DAC state to error state */ + hdac->State = HAL_DAC_STATE_ERROR; + + /* Set DAC error code to chanel1 DMA underrun error */ + hdac->ErrorCode |= HAL_DAC_ERROR_DMAUNDERRUNCH1; + + /* Clear the underrun flag */ + __HAL_DAC_CLEAR_FLAG(hdac,DAC_FLAG_DMAUDR1); + + /* Disable the selected DAC channel1 DMA request */ + hdac->Instance->CR &= ~DAC_CR_DMAEN1; + + /* Error callback */ + HAL_DAC_DMAUnderrunCallbackCh1(hdac); + } + else + { + /* Change DAC state to error state */ + hdac->State = HAL_DAC_STATE_ERROR; + + /* Set DAC error code to channel2 DMA underrun error */ + hdac->ErrorCode |= HAL_DAC_ERROR_DMAUNDERRUNCH2; + + /* Clear the underrun flag */ + __HAL_DAC_CLEAR_FLAG(hdac,DAC_FLAG_DMAUDR2); + + /* Disable the selected DAC channel1 DMA request */ + hdac->Instance->CR &= ~DAC_CR_DMAEN2; + + /* Error callback */ + HAL_DACEx_DMAUnderrunCallbackCh2(hdac); + } +} + +#endif /* STM32F071xB STM32F072xB STM32F078xx */ + +#if defined (STM32F051x8) || defined (STM32F058xx) +/* DAC channel 2 is NOT available. Only DAC channel 1 is available */ + +/** + * @brief Handles DAC interrupt request + * @param hdac: pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @retval None + */ +void HAL_DAC_IRQHandler(DAC_HandleTypeDef* hdac) +{ + /* Check Overrun flag */ + if(__HAL_DAC_GET_FLAG(hdac, DAC_FLAG_DMAUDR1)) + { + /* Change DAC state to error state */ + hdac->State = HAL_DAC_STATE_ERROR; + + /* Set DAC error code to chanel1 DMA underrun error */ + hdac->ErrorCode |= HAL_DAC_ERROR_DMAUNDERRUNCH1; + + /* Clear the underrun flag */ + __HAL_DAC_CLEAR_FLAG(hdac,DAC_FLAG_DMAUDR1); + + /* Disable the selected DAC channel1 DMA request */ + hdac->Instance->CR &= ~DAC_CR_DMAEN1; + + /* Error callback */ + HAL_DAC_DMAUnderrunCallbackCh1(hdac); + } +} + +#endif /* STM32F051x8 STM32F058xx */ + +#if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) + +/** + * @brief Returns the last data output value of the selected DAC channel. + * @param hdac: pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @retval The selected DAC channel data output value. + */ +uint32_t HAL_DACEx_DualGetValue(DAC_HandleTypeDef* hdac) +{ + uint32_t tmp = 0; + + tmp |= hdac->Instance->DOR1; + + /* DAC channel 2 is present in DAC 1 */ + tmp |= hdac->Instance->DOR2 << 16; + + /* Returns the DAC channel data output register value */ + return tmp; +} + +#endif /* STM32F071xB STM32F072xB STM32F078xx */ + +#if defined (STM32F051x8) || defined (STM32F058xx) + +/** + * @brief Returns the last data output value of the selected DAC channel. + * @param hdac: pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @retval The selected DAC channel data output value. + */ +uint32_t HAL_DACEx_DualGetValue(DAC_HandleTypeDef* hdac) +{ + uint32_t tmp = 0; + + tmp |= hdac->Instance->DOR1; + + /* Returns the DAC channel data output register value */ + return tmp; +} + +#endif /* STM32F051x8 STM32F058xx */ + +#if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) + +/** + * @brief Enables or disables the selected DAC channel wave generation. + * @param hdac: pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @param Channel: The selected DAC channel. + * This parameter can be one of the following values: + * DAC_CHANNEL_1 / DAC_CHANNEL_2 + * @param Amplitude: Select max triangle amplitude. + * This parameter can be one of the following values: + * @arg DAC_TRIANGLEAMPLITUDE_1: Select max triangle amplitude of 1 + * @arg DAC_TRIANGLEAMPLITUDE_3: Select max triangle amplitude of 3 + * @arg DAC_TRIANGLEAMPLITUDE_7: Select max triangle amplitude of 7 + * @arg DAC_TRIANGLEAMPLITUDE_15: Select max triangle amplitude of 15 + * @arg DAC_TRIANGLEAMPLITUDE_31: Select max triangle amplitude of 31 + * @arg DAC_TRIANGLEAMPLITUDE_63: Select max triangle amplitude of 63 + * @arg DAC_TRIANGLEAMPLITUDE_127: Select max triangle amplitude of 127 + * @arg DAC_TRIANGLEAMPLITUDE_255: Select max triangle amplitude of 255 + * @arg DAC_TRIANGLEAMPLITUDE_511: Select max triangle amplitude of 511 + * @arg DAC_TRIANGLEAMPLITUDE_1023: Select max triangle amplitude of 1023 + * @arg DAC_TRIANGLEAMPLITUDE_2047: Select max triangle amplitude of 2047 + * @arg DAC_TRIANGLEAMPLITUDE_4095: Select max triangle amplitude of 4095 + * @retval HAL status + */ +HAL_StatusTypeDef HAL_DACEx_TriangleWaveGenerate(DAC_HandleTypeDef* hdac, uint32_t Channel, uint32_t Amplitude) +{ + /* Check the parameters */ + assert_param(IS_DAC_CHANNEL(Channel)); + assert_param(IS_DAC_LFSR_UNMASK_TRIANGLE_AMPLITUDE(Amplitude)); + + /* Process locked */ + __HAL_LOCK(hdac); + + /* Change DAC state */ + hdac->State = HAL_DAC_STATE_BUSY; + + /* Enable the selected wave generation for the selected DAC channel */ + hdac->Instance->CR |= (DAC_WAVE_TRIANGLE | Amplitude) << Channel; + + /* Change DAC state */ + hdac->State = HAL_DAC_STATE_READY; + + /* Process unlocked */ + __HAL_UNLOCK(hdac); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Enables or disables the selected DAC channel wave generation. + * @param hdac: pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @param Channel: The selected DAC channel. + * This parameter can be one of the following values: + * DAC_CHANNEL_1 / DAC_CHANNEL_2 + * @param Amplitude: Unmask DAC channel LFSR for noise wave generation. + * This parameter can be one of the following values: + * @arg DAC_LFSRUNMASK_BIT0: Unmask DAC channel LFSR bit0 for noise wave generation + * @arg DAC_LFSRUNMASK_BITS1_0: Unmask DAC channel LFSR bit[1:0] for noise wave generation + * @arg DAC_LFSRUNMASK_BITS2_0: Unmask DAC channel LFSR bit[2:0] for noise wave generation + * @arg DAC_LFSRUNMASK_BITS3_0: Unmask DAC channel LFSR bit[3:0] for noise wave generation + * @arg DAC_LFSRUNMASK_BITS4_0: Unmask DAC channel LFSR bit[4:0] for noise wave generation + * @arg DAC_LFSRUNMASK_BITS5_0: Unmask DAC channel LFSR bit[5:0] for noise wave generation + * @arg DAC_LFSRUNMASK_BITS6_0: Unmask DAC channel LFSR bit[6:0] for noise wave generation + * @arg DAC_LFSRUNMASK_BITS7_0: Unmask DAC channel LFSR bit[7:0] for noise wave generation + * @arg DAC_LFSRUNMASK_BITS8_0: Unmask DAC channel LFSR bit[8:0] for noise wave generation + * @arg DAC_LFSRUNMASK_BITS9_0: Unmask DAC channel LFSR bit[9:0] for noise wave generation + * @arg DAC_LFSRUNMASK_BITS10_0: Unmask DAC channel LFSR bit[10:0] for noise wave generation + * @arg DAC_LFSRUNMASK_BITS11_0: Unmask DAC channel LFSR bit[11:0] for noise wave generation + * @retval HAL status + */ +HAL_StatusTypeDef HAL_DACEx_NoiseWaveGenerate(DAC_HandleTypeDef* hdac, uint32_t Channel, uint32_t Amplitude) +{ + /* Check the parameters */ + assert_param(IS_DAC_CHANNEL(Channel)); + assert_param(IS_DAC_LFSR_UNMASK_TRIANGLE_AMPLITUDE(Amplitude)); + + /* Process locked */ + __HAL_LOCK(hdac); + + /* Change DAC state */ + hdac->State = HAL_DAC_STATE_BUSY; + + /* Enable the selected wave generation for the selected DAC channel */ + hdac->Instance->CR |= (DAC_WAVE_NOISE | Amplitude) << Channel; + + /* Change DAC state */ + hdac->State = HAL_DAC_STATE_READY; + + /* Process unlocked */ + __HAL_UNLOCK(hdac); + + /* Return function status */ + return HAL_OK; +} + +#endif /* STM32F071xB STM32F072xB STM32F078xx */ + +#if defined(STM32F051x8) || defined(STM32F058xx) || \ + defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) + +/** + * @brief Set the specified data holding register value for dual DAC channel. + * @param hdac: pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @param Alignment: Specifies the data alignment for dual channel DAC. + * This parameter can be one of the following values: + * DAC_ALIGN_8B_R: 8bit right data alignment selected + * DAC_ALIGN_12B_L: 12bit left data alignment selected + * DAC_ALIGN_12B_R: 12bit right data alignment selected + * @param Data1: Data for DAC Channel2 to be loaded in the selected data holding register. + * @param Data2: Data for DAC Channel1 to be loaded in the selected data holding register. + * @note In dual mode, a unique register access is required to write in both + * DAC channels at the same time. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_DACEx_DualSetValue(DAC_HandleTypeDef* hdac, uint32_t Alignment, uint32_t Data1, uint32_t Data2) +{ + uint32_t data = 0, tmp = 0; + + /* Check the parameters */ + assert_param(IS_DAC_ALIGN(Alignment)); + assert_param(IS_DAC_DATA(Data1)); + assert_param(IS_DAC_DATA(Data2)); + + /* Calculate and set dual DAC data holding register value */ + if (Alignment == DAC_ALIGN_8B_R) + { + data = ((uint32_t)Data2 << 8) | Data1; + } + else + { + data = ((uint32_t)Data2 << 16) | Data1; + } + + tmp = (uint32_t)hdac->Instance; + tmp += __HAL_DHR12RD_ALIGNEMENT(Alignment); + + /* Set the dual DAC selected data holding register */ + *(__IO uint32_t *)tmp = data; + + /* Return function status */ + return HAL_OK; +} + +/** + * @} + */ + +/** + * @brief DMA conversion complete callback. + * @param hdma: pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void DAC_DMAConvCpltCh1(DMA_HandleTypeDef *hdma) +{ + DAC_HandleTypeDef* hdac = ( DAC_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + + HAL_DAC_ConvCpltCallbackCh1(hdac); + + hdac->State= HAL_DAC_STATE_READY; +} + +/** + * @brief DMA half transfer complete callback. + * @param hdma: pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void DAC_DMAHalfConvCpltCh1(DMA_HandleTypeDef *hdma) +{ + DAC_HandleTypeDef* hdac = ( DAC_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + /* Conversion complete callback */ + HAL_DAC_ConvHalfCpltCallbackCh1(hdac); +} + +/** + * @brief DMA error callback + * @param hdma: pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void DAC_DMAErrorCh1(DMA_HandleTypeDef *hdma) +{ + DAC_HandleTypeDef* hdac = ( DAC_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + + /* Set DAC error code to DMA error */ + hdac->ErrorCode |= HAL_DAC_ERROR_DMA; + + HAL_DAC_ErrorCallbackCh1(hdac); + + hdac->State= HAL_DAC_STATE_READY; +} + +#endif /* STM32F051x8 STM32F058xx */ + /* STM32F071xB STM32F072xB STM32F078xx */ + +#if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) + +/** + * @brief Conversion complete callback in non blocking mode for Channel2 + * @param hdac: pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @retval None + */ +__weak void HAL_DACEx_ConvCpltCallbackCh2(DAC_HandleTypeDef* hdac) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_DAC_ConvCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Conversion half DMA transfer callback in non blocking mode for Channel2 + * @param hdac: pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @retval None + */ +__weak void HAL_DACEx_ConvHalfCpltCallbackCh2(DAC_HandleTypeDef* hdac) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_DAC_ConvHalfCpltCallbackCh2 could be implemented in the user file + */ +} + +/** + * @brief Error DAC callback for Channel2. + * @param hdac: pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @retval None + */ +__weak void HAL_DACEx_ErrorCallbackCh2(DAC_HandleTypeDef *hdac) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_DAC_ErrorCallback could be implemented in the user file + */ +} + +/** + * @brief DMA underrun DAC callback for channel2. + * @param hdac: pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @retval None + */ +__weak void HAL_DACEx_DMAUnderrunCallbackCh2(DAC_HandleTypeDef *hdac) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_DAC_DMAUnderrunCallbackCh2 could be implemented in the user file + */ +} + +/** + * @brief DMA conversion complete callback. + * @param hdma: pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +void DAC_DMAConvCpltCh2(DMA_HandleTypeDef *hdma) +{ + DAC_HandleTypeDef* hdac = ( DAC_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + + HAL_DACEx_ConvCpltCallbackCh2(hdac); + + hdac->State= HAL_DAC_STATE_READY; +} + +/** + * @brief DMA half transfer complete callback. + * @param hdma: pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +void DAC_DMAHalfConvCpltCh2(DMA_HandleTypeDef *hdma) +{ + DAC_HandleTypeDef* hdac = ( DAC_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + /* Conversion complete callback */ + HAL_DACEx_ConvHalfCpltCallbackCh2(hdac); +} + +/** + * @brief DMA error callback + * @param hdma: pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +void DAC_DMAErrorCh2(DMA_HandleTypeDef *hdma) +{ + DAC_HandleTypeDef* hdac = ( DAC_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + + /* Set DAC error code to DMA error */ + hdac->ErrorCode |= HAL_DAC_ERROR_DMA; + + HAL_DACEx_ErrorCallbackCh2(hdac); + + hdac->State= HAL_DAC_STATE_READY; +} + +/** + * @} + */ + +#endif /* STM32F071xB STM32F072xB STM32F078xx */ + +#endif /* HAL_DAC_MODULE_ENABLED */ + +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_dac_ex.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_dac_ex.h new file mode 100644 index 0000000000..a8feaec169 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_dac_ex.h @@ -0,0 +1,265 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_dac.h + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief Header file of DAC HAL Extension module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32F0xx_HAL_DAC_EX_H +#define __STM32F0xx_HAL_DAC_EX_H + +#ifdef __cplusplus + extern "C" { +#endif + +#if defined(STM32F051x8) || defined(STM32F058xx) || \ + defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal_def.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @addtogroup DACEx + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ + +/** + * @brief HAL State structures definition + */ + +/* Exported constants --------------------------------------------------------*/ + +/** @defgroup DACEx_wave_generation + * @{ + */ +#define DAC_WAVEGENERATION_NONE ((uint32_t)0x00000000) +#define DAC_WAVEGENERATION_NOISE ((uint32_t)DAC_CR_WAVE1_0) +#define DAC_WAVEGENERATION_TRIANGLE ((uint32_t)DAC_CR_WAVE1_1) + +#define IS_DAC_GENERATE_WAVE(WAVE) (((WAVE) == DAC_WAVEGENERATION_NONE) || \ + ((WAVE) == DAC_WAVEGENERATION_NOISE) || \ + ((WAVE) == DAC_WAVEGENERATION_TRIANGLE)) +/** + * @} + */ + +/** @defgroup DACEx_lfsrunmask_triangleamplitude + * @{ + */ +#define DAC_LFSRUNMASK_BIT0 ((uint32_t)0x00000000) /*!< Unmask DAC channel LFSR bit0 for noise wave generation */ +#define DAC_LFSRUNMASK_BITS1_0 ((uint32_t)DAC_CR_MAMP1_0) /*!< Unmask DAC channel LFSR bit[1:0] for noise wave generation */ +#define DAC_LFSRUNMASK_BITS2_0 ((uint32_t)DAC_CR_MAMP1_1) /*!< Unmask DAC channel LFSR bit[2:0] for noise wave generation */ +#define DAC_LFSRUNMASK_BITS3_0 ((uint32_t)DAC_CR_MAMP1_1 | DAC_CR_MAMP1_0)/*!< Unmask DAC channel LFSR bit[3:0] for noise wave generation */ +#define DAC_LFSRUNMASK_BITS4_0 ((uint32_t)DAC_CR_MAMP1_2) /*!< Unmask DAC channel LFSR bit[4:0] for noise wave generation */ +#define DAC_LFSRUNMASK_BITS5_0 ((uint32_t)DAC_CR_MAMP1_2 | DAC_CR_MAMP1_0) /*!< Unmask DAC channel LFSR bit[5:0] for noise wave generation */ +#define DAC_LFSRUNMASK_BITS6_0 ((uint32_t)DAC_CR_MAMP1_2 | DAC_CR_MAMP1_1) /*!< Unmask DAC channel LFSR bit[6:0] for noise wave generation */ +#define DAC_LFSRUNMASK_BITS7_0 ((uint32_t)DAC_CR_MAMP1_2 | DAC_CR_MAMP1_1 | DAC_CR_MAMP1_0) /*!< Unmask DAC channel LFSR bit[7:0] for noise wave generation */ +#define DAC_LFSRUNMASK_BITS8_0 ((uint32_t)DAC_CR_MAMP1_3) /*!< Unmask DAC channel LFSR bit[8:0] for noise wave generation */ +#define DAC_LFSRUNMASK_BITS9_0 ((uint32_t)DAC_CR_MAMP1_3 | DAC_CR_MAMP1_0) /*!< Unmask DAC channel LFSR bit[9:0] for noise wave generation */ +#define DAC_LFSRUNMASK_BITS10_0 ((uint32_t)DAC_CR_MAMP1_3 | DAC_CR_MAMP1_1) /*!< Unmask DAC channel LFSR bit[10:0] for noise wave generation */ +#define DAC_LFSRUNMASK_BITS11_0 ((uint32_t)DAC_CR_MAMP1_3 | DAC_CR_MAMP1_1 | DAC_CR_MAMP1_0) /*!< Unmask DAC channel LFSR bit[11:0] for noise wave generation */ +#define DAC_TRIANGLEAMPLITUDE_1 ((uint32_t)0x00000000) /*!< Select max triangle amplitude of 1 */ +#define DAC_TRIANGLEAMPLITUDE_3 ((uint32_t)DAC_CR_MAMP1_0) /*!< Select max triangle amplitude of 3 */ +#define DAC_TRIANGLEAMPLITUDE_7 ((uint32_t)DAC_CR_MAMP1_1) /*!< Select max triangle amplitude of 7 */ +#define DAC_TRIANGLEAMPLITUDE_15 ((uint32_t)DAC_CR_MAMP1_1 | DAC_CR_MAMP1_0) /*!< Select max triangle amplitude of 15 */ +#define DAC_TRIANGLEAMPLITUDE_31 ((uint32_t)DAC_CR_MAMP1_2) /*!< Select max triangle amplitude of 31 */ +#define DAC_TRIANGLEAMPLITUDE_63 ((uint32_t)DAC_CR_MAMP1_2 | DAC_CR_MAMP1_0) /*!< Select max triangle amplitude of 63 */ +#define DAC_TRIANGLEAMPLITUDE_127 ((uint32_t)DAC_CR_MAMP1_2 | DAC_CR_MAMP1_1) /*!< Select max triangle amplitude of 127 */ +#define DAC_TRIANGLEAMPLITUDE_255 ((uint32_t)DAC_CR_MAMP1_2 | DAC_CR_MAMP1_1 | DAC_CR_MAMP1_0) /*!< Select max triangle amplitude of 255 */ +#define DAC_TRIANGLEAMPLITUDE_511 ((uint32_t)DAC_CR_MAMP1_3) /*!< Select max triangle amplitude of 511 */ +#define DAC_TRIANGLEAMPLITUDE_1023 ((uint32_t)DAC_CR_MAMP1_3 | DAC_CR_MAMP1_0) /*!< Select max triangle amplitude of 1023 */ +#define DAC_TRIANGLEAMPLITUDE_2047 ((uint32_t)DAC_CR_MAMP1_3 | DAC_CR_MAMP1_1) /*!< Select max triangle amplitude of 2047 */ +#define DAC_TRIANGLEAMPLITUDE_4095 ((uint32_t)DAC_CR_MAMP1_3 | DAC_CR_MAMP1_1 | DAC_CR_MAMP1_0) /*!< Select max triangle amplitude of 4095 */ + +#define IS_DAC_LFSR_UNMASK_TRIANGLE_AMPLITUDE(VALUE) (((VALUE) == DAC_LFSRUNMASK_BIT0) || \ + ((VALUE) == DAC_LFSRUNMASK_BITS1_0) || \ + ((VALUE) == DAC_LFSRUNMASK_BITS2_0) || \ + ((VALUE) == DAC_LFSRUNMASK_BITS3_0) || \ + ((VALUE) == DAC_LFSRUNMASK_BITS4_0) || \ + ((VALUE) == DAC_LFSRUNMASK_BITS5_0) || \ + ((VALUE) == DAC_LFSRUNMASK_BITS6_0) || \ + ((VALUE) == DAC_LFSRUNMASK_BITS7_0) || \ + ((VALUE) == DAC_LFSRUNMASK_BITS8_0) || \ + ((VALUE) == DAC_LFSRUNMASK_BITS9_0) || \ + ((VALUE) == DAC_LFSRUNMASK_BITS10_0) || \ + ((VALUE) == DAC_LFSRUNMASK_BITS11_0) || \ + ((VALUE) == DAC_TRIANGLEAMPLITUDE_1) || \ + ((VALUE) == DAC_TRIANGLEAMPLITUDE_3) || \ + ((VALUE) == DAC_TRIANGLEAMPLITUDE_7) || \ + ((VALUE) == DAC_TRIANGLEAMPLITUDE_15) || \ + ((VALUE) == DAC_TRIANGLEAMPLITUDE_31) || \ + ((VALUE) == DAC_TRIANGLEAMPLITUDE_63) || \ + ((VALUE) == DAC_TRIANGLEAMPLITUDE_127) || \ + ((VALUE) == DAC_TRIANGLEAMPLITUDE_255) || \ + ((VALUE) == DAC_TRIANGLEAMPLITUDE_511) || \ + ((VALUE) == DAC_TRIANGLEAMPLITUDE_1023) || \ + ((VALUE) == DAC_TRIANGLEAMPLITUDE_2047) || \ + ((VALUE) == DAC_TRIANGLEAMPLITUDE_4095)) +/** + * @} + */ + +/** @defgroup DACEx_wave_generation + * @{ + */ +#define DAC_WAVE_NOISE ((uint32_t)DAC_CR_WAVE1_0) +#define DAC_WAVE_TRIANGLE ((uint32_t)DAC_CR_WAVE1_1) + +#define IS_DAC_WAVE(WAVE) (((WAVE) == DAC_WAVE_NOISE) || \ + ((WAVE) == DAC_WAVE_TRIANGLE)) + + + + + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ +/* Exported functions --------------------------------------------------------*/ + +/** @defgroup DAC_trigger_selection + * @{ + */ +#if defined(STM32F051x8) || defined(STM32F058xx) + +#define DAC_TRIGGER_NONE ((uint32_t)0x00000000) /*!< Conversion is automatic once the DAC1_DHRxxxx register + has been loaded, and not by external trigger */ +#define DAC_TRIGGER_T2_TRGO ((uint32_t)(DAC_CR_TSEL1_2 | DAC_CR_TEN1)) /*!< TIM2 TRGO selected as external conversion trigger for DAC channel */ +#define DAC_TRIGGER_T3_TRGO ((uint32_t)(DAC_CR_TSEL1_0 | DAC_CR_TEN1)) /*!< TIM3 TRGO selected as external conversion trigger for DAC channel */ +#define DAC_TRIGGER_T6_TRGO ((uint32_t)DAC_CR_TEN1) /*!< TIM6 TRGO selected as external conversion trigger for DAC channel */ +#define DAC_TRIGGER_T15_TRGO ((uint32_t)(DAC_CR_TSEL1_1 | DAC_CR_TSEL1_0 | DAC_CR_TEN1)) /*!< TIM15 TRGO selected as external conversion trigger for DAC channel */ +#define DAC_TRIGGER_EXT_IT9 ((uint32_t)(DAC_CR_TSEL1_2 | DAC_CR_TSEL1_1 | DAC_CR_TEN1)) /*!< EXTI Line9 event selected as external conversion trigger for DAC channel */ +#define DAC_TRIGGER_SOFTWARE ((uint32_t)(DAC_CR_TSEL1 | DAC_CR_TEN1)) /*!< Conversion started by software trigger for DAC channel */ + +#define IS_DAC_TRIGGER(TRIGGER) (((TRIGGER) == DAC_TRIGGER_NONE) || \ + ((TRIGGER) == DAC_TRIGGER_T2_TRGO) || \ + ((TRIGGER) == DAC_TRIGGER_T3_TRGO) || \ + ((TRIGGER) == DAC_TRIGGER_T6_TRGO) || \ + ((TRIGGER) == DAC_TRIGGER_T15_TRGO) || \ + ((TRIGGER) == DAC_TRIGGER_EXT_IT9) || \ + ((TRIGGER) == DAC_TRIGGER_SOFTWARE)) + +#endif /* STM32F051x8 || STM32F058xx */ + +#if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) + +#define DAC_TRIGGER_NONE ((uint32_t)0x00000000) /*!< Conversion is automatic once the DAC1_DHRxxxx register + has been loaded, and not by external trigger */ +#define DAC_TRIGGER_T2_TRGO ((uint32_t)(DAC_CR_TSEL1_2 | DAC_CR_TEN1)) /*!< TIM2 TRGO selected as external conversion trigger for DAC channel */ +#define DAC_TRIGGER_T3_TRGO ((uint32_t)(DAC_CR_TSEL1_0 | DAC_CR_TEN1)) /*!< TIM3 TRGO selected as external conversion trigger for DAC channel */ +#define DAC_TRIGGER_T6_TRGO ((uint32_t)DAC_CR_TEN1) /*!< TIM6 TRGO selected as external conversion trigger for DAC channel */ +#define DAC_TRIGGER_T7_TRGO ((uint32_t)(DAC_CR_TSEL1_1 | DAC_CR_TEN1)) /*!< TIM7 TRGO selected as external conversion trigger for DAC channel */ +#define DAC_TRIGGER_T15_TRGO ((uint32_t)(DAC_CR_TSEL1_1 | DAC_CR_TSEL1_0 | DAC_CR_TEN1)) /*!< TIM15 TRGO selected as external conversion trigger for DAC channel */ +#define DAC_TRIGGER_EXT_IT9 ((uint32_t)(DAC_CR_TSEL1_2 | DAC_CR_TSEL1_1 | DAC_CR_TEN1)) /*!< EXTI Line9 event selected as external conversion trigger for DAC channel */ +#define DAC_TRIGGER_SOFTWARE ((uint32_t)(DAC_CR_TSEL1 | DAC_CR_TEN1)) /*!< Conversion started by software trigger for DAC channel */ + +#define IS_DAC_TRIGGER(TRIGGER) (((TRIGGER) == DAC_TRIGGER_NONE) || \ + ((TRIGGER) == DAC_TRIGGER_T2_TRGO) || \ + ((TRIGGER) == DAC_TRIGGER_T3_TRGO) || \ + ((TRIGGER) == DAC_TRIGGER_T6_TRGO) || \ + ((TRIGGER) == DAC_TRIGGER_T7_TRGO) || \ + ((TRIGGER) == DAC_TRIGGER_T15_TRGO) || \ + ((TRIGGER) == DAC_TRIGGER_EXT_IT9) || \ + ((TRIGGER) == DAC_TRIGGER_SOFTWARE)) + +#endif /* STM32F071xB || STM32F072xB || STM32F078xx */ + +#if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) + +/** @defgroup DAC_Channel_selection + * @{ + */ +#define DAC_CHANNEL_1 ((uint32_t)0x00000000) +#define DAC_CHANNEL_2 ((uint32_t)0x00000010) + +#define IS_DAC_CHANNEL(CHANNEL) (((CHANNEL) == DAC_CHANNEL_1) || \ + ((CHANNEL) == DAC_CHANNEL_2)) +/** + * @} + */ + +#endif /* STM32F071xB || STM32F072xB || STM32F078xx */ + +#if defined(STM32F051x8) || defined(STM32F058xx) + +#define DAC_CHANNEL_1 ((uint32_t)0x00000000) +#define IS_DAC_CHANNEL(CHANNEL) (((CHANNEL) == DAC_CHANNEL_1)) + +#endif /* STM32F051x8 || STM32F058xx */ + +/** + * @} + */ + + +/* Extension features functions ***********************************************/ +uint32_t HAL_DACEx_DualGetValue(DAC_HandleTypeDef* hdac); +HAL_StatusTypeDef HAL_DACEx_TriangleWaveGenerate(DAC_HandleTypeDef* hdac, uint32_t Channel, uint32_t Amplitude); +HAL_StatusTypeDef HAL_DACEx_NoiseWaveGenerate(DAC_HandleTypeDef* hdac, uint32_t Channel, uint32_t Amplitude); +HAL_StatusTypeDef HAL_DACEx_DualSetValue(DAC_HandleTypeDef* hdac, uint32_t Alignment, uint32_t Data1, uint32_t Data2); + +void HAL_DACEx_ConvCpltCallbackCh2(DAC_HandleTypeDef* hdac); +void HAL_DACEx_ConvHalfCpltCallbackCh2(DAC_HandleTypeDef* hdac); +void HAL_DACEx_ErrorCallbackCh2(DAC_HandleTypeDef* hdac); +void HAL_DACEx_DMAUnderrunCallbackCh2(DAC_HandleTypeDef* hdac); + +void DAC_DMAConvCpltCh2(DMA_HandleTypeDef *hdma); +void DAC_DMAErrorCh2(DMA_HandleTypeDef *hdma); +void DAC_DMAHalfConvCpltCh2(DMA_HandleTypeDef *hdma); + +#endif /* */ + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif /* STM32F051x8 || STM32F058xx || */ + /* STM32F071xB || STM32F072xB || STM32F078xx */ + +#endif /*__STM32F0xx_HAL_DAC_EX_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_def.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_def.h new file mode 100644 index 0000000000..cd25ae92c3 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_def.h @@ -0,0 +1,148 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_def.h + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief This file contains HAL common defines, enumeration, macros and + * structures definitions. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32F0xx_HAL_DEF +#define __STM32F0xx_HAL_DEF + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx.h" + +/* Exported types ------------------------------------------------------------*/ + +/** + * @brief HAL Status structures definition + */ +typedef enum +{ + HAL_OK = 0x00, + HAL_ERROR = 0x01, + HAL_BUSY = 0x02, + HAL_TIMEOUT = 0x03 +} HAL_StatusTypeDef; + +/** + * @brief HAL Lock structures definition + */ +typedef enum +{ + HAL_UNLOCKED = 0x00, + HAL_LOCKED = 0x01 +} HAL_LockTypeDef; + +/* Exported macro ------------------------------------------------------------*/ +#ifndef NULL + #define NULL (void *) 0 +#endif + +#define HAL_MAX_DELAY 0xFFFFFFFF + +#define HAL_IS_BIT_SET(REG, BIT) (((REG) & (BIT)) != RESET) +#define HAL_IS_BIT_CLR(REG, BIT) (((REG) & (BIT)) == RESET) + +#define __HAL_LINKDMA(__HANDLE__, __PPP_DMA_FIELD_, __DMA_HANDLE_) \ + do{ \ + (__HANDLE__)->__PPP_DMA_FIELD_ = &(__DMA_HANDLE_); \ + (__DMA_HANDLE_).Parent = (__HANDLE__); \ + } while(0) + +#if (USE_RTOS == 1) + #error " USE_RTOS should be 0 in the current HAL release " +#else + #define __HAL_LOCK(__HANDLE__) \ + do{ \ + if((__HANDLE__)->Lock == HAL_LOCKED) \ + { \ + return HAL_BUSY; \ + } \ + else \ + { \ + (__HANDLE__)->Lock = HAL_LOCKED; \ + } \ + }while (0) + + #define __HAL_UNLOCK(__HANDLE__) \ + do{ \ + (__HANDLE__)->Lock = HAL_UNLOCKED; \ + }while (0) +#endif /* USE_RTOS */ + +#if defined ( __GNUC__ ) + #ifndef __weak + #define __weak __attribute__((weak)) + #endif /* __weak */ + #ifndef __packed + #define __packed __attribute__((__packed__)) + #endif /* __packed */ +#endif /* __GNUC__ */ + + +/* Macro to get variable aligned on 4-bytes, for __ICCARM__ the directive "#pragma data_alignment=4" must be used instead */ +#if defined (__GNUC__) /* GNU Compiler */ + #ifndef __ALIGN_END + #define __ALIGN_END __attribute__ ((aligned (4))) + #endif /* __ALIGN_END */ + #ifndef __ALIGN_BEGIN + #define __ALIGN_BEGIN + #endif /* __ALIGN_BEGIN */ +#else + #ifndef __ALIGN_END + #define __ALIGN_END + #endif /* __ALIGN_END */ + #ifndef __ALIGN_BEGIN + #if defined (__CC_ARM) /* ARM Compiler */ + #define __ALIGN_BEGIN __align(4) + #elif defined (__ICCARM__) /* IAR Compiler */ + #define __ALIGN_BEGIN + #elif defined (__TASKING__) /* TASKING Compiler */ + #define __ALIGN_BEGIN __align(4) + #endif /* __CC_ARM */ + #endif /* __ALIGN_BEGIN */ +#endif /* __GNUC__ */ + +#ifdef __cplusplus +} +#endif + +#endif /* ___STM32F0xx_HAL_DEF */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_dma.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_dma.c new file mode 100644 index 0000000000..873f41c91b --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_dma.c @@ -0,0 +1,685 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_dma.c + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief DMA HAL module driver. + * + * This file provides firmware functions to manage the following + * functionalities of the Direct Memory Access (DMA) peripheral: + * + Initialization and de-initialization functions + * + IO operation functions + * + Peripheral State and errors functions + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + (#) Enable and configure the peripheral to be connected to the DMA Channel + (except for internal SRAM / FLASH memories: no initialization is + necessary) please refer to Reference manual for connection between peripherals + and DMA requests . + + (#) For a given Channel, program the required configuration through the following parameters: + Transfer Direction, Source and Destination data formats, + Circular, Normal or peripheral flow control mode, Channel Priority level, + Source and Destination Increment mode, FIFO mode and its Threshold (if needed), + Burst mode for Source and/or Destination (if needed) using HAL_DMA_Init() function. + + *** Polling mode IO operation *** + ================================= + [..] + (+) Use HAL_DMA_Start() to start DMA transfer after the configuration of Source + address and destination address and the Length of data to be transferred + (+) Use HAL_DMA_PollForTransfer() to poll for the end of current transfer, in this + case a fixed Timeout can be configured by User depending from his application. + + *** Interrupt mode IO operation *** + =================================== + [..] + (+) Configure the DMA interrupt priority using HAL_NVIC_SetPriority() + (+) Enable the DMA IRQ handler using HAL_NVIC_EnableIRQ() + (+) Use HAL_DMA_Start_IT() to start DMA transfer after the configuration of + Source address and destination address and the Length of data to be transferred. In this + case the DMA interrupt is configured + (+) Use HAL_DMA_IRQHandler() called under DMA_IRQHandler() Interrupt subroutine + (+) At the end of data transfer HAL_DMA_IRQHandler() function is executed and user can + add his own function by customization of function pointer XferCpltCallback and + XferErrorCallback (i.e a member of DMA handle structure). + + (#) Use HAL_DMA_GetState() function to return the DMA state and HAL_DMA_GetError() in case of error + detection. + + (#) Use HAL_DMA_Abort() function to abort the current transfer + + -@- In Memory-to-Memory transfer mode, Circular mode is not allowed. + + *** DMA HAL driver macros list *** + ============================================= + [..] + Below the list of most used macros in DMA HAL driver. + + (+) __HAL_DMA_ENABLE: Enable the specified DMA Channel. + (+) __HAL_DMA_DISABLE: Disable the specified DMA Channel. + (+) __HAL_DMA_GET_FLAG: Get the DMA Channel pending flags. + (+) __HAL_DMA_CLEAR_FLAG: Clear the DMA Channel pending flags. + (+) __HAL_DMA_ENABLE_IT: Enable the specified DMA Channel interrupts. + (+) __HAL_DMA_DISABLE_IT: Disable the specified DMA Channel interrupts. + (+) __HAL_DMA_IT_STATUS: Check whether the specified DMA Channel interrupt has occurred or not. + + [..] + (@) You can refer to the DMA HAL driver header file for more useful macros + + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @defgroup DMA + * @brief DMA HAL module driver + * @{ + */ + +#ifdef HAL_DMA_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +#define HAL_TIMEOUT_DMA_ABORT ((uint32_t)1000) /* 1s */ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +static void DMA_SetConfig(DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t DstAddress, uint32_t DataLength); + +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup DMA_Private_Functions + * @{ + */ + +/** @defgroup DMA_Group1 Initialization and de-initialization functions + * @brief Initialization and de-initialization functions + * +@verbatim + =============================================================================== + ##### Initialization and de-initialization functions ##### + =============================================================================== + [..] + This section provides functions allowing to initialize the DMA Channel source + and destination addresses, incrementation and data sizes, transfer direction, + circular/normal mode selection, memory-to-memory mode selection and Channel priority value. + [..] + The HAL_DMA_Init() function follows the DMA configuration procedures as described in + reference manual. + +@endverbatim + * @{ + */ + +/** + * @brief Initializes the DMA according to the specified + * parameters in the DMA_InitTypeDef and create the associated handle. + * @param hdma: Pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA Channel. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_DMA_Init(DMA_HandleTypeDef *hdma) +{ + uint32_t tmp = 0; + + /* Check the DMA peripheral state */ + if(hdma == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_DMA_ALL_INSTANCE(hdma->Instance)); + assert_param(IS_DMA_DIRECTION(hdma->Init.Direction)); + assert_param(IS_DMA_PERIPHERAL_INC_STATE(hdma->Init.PeriphInc)); + assert_param(IS_DMA_MEMORY_INC_STATE(hdma->Init.MemInc)); + assert_param(IS_DMA_PERIPHERAL_DATA_SIZE(hdma->Init.PeriphDataAlignment)); + assert_param(IS_DMA_MEMORY_DATA_SIZE(hdma->Init.MemDataAlignment)); + assert_param(IS_DMA_MODE(hdma->Init.Mode)); + assert_param(IS_DMA_PRIORITY(hdma->Init.Priority)); + + /* Change DMA peripheral state */ + hdma->State = HAL_DMA_STATE_BUSY; + + /* Get the CR register value */ + tmp = hdma->Instance->CCR; + + /* Clear PL, MSIZE, PSIZE, MINC, PINC, CIRC, DIR bits */ + tmp &= ((uint32_t)~(DMA_CCR_PL | DMA_CCR_MSIZE | DMA_CCR_PSIZE | \ + DMA_CCR_MINC | DMA_CCR_PINC | DMA_CCR_CIRC | \ + DMA_CCR_DIR)); + + /* Prepare the DMA Channel configuration */ + tmp |= hdma->Init.Direction | + hdma->Init.PeriphInc | hdma->Init.MemInc | + hdma->Init.PeriphDataAlignment | hdma->Init.MemDataAlignment | + hdma->Init.Mode | hdma->Init.Priority; + + /* Write to DMA Channel CR register */ + hdma->Instance->CCR = tmp; + + /* Initialise the error code */ + hdma->ErrorCode = HAL_DMA_ERROR_NONE; + + /* Initialize the DMA state*/ + hdma->State = HAL_DMA_STATE_READY; + + return HAL_OK; +} + +/** + * @brief DeInitializes the DMA peripheral + * @param hdma: pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA Channel. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_DMA_DeInit(DMA_HandleTypeDef *hdma) +{ + /* Check the DMA peripheral state */ + if(hdma == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_DMA_ALL_INSTANCE(hdma->Instance)); + + /* Check the DMA peripheral state */ + if(hdma->State == HAL_DMA_STATE_BUSY) + { + return HAL_ERROR; + } + + /* Disable the selected DMA Channelx */ + __HAL_DMA_DISABLE(hdma); + + /* Reset DMA Channel control register */ + hdma->Instance->CCR = 0; + + /* Reset DMA Channel Number of Data to Transfer register */ + hdma->Instance->CNDTR = 0; + + /* Reset DMA Channel peripheral address register */ + hdma->Instance->CPAR = 0; + + /* Reset DMA Channel memory address register */ + hdma->Instance->CMAR = 0; + + /* Clear all flags */ + __HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_TC_FLAG_INDEX(hdma)); + __HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_TE_FLAG_INDEX(hdma)); + __HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_HT_FLAG_INDEX(hdma)); + + /* Initialise the error code */ + hdma->ErrorCode = HAL_DMA_ERROR_NONE; + + /* Initialize the DMA state */ + hdma->State = HAL_DMA_STATE_RESET; + + /* Release Lock */ + __HAL_UNLOCK(hdma); + + return HAL_OK; +} + +/** + * @} + */ + +/** @defgroup DMA_Group2 I/O operation functions + * @brief I/O operation functions + * +@verbatim + =============================================================================== + ##### IO operation functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Configure the source, destination address and data length and Start DMA transfer + (+) Configure the source, destination address and data length and + Start DMA transfer with interrupt + (+) Abort DMA transfer + (+) Poll for transfer complete + (+) Handle DMA interrupt request + +@endverbatim + * @{ + */ + +/** + * @brief Starts the DMA Transfer. + * @param hdma : pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA Channel. + * @param SrcAddress: The source memory Buffer address + * @param DstAddress: The destination memory Buffer address + * @param DataLength: The length of data to be transferred from source to destination + * @retval HAL status + */ +HAL_StatusTypeDef HAL_DMA_Start(DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t DstAddress, uint32_t DataLength) +{ + /* Process locked */ + __HAL_LOCK(hdma); + + /* Change DMA peripheral state */ + hdma->State = HAL_DMA_STATE_BUSY; + + /* Check the parameters */ + assert_param(IS_DMA_BUFFER_SIZE(DataLength)); + + /* Disable the peripheral */ + __HAL_DMA_DISABLE(hdma); + + /* Configure the source, destination address and the data length */ + DMA_SetConfig(hdma, SrcAddress, DstAddress, DataLength); + + /* Enable the Peripheral */ + __HAL_DMA_ENABLE(hdma); + + return HAL_OK; +} + +/** + * @brief Start the DMA Transfer with interrupt enabled. + * @param hdma: pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA Channel. + * @param SrcAddress: The source memory Buffer address + * @param DstAddress: The destination memory Buffer address + * @param DataLength: The length of data to be transferred from source to destination + * @retval HAL status + */ +HAL_StatusTypeDef HAL_DMA_Start_IT(DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t DstAddress, uint32_t DataLength) +{ + /* Process locked */ + __HAL_LOCK(hdma); + + /* Change DMA peripheral state */ + hdma->State = HAL_DMA_STATE_BUSY; + + /* Check the parameters */ + assert_param(IS_DMA_BUFFER_SIZE(DataLength)); + + /* Disable the peripheral */ + __HAL_DMA_DISABLE(hdma); + + /* Configure the source, destination address and the data length */ + DMA_SetConfig(hdma, SrcAddress, DstAddress, DataLength); + + /* Enable the transfer complete interrupt */ + __HAL_DMA_ENABLE_IT(hdma, DMA_IT_TC); + + /* Enable the Half transfer complete interrupt */ + __HAL_DMA_ENABLE_IT(hdma, DMA_IT_HT); + + /* Enable the transfer Error interrupt */ + __HAL_DMA_ENABLE_IT(hdma, DMA_IT_TE); + + /* Enable the Peripheral */ + __HAL_DMA_ENABLE(hdma); + + return HAL_OK; +} + +/** + * @brief Aborts the DMA Transfer. + * @param hdma : pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA Channel. + * + * @note After disabling a DMA Channel, a check for wait until the DMA Channel is + * effectively disabled is added. If a Channel is disabled + * while a data transfer is ongoing, the current data will be transferred + * and the Channel will be effectively disabled only after the transfer of + * this single data is finished. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_DMA_Abort(DMA_HandleTypeDef *hdma) +{ + uint32_t tickstart = 0x00; + + /* Disable the channel */ + __HAL_DMA_DISABLE(hdma); + + /* Get timeout */ + tickstart = HAL_GetTick(); + + /* Check if the DMA Channel is effectively disabled */ + while((hdma->Instance->CCR & DMA_CCR_EN) != 0) + { + /* Check for the Timeout */ + if((HAL_GetTick() - tickstart) > HAL_TIMEOUT_DMA_ABORT) + { + /* Update error code */ + hdma->ErrorCode |= HAL_DMA_ERROR_TIMEOUT; + + /* Change the DMA state */ + hdma->State = HAL_DMA_STATE_TIMEOUT; + + /* Process Unlocked */ + __HAL_UNLOCK(hdma); + + return HAL_TIMEOUT; + } + } + /* Change the DMA state*/ + hdma->State = HAL_DMA_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hdma); + + return HAL_OK; +} + +/** + * @brief Polling for transfer complete. + * @param hdma: pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA Channel. + * @param CompleteLevel: Specifies the DMA level complete. + * @param Timeout: Timeout duration. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_DMA_PollForTransfer(DMA_HandleTypeDef *hdma, uint32_t CompleteLevel, uint32_t Timeout) +{ + uint32_t temp; + uint32_t tickstart = 0x00; + + /* Get the level transfer complete flag */ + if(CompleteLevel == HAL_DMA_FULL_TRANSFER) + { + /* Transfer Complete flag */ + temp = __HAL_DMA_GET_TC_FLAG_INDEX(hdma); + } + else + { + /* Half Transfer Complete flag */ + temp = __HAL_DMA_GET_HT_FLAG_INDEX(hdma); + } + + /* Get timeout */ + tickstart = HAL_GetTick(); + + while(__HAL_DMA_GET_FLAG(hdma, temp) == RESET) + { + if((__HAL_DMA_GET_FLAG(hdma, __HAL_DMA_GET_TE_FLAG_INDEX(hdma)) != RESET)) + { + /* Clear the transfer error flags */ + __HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_TE_FLAG_INDEX(hdma)); + + /* Change the DMA state */ + hdma->State= HAL_DMA_STATE_ERROR; + + /* Process Unlocked */ + __HAL_UNLOCK(hdma); + + return HAL_ERROR; + } + /* Check for the Timeout */ + if(Timeout != HAL_MAX_DELAY) + { + if((HAL_GetTick() - tickstart) > Timeout) + { + /* Update error code */ + hdma->ErrorCode |= HAL_DMA_ERROR_TIMEOUT; + + /* Change the DMA state */ + hdma->State = HAL_DMA_STATE_TIMEOUT; + + /* Process Unlocked */ + __HAL_UNLOCK(hdma); + + return HAL_TIMEOUT; + } + } + } + /* Clear the half transfer complete flag */ + __HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_HT_FLAG_INDEX(hdma)); + + /* Change DMA peripheral state */ + hdma->State = HAL_DMA_STATE_READY_HALF; + + if(CompleteLevel == HAL_DMA_FULL_TRANSFER) + { + /* Clear the transfer complete flag */ + __HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_TC_FLAG_INDEX(hdma)); + + /* The selected Channelx EN bit is cleared (DMA is disabled and + all transfers are complete) */ + hdma->State = HAL_DMA_STATE_READY; + + /* Process unlocked */ + __HAL_UNLOCK(hdma); + } + else + { + /* Clear the half transfer complete flag */ + __HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_HT_FLAG_INDEX(hdma)); + + /* The selected Channelx EN bit is cleared (DMA is disabled and + all transfers are complete) */ + hdma->State = HAL_DMA_STATE_READY_HALF; + } + + return HAL_OK; +} + +/** + * @brief Handles DMA interrupt request. + * @param hdma: pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA Channel. + * @retval None + */ +void HAL_DMA_IRQHandler(DMA_HandleTypeDef *hdma) +{ + /* Transfer Error Interrupt management ***************************************/ + if(__HAL_DMA_GET_FLAG(hdma, __HAL_DMA_GET_TE_FLAG_INDEX(hdma)) != RESET) + { + if(__HAL_DMA_GET_IT_SOURCE(hdma, DMA_IT_TE) != RESET) + { + /* Disable the transfer error interrupt */ + __HAL_DMA_DISABLE_IT(hdma, DMA_IT_TE); + + /* Clear the transfer error flag */ + __HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_TE_FLAG_INDEX(hdma)); + + /* Update error code */ + hdma->ErrorCode |= HAL_DMA_ERROR_TE; + + /* Change the DMA state */ + hdma->State = HAL_DMA_STATE_ERROR; + + /* Process Unlocked */ + __HAL_UNLOCK(hdma); + + if (hdma->XferErrorCallback != NULL) + { + /* Transfer error callback */ + hdma->XferErrorCallback(hdma); + } + } + } + + /* Half Transfer Complete Interrupt management ******************************/ + if(__HAL_DMA_GET_FLAG(hdma, __HAL_DMA_GET_HT_FLAG_INDEX(hdma)) != RESET) + { + if(__HAL_DMA_GET_IT_SOURCE(hdma, DMA_IT_HT) != RESET) + { + /* Disable the half transfer interrupt if the DMA mode is not CIRCULAR */ + if((hdma->Instance->CCR & DMA_CCR_CIRC) == 0) + { + /* Disable the half transfer interrupt */ + __HAL_DMA_DISABLE_IT(hdma, DMA_IT_HT); + } + /* Clear the half transfer complete flag */ + __HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_HT_FLAG_INDEX(hdma)); + + /* Change DMA peripheral state */ + hdma->State = HAL_DMA_STATE_READY_HALF; + + if(hdma->XferHalfCpltCallback != NULL) + { + /* Half transfer callback */ + hdma->XferHalfCpltCallback(hdma); + } + } + } + + /* Transfer Complete Interrupt management ***********************************/ + if(__HAL_DMA_GET_FLAG(hdma, __HAL_DMA_GET_TC_FLAG_INDEX(hdma)) != RESET) + { + if(__HAL_DMA_GET_IT_SOURCE(hdma, DMA_IT_TC) != RESET) + { + if((hdma->Instance->CCR & DMA_CCR_CIRC) == 0) + { + /* Disable the transfer complete interrupt */ + __HAL_DMA_DISABLE_IT(hdma, DMA_IT_TC); + } + /* Clear the transfer complete flag */ + __HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_TC_FLAG_INDEX(hdma)); + + /* Update error code */ + hdma->ErrorCode |= HAL_DMA_ERROR_NONE; + + /* Change the DMA state */ + hdma->State = HAL_DMA_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hdma); + + if(hdma->XferCpltCallback != NULL) + { + /* Transfer complete callback */ + hdma->XferCpltCallback(hdma); + } + } + } +} + +/** + * @} + */ + +/** @defgroup DMA_Group3 Peripheral State functions + * @brief Peripheral State functions + * +@verbatim + =============================================================================== + ##### State and Errors functions ##### + =============================================================================== + [..] + This subsection provides functions allowing to + (+) Check the DMA state + (+) Get error code + +@endverbatim + * @{ + */ + +/** + * @brief Returns the DMA state. + * @param hdma: pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA Channel. + * @retval HAL state + */ +HAL_DMA_StateTypeDef HAL_DMA_GetState(DMA_HandleTypeDef *hdma) +{ + return hdma->State; +} + +/** + * @brief Return the DMA error code + * @param hdma : pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA Channel. + * @retval DMA Error Code + */ +uint32_t HAL_DMA_GetError(DMA_HandleTypeDef *hdma) +{ + return hdma->ErrorCode; +} + +/** + * @} + */ + +/** + * @brief Sets the DMA Transfer parameter. + * @param hdma: pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA Channel. + * @param SrcAddress: The source memory Buffer address + * @param DstAddress: The destination memory Buffer address + * @param DataLength: The length of data to be transferred from source to destination + * @retval HAL status + */ +static void DMA_SetConfig(DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t DstAddress, uint32_t DataLength) +{ + /* Configure DMA Channel data length */ + hdma->Instance->CNDTR = DataLength; + + /* Peripheral to Memory */ + if((hdma->Init.Direction) == DMA_MEMORY_TO_PERIPH) + { + /* Configure DMA Channel destination address */ + hdma->Instance->CPAR = DstAddress; + + /* Configure DMA Channel source address */ + hdma->Instance->CMAR = SrcAddress; + } + /* Memory to Peripheral */ + else + { + /* Configure DMA Channel source address */ + hdma->Instance->CPAR = SrcAddress; + + /* Configure DMA Channel destination address */ + hdma->Instance->CMAR = DstAddress; + } +} + +/** + * @} + */ + +#endif /* HAL_DMA_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_dma.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_dma.h new file mode 100644 index 0000000000..753d361604 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_dma.h @@ -0,0 +1,426 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_dma.h + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief Header file of DMA HAL module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32F0xx_HAL_DMA_H +#define __STM32F0xx_HAL_DMA_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal_def.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @addtogroup DMA + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ + +/** + * @brief DMA Configuration Structure definition + */ +typedef struct +{ + uint32_t Direction; /*!< Specifies if the data will be transferred from memory to peripheral, + from memory to memory or from peripheral to memory. + This parameter can be a value of @ref DMA_Data_transfer_direction */ + + uint32_t PeriphInc; /*!< Specifies whether the Peripheral address register should be incremented or not. + This parameter can be a value of @ref DMA_Peripheral_incremented_mode */ + + uint32_t MemInc; /*!< Specifies whether the memory address register should be incremented or not. + This parameter can be a value of @ref DMA_Memory_incremented_mode */ + + uint32_t PeriphDataAlignment; /*!< Specifies the Peripheral data width. + This parameter can be a value of @ref DMA_Peripheral_data_size */ + + uint32_t MemDataAlignment; /*!< Specifies the Memory data width. + This parameter can be a value of @ref DMA_Memory_data_size */ + + uint32_t Mode; /*!< Specifies the operation mode of the DMAy Channelx. + This parameter can be a value of @ref DMA_mode + @note The circular buffer mode cannot be used if the memory-to-memory + data transfer is configured on the selected Channel */ + + uint32_t Priority; /*!< Specifies the software priority for the DMAy Channelx. + This parameter can be a value of @ref DMA_Priority_level */ + +} DMA_InitTypeDef; + +/** + * @brief DMA Configuration enumeration values definition + */ +typedef enum +{ + DMA_MODE = 0, /*!< Control related DMA mode Parameter in DMA_InitTypeDef */ + DMA_PRIORITY = 1, /*!< Control related priority level Parameter in DMA_InitTypeDef */ + +} DMA_ControlTypeDef; + +/** + * @brief HAL DMA2D State structures definition + */ +typedef enum +{ + HAL_DMA_STATE_RESET = 0x00, /*!< DMA not yet initialized or disabled */ + HAL_DMA_STATE_READY = 0x01, /*!< DMA process success and ready for use */ + HAL_DMA_STATE_READY_HALF = 0x11, /*!< DMA Half process success */ + HAL_DMA_STATE_BUSY = 0x02, /*!< DMA process is ongoing */ + HAL_DMA_STATE_TIMEOUT = 0x03, /*!< DMA timeout state */ + HAL_DMA_STATE_ERROR = 0x04, /*!< DMA error state */ + +}HAL_DMA_StateTypeDef; + +/** + * @brief HAL DMA Error Code structure definition + */ +typedef enum +{ + HAL_DMA_FULL_TRANSFER = 0x00, /*!< Full transfer */ + HAL_DMA_HALF_TRANSFER = 0x01, /*!< Half Transfer */ + +}HAL_DMA_LevelCompleteTypeDef; + + +/** + * @brief DMA handle Structure definition + */ +typedef struct __DMA_HandleTypeDef +{ + DMA_Channel_TypeDef *Instance; /*!< Register base address */ + + DMA_InitTypeDef Init; /*!< DMA communication parameters */ + + HAL_LockTypeDef Lock; /*!< DMA locking object */ + + HAL_DMA_StateTypeDef State; /*!< DMA transfer state */ + + void *Parent; /*!< Parent object state */ + + void (* XferCpltCallback)( struct __DMA_HandleTypeDef * hdma); /*!< DMA transfer complete callback */ + + void (* XferHalfCpltCallback)( struct __DMA_HandleTypeDef * hdma); /*!< DMA Half transfer complete callback */ + + void (* XferErrorCallback)( struct __DMA_HandleTypeDef * hdma); /*!< DMA transfer error callback */ + + __IO uint32_t ErrorCode; /*!< DMA Error code */ + +} DMA_HandleTypeDef; + +/* Exported constants --------------------------------------------------------*/ + +/** @defgroup DMA_Exported_Constants + * @{ + */ + +/** @defgroup DMA_Error_Code + * @{ + */ +#define HAL_DMA_ERROR_NONE ((uint32_t)0x00000000) /*!< No error */ +#define HAL_DMA_ERROR_TE ((uint32_t)0x00000001) /*!< Transfer error */ +#define HAL_DMA_ERROR_TIMEOUT ((uint32_t)0x00000020) /*!< Timeout error */ +/** + * @} + */ + +/** @defgroup DMA_Data_transfer_direction + * @{ + */ +#define DMA_PERIPH_TO_MEMORY ((uint32_t)0x00000000) /*!< Peripheral to memory direction */ +#define DMA_MEMORY_TO_PERIPH ((uint32_t)DMA_CCR_DIR) /*!< Memory to peripheral direction */ +#define DMA_MEMORY_TO_MEMORY ((uint32_t)(DMA_CCR_MEM2MEM)) /*!< Memory to memory direction */ + +#define IS_DMA_DIRECTION(DIRECTION) (((DIRECTION) == DMA_PERIPH_TO_MEMORY ) || \ + ((DIRECTION) == DMA_MEMORY_TO_PERIPH) || \ + ((DIRECTION) == DMA_MEMORY_TO_MEMORY)) +/** + * @} + */ + +/** @defgroup DMA_Data_buffer_size + * @{ + */ +#define IS_DMA_BUFFER_SIZE(SIZE) (((SIZE) >= 0x1) && ((SIZE) < 0x10000)) +/** + * @} + */ + +/** @defgroup DMA_Peripheral_incremented_mode + * @{ + */ +#define DMA_PINC_ENABLE ((uint32_t)DMA_CCR_PINC) /*!< Peripheral increment mode Enable */ +#define DMA_PINC_DISABLE ((uint32_t)0x00000000) /*!< Peripheral increment mode Disable */ + +#define IS_DMA_PERIPHERAL_INC_STATE(STATE) (((STATE) == DMA_PINC_ENABLE) || \ + ((STATE) == DMA_PINC_DISABLE)) +/** + * @} + */ + +/** @defgroup DMA_Memory_incremented_mode + * @{ + */ +#define DMA_MINC_ENABLE ((uint32_t)DMA_CCR_MINC) /*!< Memory increment mode Enable */ +#define DMA_MINC_DISABLE ((uint32_t)0x00000000) /*!< Memory increment mode Disable */ + +#define IS_DMA_MEMORY_INC_STATE(STATE) (((STATE) == DMA_MINC_ENABLE) || \ + ((STATE) == DMA_MINC_DISABLE)) +/** + * @} + */ + +/** @defgroup DMA_Peripheral_data_size + * @{ + */ +#define DMA_PDATAALIGN_BYTE ((uint32_t)0x00000000) /*!< Peripheral data alignment : Byte */ +#define DMA_PDATAALIGN_HALFWORD ((uint32_t)DMA_CCR_PSIZE_0) /*!< Peripheral data alignment : HalfWord */ +#define DMA_PDATAALIGN_WORD ((uint32_t)DMA_CCR_PSIZE_1) /*!< Peripheral data alignment : Word */ + +#define IS_DMA_PERIPHERAL_DATA_SIZE(SIZE) (((SIZE) == DMA_PDATAALIGN_BYTE) || \ + ((SIZE) == DMA_PDATAALIGN_HALFWORD) || \ + ((SIZE) == DMA_PDATAALIGN_WORD)) +/** + * @} + */ + + +/** @defgroup DMA_Memory_data_size + * @{ + */ +#define DMA_MDATAALIGN_BYTE ((uint32_t)0x00000000) /*!< Memory data alignment : Byte */ +#define DMA_MDATAALIGN_HALFWORD ((uint32_t)DMA_CCR_MSIZE_0) /*!< Memory data alignment : HalfWord */ +#define DMA_MDATAALIGN_WORD ((uint32_t)DMA_CCR_MSIZE_1) /*!< Memory data alignment : Word */ + +#define IS_DMA_MEMORY_DATA_SIZE(SIZE) (((SIZE) == DMA_MDATAALIGN_BYTE) || \ + ((SIZE) == DMA_MDATAALIGN_HALFWORD) || \ + ((SIZE) == DMA_MDATAALIGN_WORD )) +/** + * @} + */ + +/** @defgroup DMA_mode + * @{ + */ +#define DMA_NORMAL ((uint32_t)0x00000000) /*!< Normal Mode */ +#define DMA_CIRCULAR ((uint32_t)DMA_CCR_CIRC) /*!< Circular Mode */ + +#define IS_DMA_MODE(MODE) (((MODE) == DMA_NORMAL ) || \ + ((MODE) == DMA_CIRCULAR)) +/** + * @} + */ + +/** @defgroup DMA_Priority_level + * @{ + */ +#define DMA_PRIORITY_LOW ((uint32_t)0x00000000) /*!< Priority level : Low */ +#define DMA_PRIORITY_MEDIUM ((uint32_t)DMA_CCR_PL_0) /*!< Priority level : Medium */ +#define DMA_PRIORITY_HIGH ((uint32_t)DMA_CCR_PL_1) /*!< Priority level : High */ +#define DMA_PRIORITY_VERY_HIGH ((uint32_t)DMA_CCR_PL) /*!< Priority level : Very_High */ + +#define IS_DMA_PRIORITY(PRIORITY) (((PRIORITY) == DMA_PRIORITY_LOW ) || \ + ((PRIORITY) == DMA_PRIORITY_MEDIUM) || \ + ((PRIORITY) == DMA_PRIORITY_HIGH) || \ + ((PRIORITY) == DMA_PRIORITY_VERY_HIGH)) +/** + * @} + */ + + +/** @defgroup DMA_interrupt_enable_definitions + * @{ + */ + +#define DMA_IT_TC ((uint32_t)DMA_CCR_TCIE) +#define DMA_IT_HT ((uint32_t)DMA_CCR_HTIE) +#define DMA_IT_TE ((uint32_t)DMA_CCR_TEIE) + +/** + * @} + */ + +/** @defgroup DMA_flag_definitions + * @{ + */ + +#define DMA_FLAG_GL1 ((uint32_t)0x00000001) +#define DMA_FLAG_TC1 ((uint32_t)0x00000002) +#define DMA_FLAG_HT1 ((uint32_t)0x00000004) +#define DMA_FLAG_TE1 ((uint32_t)0x00000008) +#define DMA_FLAG_GL2 ((uint32_t)0x00000010) +#define DMA_FLAG_TC2 ((uint32_t)0x00000020) +#define DMA_FLAG_HT2 ((uint32_t)0x00000040) +#define DMA_FLAG_TE2 ((uint32_t)0x00000080) +#define DMA_FLAG_GL3 ((uint32_t)0x00000100) +#define DMA_FLAG_TC3 ((uint32_t)0x00000200) +#define DMA_FLAG_HT3 ((uint32_t)0x00000400) +#define DMA_FLAG_TE3 ((uint32_t)0x00000800) +#define DMA_FLAG_GL4 ((uint32_t)0x00001000) +#define DMA_FLAG_TC4 ((uint32_t)0x00002000) +#define DMA_FLAG_HT4 ((uint32_t)0x00004000) +#define DMA_FLAG_TE4 ((uint32_t)0x00008000) +#define DMA_FLAG_GL5 ((uint32_t)0x00010000) +#define DMA_FLAG_TC5 ((uint32_t)0x00020000) +#define DMA_FLAG_HT5 ((uint32_t)0x00040000) +#define DMA_FLAG_TE5 ((uint32_t)0x00080000) +#define DMA_FLAG_GL6 ((uint32_t)0x00100000) +#define DMA_FLAG_TC6 ((uint32_t)0x00200000) +#define DMA_FLAG_HT6 ((uint32_t)0x00400000) +#define DMA_FLAG_TE6 ((uint32_t)0x00800000) +#define DMA_FLAG_GL7 ((uint32_t)0x01000000) +#define DMA_FLAG_TC7 ((uint32_t)0x02000000) +#define DMA_FLAG_HT7 ((uint32_t)0x04000000) +#define DMA_FLAG_TE7 ((uint32_t)0x08000000) + + +/** + * @} + */ + +/** + * @} + */ + +/* Exported macros -----------------------------------------------------------*/ +/** @defgroup DMA_Exported_Macros + * @{ + */ + +/** @brief Reset DMA handle state + * @param __HANDLE__: DMA handle. + * @retval None + */ +#define __HAL_DMA_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_DMA_STATE_RESET) + +/** + * @brief Enable the specified DMA Channel. + * @param __HANDLE__: DMA handle + * @retval None. + */ +#define __HAL_DMA_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CCR |= DMA_CCR_EN) + +/** + * @brief Disable the specified DMA Channel. + * @param __HANDLE__: DMA handle + * @retval None. + */ +#define __HAL_DMA_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CCR &= ~DMA_CCR_EN) + + +/* Interrupt & Flag management */ + +/** + * @brief Enables the specified DMA Channel interrupts. + * @param __HANDLE__: DMA handle + * @param __INTERRUPT__: specifies the DMA interrupt sources to be enabled or disabled. + * This parameter can be any combination of the following values: + * @arg DMA_IT_TC: Transfer complete interrupt mask + * @arg DMA_IT_HT: Half transfer complete interrupt mask + * @arg DMA_IT_TE: Transfer error interrupt mask + * @retval None + */ +#define __HAL_DMA_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CCR |= (__INTERRUPT__)) + +/** + * @brief Disables the specified DMA Channel interrupts. + * @param __HANDLE__: DMA handle + * @param __INTERRUPT__: specifies the DMA interrupt sources to be enabled or disabled. + * This parameter can be any combination of the following values: + * @arg DMA_IT_TC: Transfer complete interrupt mask + * @arg DMA_IT_HT: Half transfer complete interrupt mask + * @arg DMA_IT_TE: Transfer error interrupt mask + * @retval None + */ +#define __HAL_DMA_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CCR &= ~(__INTERRUPT__)) + +/** + * @brief Checks whether the specified DMA Channel interrupt has occurred or not. + * @param __HANDLE__: DMA handle + * @param __INTERRUPT__: specifies the DMA interrupt source to check. + * This parameter can be one of the following values: + * @arg DMA_IT_TC: Transfer complete interrupt mask + * @arg DMA_IT_HT: Half transfer complete interrupt mask + * @arg DMA_IT_TE: Transfer error interrupt mask + * @retval The state of DMA_IT (SET or RESET). + */ +#define __HAL_DMA_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((((__HANDLE__)->Instance->CCR & (__INTERRUPT__)) == (__INTERRUPT__)) ? SET : RESET) + +/** + * @} + */ + +/* Include DMA HAL Extension module */ +#include "stm32f0xx_hal_dma_ex.h" + +/* Exported functions --------------------------------------------------------*/ + +/* Initialization and de-initialization functions *****************************/ +HAL_StatusTypeDef HAL_DMA_Init(DMA_HandleTypeDef *hdma); +HAL_StatusTypeDef HAL_DMA_DeInit (DMA_HandleTypeDef *hdma); + +/* IO operation functions *****************************************************/ +HAL_StatusTypeDef HAL_DMA_Start (DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t DstAddress, uint32_t DataLength); +HAL_StatusTypeDef HAL_DMA_Start_IT(DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t DstAddress, uint32_t DataLength); +HAL_StatusTypeDef HAL_DMA_Abort(DMA_HandleTypeDef *hdma); +HAL_StatusTypeDef HAL_DMA_PollForTransfer(DMA_HandleTypeDef *hdma, uint32_t CompleteLevel, uint32_t Timeout); +void HAL_DMA_IRQHandler(DMA_HandleTypeDef *hdma); + +/* Peripheral State and Error functions ***************************************/ +HAL_DMA_StateTypeDef HAL_DMA_GetState(DMA_HandleTypeDef *hdma); +uint32_t HAL_DMA_GetError(DMA_HandleTypeDef *hdma); + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __STM32F0xx_HAL_DMA_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_dma_ex.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_dma_ex.h new file mode 100644 index 0000000000..9d7905c6a9 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_dma_ex.h @@ -0,0 +1,219 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_dma_ex.h + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief Header file of DMA HAL Extension module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32F0xx_HAL_DMA_EX_H +#define __STM32F0xx_HAL_DMA_EX_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal_def.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @addtogroup DMA + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/* Exported constants --------------------------------------------------------*/ +/* Exported macros -----------------------------------------------------------*/ +/** @addtogroup DMA_Exported_Macros + * @{ + */ +/* Interrupt & Flag management */ + +#if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) +/** + * @brief Returns the current DMA Channel transfer complete flag. + * @param __HANDLE__: DMA handle + * @retval The specified transfer complete flag index. + */ +#define __HAL_DMA_GET_TC_FLAG_INDEX(__HANDLE__) \ +(((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel1))? DMA_FLAG_TC1 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel2))? DMA_FLAG_TC2 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel3))? DMA_FLAG_TC3 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel4))? DMA_FLAG_TC4 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel5))? DMA_FLAG_TC5 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel6))? DMA_FLAG_TC6 :\ + DMA_FLAG_TC7) + +/** + * @brief Returns the current DMA Channel half transfer complete flag. + * @param __HANDLE__: DMA handle + * @retval The specified half transfer complete flag index. + */ +#define __HAL_DMA_GET_HT_FLAG_INDEX(__HANDLE__)\ +(((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel1))? DMA_FLAG_HT1 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel2))? DMA_FLAG_HT2 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel3))? DMA_FLAG_HT3 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel4))? DMA_FLAG_HT4 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel5))? DMA_FLAG_HT5 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel6))? DMA_FLAG_HT6 :\ + DMA_FLAG_HT7) + +/** + * @brief Returns the current DMA Channel transfer error flag. + * @param __HANDLE__: DMA handle + * @retval The specified transfer error flag index. + */ +#define __HAL_DMA_GET_TE_FLAG_INDEX(__HANDLE__)\ +(((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel1))? DMA_FLAG_TE1 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel2))? DMA_FLAG_TE2 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel3))? DMA_FLAG_TE3 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel4))? DMA_FLAG_TE4 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel5))? DMA_FLAG_TE5 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel6))? DMA_FLAG_TE6 :\ + DMA_FLAG_TE7) + +/** + * @brief Get the DMA Channel pending flags. + * @param __HANDLE__: DMA handle + * @param __FLAG__: Get the specified flag. + * This parameter can be any combination of the following values: + * @arg DMA_FLAG_TCIFx: Transfer complete flag + * @arg DMA_FLAG_HTIFx: Half transfer complete flag + * @arg DMA_FLAG_TEIFx: Transfer error flag + * Where x can be 1_7 to select the DMA Channel flag. + * @retval The state of FLAG (SET or RESET). + */ + +#define __HAL_DMA_GET_FLAG(__HANDLE__, __FLAG__) (DMA1->ISR & (__FLAG__)) + +/** + * @brief Clears the DMA Channel pending flags. + * @param __HANDLE__: DMA handle + * @param __FLAG__: specifies the flag to clear. + * This parameter can be any combination of the following values: + * @arg DMA_FLAG_TCIFx: Transfer complete flag + * @arg DMA_FLAG_HTIFx: Half transfer complete flag + * @arg DMA_FLAG_TEIFx: Transfer error flag + * Where x can be 1_7 to select the DMA Channel flag. + * @retval None + */ +#define __HAL_DMA_CLEAR_FLAG(__HANDLE__, __FLAG__) (DMA1->IFCR |= (__FLAG__)) + +#else /* STM32F030x8_STM32F031x6_STM32F038xx_STM32F051x8_STM32F058xx Product devices */ +/** + * @brief Returns the current DMA Channel transfer complete flag. + * @param __HANDLE__: DMA handle + * @retval The specified transfer complete flag index. + */ +#define __HAL_DMA_GET_TC_FLAG_INDEX(__HANDLE__) \ +(((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel1))? DMA_FLAG_TC1 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel2))? DMA_FLAG_TC2 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel3))? DMA_FLAG_TC3 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel4))? DMA_FLAG_TC4 :\ + DMA_FLAG_TC5) + +/** + * @brief Returns the current DMA Channel half transfer complete flag. + * @param __HANDLE__: DMA handle + * @retval The specified half transfer complete flag index. + */ +#define __HAL_DMA_GET_HT_FLAG_INDEX(__HANDLE__)\ +(((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel1))? DMA_FLAG_HT1 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel2))? DMA_FLAG_HT2 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel3))? DMA_FLAG_HT3 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel4))? DMA_FLAG_HT4 :\ + DMA_FLAG_HT5) + +/** + * @brief Returns the current DMA Channel transfer error flag. + * @param __HANDLE__: DMA handle + * @retval The specified transfer error flag index. + */ +#define __HAL_DMA_GET_TE_FLAG_INDEX(__HANDLE__)\ +(((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel1))? DMA_FLAG_TE1 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel2))? DMA_FLAG_TE2 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel3))? DMA_FLAG_TE3 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel4))? DMA_FLAG_TE4 :\ + DMA_FLAG_TE5) + +/** + * @brief Get the DMA Channel pending flags. + * @param __HANDLE__: DMA handle + * @param __FLAG__: Get the specified flag. + * This parameter can be any combination of the following values: + * @arg DMA_FLAG_TCIFx: Transfer complete flag + * @arg DMA_FLAG_HTIFx: Half transfer complete flag + * @arg DMA_FLAG_TEIFx: Transfer error flag + * Where x can be 1_5 to select the DMA Channel flag. + * @retval The state of FLAG (SET or RESET). + */ + +#define __HAL_DMA_GET_FLAG(__HANDLE__, __FLAG__) (DMA1->ISR & (__FLAG__)) + +/** + * @brief Clears the DMA Channel pending flags. + * @param __HANDLE__: DMA handle + * @param __FLAG__: specifies the flag to clear. + * This parameter can be any combination of the following values: + * @arg DMA_FLAG_TCIFx: Transfer complete flag + * @arg DMA_FLAG_HTIFx: Half transfer complete flag + * @arg DMA_FLAG_TEIFx: Transfer error flag + * Where x can be 1_5 to select the DMA Channel flag. + * @retval None + */ +#define __HAL_DMA_CLEAR_FLAG(__HANDLE__, __FLAG__) (DMA1->IFCR |= (__FLAG__)) + +#endif + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __STM32F0xx_HAL_DMA_EX_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_flash.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_flash.c new file mode 100644 index 0000000000..b0612b5f50 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_flash.c @@ -0,0 +1,692 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_flash.c + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief FLASH HAL module driver. + * + * This file provides firmware functions to manage the following + * functionalities of the internal FLASH memory: + * + Program operations functions + * + Memory Control functions + * + Peripheral State functions + * + @verbatim + ============================================================================== + ##### FLASH peripheral features ##### + ============================================================================== + + [..] The Flash memory interface manages CPU AHB I-Code and D-Code accesses + to the Flash memory. It implements the erase and program Flash memory operations + and the read and write protection mechanisms. + + [..] The Flash memory interface accelerates code execution with a system of instruction + prefetch. + + [..] The FLASH main features are: + (+) Flash memory read operations + (+) Flash memory program/erase operations + (+) Read / write protections + (+) Prefetch on I-Code + + + ##### How to use this driver ##### + ============================================================================== + [..] + This driver provides functions and macros to configure and program the FLASH + memory of all STM32F0xx devices. These functions are split in 3 groups: + + (#) FLASH Memory I/O Programming functions: this group includes all needed + functions to erase and program the main memory: + (++) Lock and Unlock the FLASH interface + (++) Erase function: Erase page, erase all pages + (++) Program functions: half word and word + + (#) Option Bytes Programming functions: this group includes all needed + functions to manage the Option Bytes: + (++) Lock and Unlock the Option Bytes + (++) Erase Option Bytes + (++) Set/Reset the write protection + (++) Set the Read protection Level + (++) Program the user Option Bytes + (++) Program the data Option Bytes + (++) Launch the Option Bytes loader + + (#) Interrupts and flags management functions : this group + includes all needed functions to: + (++) Handle FLASH interrupts + (++) Wait for last FLASH operation according to its status + (++) Get error flag status + + [..] In addition to these function, this driver includes a set of macros allowing + to handle the following operations: + + (+) Set the latency + (+) Enable/Disable the prefetch buffer + (+) Enable/Disable the FLASH interrupts + (+) Monitor the FLASH flags status + + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @defgroup FLASH + * @brief FLASH HAL module driver + * @{ + */ + +#ifdef HAL_FLASH_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Variables used for Erase pages under interruption*/ +FLASH_ProcessTypeDef pFlash; + +/* Private function prototypes -----------------------------------------------*/ +/* Erase operations */ +void FLASH_PageErase(uint32_t PageAddress); + +/* Program operations */ +static void FLASH_Program_HalfWord(uint32_t Address, uint16_t Data); + +HAL_StatusTypeDef FLASH_WaitForLastOperation(uint32_t Timeout); +static void FLASH_SetErrorCode(void); + +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup FLASH_Private_Functions + * @{ + */ + +/** @defgroup HAL_FLASH_Group1 Initialization/de-initialization functions + * @brief Initialization and Configuration functions + * +@verbatim + =============================================================================== + ##### Initialization and de-initialization functions ##### + =============================================================================== + [..] This section provides functions allowing to: + +@endverbatim + * @{ + */ + + +/** + * @} + */ + +/** @defgroup HAL_FLASH_Group2 I/O operation functions + * @brief Data transfers functions + * +@verbatim + =============================================================================== + ##### IO operation functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to manage the FLASH + program operations (write/erase). + +@endverbatim + * @{ + */ + +/** + * @brief Program halfword, word or double word at a specified address + * @note The function HAL_FLASH_Unlock() should be called before to unlock the FLASH interface + * The function HAL_FLASH_Lock() should be called after to lock the FLASH interface + * + * @note If an erase and a program operations are requested simultaneously, + * the erase operation is performed before the program one. + * + * @param TypeProgram: Indicate the way to program at a specified address. + * This parameter can be a value of @ref FLASH_Type_Program + * @param Address: Specifies the address to be programmed. + * @param Data: Specifies the data to be programmed + * + * @retval HAL_StatusTypeDef HAL Status + */ +HAL_StatusTypeDef HAL_FLASH_Program(uint32_t TypeProgram, uint32_t Address, uint64_t Data) +{ + HAL_StatusTypeDef status = HAL_ERROR; + uint8_t index = 0; + uint8_t nbiterations = 0; + + /* Process Locked */ + __HAL_LOCK(&pFlash); + + /* Check the parameters */ + assert_param(IS_TYPEPROGRAM(TypeProgram)); + assert_param(IS_FLASH_PROGRAM_ADDRESS(Address)); + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE); + + if(status == HAL_OK) + { + if(TypeProgram == TYPEPROGRAM_HALFWORD) + { + /* Program halfword (16-bit) at a specified address. */ + nbiterations = 1; + } + else if(TypeProgram == TYPEPROGRAM_WORD) + { + /* Program word (32-bit = 2*16-bit) at a specified address. */ + nbiterations = 2; + } + else + { + /* Program double word (64-bit = 4*16-bit) at a specified address. */ + nbiterations = 4; + } + + for (index = 0; index < nbiterations; index++) + { + FLASH_Program_HalfWord((Address + (2*index)), (uint16_t)(Data >> (16*index))); + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE); + + /* Check FLASH End of Operation flag */ + if (__HAL_FLASH_GET_FLAG(FLASH_FLAG_EOP)) + { + /* Clear FLASH End of Operation pending bit */ + __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP); + } + + /* If the program operation is completed, disable the PG Bit */ + CLEAR_BIT(FLASH->CR, FLASH_CR_PG); + } + } + + /* Process Unlocked */ + __HAL_UNLOCK(&pFlash); + + return status; +} + +/** + * @brief Program halfword, word or double word at a specified address with interrupt enabled. + * @note The function HAL_FLASH_Unlock() should be called before to unlock the FLASH interface + * The function HAL_FLASH_Lock() should be called after to lock the FLASH interface + * + * @note If an erase and a program operations are requested simultaneously, + * the erase operation is performed before the program one. + * + * @param TypeProgram: Indicate the way to program at a specified address. + * This parameter can be a value of @ref FLASH_Type_Program + * @param Address: Specifies the address to be programmed. + * @param Data: Specifies the data to be programmed + * + * @retval HAL_StatusTypeDef HAL Status + */ +HAL_StatusTypeDef HAL_FLASH_Program_IT(uint32_t TypeProgram, uint32_t Address, uint64_t Data) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Process Locked */ + __HAL_LOCK(&pFlash); + + /* Check the parameters */ + assert_param(IS_TYPEPROGRAM(TypeProgram)); + assert_param(IS_FLASH_PROGRAM_ADDRESS(Address)); + + /* Enable End of FLASH Operation and Error source interrupts */ + __HAL_FLASH_ENABLE_IT((FLASH_IT_EOP | FLASH_IT_ERR)); + + pFlash.Address = Address; + pFlash.Data = Data; + + if(TypeProgram == TYPEPROGRAM_HALFWORD) + { + pFlash.ProcedureOnGoing = FLASH_PROC_PROGRAMHALFWORD; + /*Program halfword (16-bit) at a specified address.*/ + pFlash.DataRemaining = 1; + } + else if(TypeProgram == TYPEPROGRAM_WORD) + { + pFlash.ProcedureOnGoing = FLASH_PROC_PROGRAMWORD; + /*Program word (32-bit : 2*16-bit) at a specified address.*/ + pFlash.DataRemaining = 2; + } + else + { + pFlash.ProcedureOnGoing = FLASH_PROC_PROGRAMDOUBLEWORD; + /*Program double word (64-bit : 4*16-bit) at a specified address.*/ + pFlash.DataRemaining = 4; + } + + /*Program halfword (16-bit) at a specified address.*/ + FLASH_Program_HalfWord(Address, (uint16_t)Data); + + return status; +} + +/** + * @brief This function handles FLASH interrupt request. + * @param None + * @retval None + */ +void HAL_FLASH_IRQHandler(void) +{ + uint32_t addresstmp; + /* If the operation is completed, disable the PG, PER and MER Bits */ + CLEAR_BIT(FLASH->CR, (FLASH_CR_PG | FLASH_CR_PER | FLASH_CR_MER)); + + /* Check FLASH End of Operation flag */ + if(__HAL_FLASH_GET_FLAG(FLASH_FLAG_EOP)) + { + /* Clear FLASH End of Operation pending bit */ + __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP); + + if(pFlash.ProcedureOnGoing == FLASH_PROC_PAGEERASE) + { + /* Nb of pages to erased can be decreased */ + pFlash.DataRemaining--; + + /* Indicate user which page address has been erased*/ + HAL_FLASH_EndOfOperationCallback(pFlash.Address); + + /* Check if there are still pages to erase*/ + if(pFlash.DataRemaining != 0) + { + /* Increment page address to next page */ + pFlash.Address += FLASH_PAGE_SIZE; + addresstmp = pFlash.Address; + FLASH_PageErase(addresstmp); + } + else + { + /*No more pages to Erase*/ + + /*Reset Address and stop Erase pages procedure*/ + pFlash.Address = 0xFFFFFFFF; + pFlash.ProcedureOnGoing = FLASH_PROC_NONE; + } + } + else if(pFlash.ProcedureOnGoing == FLASH_PROC_MASSERASE) + { + /*MassErase ended. Return the selected bank*/ + /* FLASH EOP interrupt user callback */ + HAL_FLASH_EndOfOperationCallback(0); + + /* Stop Mass Erase procedure*/ + pFlash.ProcedureOnGoing = FLASH_PROC_NONE; + } + else + { + /* Nb of 16-bit data to program can be decreased */ + pFlash.DataRemaining--; + + /* Check if there are still 16-bit data to program */ + if(pFlash.DataRemaining != 0) + { + /* Increment address to 16-bit */ + pFlash.Address += 2; + addresstmp = pFlash.Address; + + /* Shift to have next 16-bit data */ + pFlash.Data = (pFlash.Data >> 16); + + /*Program halfword (16-bit) at a specified address.*/ + FLASH_Program_HalfWord(addresstmp, (uint16_t)pFlash.Data); + } + else + { + /*Program ended. Return the selected address*/ + /* FLASH EOP interrupt user callback */ + if (pFlash.ProcedureOnGoing == FLASH_PROC_PROGRAMHALFWORD) + { + HAL_FLASH_EndOfOperationCallback(pFlash.Address); + } + else if (pFlash.ProcedureOnGoing == FLASH_PROC_PROGRAMWORD) + { + HAL_FLASH_EndOfOperationCallback(pFlash.Address-2); + } + else + { + HAL_FLASH_EndOfOperationCallback(pFlash.Address-6); + } + + /* Reset Address and stop Program procedure*/ + pFlash.Address = 0xFFFFFFFF; + pFlash.ProcedureOnGoing = FLASH_PROC_NONE; + } + } + } + + /* Check FLASH operation error flags */ + if(__HAL_FLASH_GET_FLAG(FLASH_FLAG_WRPERR | FLASH_FLAG_PGERR)) + { + /*Save the Error code*/ + FLASH_SetErrorCode(); + + /* FLASH error interrupt user callback */ + HAL_FLASH_OperationErrorCallback(pFlash.Address); + + /* Clear FLASH error pending bits */ + __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_WRPERR | FLASH_FLAG_PGERR); + + /* Reset address and stop the procedure ongoing*/ + pFlash.Address = 0xFFFFFFFF; + pFlash.ProcedureOnGoing = FLASH_PROC_NONE; + } + + if(pFlash.ProcedureOnGoing == FLASH_PROC_NONE) + { + /* Disable End of FLASH Operation and Error source interrupts */ + __HAL_FLASH_DISABLE_IT((FLASH_IT_EOP | FLASH_IT_ERR)); + + /* Process Unlocked */ + __HAL_UNLOCK(&pFlash); + } +} + + +/** + * @brief FLASH end of operation interrupt callback + * @param ReturnValue: The value saved in this parameter depends on the ongoing procedure + * - Mass Erase: No return value expected + * - Pages Erase: Address of the page which has been erased + * - Program: Address which was selected for data program + * @retval none + */ +__weak void HAL_FLASH_EndOfOperationCallback(uint32_t ReturnValue) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_FLASH_EndOfOperationCallback could be implemented in the user file + */ +} + +/** + * @brief FLASH operation error interrupt callback + * @param ReturnValue: The value saved in this parameter depends on the ongoing procedure + * - Mass Erase: No return value expected + * - Pages Erase: Address of the page which returned an error + * - Program: Address which was selected for data program + * @retval none + */ +__weak void HAL_FLASH_OperationErrorCallback(uint32_t ReturnValue) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_FLASH_OperationErrorCallback could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup HAL_FLASH_Group3 Peripheral Control functions + * @brief management functions + * +@verbatim + =============================================================================== + ##### Peripheral Control functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to control the FLASH + memory operations. + +@endverbatim + * @{ + */ + +/** + * @brief Unlock the FLASH control register access + * @param None + * @retval HAL Status + */ +HAL_StatusTypeDef HAL_FLASH_Unlock(void) +{ + if((READ_BIT(FLASH->CR, FLASH_CR_LOCK)) != RESET) + { + /* Authorize the FLASH Registers access */ + WRITE_REG(FLASH->KEYR, FLASH_FKEY1); + WRITE_REG(FLASH->KEYR, FLASH_FKEY2); + } + else + { + return HAL_ERROR; + } + + return HAL_OK; +} + +/** + * @brief Locks the FLASH control register access + * @param None + * @retval HAL Status + */ +HAL_StatusTypeDef HAL_FLASH_Lock(void) +{ + /* Set the LOCK Bit to lock the FLASH Registers access */ + SET_BIT(FLASH->CR, FLASH_CR_LOCK); + + return HAL_OK; +} + + +/** + * @brief Unlock the FLASH Option Control Registers access. + * @param None + * @retval HAL Status + */ +HAL_StatusTypeDef HAL_FLASH_OB_Unlock(void) +{ + if((READ_BIT(FLASH->CR, FLASH_CR_OPTWRE)) == RESET) + { + /* Authorizes the Option Byte register programming */ + WRITE_REG(FLASH->OPTKEYR, FLASH_OPTKEY1); + WRITE_REG(FLASH->OPTKEYR, FLASH_OPTKEY2); + } + else + { + return HAL_ERROR; + } + + return HAL_OK; +} + +/** + * @brief Lock the FLASH Option Control Registers access. + * @param None + * @retval HAL Status + */ +HAL_StatusTypeDef HAL_FLASH_OB_Lock(void) +{ + /* Clear the OPTWRE Bit to lock the FLASH Option Byte Registers access */ + CLEAR_BIT(FLASH->CR, FLASH_CR_OPTWRE); + + return HAL_OK; +} + +/** + * @brief Launch the option byte loading. + * @param None + * @retval HAL status + */ +HAL_StatusTypeDef HAL_FLASH_OB_Launch(void) +{ + /* Set the bit to force the option byte reloading */ + SET_BIT(FLASH->CR, FLASH_CR_OBL_LAUNCH); + + /* Wait for last operation to be completed */ + return(FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE)); +} + +/** + * @} + */ + + +/** @defgroup HAL_FLASH_Group4 Peripheral State functions + * @brief Peripheral State functions + * +@verbatim + =============================================================================== + ##### Peripheral State functions ##### + =============================================================================== + [..] + This subsection permit to get in run-time the status of the FLASH peripheral. + +@endverbatim + * @{ + */ + +/** + * @brief Get the specific FLASH error flag. + * @param None + * @retval FLASH_ErrorCode: The returned value can be: + * @arg FLASH_ERROR_PG: FLASH Programming error flag + * @arg FLASH_ERROR_WRP: FLASH Write protected error flag + */ +FLASH_ErrorTypeDef HAL_FLASH_GetError(void) +{ + return pFlash.ErrorCode; +} + +/** + * @} + */ + +/** + * @brief Erase the specified FLASH memory page + * @param PageAddress: FLASH page to erase + * The value of this parameter depend on device used within the same series + * + * @retval None + */ +void FLASH_PageErase(uint32_t PageAddress) +{ + /* Clear pending flags (if any) */ + __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP | FLASH_FLAG_WRPERR | FLASH_FLAG_PGERR); + + /* Proceed to erase the page */ + SET_BIT(FLASH->CR, FLASH_CR_PER); + WRITE_REG(FLASH->AR, PageAddress); + SET_BIT(FLASH->CR, FLASH_CR_STRT); +} + +/** + * @brief Program a half-word (16-bit) at a specified address. + * @param Address: specifies the address to be programmed. + * @param Data: specifies the data to be programmed. + * @retval None + */ +static void FLASH_Program_HalfWord(uint32_t Address, uint16_t Data) +{ + /* Clear pending flags (if any) */ + __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP | FLASH_FLAG_WRPERR | FLASH_FLAG_PGERR); + + /* Proceed to program the new data */ + SET_BIT(FLASH->CR, FLASH_CR_PG); + + *(__IO uint16_t*)Address = Data; +} + +/** + * @brief Wait for a FLASH operation to complete. + * @param Timeout: maximum flash operationtimeout + * @retval HAL_StatusTypeDef HAL Status + */ +HAL_StatusTypeDef FLASH_WaitForLastOperation(uint32_t Timeout) +{ + /* Wait for the FLASH operation to complete by polling on BUSY flag to be reset. + Even if the FLASH operation fails, the BUSY flag will be reset and an error + flag will be set */ + + uint32_t tickstart = HAL_GetTick(); + + while(__HAL_FLASH_GET_FLAG(FLASH_FLAG_BSY)) + { + if(Timeout != HAL_MAX_DELAY) + { + if((HAL_GetTick() - tickstart) > Timeout) + { + return HAL_TIMEOUT; + } + } + } + + if(__HAL_FLASH_GET_FLAG(FLASH_FLAG_WRPERR) || __HAL_FLASH_GET_FLAG(FLASH_FLAG_PGERR)) + { + /*Save the error code*/ + FLASH_SetErrorCode(); + return HAL_ERROR; + } + + /* If there is an error flag set */ + return HAL_OK; + +} + +/** + * @brief Set the specific FLASH error flag. + * @param None + * @retval None + */ +static void FLASH_SetErrorCode(void) +{ + if(__HAL_FLASH_GET_FLAG(FLASH_FLAG_WRPERR)) + { + pFlash.ErrorCode = FLASH_ERROR_WRP; + } + if(__HAL_FLASH_GET_FLAG(FLASH_FLAG_PGERR)) + { + pFlash.ErrorCode |= FLASH_ERROR_PG; + } +} + +/** + * @} + */ + +#endif /* HAL_FLASH_MODULE_ENABLED */ + +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_flash.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_flash.h new file mode 100644 index 0000000000..e74699da43 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_flash.h @@ -0,0 +1,478 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_flash.h + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief Header file of Flash HAL module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32F0xx_HAL_FLASH_H +#define __STM32F0xx_HAL_FLASH_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal_def.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @addtogroup FLASH + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/** @defgroup FLASH_Exported_Types + * @{ + */ + +/** + * @brief FLASH Error source + */ +typedef enum +{ + FLASH_ERROR_PG = 0x01, + FLASH_ERROR_WRP = 0x02 +} FLASH_ErrorTypeDef; + +/** + * @brief FLASH Erase structure definition + */ +typedef struct +{ + uint32_t TypeErase; /*!< TypeErase: Mass erase or page erase. + This parameter can be a value of @ref FLASH_Type_Erase */ + + uint32_t PageAddress; /*!< PageAdress: Initial FLASH page address to erase when mass erase is disabled + This parameter must be a value of @ref FLASHEx_Address */ + + uint32_t NbPages; /*!< NbPages: Number of pagess to be erased. + This parameter must be a value between 1 and (max number of pages - value of initial page)*/ + +} FLASH_EraseInitTypeDef; + +/** + * @brief FLASH Options bytes program structure definition + */ +typedef struct +{ + uint32_t OptionType; /*!< OptionType: Option byte to be configured. + This parameter can be a value of @ref FLASH_OB_Type */ + + uint32_t WRPState; /*!< WRPState: Write protection activation or deactivation. + This parameter can be a value of @ref FLASH_OB_WRP_State */ + + uint32_t WRPPage; /*!< WRPSector: specifies the page(s) to be write protected + This parameter can be a value of @ref FLASHEx_OB_Write_Protection */ + + uint8_t RDPLevel; /*!< RDPLevel: Set the read protection level.. + This parameter can be a value of @ref FLASH_OB_Read_Protection */ + + uint8_t USERConfig; /*!< USERConfig: Program the FLASH User Option Byte: + IWDG / STOP / STDBY / BOOT1 / VDDA_ANALOG / SRAM_PARITY + This parameter can be a combination of @ref FLASH_OB_Watchdog, @ref FLASH_OB_nRST_STOP, + @ref FLASH_OB_nRST_STDBY, @ref FLASH_OB_BOOT1, @ref FLASH_OB_VDDA_Analog_Monitoring and + @ref FLASH_OB_RAM_Parity_Check_Enable */ + + uint32_t DATAAddress; /*!< DATAAddress: Address of the option byte DATA to be prgrammed + This parameter can be a value of @ref FLASH_OB_Data_Address */ + + uint8_t DATAData; /*!< DATAData: Data to be stored in the option byte DATA + This parameter can have any value */ + +} FLASH_OBProgramInitTypeDef; + +/** + * @brief FLASH Procedure structure definition + */ +typedef enum +{ + FLASH_PROC_NONE = 0, + FLASH_PROC_PAGEERASE = 1, + FLASH_PROC_MASSERASE = 2, + FLASH_PROC_PROGRAMHALFWORD = 3, + FLASH_PROC_PROGRAMWORD = 4, + FLASH_PROC_PROGRAMDOUBLEWORD = 5 +} FLASH_ProcedureTypeDef; + +/** + * @brief FLASH handle Structure definition + */ +typedef struct +{ + __IO FLASH_ProcedureTypeDef ProcedureOnGoing; /* Internal variable to indicate which procedure is ongoing or not in IT context */ + + __IO uint32_t DataRemaining; /* Internal variable to save the remaining pages to erase or half-word to program in IT context */ + + __IO uint32_t Address; /* Internal variable to save address selected for program or erase */ + + __IO uint64_t Data; /* Internal variable to save data to be programmed */ + + HAL_LockTypeDef Lock; /* FLASH locking object */ + + __IO FLASH_ErrorTypeDef ErrorCode; /* FLASH error code */ + +} FLASH_ProcessTypeDef; + +/** + * @} + */ + +/* Exported constants --------------------------------------------------------*/ + +/** @defgroup FLASH_Exported_Constants + * @{ + */ + +/** @defgroup FLASH_Type_Erase FLASH Type Erase + * @{ + */ +#define TYPEERASE_PAGES ((uint32_t)0x00) /*!ACR = (FLASH->ACR&(~FLASH_ACR_LATENCY)) | (__LATENCY__)) + +/** + * @brief Enable the FLASH prefetch buffer. + * @param None + * @retval None + */ +#define __HAL_FLASH_PREFETCH_BUFFER_ENABLE() (FLASH->ACR |= FLASH_ACR_PRFTBE) + +/** + * @brief Disable the FLASH prefetch buffer. + * @param None + * @retval None + */ +#define __HAL_FLASH_PREFETCH_BUFFER_DISABLE() (FLASH->ACR &= (~FLASH_ACR_PRFTBE)) + +/** + * @} + */ + +/** @defgroup FLASH_Interrupt + * @brief macros to handle FLASH interrupts + * @{ + */ + +/** + * @brief Enable the specified FLASH interrupt. + * @param __INTERRUPT__ : FLASH interrupt + * This parameter can be any combination of the following values: + * @arg FLASH_IT_EOP: End of FLASH Operation Interrupt + * @arg FLASH_IT_ERR: Error Interrupt + * @retval none + */ +#define __HAL_FLASH_ENABLE_IT(__INTERRUPT__) (FLASH->CR |= (__INTERRUPT__)) + +/** + * @brief Disable the specified FLASH interrupt. + * @param __INTERRUPT__ : FLASH interrupt + * This parameter can be any combination of the following values: + * @arg FLASH_IT_EOP: End of FLASH Operation Interrupt + * @arg FLASH_IT_ERR: Error Interrupt + * @retval none + */ +#define __HAL_FLASH_DISABLE_IT(__INTERRUPT__) (FLASH->CR &= ~(uint32_t)(__INTERRUPT__)) + +/** + * @brief Get the specified FLASH flag status. + * @param __FLAG__: specifies the FLASH flag to check. + * This parameter can be one of the following values: + * @arg FLASH_FLAG_EOP : FLASH End of Operation flag + * @arg FLASH_FLAG_WRPERR: FLASH Write protected error flag + * @arg FLASH_FLAG_PGERR : FLASH Programming error flag + * @arg FLASH_FLAG_BSY : FLASH Busy flag + * @retval The new state of __FLAG__ (SET or RESET). + */ +#define __HAL_FLASH_GET_FLAG(__FLAG__) ((FLASH->SR & (__FLAG__)) == (__FLAG__)) + +/** + * @brief Clear the specified FLASH flag. + * @param __FLAG__: specifies the FLASH flags to clear. + * This parameter can be any combination of the following values: + * @arg FLASH_FLAG_EOP : FLASH End of Operation flag + * @arg FLASH_FLAG_WRPERR: FLASH Write protected error flag + * @arg FLASH_FLAG_PGERR : FLASH Programming error flag + * @retval none + */ +#define __HAL_FLASH_CLEAR_FLAG(__FLAG__) (FLASH->SR = (__FLAG__)) + +/** + * @} + */ + +/* Include FLASH HAL Extension module */ +#include "stm32f0xx_hal_flash_ex.h" + +/* Exported functions --------------------------------------------------------*/ +/** @defgroup FLASH_Exported_Functions + * @{ + */ + +/* Exported functions --------------------------------------------------------*/ +/* IO operation functions *****************************************************/ +HAL_StatusTypeDef HAL_FLASH_Program(uint32_t TypeProgram, uint32_t Address, uint64_t Data); +HAL_StatusTypeDef HAL_FLASH_Program_IT(uint32_t TypeProgram, uint32_t Address, uint64_t Data); + +/* FLASH IRQ handler method */ +void HAL_FLASH_IRQHandler(void); +/* Callbacks in non blocking modes */ +void HAL_FLASH_EndOfOperationCallback(uint32_t ReturnValue); +void HAL_FLASH_OperationErrorCallback(uint32_t ReturnValue); + +/* Peripheral Control functions ***********************************************/ +HAL_StatusTypeDef HAL_FLASH_Unlock(void); +HAL_StatusTypeDef HAL_FLASH_Lock(void); +HAL_StatusTypeDef HAL_FLASH_OB_Unlock(void); +HAL_StatusTypeDef HAL_FLASH_OB_Lock(void); +/* Option bytes control */ +HAL_StatusTypeDef HAL_FLASH_OB_Launch(void); + +/* Peripheral State and Error functions ***************************************/ +FLASH_ErrorTypeDef HAL_FLASH_GetError(void); + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __STM32F0xx_HAL_FLASH_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_flash_ex.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_flash_ex.c new file mode 100644 index 0000000000..be038ee008 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_flash_ex.c @@ -0,0 +1,828 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_flash_ex.c + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief Extended FLASH HAL module driver. + * + * This file provides firmware functions to manage the following + * functionalities of the FLASH peripheral: + * + Extended Initialization/de-initialization functions + * + Extended I/O operation functions + * + Extended Peripheral Control functions + * + Extended Peripheral State functions + * + @verbatim + ============================================================================== + ##### Flash peripheral extended features ##### + ============================================================================== + + ##### How to use this driver ##### + ============================================================================== + [..] This driver provides functions to configure and program the FLASH memory + of all STM32F0xxx devices. It includes + + (++) Set/Reset the write protection + (++) Program the user Option Bytes + (++) Get the Read protection Level + + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @defgroup FLASHEx + * @brief FLASH Extended HAL module driver + * @{ + */ + +#ifdef HAL_FLASH_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +#define HAL_FLASH_TIMEOUT_VALUE ((uint32_t)50000)/* 50 s */ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Variables used for Erase pages under interruption*/ +extern FLASH_ProcessTypeDef pFlash; +/* Private function prototypes -----------------------------------------------*/ +/* Erase operations */ +extern void FLASH_PageErase(uint32_t PageAddress); +static void FLASH_MassErase(void); + +/* Option bytes control */ +static HAL_StatusTypeDef FLASH_OB_EnableWRP(uint32_t WriteProtectPage); +static HAL_StatusTypeDef FLASH_OB_DisableWRP(uint32_t WriteProtectPage); +static HAL_StatusTypeDef FLASH_OB_RDP_LevelConfig(uint8_t ReadProtectLevel); +static HAL_StatusTypeDef FLASH_OB_UserConfig(uint8_t UserConfig); +static HAL_StatusTypeDef FLASH_OB_ProgramData(uint32_t Address, uint8_t Data); +static uint32_t FLASH_OB_GetWRP(void); +static FlagStatus FLASH_OB_GetRDP(void); +static uint8_t FLASH_OB_GetUser(void); + +/* Private functions ---------------------------------------------------------*/ +extern HAL_StatusTypeDef FLASH_WaitForLastOperation(uint32_t Timeout); + +/** @defgroup FLASHEx_Private_Functions + * @{ + */ + +/** @defgroup FLASHEx_Group1 Extended Initialization/de-initialization functions + * @brief Extended Initialization and Configuration functions + * +@verbatim + =============================================================================== + ##### Initialization/de-initialization functions ##### + =============================================================================== + +@endverbatim + * @{ + */ + + +/** + * @} + */ + +/** @defgroup FLASHEx__Group2 Extended I/O operation functions + * @brief Extended I/O operation functions + * +@verbatim + =============================================================================== + ##### IO operation functions ##### + =============================================================================== + +@endverbatim + * @{ + */ +/** + * @brief Perform a mass erase or erase the specified FLASH memory pages + * @note The function HAL_FLASH_Unlock() should be called before to unlock the FLASH interface + * The function HAL_FLASH_Lock() should be called after to lock the FLASH interface + * @param[in] pEraseInit: pointer to an FLASH_EraseInitTypeDef structure that + * contains the configuration information for the erasing. + * + * @param[out] PageError: pointer to variable that + * contains the configuration information on faulty page in case of error + * (0xFFFFFFFF means that all the pages have been correctly erased) + * + * @retval HAL_StatusTypeDef HAL Status + */ +HAL_StatusTypeDef HAL_FLASHEx_Erase(FLASH_EraseInitTypeDef *pEraseInit, uint32_t *PageError) +{ + HAL_StatusTypeDef status = HAL_ERROR; + uint32_t address = 0; + + /* Process Locked */ + __HAL_LOCK(&pFlash); + + /* Check the parameters */ + assert_param(IS_TYPEERASE(pEraseInit->TypeErase)); + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE); + + if (status == HAL_OK) + { + if (pEraseInit->TypeErase == TYPEERASE_MASSERASE) + { + /*Mass erase to be done*/ + FLASH_MassErase(); + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE); + + /* Check FLASH End of Operation flag */ + if (__HAL_FLASH_GET_FLAG(FLASH_FLAG_EOP)) + { + /* Clear FLASH End of Operation pending bit */ + __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP); + } + + /* If the erase operation is completed, disable the MER Bit */ + CLEAR_BIT(FLASH->CR, FLASH_CR_MER); + } + else + { + /* Check the parameters */ + assert_param(IS_FLASH_PROGRAM_ADDRESS(pEraseInit->PageAddress)); + assert_param(IS_FLASH_NB_PAGES(pEraseInit->PageAddress, pEraseInit->NbPages)); + + /*Initialization of PageError variable*/ + *PageError = 0xFFFFFFFF; + + /* Erase by page by page to be done*/ + for(address = pEraseInit->PageAddress; + address < (pEraseInit->PageAddress + (pEraseInit->NbPages)*FLASH_PAGE_SIZE); + address += FLASH_PAGE_SIZE) + { + FLASH_PageErase(address); + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE); + + /* Check FLASH End of Operation flag */ + if (__HAL_FLASH_GET_FLAG(FLASH_FLAG_EOP)) + { + /* Clear FLASH End of Operation pending bit */ + __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP); + } + + /* If the erase operation is completed, disable the PER Bit */ + CLEAR_BIT(FLASH->CR, FLASH_CR_PER); + + if (status != HAL_OK) + { + /* In case of error, stop erase procedure and return the faulty address */ + *PageError = address; + break; + } + } + } + } + + /* Process Unlocked */ + __HAL_UNLOCK(&pFlash); + + return status; +} + +/** + * @brief Perform a mass erase or erase the specified FLASH memory sectors with interrupt enabled + * @note The function HAL_FLASH_Unlock() should be called before to unlock the FLASH interface + * The function HAL_FLASH_Lock() should be called after to lock the FLASH interface + * @param pEraseInit: pointer to an FLASH_EraseInitTypeDef structure that + * contains the configuration information for the erasing. + * + * @retval HAL_StatusTypeDef HAL Status + */ +HAL_StatusTypeDef HAL_FLASHEx_Erase_IT(FLASH_EraseInitTypeDef *pEraseInit) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Process Locked */ + __HAL_LOCK(&pFlash); + + /* Check the parameters */ + assert_param(IS_TYPEERASE(pEraseInit->TypeErase)); + + /* Enable End of FLASH Operation and Error source interrupts */ + __HAL_FLASH_ENABLE_IT((FLASH_IT_EOP | FLASH_IT_ERR)); + + if (pEraseInit->TypeErase == TYPEERASE_MASSERASE) + { + /*Mass erase to be done*/ + pFlash.ProcedureOnGoing = FLASH_PROC_MASSERASE; + FLASH_MassErase(); + } + else + { + /* Erase by page to be done*/ + + /* Check the parameters */ + assert_param(IS_FLASH_PROGRAM_ADDRESS(pEraseInit->PageAddress)); + assert_param(IS_FLASH_NB_PAGES(pEraseInit->PageAddress, pEraseInit->NbPages)); + + pFlash.ProcedureOnGoing = FLASH_PROC_PAGEERASE; + pFlash.DataRemaining = pEraseInit->NbPages; + pFlash.Address = pEraseInit->PageAddress; + + /*Erase 1st page and wait for IT*/ + FLASH_PageErase(pEraseInit->PageAddress); + } + + return status; +} + +/** + * @} + */ + +/** @defgroup FLASHEx__Group3 Extended Peripheral Control functions + * @brief Extended Peripheral Control functions + * +@verbatim + =============================================================================== + ##### Peripheral Control functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to control the FLASH + memory operations. + +@endverbatim + * @{ + */ +/** + * @brief Erases the FLASH option bytes. + * @note This functions erases all option bytes except the Read protection (RDP). + * The function HAL_FLASH_Unlock() should be called before to unlock the FLASH interface + * The function HAL_FLASH_OB_Unlock() should be called before to unlock the options bytes + * The function HAL_FLASH_OB_Launch() should be called after to force the reload of the options bytes + * (system reset will occur) + * @param None + * @retval HAL status + */ + +HAL_StatusTypeDef HAL_FLASHEx_OBErase(void) +{ + uint8_t rdptmp = OB_RDP_LEVEL_0; + HAL_StatusTypeDef status = HAL_ERROR; + FLASH_OBProgramInitTypeDef optionsbytes; + + /* Get the actual read protection Option Byte value */ + HAL_FLASHEx_OBGetConfig(&optionsbytes); + if(optionsbytes.RDPLevel != RESET) + { + rdptmp = OB_RDP_LEVEL_1; + } + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE); + + /* Clear pending flags (if any) */ + __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP | FLASH_FLAG_WRPERR | FLASH_FLAG_PGERR); + + if(status == HAL_OK) + { + /* If the previous operation is completed, proceed to erase the option bytes */ + SET_BIT(FLASH->CR, FLASH_CR_OPTER); + SET_BIT(FLASH->CR, FLASH_CR_STRT); + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE); + + /* If the erase operation is completed, disable the OPTER Bit */ + CLEAR_BIT(FLASH->CR, FLASH_CR_OPTER); + + if(status == HAL_OK) + { + /* Restore the last read protection Option Byte value */ + optionsbytes.OptionType = OPTIONBYTE_RDP; + optionsbytes.RDPLevel = rdptmp; + status = HAL_FLASHEx_OBProgram(&optionsbytes); + } + } + + /* Return the erase status */ + return status; +} + +/** + * @brief Program option bytes + * @note The function HAL_FLASH_Unlock() should be called before to unlock the FLASH interface + * The function HAL_FLASH_OB_Unlock() should be called before to unlock the options bytes + * The function HAL_FLASH_OB_Launch() should be called after to force the reload of the options bytes + * (system reset will occur) + * + * @param pOBInit: pointer to an FLASH_OBInitStruct structure that + * contains the configuration information for the programming. + * + * @retval HAL_StatusTypeDef HAL Status + */ +HAL_StatusTypeDef HAL_FLASHEx_OBProgram(FLASH_OBProgramInitTypeDef *pOBInit) +{ + HAL_StatusTypeDef status = HAL_ERROR; + + /* Check the parameters */ + assert_param(IS_OPTIONBYTE(pOBInit->OptionType)); + + /* Write protection configuration */ + if((pOBInit->OptionType & OPTIONBYTE_WRP) == OPTIONBYTE_WRP) + { + assert_param(IS_WRPSTATE(pOBInit->WRPState)); + if (pOBInit->WRPState == WRPSTATE_ENABLE) + { + /* Enable of Write protection on the selected page */ + status = FLASH_OB_EnableWRP(pOBInit->WRPPage); + } + else + { + /* Disable of Write protection on the selected page */ + status = FLASH_OB_DisableWRP(pOBInit->WRPPage); + } + } + + /* Read protection configuration */ + if((pOBInit->OptionType & OPTIONBYTE_RDP) == OPTIONBYTE_RDP) + { + status = FLASH_OB_RDP_LevelConfig(pOBInit->RDPLevel); + } + + /* USER configuration */ + if((pOBInit->OptionType & OPTIONBYTE_USER) == OPTIONBYTE_USER) + { + status = FLASH_OB_UserConfig(pOBInit->USERConfig); + } + + /* DATA configuration*/ + if((pOBInit->OptionType & OPTIONBYTE_DATA) == OPTIONBYTE_DATA) + { + status = FLASH_OB_ProgramData(pOBInit->DATAAddress, pOBInit->DATAData); + } + + return status; +} + +/** + * @brief Get the Option byte configuration + * @param pOBInit: pointer to an FLASH_OBInitStruct structure that + * contains the configuration information for the programming. + * + * @retval None + */ +void HAL_FLASHEx_OBGetConfig(FLASH_OBProgramInitTypeDef *pOBInit) +{ + pOBInit->OptionType = OPTIONBYTE_WRP | OPTIONBYTE_RDP | OPTIONBYTE_USER; + + /*Get WRP*/ + pOBInit->WRPPage = FLASH_OB_GetWRP(); + + /*Get RDP Level*/ + pOBInit->RDPLevel = FLASH_OB_GetRDP(); + + /*Get USER*/ + pOBInit->USERConfig = FLASH_OB_GetUser(); +} + +/** + * @} + */ + +/** + * @brief Mass erase of FLASH memory + * @param None + * + * @retval None + */ +static void FLASH_MassErase(void) +{ + /* Clear pending flags (if any) */ + __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP | FLASH_FLAG_WRPERR | FLASH_FLAG_PGERR); + + /* Proceed to erase all sectors */ + SET_BIT(FLASH->CR, FLASH_CR_MER); + SET_BIT(FLASH->CR, FLASH_CR_STRT); +} + +/** + * @brief Enable the write protection of the desired pages + * @note When the memory read protection level is selected (RDP level = 1), + * it is not possible to program or erase the flash page i if CortexM4 + * debug features are connected or boot code is executed in RAM, even if nWRPi = 1 + * + * @param WriteProtectPage: specifies the page(s) to be write protected. + * The value of this parameter depend on device used within the same series + * @retval HAL status + */ +static HAL_StatusTypeDef FLASH_OB_EnableWRP(uint32_t WriteProtectPage) +{ + HAL_StatusTypeDef status = HAL_OK; +#if defined(STM32F030x6) || defined(STM32F030x8) || defined(STM32F031x6) || defined(STM32F038xx) || \ + defined(STM32F051x8) || defined(STM32F042x6) || defined(STM32F048xx) || defined(STM32F058xx) + uint16_t WRP0_Data = 0xFFFF; +#if defined(STM32F030x8) || defined(STM32F051x8) || defined(STM32F058xx) + uint16_t WRP1_Data = 0xFFFF; +#endif /* STM32F030x8 || STM32F051x8 || STM32F058xx */ +#endif /* STM32F030x6 || STM32F030x8 || STM32F031x6 || STM32F038xx || STM32F051x8 || STM32F042x6 || STM32F048xx || STM32F058xx */ + +#if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) + uint16_t WRP0_Data = 0xFFFF, WRP1_Data = 0xFFFF, WRP2_Data = 0xFFFF, WRP3_Data = 0xFFFF; +#endif /* STM32F071xB || STM32F072xB || STM32F078xx */ + + /* Check the parameters */ + assert_param(IS_OB_WRP(WriteProtectPage)); + + WriteProtectPage = (uint32_t)(~WriteProtectPage); +#if defined(STM32F030x6) || defined(STM32F030x8) || defined(STM32F031x6) || defined(STM32F038xx) || \ + defined(STM32F051x8) || defined(STM32F042x6) || defined(STM32F048xx) || defined(STM32F058xx) + WRP0_Data = (uint16_t)(WriteProtectPage & OB_WRP_PAGES0TO31MASK); +#if defined(STM32F030x8) || defined(STM32F051x8) || defined(STM32F058xx) + WRP1_Data = (uint16_t)((WriteProtectPage & OB_WRP_PAGES32TO63MASK) >> 8); +#endif /* STM32F030x8 || STM32F051x8 || STM32F058xx */ +#endif /* STM32F030x6 || STM32F030x8 || STM32F031x6 || STM32F038xx || STM32F051x8 || STM32F042x6 || STM32F048xx || STM32F058xx */ + +#if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) + WRP0_Data = (uint16_t)(WriteProtectPage & OB_WRP_PAGES0TO15MASK); + WRP1_Data = (uint16_t)((WriteProtectPage & OB_WRP_PAGES16TO31MASK) >> 8); + WRP2_Data = (uint16_t)((WriteProtectPage & OB_WRP_PAGES32TO47MASK) >> 16); + WRP3_Data = (uint16_t)((WriteProtectPage & OB_WRP_PAGES48TO63MASK) >> 24); +#endif /* STM32F071xB || STM32F072xB || STM32F078xx */ + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE); + + /* Clear pending flags (if any) */ + __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP | FLASH_FLAG_WRPERR | FLASH_FLAG_PGERR); + + if(status == HAL_OK) + { + SET_BIT(FLASH->CR, FLASH_CR_OPTPG); + + if(WRP0_Data != 0xFF) + { + OB->WRP0 &= WRP0_Data; + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE); + } + +#if defined(STM32F030x8) || defined(STM32F051x8) || defined(STM32F058xx) || \ + defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) + if((status == HAL_OK) && (WRP1_Data != 0xFF)) + { + OB->WRP1 &= WRP1_Data; + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE); + } +#endif /* STM32F030x8 || STM32F051x8 || STM32F058xx || STM32F071xB || + STM32F072xB || STM32F078xx */ + +#if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) + if((status == HAL_OK) && (WRP2_Data != 0xFF)) + { + OB->WRP2 &= WRP2_Data; + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE); + } + + if((status == HAL_OK) && (WRP3_Data != 0xFF)) + { + OB->WRP3 &= WRP3_Data; + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE); + } +#endif /* STM32F071xB || STM32F072xB || STM32F078xx */ + + /* if the program operation is completed, disable the OPTPG Bit */ + CLEAR_BIT(FLASH->CR, FLASH_CR_OPTPG); + } + + return status; + +} + +/** + * @brief Disable the write protection of the desired pages + * @note When the memory read protection level is selected (RDP level = 1), + * it is not possible to program or erase the flash page i if CortexM4 + * debug features are connected or boot code is executed in RAM, even if nWRPi = 1 + * + * @param WriteProtectPage: specifies the page(s) to be write unprotected. + * The value of this parameter depend on device used within the same series + * @retval HAL status + */ +static HAL_StatusTypeDef FLASH_OB_DisableWRP(uint32_t WriteProtectPage) +{ + HAL_StatusTypeDef status = HAL_OK; +#if defined(STM32F030x6) || defined(STM32F030x8) || defined(STM32F031x6) || defined(STM32F038xx) || \ + defined(STM32F051x8) || defined(STM32F042x6) || defined(STM32F048xx) || defined(STM32F058xx) + uint16_t WRP0_Data = 0xFFFF; +#if defined(STM32F030x8) || defined(STM32F051x8) || defined(STM32F058xx) + uint16_t WRP1_Data = 0xFFFF; +#endif /* STM32F030x8 || STM32F051x8 || STM32F058xx */ +#endif /* STM32F030x6 || STM32F030x8 || STM32F031x6 || STM32F038xx || STM32F051x8 || STM32F042x6 || STM32F048xx || STM32F058xx */ + +#if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) + uint16_t WRP0_Data = 0xFFFF, WRP1_Data = 0xFFFF, WRP2_Data = 0xFFFF, WRP3_Data = 0xFFFF; +#endif /* STM32F071xB || STM32F072xB || STM32F078xx */ + + /* Check the parameters */ + assert_param(IS_OB_WRP(WriteProtectPage)); + +#if defined(STM32F030x6) || defined(STM32F030x8) || defined(STM32F031x6) || defined(STM32F038xx) || \ + defined(STM32F051x8) || defined(STM32F042x6) || defined(STM32F048xx) || defined(STM32F058xx) + WRP0_Data = (uint16_t)(WriteProtectPage & OB_WRP_PAGES0TO31MASK); +#if defined(STM32F030x8) || defined(STM32F051x8) || defined(STM32F058xx) + WRP1_Data = (uint16_t)((WriteProtectPage & OB_WRP_PAGES32TO63MASK) >> 8); +#endif /* STM32F030x8 || STM32F051x8 || STM32F058xx */ +#endif /* STM32F030x6 || STM32F030x8 || STM32F031x6 || STM32F038xx || STM32F051x8 || STM32F042x6 || STM32F048xx || STM32F058xx */ + +#if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) + WRP0_Data = (uint16_t)(WriteProtectPage & OB_WRP_PAGES0TO15MASK); + WRP1_Data = (uint16_t)((WriteProtectPage & OB_WRP_PAGES16TO31MASK) >> 8); + WRP2_Data = (uint16_t)((WriteProtectPage & OB_WRP_PAGES32TO47MASK) >> 16); + WRP3_Data = (uint16_t)((WriteProtectPage & OB_WRP_PAGES48TO63MASK) >> 24); +#endif /* STM32F071xB || STM32F072xB || STM32F078xx */ + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE); + + /* Clear pending flags (if any) */ + __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP | FLASH_FLAG_WRPERR | FLASH_FLAG_PGERR); + + if(status == HAL_OK) + { + SET_BIT(FLASH->CR, FLASH_CR_OPTPG); + + if(WRP0_Data != 0xFF) + { + OB->WRP0 |= WRP0_Data; + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE); + } + +#if defined(STM32F030x8) || defined(STM32F051x8) || defined(STM32F058xx) || \ + defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) + if((status == HAL_OK) && (WRP1_Data != 0xFF)) + { + OB->WRP1 |= WRP1_Data; + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE); + } +#endif /* STM32F030x8 || STM32F051x8 || STM32F058xx || STM32F071xB || + STM32F072xB || STM32F078xx */ + +#if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) + if((status == HAL_OK) && (WRP2_Data != 0xFF)) + { + OB->WRP2 |= WRP2_Data; + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE); + } + + if((status == HAL_OK) && (WRP3_Data != 0xFF)) + { + OB->WRP3 |= WRP3_Data; + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE); + } +#endif /* STM32F071xB || STM32F072xB || STM32F078xx */ + + /* if the program operation is completed, disable the OPTPG Bit */ + CLEAR_BIT(FLASH->CR, FLASH_CR_OPTPG); + } + + return status; +} + +/** + * @brief Set the read protection level. + * @param ReadProtectLevel: specifies the read protection level. + * This parameter can be one of the following values: + * @arg OB_RDP_LEVEL_0: No protection + * @arg OB_RDP_LEVEL_1: Read protection of the memory + * @arg OB_RDP_LEVEL_2: Full chip protection + * + * @note Warning: When enabling OB_RDP level 2 it's no more possible to go back to level 1 or 0 + * + * @retval HAL status + */ +static HAL_StatusTypeDef FLASH_OB_RDP_LevelConfig(uint8_t ReadProtectLevel) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check the parameters */ + assert_param(IS_OB_RDP_LEVEL(ReadProtectLevel)); + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE); + + /* Clear pending flags (if any) */ + __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP | FLASH_FLAG_WRPERR | FLASH_FLAG_PGERR); + + if(status == HAL_OK) + { + /* Enable the Option Bytes Programming operation */ + SET_BIT(FLASH->CR, FLASH_CR_OPTPG); + + WRITE_REG(OB->RDP, ReadProtectLevel); + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE); + + /* if the program operation is completed, disable the OPTPG Bit */ + CLEAR_BIT(FLASH->CR, FLASH_CR_OPTPG); + } + + return status; +} + +/** + * @brief Program the FLASH User Option Byte. + * @note Programming of the OB should be performed only after an erase (otherwise PGERR occurs) + * @param UserConfig: The FLASH User Option Bytes values: IWDG_SW(Bit0), RST_STOP(Bit1), RST_STDBY(Bit2), BOOT1(Bit4), + * VDDA_Analog_Monitoring(Bit5) and SRAM_Parity_Enable(Bit6). + * @retval HAL status + */ +static HAL_StatusTypeDef FLASH_OB_UserConfig(uint8_t UserConfig) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check the parameters */ + assert_param(IS_OB_WDG_SOURCE((UserConfig&OB_WDG_SW))); + assert_param(IS_OB_STOP_SOURCE((UserConfig&OB_STOP_NO_RST))); + assert_param(IS_OB_STDBY_SOURCE((UserConfig&OB_STDBY_NO_RST))); + assert_param(IS_OB_BOOT1((UserConfig&OB_BOOT1_SET))); + assert_param(IS_OB_VDDA_ANALOG((UserConfig&OB_VDDA_ANALOG_ON))); + assert_param(IS_OB_SRAM_PARITY((UserConfig&OB_RAM_PARITY_CHECK_RESET))); +#if defined(STM32F042x6) || defined(STM32F048xx) + assert_param(IS_OB_BOOT_SEL((UserConfig&OB_BOOT_SEL_SET))); + assert_param(IS_OB_BOOT0((UserConfig&OB_BOOT0_SET))); +#endif /* STM32F042x6 || STM32F048xx */ + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE); + + /* Clear pending flags (if any) */ + __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP | FLASH_FLAG_WRPERR | FLASH_FLAG_PGERR); + + if(status == HAL_OK) + { + /* Enable the Option Bytes Programming operation */ + SET_BIT(FLASH->CR, FLASH_CR_OPTPG); + +#if defined(STM32F042x6) || defined(STM32F048xx) + OB->USER = UserConfig; +#else + OB->USER = (UserConfig | 0x88); +#endif /* STM32F042x6 || STM32F048xx */ + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE); + + /* if the program operation is completed, disable the OPTPG Bit */ + CLEAR_BIT(FLASH->CR, FLASH_CR_OPTPG); + } + + return status; +} + +/** + * @brief Programs a half word at a specified Option Byte Data address. + * @note The function HAL_FLASH_Unlock() should be called before to unlock the FLASH interface + * The function HAL_FLASH_OB_Unlock() should be called before to unlock the options bytes + * The function HAL_FLASH_OB_Launch() should be called after to force the reload of the options bytes + * (system reset will occur) + * Programming of the OB should be performed only after an erase (otherwise PGERR occurs) + * @param Address: specifies the address to be programmed. + * This parameter can be 0x1FFFF804 or 0x1FFFF806. + * @param Data: specifies the data to be programmed. + * @retval HAL status + */ +static HAL_StatusTypeDef FLASH_OB_ProgramData(uint32_t Address, uint8_t Data) +{ + HAL_StatusTypeDef status = HAL_ERROR; + + /* Check the parameters */ + assert_param(IS_OB_DATA_ADDRESS(Address)); + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE); + + /* Clear pending flags (if any) */ + __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP | FLASH_FLAG_WRPERR | FLASH_FLAG_PGERR); + + if(status == HAL_OK) + { + /* Enables the Option Bytes Programming operation */ + SET_BIT(FLASH->CR, FLASH_CR_OPTPG); + *(__IO uint16_t*)Address = Data; + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE); + + /* If the program operation is completed, disable the OPTPG Bit */ + CLEAR_BIT(FLASH->CR, FLASH_CR_OPTPG); + } + /* Return the Option Byte Data Program Status */ + return status; +} + +/** + * @brief Return the FLASH Write Protection Option Bytes value. + * @param None + * @retval The FLASH Write Protection Option Bytes value + */ +static uint32_t FLASH_OB_GetWRP(void) +{ + /* Return the FLASH write protection Register value */ + return (uint32_t)(READ_REG(FLASH->WRPR)); +} + +/** + * @brief Returns the FLASH Read Protection level. + * @param None + * @retval FLASH ReadOut Protection Status: + * - SET, when OB_RDP_Level_1 or OB_RDP_Level_2 is set + * - RESET, when OB_RDP_Level_0 is set + */ +static FlagStatus FLASH_OB_GetRDP(void) +{ + FlagStatus readstatus = RESET; + + if ((uint8_t)READ_BIT(FLASH->OBR, FLASH_OBR_RDPRT1) != RESET) + { + readstatus = SET; + } + + return readstatus; +} + +/** + * @brief Return the FLASH User Option Byte value. + * @param None + * @retval The FLASH User Option Bytes values: IWDG_SW(Bit0), RST_STOP(Bit1), RST_STDBY(Bit2), BOOT1(Bit4), + * VDDA_Analog_Monitoring(Bit5) and SRAM_Parity_Enable(Bit6). + */ +static uint8_t FLASH_OB_GetUser(void) +{ + /* Return the User Option Byte */ + return (uint8_t)(READ_REG(FLASH->OBR) >> 8); +} + +/** + * @} + */ + +#endif /* HAL_FLASH_MODULE_ENABLED */ + +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_flash_ex.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_flash_ex.h new file mode 100644 index 0000000000..af36020738 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_flash_ex.h @@ -0,0 +1,262 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_flash_ex.h + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief Header file of FLASH HAL Extension module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32F0xx_HAL_FLASH_EX_H +#define __STM32F0xx_HAL_FLASH_EX_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal_def.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @addtogroup FLASHEx + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/** @defgroup FLASHEx_Exported_Types + * @{ + */ +/** + * @} + */ + +/* Exported constants --------------------------------------------------------*/ +/** @defgroup FLASHEx_Exported_Constants + * @{ + */ +/** @defgroup FLASHEx_Address + * @{ + */ +#if defined(STM32F030x6) || defined(STM32F031x6) || defined(STM32F042x6) || defined(STM32F048xx) || defined(STM32F038xx) +#define IS_FLASH_PROGRAM_ADDRESS(ADDRESS) (((ADDRESS) >= 0x08000000) && ((ADDRESS) <= 0x08007FFF)) +#endif /* STM32F030x6 || STM32F031x6 || STM32F042x6 || STM32F048xx || STM32F038xx */ + +#if defined(STM32F030x8) || defined(STM32F051x8) || defined(STM32F058xx) +#define IS_FLASH_PROGRAM_ADDRESS(ADDRESS) (((ADDRESS) >= 0x08000000) && ((ADDRESS) <= 0x0800FFFF)) +#endif /* STM32F030x8 || STM32F051x8 || STM32F058xx */ + +#if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) +#define IS_FLASH_PROGRAM_ADDRESS(ADDRESS) (((ADDRESS) >= 0x08000000) && ((ADDRESS) <= 0x0801FFFF)) +#endif /* STM32F071xB || STM32F072xB || STM32F078xx */ +/** + * @} + */ + +/** @defgroup FLASHEx_Page_Size + * @{ + */ +#if defined(STM32F030x6) || defined(STM32F030x8) || defined(STM32F031x6) || defined(STM32F038xx) || \ + defined(STM32F051x8) || defined(STM32F042x6) || defined(STM32F048xx) || defined(STM32F058xx) +#define FLASH_PAGE_SIZE 0x400 +#endif /* STM32F030x6 || STM32F030x8 || STM32F031x6 || STM32F051x8 || STM32F042x6 || STM32F048xx || STM32F058xx */ + +#if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) +#define FLASH_PAGE_SIZE 0x800 +#endif /* STM32F071xB || STM32F072xB || STM32F078xx */ + +/** + * @} + */ + +/** @defgroup FLASHEx_Nb_Pages + * @{ + */ +#if defined(STM32F030x6) || defined(STM32F031x6) || defined(STM32F042x6) || defined(STM32F048xx) || defined(STM32F038xx) +#define IS_FLASH_NB_PAGES(ADDRESS,NBPAGES) ((ADDRESS)+((NBPAGES)*FLASH_PAGE_SIZE)-1 <= 0x08007FFF) +#endif /* STM32F030x6 || STM32F031x6 || STM32F042x6 || STM32F048xx || STM32F038xx */ + +#if defined(STM32F030x8) || defined(STM32F051x8) || defined(STM32F058xx) +#define IS_FLASH_NB_PAGES(ADDRESS,NBPAGES) ((ADDRESS)+((NBPAGES)*FLASH_PAGE_SIZE)-1 <= 0x0800FFFF) +#endif /* STM32F030x8 || STM32F051x8 || STM32F058xx */ + +#if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) +#define IS_FLASH_NB_PAGES(ADDRESS,NBPAGES) ((ADDRESS)+((NBPAGES)*FLASH_PAGE_SIZE)-1 <= 0x0801FFFF) +#endif /* STM32F071xB || STM32F072xB || STM32F078xx */ +/** + * @} + */ + +/** @defgroup FLASHEx_OB_Write_Protection + * @{ + */ +#if defined(STM32F030x6) || defined(STM32F030x8) || defined(STM32F031x6) || defined(STM32F038xx) || \ + defined(STM32F051x8) || defined(STM32F042x6) || defined(STM32F048xx) || defined(STM32F058xx) +#define OB_WRP_PAGES0TO3 ((uint32_t)0x00000001) /* Write protection of page 0 to 3 */ +#define OB_WRP_PAGES4TO7 ((uint32_t)0x00000002) /* Write protection of page 4 to 7 */ +#define OB_WRP_PAGES8TO11 ((uint32_t)0x00000004) /* Write protection of page 8 to 11 */ +#define OB_WRP_PAGES12TO15 ((uint32_t)0x00000008) /* Write protection of page 12 to 15 */ +#define OB_WRP_PAGES16TO19 ((uint32_t)0x00000010) /* Write protection of page 16 to 19 */ +#define OB_WRP_PAGES20TO23 ((uint32_t)0x00000020) /* Write protection of page 20 to 23 */ +#define OB_WRP_PAGES24TO27 ((uint32_t)0x00000040) /* Write protection of page 24 to 27 */ +#define OB_WRP_PAGES28TO31 ((uint32_t)0x00000080) /* Write protection of page 28 to 31 */ +#if defined(STM32F030x8) || defined(STM32F051x8) || defined(STM32F058xx) +#define OB_WRP_PAGES32TO35 ((uint32_t)0x00000100) /* Write protection of page 32 to 35 */ +#define OB_WRP_PAGES36TO39 ((uint32_t)0x00000200) /* Write protection of page 36 to 39 */ +#define OB_WRP_PAGES40TO43 ((uint32_t)0x00000400) /* Write protection of page 40 to 43 */ +#define OB_WRP_PAGES44TO47 ((uint32_t)0x00000800) /* Write protection of page 44 to 47 */ +#define OB_WRP_PAGES48TO51 ((uint32_t)0x00001000) /* Write protection of page 48 to 51 */ +#define OB_WRP_PAGES52TO57 ((uint32_t)0x00002000) /* Write protection of page 52 to 57 */ +#define OB_WRP_PAGES56TO59 ((uint32_t)0x00004000) /* Write protection of page 56 to 59 */ +#define OB_WRP_PAGES60TO63 ((uint32_t)0x00008000) /* Write protection of page 60 to 63 */ +#endif /* STM32F030x8 || STM32F051x8 || STM32F058xx */ + +#define OB_WRP_PAGES0TO31MASK ((uint32_t)0x000000FF) +#if defined(STM32F030x8) || defined(STM32F051x8) || defined(STM32F058xx) +#define OB_WRP_PAGES32TO63MASK ((uint32_t)0x0000FF00) +#endif /* STM32F030x8 || STM32F051x8 || STM32F058xx */ + +#if defined(STM32F030x6) || defined(STM32F031x6) || defined(STM32F042x6) || defined(STM32F048xx) || defined(STM32F038xx) +#define OB_WRP_ALLPAGES ((uint32_t)0x000000FF) /*!< Write protection of all pages */ +#endif /* STM32F030x6 || STM32F031x6 || STM32F042x6 || STM32F048xx || STM32F038xx */ + +#if defined(STM32F030x8) || defined(STM32F051x8) || defined(STM32F058xx) +#define OB_WRP_ALLPAGES ((uint32_t)0x0000FFFF) /*!< Write protection of all pages */ +#endif /* STM32F030x8 || STM32F051x8 || STM32F058xx */ +#endif /* STM32F030x6 || STM32F030x8 || STM32F031x6 || STM32F051x8 || STM32F042x6 || STM32F048xx || STM32F038xx || STM32F058xx */ + +#if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) +#define OB_WRP_PAGES0TO1 ((uint32_t)0x00000001) /* Write protection of page 0 to 1 */ +#define OB_WRP_PAGES2TO3 ((uint32_t)0x00000002) /* Write protection of page 2 to 3 */ +#define OB_WRP_PAGES4TO5 ((uint32_t)0x00000004) /* Write protection of page 4 to 5 */ +#define OB_WRP_PAGES6TO7 ((uint32_t)0x00000008) /* Write protection of page 6 to 7 */ +#define OB_WRP_PAGES8TO9 ((uint32_t)0x00000010) /* Write protection of page 8 to 9 */ +#define OB_WRP_PAGES10TO11 ((uint32_t)0x00000020) /* Write protection of page 10 to 11 */ +#define OB_WRP_PAGES12TO13 ((uint32_t)0x00000040) /* Write protection of page 12 to 13 */ +#define OB_WRP_PAGES14TO15 ((uint32_t)0x00000080) /* Write protection of page 14 to 15 */ +#define OB_WRP_PAGES16TO17 ((uint32_t)0x00000100) /* Write protection of page 16 to 17 */ +#define OB_WRP_PAGES18TO19 ((uint32_t)0x00000200) /* Write protection of page 18 to 19 */ +#define OB_WRP_PAGES20TO21 ((uint32_t)0x00000400) /* Write protection of page 20 to 21 */ +#define OB_WRP_PAGES22TO23 ((uint32_t)0x00000800) /* Write protection of page 22 to 23 */ +#define OB_WRP_PAGES24TO25 ((uint32_t)0x00001000) /* Write protection of page 24 to 25 */ +#define OB_WRP_PAGES26TO27 ((uint32_t)0x00002000) /* Write protection of page 26 to 27 */ +#define OB_WRP_PAGES28TO29 ((uint32_t)0x00004000) /* Write protection of page 28 to 29 */ +#define OB_WRP_PAGES30TO31 ((uint32_t)0x00008000) /* Write protection of page 30 to 31 */ +#define OB_WRP_PAGES32TO33 ((uint32_t)0x00010000) /* Write protection of page 32 to 33 */ +#define OB_WRP_PAGES34TO35 ((uint32_t)0x00020000) /* Write protection of page 34 to 35 */ +#define OB_WRP_PAGES36TO37 ((uint32_t)0x00040000) /* Write protection of page 36 to 37 */ +#define OB_WRP_PAGES38TO39 ((uint32_t)0x00080000) /* Write protection of page 38 to 39 */ +#define OB_WRP_PAGES40TO41 ((uint32_t)0x00100000) /* Write protection of page 40 to 41 */ +#define OB_WRP_PAGES42TO43 ((uint32_t)0x00200000) /* Write protection of page 42 to 43 */ +#define OB_WRP_PAGES44TO45 ((uint32_t)0x00400000) /* Write protection of page 44 to 45 */ +#define OB_WRP_PAGES46TO47 ((uint32_t)0x00800000) /* Write protection of page 46 to 47 */ +#define OB_WRP_PAGES48TO49 ((uint32_t)0x01000000) /* Write protection of page 48 to 49 */ +#define OB_WRP_PAGES50TO51 ((uint32_t)0x02000000) /* Write protection of page 50 to 51 */ +#define OB_WRP_PAGES52TO53 ((uint32_t)0x04000000) /* Write protection of page 52 to 53 */ +#define OB_WRP_PAGES54TO55 ((uint32_t)0x08000000) /* Write protection of page 54 to 55 */ +#define OB_WRP_PAGES56TO57 ((uint32_t)0x10000000) /* Write protection of page 56 to 57 */ +#define OB_WRP_PAGES58TO59 ((uint32_t)0x20000000) /* Write protection of page 58 to 59 */ +#define OB_WRP_PAGES60TO61 ((uint32_t)0x40000000) /* Write protection of page 60 to 61 */ +#if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) +#define OB_WRP_PAGES62TO63 ((uint32_t)0x80000000) /* Write protection of page 62 to 63 */ +#endif /* STM32F071xB || STM32F072xB || STM32F078xx */ + +#define OB_WRP_PAGES0TO15MASK ((uint32_t)0x000000FF) +#define OB_WRP_PAGES16TO31MASK ((uint32_t)0x0000FF00) +#define OB_WRP_PAGES32TO47MASK ((uint32_t)0x00FF0000) +#if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) +#define OB_WRP_PAGES48TO63MASK ((uint32_t)0xFF000000) +#endif /* STM32F071xB || STM32F072xB || STM32F078xx */ + +#define OB_WRP_ALLPAGES ((uint32_t)0xFFFFFFFF) /*!< Write protection of all pages */ +#endif /* STM32F071xB || STM32F072xB || STM32F078xx */ + +#define IS_OB_WRP(PAGE) (((PAGE) != 0x0000000)) +/** + * @} + */ + +#if defined(STM32F042x6) || defined(STM32F048xx) +/** @defgroup FLASHEx_OB_BOOT_SEL + * @{ + */ +#define OB_BOOT_SEL_RESET ((uint8_t)0x00) /*!< BOOT_SEL Reset */ +#define OB_BOOT_SEL_SET ((uint8_t)0x80) /*!< BOOT_SEL Set */ +#define IS_OB_BOOT_SEL(BOOT_SEL) (((BOOT_SEL) == OB_BOOT_SEL_RESET) || ((BOOT_SEL) == OB_BOOT_SEL_SET)) +/** + * @} + */ + +/** @defgroup FLASHEx_OB_BOOT0 + * @{ + */ +#define OB_BOOT0_RESET ((uint8_t)0x00) /*!< BOOT0 Reset */ +#define OB_BOOT0_SET ((uint8_t)0x08) /*!< BOOT0 Set */ +#define IS_OB_BOOT0(BOOT0) (((BOOT0) == OB_BOOT0_RESET) || ((BOOT0) == OB_BOOT0_SET)) +/** + * @} + */ +#endif /* STM32F042x6 || STM32F048xx */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ + +/* Exported functions --------------------------------------------------------*/ + +/* IO operation functions *****************************************************/ +HAL_StatusTypeDef HAL_FLASHEx_Erase(FLASH_EraseInitTypeDef *pEraseInit, uint32_t *PageError); +HAL_StatusTypeDef HAL_FLASHEx_Erase_IT(FLASH_EraseInitTypeDef *pEraseInit); + +/* Peripheral Control functions ***********************************************/ +HAL_StatusTypeDef HAL_FLASHEx_OBErase(void); +HAL_StatusTypeDef HAL_FLASHEx_OBProgram(FLASH_OBProgramInitTypeDef *pOBInit); +void HAL_FLASHEx_OBGetConfig(FLASH_OBProgramInitTypeDef *pOBInit); + +/** + * @} + */ + +/** + * @} + */ +#ifdef __cplusplus +} +#endif + +#endif /* __STM32F0xx_HAL_FLASH_EX_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_gpio.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_gpio.c new file mode 100644 index 0000000000..25249b9857 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_gpio.c @@ -0,0 +1,570 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_gpio.c + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief GPIO HAL module driver. + * + * This file provides firmware functions to manage the following + * functionalities of the General Purpose Input/Output (GPIO) peripheral: + * + Initialization/de-initialization function + * + IO operation function + * + @verbatim + ============================================================================== + ##### GPIO specific features ##### + ============================================================================== + [..] + Each port bit of the general-purpose I/O (GPIO) ports can be individually + configured by software in several modes: + (+) Input mode + (+) Analog mode + (+) Output mode + (+) Alternate function mode + (+) External interrupt/event lines + + [..] + During and just after reset, the alternate functions and external interrupt + lines are not active and the I/O ports are configured in input floating mode. + + [..] + All GPIO pins have weak internal pull-up and pull-down resistors, which can be + activated or not. + + [..] + In Output or Alternate mode, each IO can be configured on open-drain or push-pull + type and the IO speed can be selected depending on the VDD value. + + [..] + The microcontroller IO pins are connected to onboard peripherals/modules through a + multiplexer that allows only one peripheral’s alternate function (AF) connected + to an IO pin at a time. In this way, there can be no conflict between peripherals + sharing the same IO pin. + + [..] + All ports have external interrupt/event capability. To use external interrupt + lines, the port must be configured in input mode. All available GPIO pins are + connected to the 16 external interrupt/event lines from EXTI0 to EXTI15. + + [..] + The external interrupt/event controller consists of up to 23 edge detectors + (16 lines are connected to GPIO) for generating event/interrupt requests (each + input line can be independently configured to select the type (interrupt or event) + and the corresponding trigger event (rising or falling or both). Each line can + also be masked independently. + + ##### How to use this driver ##### + ============================================================================== + [..] + (#) Enable the GPIO AHB clock using the following function : __GPIOx_CLK_ENABLE(). + + (#) In case of external interrupt/event mode selection, enable the SYSCFG clock + using the following function __SYSCFG_CLK_ENABLE(). + + (#) Configure the GPIO pin(s) using HAL_GPIO_Init(). + (++) Configure the IO mode using "Mode" member from GPIO_InitTypeDef structure + (++) Activate Pull-up, Pull-down resistor using "Pull" member from GPIO_InitTypeDef + structure. + (++) In case of Output or alternate function mode selection: the speed is + configured through "Speed" member from GPIO_InitTypeDef structure, + the speed is configurable: 2 MHz, 10 MHz and 50 MHz. + (++) If alternate mode is selected, the alternate function connected to the IO + is configured through "Alternate" member from GPIO_InitTypeDef structure + (++) Analog mode is required when a pin is to be used as ADC channel + or DAC output. + (++) In case of external interrupt/event selection the "Mode" member from + GPIO_InitTypeDef structure select the type (interrupt or event) and + the corresponding trigger event (rising or falling or both). + + (#) In case of external interrupt/event mode selection, configure NVIC IRQ priority + mapped to the EXTI line using HAL_NVIC_SetPriority() and enable it using + HAL_NVIC_EnableIRQ(). + + (#) To get the level of a pin configured in input mode use HAL_GPIO_ReadPin(). + + (#) To set/reset the level of a pin configured in output mode use + HAL_GPIO_WritePin()/HAL_GPIO_TogglePin(). + + (#) To lock pin configuration until next reset use HAL_GPIO_LockPin(). + + (#) During and just after reset, the alternate functions are not + active and the GPIO pins are configured in input floating mode (except JTAG + pins). + + (#) The LSE oscillator pins OSC32_IN and OSC32_OUT can be used as general purpose + (PC14 and PC15, respectively) when the LSE oscillator is off. The LSE has + priority over the GPIO function. + + (#) The HSE oscillator pins OSC_IN/OSC_OUT can be used as + general purpose PD0 and PD1, respectively, when the HSE oscillator is off. + The HSE has priority over the GPIO function. + + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @defgroup GPIO GPIO + * @brief GPIO HAL module driver + * @{ + */ + +#ifdef HAL_GPIO_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +#define __HAL_GET_GPIO_SOURCE(__GPIOx__) \ +(((uint32_t)(__GPIOx__) == ((uint32_t)GPIOA_BASE))? 0 :\ + ((uint32_t)(__GPIOx__) == ((uint32_t)(GPIOA_BASE + 0x0400)))? 1 :\ + ((uint32_t)(__GPIOx__) == ((uint32_t)(GPIOA_BASE + 0x0800)))? 2 :\ + ((uint32_t)(__GPIOx__) == ((uint32_t)(GPIOA_BASE + 0x0C00)))? 3 :\ + ((uint32_t)(__GPIOx__) == ((uint32_t)(GPIOA_BASE + 0x1000)))? 4 :\ + ((uint32_t)(__GPIOx__) == ((uint32_t)(GPIOA_BASE + 0x1400)))? 5 : 6) + +#define GPIO_MODE ((uint32_t)0x00000003) +#define EXTI_MODE ((uint32_t)0x10000000) +#define GPIO_MODE_IT ((uint32_t)0x00010000) +#define GPIO_MODE_EVT ((uint32_t)0x00020000) +#define RISING_EDGE ((uint32_t)0x00100000) +#define FALLING_EDGE ((uint32_t)0x00200000) +#define GPIO_OUTPUT_TYPE ((uint32_t)0x00000010) + +#define GPIO_NUMBER ((uint32_t)16) +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup GPIO_Private_Functions + * @{ + */ + +/** @defgroup HAL_GPIO_Group1 Initialization/de-initialization functions + * @brief Initialization and Configuration functions + * +@verbatim + =============================================================================== + ##### Initialization and de-initialization functions ##### + =============================================================================== + +@endverbatim + * @{ + */ + +/** + * @brief Initializes the GPIOx peripheral according to the specified parameters in the GPIO_Init. + * @param GPIOx: where x can be (A..F) to select the GPIO peripheral for STM32F0 family + * @param GPIO_Init: pointer to a GPIO_InitTypeDef structure that contains + * the configuration information for the specified GPIO peripheral. + * @note GPIOE is available only for STM32F072. + * @note GPIOD is not available for STM32F031. + * @retval None + */ +void HAL_GPIO_Init(GPIO_TypeDef *GPIOx, GPIO_InitTypeDef *GPIO_Init) +{ + uint32_t position; + uint32_t ioposition = 0x00; + uint32_t iocurrent = 0x00; + uint32_t temp = 0x00; + + /* Check the parameters */ + assert_param(IS_GPIO_ALL_INSTANCE(GPIOx)); + assert_param(IS_GPIO_PIN(GPIO_Init->Pin)); + assert_param(IS_GPIO_MODE(GPIO_Init->Mode)); + assert_param(IS_GPIO_PULL(GPIO_Init->Pull)); + + /* Configure the port pins */ + for (position = 0; position < GPIO_NUMBER; position++) + { + /* Get the IO position */ + ioposition = ((uint32_t)0x01) << position; + /* Get the current IO position */ + iocurrent = (uint32_t)(GPIO_Init->Pin) & ioposition; + + if (iocurrent == ioposition) + { + /*--------------------- GPIO Mode Configuration ------------------------*/ + /* In case of Alternate function mode selection */ + if((GPIO_Init->Mode == GPIO_MODE_AF_PP) || (GPIO_Init->Mode == GPIO_MODE_AF_OD)) + { + /* Check the Alternate function parameter */ + assert_param(IS_GPIO_AF(GPIO_Init->Alternate)); + /* Configure Alternate function mapped with the current IO */ + temp = GPIOx->AFR[position >> 3]; + temp &= ~((uint32_t)0xF << ((uint32_t)(position & (uint32_t)0x07) * 4)) ; + temp |= ((uint32_t)(GPIO_Init->Alternate) << (((uint32_t)position & (uint32_t)0x07) * 4)); + GPIOx->AFR[position >> 3] = temp; + } + + /* Configure IO Direction mode (Input, Output, Alternate or Analog) */ + temp = GPIOx->MODER; + temp &= ~(GPIO_MODER_MODER0 << (position * 2)); + temp |= ((GPIO_Init->Mode & GPIO_MODE) << (position * 2)); + GPIOx->MODER = temp; + + /* In case of Output or Alternate function mode selection */ + if ((GPIO_Init->Mode == GPIO_MODE_OUTPUT_PP) || (GPIO_Init->Mode == GPIO_MODE_AF_PP) || + (GPIO_Init->Mode == GPIO_MODE_OUTPUT_OD) || (GPIO_Init->Mode == GPIO_MODE_AF_OD)) + { + /* Check the Speed parameter */ + assert_param(IS_GPIO_SPEED(GPIO_Init->Speed)); + /* Configure the IO Speed */ + temp = GPIOx->OSPEEDR; + temp &= ~(GPIO_OSPEEDER_OSPEEDR0 << (position * 2)); + temp |= (GPIO_Init->Speed << (position * 2)); + GPIOx->OSPEEDR = temp; + + /* Configure the IO Output Type */ + temp = GPIOx->OTYPER; + temp &= ~(GPIO_OTYPER_OT_0 << position) ; + temp |= (((GPIO_Init->Mode & GPIO_OUTPUT_TYPE) >> 4) << position); + GPIOx->OTYPER = temp; + } + + /* Activate the Pull-up or Pull down resistor for the current IO */ + temp = GPIOx->PUPDR; + temp &= ~(GPIO_PUPDR_PUPDR0 << (position * 2)); + temp |= ((GPIO_Init->Pull) << (position * 2)); + GPIOx->PUPDR = temp; + + /*--------------------- EXTI Mode Configuration ------------------------*/ + /* Configure the External Interrupt or event for the current IO */ + if((GPIO_Init->Mode & EXTI_MODE) == EXTI_MODE) + { + /* Enable SYSCFG Clock */ + __SYSCFG_CLK_ENABLE(); + + temp = SYSCFG->EXTICR[position >> 2]; + temp &= ~(((uint32_t)0x0F) << (4 * (position & 0x03))); + temp |= ((uint32_t)(__HAL_GET_GPIO_SOURCE(GPIOx)) << (4 * (position & 0x03))); + SYSCFG->EXTICR[position >> 2] = temp; + + /* Clear EXTI line configuration */ + temp = EXTI->IMR; + temp &= ~((uint32_t)iocurrent); + if((GPIO_Init->Mode & GPIO_MODE_IT) == GPIO_MODE_IT) + { + temp |= iocurrent; + } + EXTI->IMR = temp; + + temp = EXTI->EMR; + temp &= ~((uint32_t)iocurrent); + if((GPIO_Init->Mode & GPIO_MODE_EVT) == GPIO_MODE_EVT) + { + temp |= iocurrent; + } + EXTI->EMR = temp; + + /* Clear Rising Falling edge configuration */ + temp = EXTI->RTSR; + temp &= ~((uint32_t)iocurrent); + if((GPIO_Init->Mode & RISING_EDGE) == RISING_EDGE) + { + temp |= iocurrent; + } + EXTI->RTSR = temp; + + temp = EXTI->FTSR; + temp &= ~((uint32_t)iocurrent); + if((GPIO_Init->Mode & FALLING_EDGE) == FALLING_EDGE) + { + temp |= iocurrent; + } + EXTI->FTSR = temp; + } + } + } +} + +/** + * @brief De-initializes the GPIOx peripheral registers to their default reset values. + * @param GPIOx: where x can be (A..F) to select the GPIO peripheral for STM32F0 family + * @param GPIO_Pin: specifies the port bit to be written. + * This parameter can be one of GPIO_PIN_x where x can be (0..15). + * @note GPIOE is available only for STM32F072. + * @note GPIOD is not available for STM32F031. + * For STM32F051 and STM32F030: (0..15) for GPIOA, GPIOB, GPIOC, (2) for GPIOD and (0..1, 4..7) for GPIOF. + * For STM32F072: (0..15) for GPIOA, GPIOB, GPIOC, GPIOD, GPIOE, (0..10) for GPIOF. + * For STM32F031: (0..15) for GPIOA, GPIOB, (13..15) for GPIOC and (0..1, 6..7) for GPIOF. + * @retval None + */ +void HAL_GPIO_DeInit(GPIO_TypeDef *GPIOx, uint32_t GPIO_Pin) +{ + uint32_t position; + uint32_t ioposition = 0x00; + uint32_t iocurrent = 0x00; + uint32_t tmp = 0x00; + + /* Check the parameters */ + assert_param(IS_GPIO_ALL_INSTANCE(GPIOx)); + + /* Configure the port pins */ + for (position = 0; position < GPIO_NUMBER; position++) + { + /* Get the IO position */ + ioposition = ((uint32_t)0x01) << position; + /* Get the current IO position */ + iocurrent = (GPIO_Pin) & ioposition; + + if (iocurrent == ioposition) + { + /*------------------------- GPIO Mode Configuration --------------------*/ + /* Configure IO Direction in Input Floting Mode */ + GPIOx->MODER &= ~(GPIO_MODER_MODER0 << (position * 2)); + + /* Configure the default Alternate Function in current IO */ + GPIOx->AFR[position >> 3] &= ~((uint32_t)0xF << ((uint32_t)(position & (uint32_t)0x07) * 4)) ; + + /* Configure the default value for IO Speed */ + GPIOx->OSPEEDR &= ~(GPIO_OSPEEDER_OSPEEDR0 << (position * 2)); + + /* Configure the default value IO Output Type */ + GPIOx->OTYPER &= ~(GPIO_OTYPER_OT_0 << position) ; + + /* Deactivate the Pull-up oand Pull-down resistor for the current IO */ + GPIOx->PUPDR &= ~(GPIO_PUPDR_PUPDR0 << (position * 2)); + + + /*------------------------- EXTI Mode Configuration --------------------*/ + /* Configure the External Interrupt or event for the current IO */ + tmp = ((uint32_t)0x0F) << (4 * (position & 0x03)); + SYSCFG->EXTICR[position >> 2] &= ~tmp; + + /* Clear EXTI line configuration */ + EXTI->IMR &= ~((uint32_t)iocurrent); + EXTI->EMR &= ~((uint32_t)iocurrent); + + /* Clear Rising Falling edge configuration */ + EXTI->RTSR &= ~((uint32_t)iocurrent); + EXTI->FTSR &= ~((uint32_t)iocurrent); + } + } +} + +/** + * @} + */ + +/** @defgroup HAL_GPIO_Group2 IO operation functions + * @brief GPIO Read and Write + * +@verbatim + =============================================================================== + ##### IO operation functions ##### + =============================================================================== + +@endverbatim + * @{ + */ + +/** + * @brief Reads the specified input port pin. + * @param GPIOx: where x can be (A..F) to select the GPIO peripheral for STM32F0 family + * @param GPIO_Pin: specifies the port bit to read. + * This parameter can be GPIO_PIN_x where x can be (0..15). + * @note GPIOE is available only for STM32F072. + * @note GPIOD is not available for STM32F031. + * For STM32F051 and STM32F030: (0..15) for GPIOA, GPIOB, GPIOC, (2) for GPIOD and (0..1, 4..7) for GPIOF. + * For STM32F072: (0..15) for GPIOA, GPIOB, GPIOC, GPIOD, GPIOE, (0..10) for GPIOF. + * For STM32F031: (0..15) for GPIOA, GPIOB, (13..15) for GPIOC and (0..1, 6..7) for GPIOF. + * @retval The input port pin value. + */ +GPIO_PinState HAL_GPIO_ReadPin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin) +{ + GPIO_PinState bitstatus; + + /* Check the parameters */ + assert_param(IS_GPIO_PIN(GPIO_Pin)); + + if ((GPIOx->IDR & GPIO_Pin) != (uint32_t)GPIO_PIN_RESET) + { + bitstatus = GPIO_PIN_SET; + } + else + { + bitstatus = GPIO_PIN_RESET; + } + return bitstatus; + } + +/** + * @brief Sets or clears the selected data port bit. + * + * @note This function uses GPIOx_BSRR register to allow atomic read/modify + * accesses. In this way, there is no risk of an IRQ occurring between + * the read and the modify access. + * + * @param GPIOx: where x can be (A..F) to select the GPIO peripheral for STM32F0 family + * @note GPIOE is available only for STM32F072. + * @note GPIOD is not available for STM32F031. + * For STM32F051 and STM32F030: (0..15) for GPIOA, GPIOB, GPIOC, (2) for GPIOD and (0..1, 4..7) for GPIOF. + * For STM32F072: (0..15) for GPIOA, GPIOB, GPIOC, GPIOD, GPIOE, (0..10) for GPIOF. + * For STM32F031: (0..15) for GPIOA, GPIOB, (13..15) for GPIOC and (0..1, 6..7) for GPIOF. + * @param GPIO_Pin: specifies the port bit to be written. + * This parameter can be one of GPIO_PIN_x where x can be (0..15). + * @param PinState: specifies the value to be written to the selected bit. + * This parameter can be one of the GPIO_PinState enum values: + * @arg GPIO_BIT_RESET: to clear the port pin + * @arg GPIO_BIT_SET: to set the port pin + * @retval None + */ +void HAL_GPIO_WritePin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin, GPIO_PinState PinState) +{ + /* Check the parameters */ + assert_param(IS_GPIO_PIN(GPIO_Pin)); + assert_param(IS_GPIO_PIN_ACTION(PinState)); + + if (PinState != GPIO_PIN_RESET) + { + GPIOx->BSRRL = GPIO_Pin; + } + else + { + GPIOx->BSRRH = GPIO_Pin ; + } +} + +/** + * @brief Toggles the specified GPIO pin + * @param GPIOx: where x can be (A..F) to select the GPIO peripheral for STM32F0 family + * @param GPIO_Pin: specifies the pins to be toggled. + * @note GPIOE is available only for STM32F072. + * @note GPIOD is not available for STM32F031. + * For STM32F051 and STM32F030: (0..15) for GPIOA, GPIOB, GPIOC, (2) for GPIOD and (0..1, 4..7) for GPIOF. + * For STM32F072: (0..15) for GPIOA, GPIOB, GPIOC, GPIOD, GPIOE, (0..10) for GPIOF. + * For STM32F031: (0..15) for GPIOA, GPIOB, (13..15) for GPIOC and (0..1, 6..7) for GPIOF. + * @retval None + */ +void HAL_GPIO_TogglePin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin) +{ + /* Check the parameters */ + assert_param(IS_GPIO_PIN(GPIO_Pin)); + + GPIOx->ODR ^= GPIO_Pin; +} + +/** +* @brief Locks GPIO Pins configuration registers. +* @note The locked registers are GPIOx_MODER, GPIOx_OTYPER, GPIOx_OSPEEDR, +* GPIOx_PUPDR, GPIOx_AFRL and GPIOx_AFRH. +* @note The configuration of the locked GPIO pins can no longer be modified +* until the next reset. +* @param GPIOx: where x can be (A..F) to select the GPIO peripheral for STM32F0 family +* @param GPIO_Pin: specifies the port bit to be locked. +* This parameter can be any combination of GPIO_Pin_x where x can be (0..15). + * @note GPIOE is available only for STM32F072. + * @note GPIOD is not available for STM32F031. + * For STM32F051 and STM32F030: (0..15) for GPIOA, GPIOB, GPIOC, (2) for GPIOD and (0..1, 4..7) for GPIOF. + * For STM32F072: (0..15) for GPIOA, GPIOB, GPIOC, GPIOD, GPIOE, (0..10) for GPIOF. + * For STM32F031: (0..15) for GPIOA, GPIOB, (13..15) for GPIOC and (0..1, 6..7) for GPIOF. +* @retval None +*/ +HAL_StatusTypeDef HAL_GPIO_LockPin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin) +{ + __IO uint32_t tmp = GPIO_LCKR_LCKK; + + /* Check the parameters */ + assert_param(IS_GPIO_PIN(GPIO_Pin)); + + /* Apply lock key write sequence */ + tmp |= GPIO_Pin; + /* Set LCKx bit(s): LCKK='1' + LCK[15-0] */ + GPIOx->LCKR = tmp; + /* Reset LCKx bit(s): LCKK='0' + LCK[15-0] */ + GPIOx->LCKR = GPIO_Pin; + /* Set LCKx bit(s): LCKK='1' + LCK[15-0] */ + GPIOx->LCKR = tmp; + /* Read LCKK bit*/ + tmp = GPIOx->LCKR; + + if(GPIOx->LCKR & GPIO_LCKR_LCKK) + { + return HAL_OK; + } + else + { + return HAL_ERROR; + } +} + +/** + * @brief This function handles EXTI interrupt request. + * @param GPIO_Pin: Specifies the pins connected EXTI line + * @retval None + */ +void HAL_GPIO_EXTI_IRQHandler(uint16_t GPIO_Pin) +{ + /* EXTI line interrupt detected */ + if(__HAL_GPIO_EXTI_GET_IT(GPIO_Pin) != RESET) + { + __HAL_GPIO_EXTI_CLEAR_IT(GPIO_Pin); + HAL_GPIO_EXTI_Callback(GPIO_Pin); + } +} + +/** + * @brief EXTI line detection callbacks. + * @param GPIO_Pin: Specifies the pins connected EXTI line + * @retval None + */ +__weak void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_GPIO_EXTI_Callback could be implemented in the user file + */ +} + +/** + * @} + */ + + +/** + * @} + */ + +#endif /* HAL_GPIO_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_gpio.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_gpio.h new file mode 100644 index 0000000000..f8ecf63b31 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_gpio.h @@ -0,0 +1,271 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_gpio.h + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief Header file of GPIO HAL module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32F0xx_HAL_GPIO_H +#define __STM32F0xx_HAL_GPIO_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal_def.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @addtogroup GPIO + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ + +/** + * @brief GPIO Init structure definition + */ +typedef struct +{ + uint32_t Pin; /*!< Specifies the GPIO pins to be configured. + This parameter can be any value of @ref GPIO_pins_define */ + + uint32_t Mode; /*!< Specifies the operating mode for the selected pins. + This parameter can be a value of @ref GPIO_mode_define */ + + uint32_t Pull; /*!< Specifies the Pull-up or Pull-Down activation for the selected pins. + This parameter can be a value of @ref GPIO_pull_define */ + + uint32_t Speed; /*!< Specifies the speed for the selected pins. + This parameter can be a value of @ref GPIO_speed_define */ + + uint32_t Alternate; /*!< Peripheral to be connected to the selected pins + This parameter can be a value of @ref GPIOEx_Alternate_function_selection */ +}GPIO_InitTypeDef; + +/** + * @brief GPIO Bit SET and Bit RESET enumeration + */ +typedef enum +{ + GPIO_PIN_RESET = 0, + GPIO_PIN_SET +}GPIO_PinState; +#define IS_GPIO_PIN_ACTION(ACTION) (((ACTION) == GPIO_PIN_RESET) || ((ACTION) == GPIO_PIN_SET)) + +/* Exported constants --------------------------------------------------------*/ + +/** @defgroup GPIO_Exported_Constants GPIO_Exported_Constants + * @{ + */ + +/** @defgroup GPIO_pins_define GPIO_pins_define + * @{ + */ +#define GPIO_PIN_0 ((uint16_t)0x0001) /* Pin 0 selected */ +#define GPIO_PIN_1 ((uint16_t)0x0002) /* Pin 1 selected */ +#define GPIO_PIN_2 ((uint16_t)0x0004) /* Pin 2 selected */ +#define GPIO_PIN_3 ((uint16_t)0x0008) /* Pin 3 selected */ +#define GPIO_PIN_4 ((uint16_t)0x0010) /* Pin 4 selected */ +#define GPIO_PIN_5 ((uint16_t)0x0020) /* Pin 5 selected */ +#define GPIO_PIN_6 ((uint16_t)0x0040) /* Pin 6 selected */ +#define GPIO_PIN_7 ((uint16_t)0x0080) /* Pin 7 selected */ +#define GPIO_PIN_8 ((uint16_t)0x0100) /* Pin 8 selected */ +#define GPIO_PIN_9 ((uint16_t)0x0200) /* Pin 9 selected */ +#define GPIO_PIN_10 ((uint16_t)0x0400) /* Pin 10 selected */ +#define GPIO_PIN_11 ((uint16_t)0x0800) /* Pin 11 selected */ +#define GPIO_PIN_12 ((uint16_t)0x1000) /* Pin 12 selected */ +#define GPIO_PIN_13 ((uint16_t)0x2000) /* Pin 13 selected */ +#define GPIO_PIN_14 ((uint16_t)0x4000) /* Pin 14 selected */ +#define GPIO_PIN_15 ((uint16_t)0x8000) /* Pin 15 selected */ +#define GPIO_PIN_All ((uint16_t)0xFFFF) /* All pins selected */ + +#define GPIO_PIN_MASK ((uint32_t)0x0000FFFF) /* PIN mask for assert test */ + +#define IS_GPIO_PIN(PIN) ((PIN & GPIO_PIN_MASK ) != (uint32_t)0x00) +/** + * @} + */ + +/** @defgroup GPIO_mode_define GPIO_mode_define + * @brief GPIO Configuration Mode + * Elements values convention: 0xX0yz00YZ + * - X : GPIO mode or EXTI Mode + * - y : External IT or Event trigger detection + * - z : IO configuration on External IT or Event + * - Y : Output type (Push Pull or Open Drain) + * - Z : IO Direction mode (Input, Output, Alternate or Analog) + * @{ + */ +#define GPIO_MODE_INPUT ((uint32_t)0x00000000) /*!< Input Floating Mode */ +#define GPIO_MODE_OUTPUT_PP ((uint32_t)0x00000001) /*!< Output Push Pull Mode */ +#define GPIO_MODE_OUTPUT_OD ((uint32_t)0x00000011) /*!< Output Open Drain Mode */ +#define GPIO_MODE_AF_PP ((uint32_t)0x00000002) /*!< Alternate Function Push Pull Mode */ +#define GPIO_MODE_AF_OD ((uint32_t)0x00000012) /*!< Alternate Function Open Drain Mode */ + +#define GPIO_MODE_ANALOG ((uint32_t)0x00000003) /*!< Analog Mode */ + +#define GPIO_MODE_IT_RISING ((uint32_t)0x10110000) /*!< External Interrupt Mode with Rising edge trigger detection */ +#define GPIO_MODE_IT_FALLING ((uint32_t)0x10210000) /*!< External Interrupt Mode with Falling edge trigger detection */ +#define GPIO_MODE_IT_RISING_FALLING ((uint32_t)0x10310000) /*!< External Interrupt Mode with Rising/Falling edge trigger detection */ + +#define GPIO_MODE_EVT_RISING ((uint32_t)0x10120000) /*!< External Event Mode with Rising edge trigger detection */ +#define GPIO_MODE_EVT_FALLING ((uint32_t)0x10220000) /*!< External Event Mode with Falling edge trigger detection */ +#define GPIO_MODE_EVT_RISING_FALLING ((uint32_t)0x10320000) /*!< External Event Mode with Rising/Falling edge trigger detection */ + +#define IS_GPIO_MODE(MODE) (((MODE) == GPIO_MODE_INPUT) ||\ + ((MODE) == GPIO_MODE_OUTPUT_PP) ||\ + ((MODE) == GPIO_MODE_OUTPUT_OD) ||\ + ((MODE) == GPIO_MODE_AF_PP) ||\ + ((MODE) == GPIO_MODE_AF_OD) ||\ + ((MODE) == GPIO_MODE_IT_RISING) ||\ + ((MODE) == GPIO_MODE_IT_FALLING) ||\ + ((MODE) == GPIO_MODE_IT_RISING_FALLING) ||\ + ((MODE) == GPIO_MODE_EVT_RISING) ||\ + ((MODE) == GPIO_MODE_EVT_FALLING) ||\ + ((MODE) == GPIO_MODE_EVT_RISING_FALLING) ||\ + ((MODE) == GPIO_MODE_ANALOG)) + +/** + * @} + */ + +/** @defgroup GPIO_speed_define GPIO_speed_define + * @brief GPIO Output Maximum frequency + * @{ + */ +#define GPIO_SPEED_LOW ((uint32_t)0x00000000) /*!< Low speed */ +#define GPIO_SPEED_MEDIUM ((uint32_t)0x00000001) /*!< Medium speed */ +#define GPIO_SPEED_HIGH ((uint32_t)0x00000003) /*!< High speed */ + +#define IS_GPIO_SPEED(SPEED) (((SPEED) == GPIO_SPEED_LOW) || ((SPEED) == GPIO_SPEED_MEDIUM) || \ + ((SPEED) == GPIO_SPEED_HIGH)) +/** + * @} + */ + + /** @defgroup GPIO_pull_define GPIO_pull_define + * @brief GPIO Pull-Up or Pull-Down Activation + * @{ + */ +#define GPIO_NOPULL ((uint32_t)0x00000000) /*!< No Pull-up or Pull-down activation */ +#define GPIO_PULLUP ((uint32_t)0x00000001) /*!< Pull-up activation */ +#define GPIO_PULLDOWN ((uint32_t)0x00000002) /*!< Pull-down activation */ + +#define IS_GPIO_PULL(PULL) (((PULL) == GPIO_NOPULL) || ((PULL) == GPIO_PULLUP) || \ + ((PULL) == GPIO_PULLDOWN)) +/** + * @} + */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ + +/** + * @brief Checks whether the specified EXTI line flag is set or not. + * @param __EXTI_LINE__: specifies the EXTI line flag to check. + * This parameter can be GPIO_PIN_x where x can be(0..15) + * @retval The new state of __EXTI_LINE__ (SET or RESET). + */ +#define __HAL_GPIO_EXTI_GET_FLAG(__EXTI_LINE__) (EXTI->PR & (__EXTI_LINE__)) + +/** + * @brief Clears the EXTI's line pending flags. + * @param __EXTI_LINE__: specifies the EXTI lines flags to clear. + * This parameter can be any combination of GPIO_PIN_x where x can be (0..15) + * @retval None + */ +#define __HAL_GPIO_EXTI_CLEAR_FLAG(__EXTI_LINE__) (EXTI->PR = (__EXTI_LINE__)) + +/** + * @brief Checks whether the specified EXTI line is asserted or not. + * @param __EXTI_LINE__: specifies the EXTI line to check. + * This parameter can be GPIO_PIN_x where x can be(0..15) + * @retval The new state of __EXTI_LINE__ (SET or RESET). + */ +#define __HAL_GPIO_EXTI_GET_IT(__EXTI_LINE__) (EXTI->PR & (__EXTI_LINE__)) + +/** + * @brief Clears the EXTI's line pending bits. + * @param __EXTI_LINE__: specifies the EXTI lines to clear. + * This parameter can be any combination of GPIO_PIN_x where x can be (0..15) + * @retval None + */ +#define __HAL_GPIO_EXTI_CLEAR_IT(__EXTI_LINE__) (EXTI->PR = (__EXTI_LINE__)) + +/** + * @brief Generates a Software interrupt on selected EXTI line. + * @param __EXTI_LINE__: specifies the EXTI line to check. + * This parameter can be GPIO_PIN_x where x can be(0..15) + * @retval None + */ +#define __HAL_GPIO_EXTI_GENERATE_SWIT(__EXTI_LINE__) (EXTI->SWIER |= (__EXTI_LINE__)) + +/* Include GPIO HAL Extension module */ +#include "stm32f0xx_hal_gpio_ex.h" + +/* Exported functions --------------------------------------------------------*/ +/* Initialization and de-initialization functions *****************************/ +void HAL_GPIO_Init(GPIO_TypeDef *GPIOx, GPIO_InitTypeDef *GPIO_Init); +void HAL_GPIO_DeInit(GPIO_TypeDef *GPIOx, uint32_t GPIO_Pin); + +/* IO operation functions *****************************************************/ +GPIO_PinState HAL_GPIO_ReadPin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin); +void HAL_GPIO_WritePin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin, GPIO_PinState PinState); +void HAL_GPIO_TogglePin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin); +HAL_StatusTypeDef HAL_GPIO_LockPin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin); +void HAL_GPIO_EXTI_IRQHandler(uint16_t GPIO_Pin); +void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin); + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __STM32F0xx_HAL_GPIO_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_gpio_ex.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_gpio_ex.h new file mode 100644 index 0000000000..4e108e3fc4 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_gpio_ex.h @@ -0,0 +1,615 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_gpio_ex.h + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief Header file of GPIO HAL Extension module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32F0xx_HAL_GPIO_EX_H +#define __STM32F0xx_HAL_GPIO_EX_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal_def.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @addtogroup GPIOEx + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ + +/* Exported constants --------------------------------------------------------*/ + +/** @defgroup GPIOEx_Exported_Constants GPIOEx_Exported_Constants + * @{ + */ + +/** @defgroup GPIOEx_Alternate_function_selection GPIOEx_Alternate_function_selection + * @{ + */ + +#if defined (STM32F030x6) +/*------------------------- STM32F030x6---------------------------*/ +/** + * @brief AF 0 selection + */ +#define GPIO_AF0_EVENTOUT ((uint8_t)0x00) /* EVENTOUT Alternate Function mapping */ +#define GPIO_AF0_MCO ((uint8_t)0x00) /* MCO Alternate Function mapping */ +#define GPIO_AF0_SPI1 ((uint8_t)0x00) /* SPI1 Alternate Function mapping */ +#define GPIO_AF0_TIM17 ((uint8_t)0x00) /* TIM17 Alternate Function mapping */ +#define GPIO_AF0_SWDIO ((uint8_t)0x00) /* SWDIO Alternate Function mapping */ +#define GPIO_AF0_SWCLK ((uint8_t)0x00) /* SWCLK Alternate Function mapping */ +#define GPIO_AF0_TIM14 ((uint8_t)0x00) /* TIM14 Alternate Function mapping */ +#define GPIO_AF0_USART1 ((uint8_t)0x00) /* USART1 Alternate Function mapping */ +#define GPIO_AF0_IR ((uint8_t)0x00) /* IR Alternate Function mapping */ + +/** + * @brief AF 1 selection + */ +#define GPIO_AF1_TIM3 ((uint8_t)0x01) /* TIM3 Alternate Function mapping */ +#define GPIO_AF1_USART1 ((uint8_t)0x01) /* USART1 Alternate Function mapping */ +#define GPIO_AF1_EVENTOUT ((uint8_t)0x01) /* EVENTOUT Alternate Function mapping */ +#define GPIO_AF1_I2C1 ((uint8_t)0x01) /* I2C1 Alternate Function mapping */ + +/** + * @brief AF 2 selection + */ +#define GPIO_AF2_TIM1 ((uint8_t)0x02) /* TIM1 Alternate Function mapping */ +#define GPIO_AF2_TIM16 ((uint8_t)0x02) /* TIM16 Alternate Function mapping */ +#define GPIO_AF2_TIM17 ((uint8_t)0x02) /* TIM17 Alternate Function mapping */ +#define GPIO_AF2_EVENTOUT ((uint8_t)0x02) /* EVENTOUT Alternate Function mapping */ + +/** + * @brief AF 3 selection + */ +#define GPIO_AF3_EVENTOUT ((uint8_t)0x03) /* EVENTOUT Alternate Function mapping */ +#define GPIO_AF3_I2C1 ((uint8_t)0x03) /* I2C1 Alternate Function mapping */ + +/** + * @brief AF 4 selection + */ +#define GPIO_AF4_TIM14 ((uint8_t)0x04) /* TIM14 Alternate Function mapping */ +#define GPIO_AF4_I2C1 ((uint8_t)0x04) /* I2C1 Alternate Function mapping */ + +/** + * @brief AF 5 selection + */ +#define GPIO_AF5_TIM16 ((uint8_t)0x05) /* TIM16 Alternate Function mapping */ +#define GPIO_AF5_TIM17 ((uint8_t)0x05) /* TIM17 Alternate Function mapping */ + +/** + * @brief AF 6 selection + */ +#define GPIO_AF6_EVENTOUT ((uint8_t)0x06) /* EVENTOUT Alternate Function mapping */ + +#define IS_GPIO_AF(AF) ((AF) <= (uint8_t)0x06) + +#endif /* STM32F030x6 */ + +/*---------------------------------- STM32F030x8 -------------------------------------------*/ +#if defined (STM32F030x8) +/** + * @brief AF 0 selection + */ +#define GPIO_AF0_EVENTOUT ((uint8_t)0x00) /* EVENTOUT Alternate Function mapping */ +#define GPIO_AF0_MCO ((uint8_t)0x00) /* MCO Alternate Function mapping */ +#define GPIO_AF0_SPI1 ((uint8_t)0x00) /* SPI1 Alternate Function mapping */ +#define GPIO_AF0_SPI2 ((uint8_t)0x00) /* SPI2 Alternate Function mapping */ +#define GPIO_AF0_TIM15 ((uint8_t)0x00) /* TIM15 Alternate Function mapping */ +#define GPIO_AF0_TIM17 ((uint8_t)0x00) /* TIM17 Alternate Function mapping */ +#define GPIO_AF0_SWDIO ((uint8_t)0x00) /* SWDIO Alternate Function mapping */ +#define GPIO_AF0_SWCLK ((uint8_t)0x00) /* SWCLK Alternate Function mapping */ +#define GPIO_AF0_TIM14 ((uint8_t)0x00) /* TIM14 Alternate Function mapping */ +#define GPIO_AF0_USART1 ((uint8_t)0x00) /* USART1 Alternate Function mapping */ +#define GPIO_AF0_IR ((uint8_t)0x00) /* IR Alternate Function mapping */ + +/** + * @brief AF 1 selection + */ +#define GPIO_AF1_TIM3 ((uint8_t)0x01) /* TIM3 Alternate Function mapping */ +#define GPIO_AF1_TIM15 ((uint8_t)0x01) /* TIM15 Alternate Function mapping */ +#define GPIO_AF1_USART1 ((uint8_t)0x01) /* USART1 Alternate Function mapping */ +#define GPIO_AF1_USART2 ((uint8_t)0x01) /* USART2 Alternate Function mapping */ +#define GPIO_AF1_EVENTOUT ((uint8_t)0x01) /* EVENTOUT Alternate Function mapping */ +#define GPIO_AF1_I2C1 ((uint8_t)0x01) /* I2C1 Alternate Function mapping */ +#define GPIO_AF1_I2C2 ((uint8_t)0x01) /* I2C2 Alternate Function mapping */ +#define GPIO_AF1_IR ((uint8_t)0x01) /* IR Alternate Function mapping */ + +/** + * @brief AF 2 selection + */ +#define GPIO_AF2_TIM1 ((uint8_t)0x02) /* TIM1 Alternate Function mapping */ +#define GPIO_AF2_TIM16 ((uint8_t)0x02) /* TIM16 Alternate Function mapping */ +#define GPIO_AF2_TIM17 ((uint8_t)0x02) /* TIM17 Alternate Function mapping */ +#define GPIO_AF2_EVENTOUT ((uint8_t)0x02) /* EVENTOUT Alternate Function mapping */ + +/** + * @brief AF 3 selection + */ +#define GPIO_AF3_EVENTOUT ((uint8_t)0x03) /* EVENTOUT Alternate Function mapping */ +#define GPIO_AF3_I2C1 ((uint8_t)0x03) /* I2C1 Alternate Function mapping */ +#define GPIO_AF3_TIM15 ((uint8_t)0x03) /* TIM15 Alternate Function mapping */ + +/** + * @brief AF 4 selection + */ +#define GPIO_AF4_TIM14 ((uint8_t)0x04) /* TIM14 Alternate Function mapping */ + +/** + * @brief AF 5 selection + */ +#define GPIO_AF5_TIM16 ((uint8_t)0x05) /* TIM16 Alternate Function mapping */ +#define GPIO_AF5_TIM17 ((uint8_t)0x05) /* TIM17 Alternate Function mapping */ + +/** + * @brief AF 6 selection + */ +#define GPIO_AF6_EVENTOUT ((uint8_t)0x06) /* EVENTOUT Alternate Function mapping */ + +#define IS_GPIO_AF(AF) ((AF) <= (uint8_t)0x06) + +#endif /* STM32F030x8 */ + +#if defined (STM32F031x6) || defined (STM32F038xx) +/*--------------------------- STM32F031x6/STM32F038xx ---------------------------*/ +/** + * @brief AF 0 selection + */ +#define GPIO_AF0_EVENTOUT ((uint8_t)0x00) /* EVENTOUT Alternate Function mapping */ +#define GPIO_AF0_MCO ((uint8_t)0x00) /* MCO Alternate Function mapping */ +#define GPIO_AF0_SPI1 ((uint8_t)0x00) /* SPI1/I2S1 Alternate Function mapping */ +#define GPIO_AF0_TIM17 ((uint8_t)0x00) /* TIM17 Alternate Function mapping */ +#define GPIO_AF0_SWDAT ((uint8_t)0x00) /* SWDAT Alternate Function mapping */ +#define GPIO_AF0_SWCLK ((uint8_t)0x00) /* SWCLK Alternate Function mapping */ +#define GPIO_AF0_TIM14 ((uint8_t)0x00) /* TIM14 Alternate Function mapping */ +#define GPIO_AF0_USART1 ((uint8_t)0x00) /* USART1 Alternate Function mapping */ +#define GPIO_AF0_IR ((uint8_t)0x00) /* IR Alternate Function mapping */ + +/** + * @brief AF 1 selection + */ +#define GPIO_AF1_TIM3 ((uint8_t)0x01) /* TIM3 Alternate Function mapping */ +#define GPIO_AF1_USART1 ((uint8_t)0x01) /* USART1 Alternate Function mapping */ +#define GPIO_AF1_IR ((uint8_t)0x01) /* IR Alternate Function mapping */ +#define GPIO_AF1_EVENTOUT ((uint8_t)0x01) /* EVENTOUT Alternate Function mapping */ +#define GPIO_AF1_I2C1 ((uint8_t)0x01) /* I2C1 Alternate Function mapping */ + +/** + * @brief AF 2 selection + */ +#define GPIO_AF2_TIM1 ((uint8_t)0x02) /* TIM1 Alternate Function mapping */ +#define GPIO_AF2_TIM2 ((uint8_t)0x02) /* TIM2 Alternate Function mapping */ +#define GPIO_AF2_TIM16 ((uint8_t)0x02) /* TIM16 Alternate Function mapping */ +#define GPIO_AF2_TIM17 ((uint8_t)0x02) /* TIM17 Alternate Function mapping */ +#define GPIO_AF2_EVENTOUT ((uint8_t)0x02) /* EVENTOUT Alternate Function mapping */ + +/** + * @brief AF 3 selection + */ +#define GPIO_AF3_EVENTOUT ((uint8_t)0x03) /* EVENTOUT Alternate Function mapping */ +#define GPIO_AF3_I2C1 ((uint8_t)0x03) /* I2C1 Alternate Function mapping */ + +/** + * @brief AF 4 selection + */ +#define GPIO_AF4_TIM14 ((uint8_t)0x04) /* TIM14 Alternate Function mapping */ +#define GPIO_AF4_I2C1 ((uint8_t)0x04) /* I2C1 Alternate Function mapping */ + +/** + * @brief AF 5 selection + */ +#define GPIO_AF5_TIM16 ((uint8_t)0x05) /* TIM16 Alternate Function mapping */ +#define GPIO_AF5_TIM17 ((uint8_t)0x05) /* TIM17 Alternate Function mapping */ + +/** + * @brief AF 6 selection + */ +#define GPIO_AF6_EVENTOUT ((uint8_t)0x06) /* EVENTOUT Alternate Function mapping */ + +#define IS_GPIO_AF(AF) ((AF) <= (uint8_t)0x06) + +#endif /* STM32F031x6 || STM32F038xx */ + +#if defined (STM32F051x8) || defined (STM32F058xx) +/*--------------------------- STM32F051x8/STM32F058xx---------------------------*/ +/** + * @brief AF 0 selection + */ +#define GPIO_AF0_EVENTOUT ((uint8_t)0x00) /* EVENTOUT Alternate Function mapping */ +#define GPIO_AF0_MCO ((uint8_t)0x00) /* MCO Alternate Function mapping */ +#define GPIO_AF0_SPI1 ((uint8_t)0x00) /* SPI1/I2S1 Alternate Function mapping */ +#define GPIO_AF0_SPI2 ((uint8_t)0x00) /* SPI2 Alternate Function mapping */ +#define GPIO_AF0_TIM15 ((uint8_t)0x00) /* TIM15 Alternate Function mapping */ +#define GPIO_AF0_TIM17 ((uint8_t)0x00) /* TIM17 Alternate Function mapping */ +#define GPIO_AF0_SWDIO ((uint8_t)0x00) /* SWDIO Alternate Function mapping */ +#define GPIO_AF0_SWCLK ((uint8_t)0x00) /* SWCLK Alternate Function mapping */ +#define GPIO_AF0_TIM14 ((uint8_t)0x00) /* TIM14 Alternate Function mapping */ +#define GPIO_AF0_USART1 ((uint8_t)0x00) /* USART1 Alternate Function mapping */ +#define GPIO_AF0_IR ((uint8_t)0x00) /* IR Alternate Function mapping */ +#define GPIO_AF0_CEC ((uint8_t)0x00) /* CEC Alternate Function mapping */ + +/** + * @brief AF 1 selection + */ +#define GPIO_AF1_TIM3 ((uint8_t)0x01) /* TIM3 Alternate Function mapping */ +#define GPIO_AF1_TIM15 ((uint8_t)0x01) /* TIM15 Alternate Function mapping */ +#define GPIO_AF1_USART1 ((uint8_t)0x01) /* USART1 Alternate Function mapping */ +#define GPIO_AF1_USART2 ((uint8_t)0x01) /* USART2 Alternate Function mapping */ +#define GPIO_AF1_EVENTOUT ((uint8_t)0x01) /* EVENTOUT Alternate Function mapping */ +#define GPIO_AF1_I2C1 ((uint8_t)0x01) /* I2C1 Alternate Function mapping */ +#define GPIO_AF1_I2C2 ((uint8_t)0x01) /* I2C2 Alternate Function mapping */ +#define GPIO_AF1_IR ((uint8_t)0x01) /* IR Alternate Function mapping */ +#define GPIO_AF1_CEC ((uint8_t)0x01) /* CEC Alternate Function mapping */ + +/** + * @brief AF 2 selection + */ +#define GPIO_AF2_TIM1 ((uint8_t)0x02) /* TIM1 Alternate Function mapping */ +#define GPIO_AF2_TIM2 ((uint8_t)0x02) /* TIM2 Alternate Function mapping */ +#define GPIO_AF2_TIM16 ((uint8_t)0x02) /* TIM16 Alternate Function mapping */ +#define GPIO_AF2_TIM17 ((uint8_t)0x02) /* TIM17 Alternate Function mapping */ +#define GPIO_AF2_EVENTOUT ((uint8_t)0x02) /* EVENTOUT Alternate Function mapping */ + +/** + * @brief AF 3 selection + */ +#define GPIO_AF3_EVENTOUT ((uint8_t)0x03) /* EVENTOUT Alternate Function mapping */ +#define GPIO_AF3_I2C1 ((uint8_t)0x03) /* I2C1 Alternate Function mapping */ +#define GPIO_AF3_TIM15 ((uint8_t)0x03) /* TIM15 Alternate Function mapping */ +#define GPIO_AF3_TSC ((uint8_t)0x03) /* TSC Alternate Function mapping */ + +/** + * @brief AF 4 selection + */ +#define GPIO_AF4_TIM14 ((uint8_t)0x04) /* TIM14 Alternate Function mapping */ + +/** + * @brief AF 5 selection + */ +#define GPIO_AF5_TIM16 ((uint8_t)0x05) /* TIM16 Alternate Function mapping */ +#define GPIO_AF5_TIM17 ((uint8_t)0x05) /* TIM17 Alternate Function mapping */ + +/** + * @brief AF 6 selection + */ +#define GPIO_AF6_EVENTOUT ((uint8_t)0x06) /* EVENTOUT Alternate Function mapping */ + +/** + * @brief AF 7 selection + */ +#define GPIO_AF7_COMP1 ((uint8_t)0x07) /* COMP1 Alternate Function mapping */ +#define GPIO_AF7_COMP2 ((uint8_t)0x07) /* COMP2 Alternate Function mapping */ + +#define IS_GPIO_AF(AF) ((AF) <= (uint8_t)0x07) + +#endif /* STM32F051x8/STM32F058xx */ + +#if defined (STM32F071xB) +/*--------------------------- STM32F071xB ---------------------------*/ +/** + * @brief AF 0 selection + */ +#define GPIO_AF0_EVENTOUT ((uint8_t)0x00) /* EVENTOUT Alternate Function mapping */ +#define GPIO_AF0_SWDIO ((uint8_t)0x00) /* SWDIO Alternate Function mapping */ +#define GPIO_AF0_SWCLK ((uint8_t)0x00) /* SWCLK Alternate Function mapping */ +#define GPIO_AF0_MCO ((uint8_t)0x00) /* MCO Alternate Function mapping */ +#define GPIO_AF0_CEC ((uint8_t)0x00) /* CEC Alternate Function mapping */ +#define GPIO_AF0_CRS ((uint8_t)0x00) /* CRS Alternate Function mapping */ +#define GPIO_AF0_IR ((uint8_t)0x00) /* IR Alternate Function mapping */ +#define GPIO_AF0_SPI1 ((uint8_t)0x00) /* SPI1/I2S1 Alternate Function mapping */ +#define GPIO_AF0_SPI2 ((uint8_t)0x00) /* SPI2/I2S2 Alternate Function mapping */ +#define GPIO_AF0_TIM1 ((uint8_t)0x00) /* TIM1 Alternate Function mapping */ +#define GPIO_AF0_TIM3 ((uint8_t)0x00) /* TIM3 Alternate Function mapping */ +#define GPIO_AF0_TIM14 ((uint8_t)0x00) /* TIM14 Alternate Function mapping */ +#define GPIO_AF0_TIM15 ((uint8_t)0x00) /* TIM15 Alternate Function mapping */ +#define GPIO_AF0_TIM16 ((uint8_t)0x00) /* TIM16 Alternate Function mapping */ +#define GPIO_AF0_TIM17 ((uint8_t)0x00) /* TIM17 Alternate Function mapping */ +#define GPIO_AF0_TSC ((uint8_t)0x00) /* TSC Alternate Function mapping */ +#define GPIO_AF0_USART1 ((uint8_t)0x00) /* USART1 Alternate Function mapping */ +#define GPIO_AF0_USART2 ((uint8_t)0x00) /* USART2 Alternate Function mapping */ +#define GPIO_AF0_USART3 ((uint8_t)0x00) /* USART3 Alternate Function mapping */ +#define GPIO_AF0_USART4 ((uint8_t)0x00) /* USART4 Alternate Function mapping */ + +/** + * @brief AF 1 selection + */ +#define GPIO_AF1_TIM3 ((uint8_t)0x01) /* TIM3 Alternate Function mapping */ +#define GPIO_AF1_TIM15 ((uint8_t)0x01) /* TIM15 Alternate Function mapping */ +#define GPIO_AF1_USART1 ((uint8_t)0x01) /* USART1 Alternate Function mapping */ +#define GPIO_AF1_USART2 ((uint8_t)0x01) /* USART2 Alternate Function mapping */ +#define GPIO_AF1_USART3 ((uint8_t)0x01) /* USART3 Alternate Function mapping */ +#define GPIO_AF1_IR ((uint8_t)0x01) /* IR Alternate Function mapping */ +#define GPIO_AF1_CEC ((uint8_t)0x01) /* CEC Alternate Function mapping */ +#define GPIO_AF1_EVENTOUT ((uint8_t)0x01) /* EVENTOUT Alternate Function mapping */ +#define GPIO_AF1_I2C1 ((uint8_t)0x01) /* I2C1 Alternate Function mapping */ +#define GPIO_AF1_I2C2 ((uint8_t)0x01) /* I2C2 Alternate Function mapping */ +#define GPIO_AF1_TSC ((uint8_t)0x01) /* TSC Alternate Function mapping */ +#define GPIO_AF1_SPI1 ((uint8_t)0x01) /* SPI1 Alternate Function mapping */ +#define GPIO_AF1_SPI2 ((uint8_t)0x01) /* SPI2 Alternate Function mapping */ + +/** + * @brief AF 2 selection + */ +#define GPIO_AF2_TIM1 ((uint8_t)0x02) /* TIM1 Alternate Function mapping */ +#define GPIO_AF2_TIM2 ((uint8_t)0x02) /* TIM2 Alternate Function mapping */ +#define GPIO_AF2_TIM16 ((uint8_t)0x02) /* TIM16 Alternate Function mapping */ +#define GPIO_AF2_TIM17 ((uint8_t)0x02) /* TIM17 Alternate Function mapping */ +#define GPIO_AF2_EVENTOUT ((uint8_t)0x02) /* EVENTOUT Alternate Function mapping */ + +/** + * @brief AF 3 selection + */ +#define GPIO_AF3_EVENTOUT ((uint8_t)0x03) /* EVENTOUT Alternate Function mapping */ +#define GPIO_AF3_TSC ((uint8_t)0x03) /* TSC Alternate Function mapping */ +#define GPIO_AF3_TIM15 ((uint8_t)0x03) /* TIM15 Alternate Function mapping */ +#define GPIO_AF3_I2C1 ((uint8_t)0x03) /* I2C1 Alternate Function mapping */ + +/** + * @brief AF 4 selection + */ +#define GPIO_AF4_TIM14 ((uint8_t)0x04) /* TIM14 Alternate Function mapping */ +#define GPIO_AF4_USART4 ((uint8_t)0x04) /* USART4 Alternate Function mapping */ +#define GPIO_AF4_USART3 ((uint8_t)0x04) /* USART3 Alternate Function mapping */ +#define GPIO_AF4_CRS ((uint8_t)0x04) /* CRS Alternate Function mapping */ + +/** + * @brief AF 5 selection + */ +#define GPIO_AF5_TIM15 ((uint8_t)0x05) /* TIM15 Alternate Function mapping */ +#define GPIO_AF5_TIM16 ((uint8_t)0x05) /* TIM16 Alternate Function mapping */ +#define GPIO_AF5_TIM17 ((uint8_t)0x05) /* TIM17 Alternate Function mapping */ +#define GPIO_AF5_SPI2 ((uint8_t)0x05) /* SPI2 Alternate Function mapping */ +#define GPIO_AF5_I2C2 ((uint8_t)0x05) /* I2C2 Alternate Function mapping */ + +/** + * @brief AF 6 selection + */ +#define GPIO_AF6_EVENTOUT ((uint8_t)0x06) /* EVENTOUT Alternate Function mapping */ + +/** + * @brief AF 7 selection + */ +#define GPIO_AF7_COMP1 ((uint8_t)0x07) /* COMP1 Alternate Function mapping */ +#define GPIO_AF7_COMP2 ((uint8_t)0x07) /* COMP2 Alternate Function mapping */ + +#define IS_GPIO_AF(AF) ((AF) <= (uint8_t)0x07) + +#endif /* STM32F071xB */ + + +#if defined (STM32F072xB) || defined (STM32F078xx) +/*--------------------------- STM32F072xB/STM32F078xx ---------------------------*/ +/** + * @brief AF 0 selection + */ +#define GPIO_AF0_EVENTOUT ((uint8_t)0x00) /* EVENTOUT Alternate Function mapping */ +#define GPIO_AF0_SWDIO ((uint8_t)0x00) /* SWDIO Alternate Function mapping */ +#define GPIO_AF0_SWCLK ((uint8_t)0x00) /* SWCLK Alternate Function mapping */ +#define GPIO_AF0_MCO ((uint8_t)0x00) /* MCO Alternate Function mapping */ +#define GPIO_AF0_CEC ((uint8_t)0x00) /* CEC Alternate Function mapping */ +#define GPIO_AF0_CRS ((uint8_t)0x00) /* CRS Alternate Function mapping */ +#define GPIO_AF0_IR ((uint8_t)0x00) /* IR Alternate Function mapping */ +#define GPIO_AF0_SPI1 ((uint8_t)0x00) /* SPI1/I2S1 Alternate Function mapping */ +#define GPIO_AF0_SPI2 ((uint8_t)0x00) /* SPI2/I2S2 Alternate Function mapping */ +#define GPIO_AF0_TIM1 ((uint8_t)0x00) /* TIM1 Alternate Function mapping */ +#define GPIO_AF0_TIM3 ((uint8_t)0x00) /* TIM3 Alternate Function mapping */ +#define GPIO_AF0_TIM14 ((uint8_t)0x00) /* TIM14 Alternate Function mapping */ +#define GPIO_AF0_TIM15 ((uint8_t)0x00) /* TIM15 Alternate Function mapping */ +#define GPIO_AF0_TIM16 ((uint8_t)0x00) /* TIM16 Alternate Function mapping */ +#define GPIO_AF0_TIM17 ((uint8_t)0x00) /* TIM17 Alternate Function mapping */ +#define GPIO_AF0_TSC ((uint8_t)0x00) /* TSC Alternate Function mapping */ +#define GPIO_AF0_USART1 ((uint8_t)0x00) /* USART1 Alternate Function mapping */ +#define GPIO_AF0_USART2 ((uint8_t)0x00) /* USART2 Alternate Function mapping */ +#define GPIO_AF0_USART3 ((uint8_t)0x00) /* USART2 Alternate Function mapping */ +#define GPIO_AF0_USART4 ((uint8_t)0x00) /* USART4 Alternate Function mapping */ +#define GPIO_AF0_CAN ((uint8_t)0x00) /* CAN Alternate Function mapping */ + +/** + * @brief AF 1 selection + */ +#define GPIO_AF1_TIM3 ((uint8_t)0x01) /* TIM3 Alternate Function mapping */ +#define GPIO_AF1_TIM15 ((uint8_t)0x01) /* TIM15 Alternate Function mapping */ +#define GPIO_AF1_USART1 ((uint8_t)0x01) /* USART1 Alternate Function mapping */ +#define GPIO_AF1_USART2 ((uint8_t)0x01) /* USART2 Alternate Function mapping */ +#define GPIO_AF1_USART3 ((uint8_t)0x01) /* USART3 Alternate Function mapping */ +#define GPIO_AF1_IR ((uint8_t)0x01) /* IR Alternate Function mapping */ +#define GPIO_AF1_CEC ((uint8_t)0x01) /* CEC Alternate Function mapping */ +#define GPIO_AF1_EVENTOUT ((uint8_t)0x01) /* EVENTOUT Alternate Function mapping */ +#define GPIO_AF1_I2C1 ((uint8_t)0x01) /* I2C1 Alternate Function mapping */ +#define GPIO_AF1_I2C2 ((uint8_t)0x01) /* I2C1 Alternate Function mapping */ +#define GPIO_AF1_TSC ((uint8_t)0x01) /* I2C1 Alternate Function mapping */ +#define GPIO_AF1_SPI1 ((uint8_t)0x01) /* SPI1 Alternate Function mapping */ +#define GPIO_AF1_SPI2 ((uint8_t)0x01) /* SPI2 Alternate Function mapping */ + +/** + * @brief AF 2 selection + */ +#define GPIO_AF2_TIM1 ((uint8_t)0x02) /* TIM1 Alternate Function mapping */ +#define GPIO_AF2_TIM2 ((uint8_t)0x02) /* TIM2 Alternate Function mapping */ +#define GPIO_AF2_TIM16 ((uint8_t)0x02) /* TIM16 Alternate Function mapping */ +#define GPIO_AF2_TIM17 ((uint8_t)0x02) /* TIM17 Alternate Function mapping */ +#define GPIO_AF2_EVENTOUT ((uint8_t)0x02) /* EVENTOUT Alternate Function mapping */ + +#define GPIO_AF2_USB ((uint8_t)0x02) /* USB Alternate Function mapping */ + +/** + * @brief AF 3 selection + */ +#define GPIO_AF3_EVENTOUT ((uint8_t)0x03) /* EVENTOUT Alternate Function mapping */ +#define GPIO_AF3_TSC ((uint8_t)0x03) /* TSC Alternate Function mapping */ +#define GPIO_AF3_TIM15 ((uint8_t)0x03) /* TIM15 Alternate Function mapping */ +#define GPIO_AF3_I2C1 ((uint8_t)0x03) /* I2C1 Alternate Function mapping */ + +/** + * @brief AF 4 selection + */ +#define GPIO_AF4_TIM14 ((uint8_t)0x04) /* TIM14 Alternate Function mapping */ +#define GPIO_AF4_USART4 ((uint8_t)0x04) /* USART4 Alternate Function mapping */ +#define GPIO_AF4_USART3 ((uint8_t)0x04) /* USART3 Alternate Function mapping */ +#define GPIO_AF4_CRS ((uint8_t)0x04) /* CRS Alternate Function mapping */ + +#define GPIO_AF4_CAN ((uint8_t)0x04) /* CAN Alternate Function mapping */ + +/** + * @brief AF 5 selection + */ +#define GPIO_AF5_TIM15 ((uint8_t)0x05) /* TIM15 Alternate Function mapping */ +#define GPIO_AF5_TIM16 ((uint8_t)0x05) /* TIM16 Alternate Function mapping */ +#define GPIO_AF5_TIM17 ((uint8_t)0x05) /* TIM17 Alternate Function mapping */ +#define GPIO_AF5_SPI2 ((uint8_t)0x05) /* SPI2 Alternate Function mapping */ +#define GPIO_AF5_I2C2 ((uint8_t)0x05) /* I2C2 Alternate Function mapping */ + +/** + * @brief AF 6 selection + */ +#define GPIO_AF6_EVENTOUT ((uint8_t)0x06) /* EVENTOUT Alternate Function mapping */ + +/** + * @brief AF 7 selection + */ +#define GPIO_AF7_COMP1 ((uint8_t)0x07) /* COMP1 Alternate Function mapping */ +#define GPIO_AF7_COMP2 ((uint8_t)0x07) /* COMP2 Alternate Function mapping */ + +#define IS_GPIO_AF(AF) ((AF) <= (uint8_t)0x07) + +#endif /* STM32F072xB || STM32F078xx */ + +#if defined (STM32F042x6) || defined (STM32F048xx) +/*--------------------------- STM32F042x6/STM32F048xx ---------------------------*/ +/** + * @brief AF 0 selection on PA, PB, PF + */ +#define GPIO_AF0_EVENTOUT ((uint8_t)0x00) /* EVENTOUT Alternate Function mapping */ +#define GPIO_AF0_CEC ((uint8_t)0x00) /* CEC Alternate Function mapping */ +#define GPIO_AF0_CRS ((uint8_t)0x00) /* CRS Alternate Function mapping */ +#define GPIO_AF0_IR ((uint8_t)0x00) /* IR Alternate Function mapping */ +#define GPIO_AF0_MCO ((uint8_t)0x00) /* MCO Alternate Function mapping */ +#define GPIO_AF0_SPI1 ((uint8_t)0x00) /* SPI1/I2S1 Alternate Function mapping */ +#define GPIO_AF0_SPI2 ((uint8_t)0x00) /* SPI2/I2S2 Alternate Function mapping */ +#define GPIO_AF0_SWDIO ((uint8_t)0x00) /* SWDIO Alternate Function mapping */ +#define GPIO_AF0_SWCLK ((uint8_t)0x00) /* SWCLK Alternate Function mapping */ +#define GPIO_AF0_TIM14 ((uint8_t)0x00) /* TIM14 Alternate Function mapping */ +#define GPIO_AF0_TIM17 ((uint8_t)0x00) /* TIM17 Alternate Function mapping */ +#define GPIO_AF0_USART1 ((uint8_t)0x00) /* USART1 Alternate Function mapping */ + +/** + * @brief AF 1 selection on PA, PB, PF + */ +#define GPIO_AF1_CEC ((uint8_t)0x01) /* CEC Alternate Function mapping */ +#define GPIO_AF1_EVENTOUT ((uint8_t)0x01) /* EVENTOUT Alternate Function mapping */ +#define GPIO_AF1_I2C1 ((uint8_t)0x01) /* I2C1 Alternate Function mapping */ +#define GPIO_AF1_IR ((uint8_t)0x01) /* IR Alternate Function mapping */ +#define GPIO_AF1_USART1 ((uint8_t)0x01) /* USART1 Alternate Function mapping */ +#define GPIO_AF1_USART2 ((uint8_t)0x01) /* USART2 Alternate Function mapping */ +#define GPIO_AF1_TIM3 ((uint8_t)0x01) /* TIM3 Alternate Function mapping */ + +/** + * @brief AF 2 selection on PA, PB + */ +#define GPIO_AF2_EVENTOUT ((uint8_t)0x02) /* EVENTOUT Alternate Function mapping */ +#define GPIO_AF2_TIM1 ((uint8_t)0x02) /* TIM1 Alternate Function mapping */ +#define GPIO_AF2_TIM2 ((uint8_t)0x02) /* TIM2 Alternate Function mapping */ +#define GPIO_AF2_TIM16 ((uint8_t)0x02) /* TIM16 Alternate Function mapping */ +#define GPIO_AF2_TIM17 ((uint8_t)0x02) /* TIM17 Alternate Function mapping */ +#define GPIO_AF2_USB ((uint8_t)0x02) /* USB Alternate Function mapping */ + +/** + * @brief AF 3 selection on PA, PB + */ +#define GPIO_AF3_EVENTOUT ((uint8_t)0x03) /* EVENTOUT Alternate Function mapping */ +#define GPIO_AF3_I2C1 ((uint8_t)0x03) /* I2C1 Alternate Function mapping */ +#define GPIO_AF3_TSC ((uint8_t)0x03) /* TSC Alternate Function mapping */ + +/** + * @brief AF 4 selection on PA, PB + */ +#define GPIO_AF4_TIM14 ((uint8_t)0x04) /* TIM14 Alternate Function mapping */ +#define GPIO_AF4_CAN ((uint8_t)0x04) /* CAN Alternate Function mapping */ +#define GPIO_AF4_CRS ((uint8_t)0x04) /* CRS Alternate Function mapping */ +#define GPIO_AF4_I2C1 ((uint8_t)0x04) /* I2C1 Alternate Function mapping */ + +/** + * @brief AF 5 selection on PA, PB + */ +#define GPIO_AF5_MCO ((uint8_t)0x05) /* MCO Alternate Function mapping */ +#define GPIO_AF5_I2C1 ((uint8_t)0x05) /* I2C1 Alternate Function mapping */ +#define GPIO_AF5_I2C2 ((uint8_t)0x05) /* I2C2 Alternate Function mapping */ +#define GPIO_AF5_SPI2 ((uint8_t)0x05) /* SPI2 Alternate Function mapping */ +#define GPIO_AF5_TIM16 ((uint8_t)0x05) /* TIM16 Alternate Function mapping */ +#define GPIO_AF5_TIM17 ((uint8_t)0x05) /* TIM17 Alternate Function mapping */ +#define GPIO_AF5_USB ((uint8_t)0x05) /* USB Alternate Function mapping */ + +/** + * @brief AF 6 selection on PA + */ +#define GPIO_AF6_EVENTOUT ((uint8_t)0x06) /* EVENTOUT Alternate Function mapping */ + +#define IS_GPIO_AF(AF) ((AF) <= (uint8_t)0x06) + +#endif /* STM32F042x6 || STM32F048xx */ + +/** + * @} + */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ +/* Exported functions --------------------------------------------------------*/ + + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __STM32F0xx_HAL_GPIO_EX_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_i2c.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_i2c.c new file mode 100644 index 0000000000..f2e14e802d --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_i2c.c @@ -0,0 +1,3754 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_i2c.c + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief I2C HAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the Inter Integrated Circuit (I2C) peripheral: + * + Initialization and de-initialization functions + * + IO operation functions + * + Peripheral State functions + * + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + The I2C HAL driver can be used as follows: + + (#) Declare a I2C_HandleTypeDef handle structure, for example: + I2C_HandleTypeDef hi2c; + + (#)Initialize the I2C low level resources by implement the HAL_I2C_MspInit ()API: + (##) Enable the I2Cx interface clock + (##) I2C pins configuration + (+++) Enable the clock for the I2C GPIOs + (+++) Configure I2C pins as alternate function open-drain + (##) NVIC configuration if you need to use interrupt process + (+++) Configure the I2Cx interrupt priority + (+++) Enable the NVIC I2C IRQ Channel + (##) DMA Configuration if you need to use DMA process + (+++) Declare a DMA_HandleTypeDef handle structure for the transmit or receive stream + (+++) Enable the DMAx interface clock using + (+++) Configure the DMA handle parameters + (+++) Configure the DMA Tx or Rx Stream + (+++) Associate the initilalized DMA handle to the hi2c DMA Tx or Rx handle + (+++) Configure the priority and enable the NVIC for the transfer complete interrupt on the DMA Tx or Rx Stream + + (#) Configure the Communication Clock Timing, Own Address1, Master Adressing Mode, Dual Addressing mode, + Own Address2, Own Address2 Mask, General call and Nostretch mode in the hi2c Init structure. + + (#) Initialize the I2C registers by calling the HAL_I2C_Init() API: + (+++) These API's configures also the low level Hardware GPIO, CLOCK, CORTEX...etc) + by calling the customed HAL_I2C_MspInit(&hi2c) API. + + (#) To check if target device is ready for communication, use the function HAL_I2C_IsDeviceReady() + + (#) For I2C IO and IO MEM operations, three mode of operations are available within this driver : + + *** Polling mode IO operation *** + ================================= + [..] + (+) Transmit in master mode an amount of data in blocking mode using HAL_I2C_Master_Transmit() + (+) Receive in master mode an amount of data in blocking mode using HAL_I2C_Master_Receive() + (+) Transmit in slave mode an amount of data in blocking mode using HAL_I2C_Slave_Transmit() + (+) Receive in slave mode an amount of data in blocking mode using HAL_I2C_Slave_Receive() + + *** Polling mode IO MEM operation *** + ===================================== + [..] + (+) Write an amount of data in blocking mode to a specific memory address using HAL_I2C_Mem_Write() + (+) Read an amount of data in blocking mode from a specific memory address using HAL_I2C_Mem_Read() + + + *** Interrupt mode IO operation *** + =================================== + [..] + (+) Transmit in master mode an amount of data in non blocking mode using HAL_I2C_Master_Transmit_IT() + (+) At transmission end of transfer HAL_I2C_MasterTxCpltCallback is executed and user can + add his own code by customization of function pointer HAL_I2C_MasterTxCpltCallback + (+) Receive in master mode an amount of data in non blocking mode using HAL_I2C_Master_Receive_IT() + (+) At reception end of transfer HAL_I2C_MasterRxCpltCallback is executed and user can + add his own code by customization of function pointer HAL_I2C_MasterRxCpltCallback + (+) Transmit in slave mode an amount of data in non blocking mode using HAL_I2C_Slave_Transmit_IT() + (+) At transmission end of transfer HAL_I2C_SlaveTxCpltCallback is executed and user can + add his own code by customization of function pointer HAL_I2C_SlaveTxCpltCallback + (+) Receive in slave mode an amount of data in non blocking mode using HAL_I2C_Slave_Receive_IT() + (+) At reception end of transfer HAL_I2C_SlaveRxCpltCallback is executed and user can + add his own code by customization of function pointer HAL_I2C_SlaveRxCpltCallback + (+) In case of transfer Error, HAL_I2C_ErrorCallback() function is executed and user can + add his own code by customization of function pointer HAL_I2C_ErrorCallback + + *** Interrupt mode IO MEM operation *** + ======================================= + [..] + (+) Write an amount of data in no-blocking mode with Interrupt to a specific memory address using + HAL_I2C_Mem_Write_IT() + (+) At MEM end of write transfer HAL_I2C_MemTxCpltCallback is executed and user can + add his own code by customization of function pointer HAL_I2C_MemTxCpltCallback + (+) Read an amount of data in no-blocking mode with Interrupt from a specific memory address using + HAL_I2C_Mem_Read_IT() + (+) At MEM end of read transfer HAL_I2C_MemRxCpltCallback is executed and user can + add his own code by customization of function pointer HAL_I2C_MemRxCpltCallback + (+) In case of transfer Error, HAL_I2C_ErrorCallback() function is executed and user can + add his own code by customization of function pointer HAL_I2C_ErrorCallback + + *** DMA mode IO operation *** + ============================== + [..] + (+) Transmit in master mode an amount of data in non blocking mode (DMA) using + HAL_I2C_Master_Transmit_DMA() + (+) At transmission end of transfer HAL_I2C_MasterTxCpltCallback is executed and user can + add his own code by customization of function pointer HAL_I2C_MasterTxCpltCallback + (+) Receive in master mode an amount of data in non blocking mode (DMA) using + HAL_I2C_Master_Receive_DMA() + (+) At reception end of transfer HAL_I2C_MasterRxCpltCallback is executed and user can + add his own code by customization of function pointer HAL_I2C_MasterRxCpltCallback + (+) Transmit in slave mode an amount of data in non blocking mode (DMA) using + HAL_I2C_Slave_Transmit_DMA() + (+) At transmission end of transfer HAL_I2C_SlaveTxCpltCallback is executed and user can + add his own code by customization of function pointer HAL_I2C_SlaveTxCpltCallback + (+) Receive in slave mode an amount of data in non blocking mode (DMA) using + HAL_I2C_Slave_Receive_DMA() + (+) At reception end of transfer HAL_I2C_SlaveRxCpltCallback is executed and user can + add his own code by customization of function pointer HAL_I2C_SlaveRxCpltCallback + (+) In case of transfer Error, HAL_I2C_ErrorCallback() function is executed and user can + add his own code by customization of function pointer HAL_I2C_ErrorCallback + + *** DMA mode IO MEM operation *** + ================================= + [..] + (+) Write an amount of data in no-blocking mode with DMA to a specific memory address using + HAL_I2C_Mem_Write_DMA() + (+) At MEM end of write transfer HAL_I2C_MemTxCpltCallback is executed and user can + add his own code by customization of function pointer HAL_I2C_MemTxCpltCallback + (+) Read an amount of data in no-blocking mode with DMA from a specific memory address using + HAL_I2C_Mem_Read_DMA() + (+) At MEM end of read transfer HAL_I2C_MemRxCpltCallback is executed and user can + add his own code by customization of function pointer HAL_I2C_MemRxCpltCallback + (+) In case of transfer Error, HAL_I2C_ErrorCallback() function is executed and user can + add his own code by customization of function pointer HAL_I2C_ErrorCallback + + + *** I2C HAL driver macros list *** + ================================== + [..] + Below the list of most used macros in I2C HAL driver. + + (+) __HAL_I2C_ENABLE: Enable the I2C peripheral + (+) __HAL_I2C_DISABLE: Disable the I2C peripheral + (+) __HAL_I2C_GET_FLAG : Checks whether the specified I2C flag is set or not + (+) __HAL_I2C_CLEAR_FLAG : Clears the specified I2C pending flag + (+) __HAL_I2C_ENABLE_IT: Enables the specified I2C interrupt + (+) __HAL_I2C_DISABLE_IT: Disables the specified I2C interrupt + + [..] + (@) You can refer to the I2C HAL driver header file for more useful macros + + + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @defgroup I2C + * @brief I2C HAL module driver + * @{ + */ + +#ifdef HAL_I2C_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +#define TIMING_CLEAR_MASK ((uint32_t)0xF0FFFFFF) /*Instance)); + assert_param(IS_I2C_OWN_ADDRESS1(hi2c->Init.OwnAddress1)); + assert_param(IS_I2C_ADDRESSING_MODE(hi2c->Init.AddressingMode)); + assert_param(IS_I2C_DUAL_ADDRESS(hi2c->Init.DualAddressMode)); + assert_param(IS_I2C_OWN_ADDRESS2(hi2c->Init.OwnAddress2)); + assert_param(IS_I2C_OWN_ADDRESS2_MASK(hi2c->Init.OwnAddress2Masks)); + assert_param(IS_I2C_GENERAL_CALL(hi2c->Init.GeneralCallMode)); + assert_param(IS_I2C_NO_STRETCH(hi2c->Init.NoStretchMode)); + + if(hi2c->State == HAL_I2C_STATE_RESET) + { + /* Init the low level hardware : GPIO, CLOCK, NVIC */ + HAL_I2C_MspInit(hi2c); + } + + hi2c->State = HAL_I2C_STATE_BUSY; + + /* Disable the selected I2C peripheral */ + __HAL_I2C_DISABLE(hi2c); + + /*---------------------------- I2Cx TIMINGR Configuration ------------------------*/ + /* Configure I2Cx: Frequency range */ + hi2c->Instance->TIMINGR = hi2c->Init.Timing & TIMING_CLEAR_MASK; + + /*---------------------------- I2Cx OAR1 Configuration -----------------------*/ + /* Configure I2Cx: Own Address1 and ack own address1 mode */ + hi2c->Instance->OAR1 &= ~I2C_OAR1_OA1EN; + if(hi2c->Init.OwnAddress1 != 0) + { + if(hi2c->Init.AddressingMode == I2C_ADDRESSINGMODE_7BIT) + { + hi2c->Instance->OAR1 = (I2C_OAR1_OA1EN | hi2c->Init.OwnAddress1); + } + else /* SMBUS_ADDRESSINGMODE_10BIT */ + { + hi2c->Instance->OAR1 = (I2C_OAR1_OA1EN | I2C_OAR1_OA1MODE | hi2c->Init.OwnAddress1); + } + } + + /*---------------------------- I2Cx CR2 Configuration ------------------------*/ + /* Configure I2Cx: Addressing Master mode */ + if(hi2c->Init.AddressingMode == I2C_ADDRESSINGMODE_10BIT) + { + hi2c->Instance->CR2 = (I2C_CR2_ADD10); + } + /* Enable the AUTOEND by default, and enable NACK (should be disable only during Slave process */ + hi2c->Instance->CR2 |= (I2C_CR2_AUTOEND | I2C_CR2_NACK); + + /*---------------------------- I2Cx OAR2 Configuration -----------------------*/ + /* Configure I2Cx: Dual mode and Own Address2 */ + hi2c->Instance->OAR2 = (hi2c->Init.DualAddressMode | hi2c->Init.OwnAddress2 | (hi2c->Init.OwnAddress2Masks << 8)); + + /*---------------------------- I2Cx CR1 Configuration ------------------------*/ + /* Configure I2Cx: Generalcall and NoStretch mode */ + hi2c->Instance->CR1 = (hi2c->Init.GeneralCallMode | hi2c->Init.NoStretchMode); + + /* Enable the selected I2C peripheral */ + __HAL_I2C_ENABLE(hi2c); + + hi2c->ErrorCode = HAL_I2C_ERROR_NONE; + hi2c->State = HAL_I2C_STATE_READY; + + return HAL_OK; +} + +/** + * @brief DeInitializes the I2C peripheral. + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2C_DeInit(I2C_HandleTypeDef *hi2c) +{ + /* Check the I2C handle allocation */ + if(hi2c == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_I2C_ALL_INSTANCE(hi2c->Instance)); + + hi2c->State = HAL_I2C_STATE_BUSY; + + /* Disable the I2C Peripheral Clock */ + __HAL_I2C_DISABLE(hi2c); + + /* DeInit the low level hardware: GPIO, CLOCK, NVIC */ + HAL_I2C_MspDeInit(hi2c); + + hi2c->ErrorCode = HAL_I2C_ERROR_NONE; + + hi2c->State = HAL_I2C_STATE_RESET; + + /* Release Lock */ + __HAL_UNLOCK(hi2c); + + return HAL_OK; +} + +/** + * @brief I2C MSP Init. + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @retval None + */ + __weak void HAL_I2C_MspInit(I2C_HandleTypeDef *hi2c) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_I2C_MspInit could be implemented in the user file + */ +} + +/** + * @brief I2C MSP DeInit + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @retval None + */ + __weak void HAL_I2C_MspDeInit(I2C_HandleTypeDef *hi2c) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_I2C_MspDeInit could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup I2C_Group2 IO operation functions + * @brief Data transfers functions + * +@verbatim + =============================================================================== + ##### IO operation functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to manage the I2C data + transfers. + + (#) There is two mode of transfer: + (++) Blocking mode : The communication is performed in the polling mode. + The status of all data processing is returned by the same function + after finishing transfer. + (++) No-Blocking mode : The communication is performed using Interrupts + or DMA. These functions return the status of the transfer startup. + The end of the data processing will be indicated through the + dedicated I2C IRQ when using Interrupt mode or the DMA IRQ when + using DMA mode. + + (#) Blocking mode functions are : + (++) HAL_I2C_Master_Transmit() + (++) HAL_I2C_Master_Receive() + (++) HAL_I2C_Slave_Transmit() + (++) HAL_I2C_Slave_Receive() + (++) HAL_I2C_Mem_Write() + (++) HAL_I2C_Mem_Read() + (++) HAL_I2C_IsDeviceReady() + + (#) No-Blocking mode functions with Interrupt are : + (++) HAL_I2C_Master_Transmit_IT() + (++) HAL_I2C_Master_Receive_IT() + (++) HAL_I2C_Slave_Transmit_IT() + (++) HAL_I2C_Slave_Receive_IT() + (++) HAL_I2C_Mem_Write_IT() + (++) HAL_I2C_Mem_Read_IT() + + (#) No-Blocking mode functions with DMA are : + (++) HAL_I2C_Master_Transmit_DMA() + (++) HAL_I2C_Master_Receive_DMA() + (++) HAL_I2C_Slave_Transmit_DMA() + (++) HAL_I2C_Slave_Receive_DMA() + (++) HAL_I2C_Mem_Write_DMA() + (++) HAL_I2C_Mem_Read_DMA() + + (#) A set of Transfer Complete Callbacks are provided in No_Blocking mode: + (++) HAL_I2C_MemTxCpltCallback() + (++) HAL_I2C_MemRxCpltCallback() + (++) HAL_I2C_MasterTxCpltCallback() + (++) HAL_I2C_MasterRxCpltCallback() + (++) HAL_I2C_SlaveTxCpltCallback() + (++) HAL_I2C_SlaveRxCpltCallback() + (++) HAL_I2C_ErrorCallback() + +@endverbatim + * @{ + */ + +/** + * @brief Transmits in master mode an amount of data in blocking mode. + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param DevAddress: Target device address + * @param pData: Pointer to data buffer + * @param Size: Amount of data to be sent + * @param Timeout: Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2C_Master_Transmit(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t Timeout) +{ + uint32_t sizetmp = 0; + + if(hi2c->State == HAL_I2C_STATE_READY) + { + if((pData == NULL ) || (Size == 0)) + { + return HAL_ERROR; + } + + if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) == SET) + { + return HAL_BUSY; + } + + /* Process Locked */ + __HAL_LOCK(hi2c); + + hi2c->State = HAL_I2C_STATE_MASTER_BUSY_TX; + hi2c->ErrorCode = HAL_I2C_ERROR_NONE; + + /* Send Slave Address */ + /* Set NBYTES to write and reload if size > 255 and generate RESTART */ + /* Size > 255, need to set RELOAD bit */ + if(Size > 255) + { + I2C_TransferConfig(hi2c,DevAddress,255, I2C_RELOAD_MODE, I2C_GENERATE_START_WRITE); + sizetmp = 255; + } + else + { + I2C_TransferConfig(hi2c,DevAddress,Size, I2C_AUTOEND_MODE, I2C_GENERATE_START_WRITE); + sizetmp = Size; + } + + do + { + /* Wait until TXIS flag is set */ + if(I2C_WaitOnTXISFlagUntilTimeout(hi2c, Timeout) != HAL_OK) + { + if(hi2c->ErrorCode == HAL_I2C_ERROR_AF) + { + return HAL_ERROR; + } + else + { + return HAL_TIMEOUT; + } + } + + /* Write data to TXDR */ + hi2c->Instance->TXDR = (*pData++); + sizetmp--; + Size--; + + if((sizetmp == 0)&&(Size!=0)) + { + /* Wait until TXE flag is set */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_TCR, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + if(Size > 255) + { + I2C_TransferConfig(hi2c,DevAddress,255, I2C_RELOAD_MODE, I2C_NO_STARTSTOP); + sizetmp = 255; + } + else + { + I2C_TransferConfig(hi2c,DevAddress,Size, I2C_AUTOEND_MODE, I2C_NO_STARTSTOP); + sizetmp = Size; + } + } + + }while(Size > 0); + + /* No need to Check TC flag, with AUTOEND mode the stop is automatically generated */ + /* Wait until STOPF flag is set */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_STOPF, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + /* Clear STOP Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); + + /* Clear Configuration Register 2 */ + __HAL_I2C_RESET_CR2(hi2c); + + hi2c->State = HAL_I2C_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receives in master mode an amount of data in blocking mode. + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param DevAddress: Target device address + * @param pData: Pointer to data buffer + * @param Size: Amount of data to be sent + * @param Timeout: Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2C_Master_Receive(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t Timeout) +{ + uint32_t sizetmp = 0; + + if(hi2c->State == HAL_I2C_STATE_READY) + { + if((pData == NULL ) || (Size == 0)) + { + return HAL_ERROR; + } + + if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) == SET) + { + return HAL_BUSY; + } + + /* Process Locked */ + __HAL_LOCK(hi2c); + + hi2c->State = HAL_I2C_STATE_MASTER_BUSY_RX; + hi2c->ErrorCode = HAL_I2C_ERROR_NONE; + + /* Send Slave Address */ + /* Set NBYTES to write and reload if size > 255 and generate RESTART */ + /* Size > 255, need to set RELOAD bit */ + if(Size > 255) + { + I2C_TransferConfig(hi2c,DevAddress,255, I2C_RELOAD_MODE, I2C_GENERATE_START_READ); + sizetmp = 255; + } + else + { + I2C_TransferConfig(hi2c,DevAddress,Size, I2C_AUTOEND_MODE, I2C_GENERATE_START_READ); + sizetmp = Size; + } + + do + { + /* Wait until RXNE flag is set */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_RXNE, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + /* Write data to RXDR */ + (*pData++) =hi2c->Instance->RXDR; + sizetmp--; + Size--; + + if((sizetmp == 0)&&(Size!=0)) + { + /* Wait until TCR flag is set */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_TCR, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + if(Size > 255) + { + I2C_TransferConfig(hi2c,DevAddress,255, I2C_RELOAD_MODE, I2C_NO_STARTSTOP); + sizetmp = 255; + } + else + { + I2C_TransferConfig(hi2c,DevAddress,Size, I2C_AUTOEND_MODE, I2C_NO_STARTSTOP); + sizetmp = Size; + } + } + + }while(Size > 0); + + /* No need to Check TC flag, with AUTOEND mode the stop is automatically generated */ + /* Wait until STOPF flag is set */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_STOPF, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + /* Clear STOP Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); + + /* Clear Configuration Register 2 */ + __HAL_I2C_RESET_CR2(hi2c); + + hi2c->State = HAL_I2C_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Transmits in slave mode an amount of data in blocking mode. + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param pData: Pointer to data buffer + * @param Size: Amount of data to be sent + * @param Timeout: Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2C_Slave_Transmit(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size, uint32_t Timeout) +{ + if(hi2c->State == HAL_I2C_STATE_READY) + { + if((pData == NULL ) || (Size == 0)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(hi2c); + + hi2c->State = HAL_I2C_STATE_SLAVE_BUSY_RX; + hi2c->ErrorCode = HAL_I2C_ERROR_NONE; + + /* Enable Address Acknowledge */ + hi2c->Instance->CR2 &= ~I2C_CR2_NACK; + + /* Wait until ADDR flag is set */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, RESET, Timeout) != HAL_OK) + { + /* Disable Address Acknowledge */ + hi2c->Instance->CR2 |= I2C_CR2_NACK; + return HAL_TIMEOUT; + } + + /* Clear ADDR flag */ + __HAL_I2C_CLEAR_FLAG(hi2c,I2C_FLAG_ADDR); + + /* If 10bit addressing mode is selected */ + if(hi2c->Init.AddressingMode == I2C_ADDRESSINGMODE_10BIT) + { + /* Wait until ADDR flag is set */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, RESET, Timeout) != HAL_OK) + { + /* Disable Address Acknowledge */ + hi2c->Instance->CR2 |= I2C_CR2_NACK; + return HAL_TIMEOUT; + } + + /* Clear ADDR flag */ + __HAL_I2C_CLEAR_FLAG(hi2c,I2C_FLAG_ADDR); + } + + /* Wait until DIR flag is set Transmitter mode */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_DIR, RESET, Timeout) != HAL_OK) + { + /* Disable Address Acknowledge */ + hi2c->Instance->CR2 |= I2C_CR2_NACK; + return HAL_TIMEOUT; + } + + do + { + /* Wait until TXIS flag is set */ + if(I2C_WaitOnTXISFlagUntilTimeout(hi2c, Timeout) != HAL_OK) + { + /* Disable Address Acknowledge */ + hi2c->Instance->CR2 |= I2C_CR2_NACK; + + if(hi2c->ErrorCode == HAL_I2C_ERROR_AF) + { + return HAL_ERROR; + } + else + { + return HAL_TIMEOUT; + } + } + + /* Read data from TXDR */ + hi2c->Instance->TXDR = (*pData++); + Size--; + }while(Size > 0); + + /* Wait until STOP flag is set */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_STOPF, RESET, Timeout) != HAL_OK) + { + /* Disable Address Acknowledge */ + hi2c->Instance->CR2 |= I2C_CR2_NACK; + return HAL_TIMEOUT; + } + + /* Clear STOP flag */ + __HAL_I2C_CLEAR_FLAG(hi2c,I2C_FLAG_STOPF); + + /* Wait until BUSY flag is reset */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, Timeout) != HAL_OK) + { + /* Disable Address Acknowledge */ + hi2c->Instance->CR2 |= I2C_CR2_NACK; + return HAL_TIMEOUT; + } + + /* Disable Address Acknowledge */ + hi2c->Instance->CR2 |= I2C_CR2_NACK; + + hi2c->State = HAL_I2C_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive in slave mode an amount of data in blocking mode + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param pData: Pointer to data buffer + * @param Size: Amount of data to be sent + * @param Timeout: Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2C_Slave_Receive(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size, uint32_t Timeout) +{ + if(hi2c->State == HAL_I2C_STATE_READY) + { + if((pData == NULL ) || (Size == 0)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(hi2c); + + hi2c->State = HAL_I2C_STATE_SLAVE_BUSY_RX; + hi2c->ErrorCode = HAL_I2C_ERROR_NONE; + + /* Enable Address Acknowledge */ + hi2c->Instance->CR2 &= ~I2C_CR2_NACK; + + /* Wait until ADDR flag is set */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, RESET, Timeout) != HAL_OK) + { + /* Disable Address Acknowledge */ + hi2c->Instance->CR2 |= I2C_CR2_NACK; + return HAL_TIMEOUT; + } + + /* Clear ADDR flag */ + __HAL_I2C_CLEAR_FLAG(hi2c,I2C_FLAG_ADDR); + + /* Wait until DIR flag is reset Receiver mode */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_DIR, SET, Timeout) != HAL_OK) + { + /* Disable Address Acknowledge */ + hi2c->Instance->CR2 |= I2C_CR2_NACK; + return HAL_TIMEOUT; + } + + while(Size > 0) + { + /* Wait until RXNE flag is set */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_RXNE, RESET, Timeout) != HAL_OK) + { + /* Disable Address Acknowledge */ + hi2c->Instance->CR2 |= I2C_CR2_NACK; + return HAL_TIMEOUT; + } + + /* Read data from RXDR */ + (*pData++) = hi2c->Instance->RXDR; + Size--; + } + + /* Wait until STOP flag is set */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_STOPF, RESET, Timeout) != HAL_OK) + { + /* Disable Address Acknowledge */ + hi2c->Instance->CR2 |= I2C_CR2_NACK; + return HAL_TIMEOUT; + } + + /* Clear STOP flag */ + __HAL_I2C_CLEAR_FLAG(hi2c,I2C_FLAG_STOPF); + + /* Wait until BUSY flag is reset */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, Timeout) != HAL_OK) + { + /* Disable Address Acknowledge */ + hi2c->Instance->CR2 |= I2C_CR2_NACK; + return HAL_TIMEOUT; + } + + + /* Disable Address Acknowledge */ + hi2c->Instance->CR2 |= I2C_CR2_NACK; + + hi2c->State = HAL_I2C_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Transmit in master mode an amount of data in no-blocking mode with Interrupt + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param DevAddress: Target device address + * @param pData: Pointer to data buffer + * @param Size: Amount of data to be sent + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2C_Master_Transmit_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size) +{ + if(hi2c->State == HAL_I2C_STATE_READY) + { + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) == SET) + { + return HAL_BUSY; + } + + /* Process Locked */ + __HAL_LOCK(hi2c); + + hi2c->State = HAL_I2C_STATE_MASTER_BUSY_TX; + hi2c->ErrorCode = HAL_I2C_ERROR_NONE; + + hi2c->pBuffPtr = pData; + hi2c->XferCount = Size; + if(Size > 255) + { + hi2c->XferSize = 255; + } + else + { + hi2c->XferSize = Size; + } + + /* Send Slave Address */ + /* Set NBYTES to write and reload if size > 255 and generate RESTART */ + if( (hi2c->XferSize == 255) && (hi2c->XferSize < hi2c->XferCount) ) + { + I2C_TransferConfig(hi2c,DevAddress,hi2c->XferSize, I2C_RELOAD_MODE, I2C_GENERATE_START_WRITE); + } + else + { + I2C_TransferConfig(hi2c,DevAddress,hi2c->XferSize, I2C_AUTOEND_MODE, I2C_GENERATE_START_WRITE); + } + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + /* Note : The I2C interrupts must be enabled after unlocking current process + to avoid the risk of I2C interrupt handle execution before current + process unlock */ + + + /* Enable ERR, TC, STOP, NACK, TXI interrupt */ + /* possible to enable all of these */ + /* I2C_IT_ERRI | I2C_IT_TCI| I2C_IT_STOPI| I2C_IT_NACKI | I2C_IT_ADDRI | I2C_IT_RXI | I2C_IT_TXI */ + __HAL_I2C_ENABLE_IT(hi2c,I2C_IT_ERRI | I2C_IT_TCI| I2C_IT_STOPI| I2C_IT_NACKI | I2C_IT_ADDRI | I2C_IT_TXI ); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive in master mode an amount of data in no-blocking mode with Interrupt + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param DevAddress: Target device address + * @param pData: Pointer to data buffer + * @param Size: Amount of data to be sent + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2C_Master_Receive_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size) +{ + if(hi2c->State == HAL_I2C_STATE_READY) + { + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) == SET) + { + return HAL_BUSY; + } + + /* Process Locked */ + __HAL_LOCK(hi2c); + + hi2c->State = HAL_I2C_STATE_MASTER_BUSY_RX; + hi2c->ErrorCode = HAL_I2C_ERROR_NONE; + + hi2c->pBuffPtr = pData; + hi2c->XferCount = Size; + if(Size > 255) + { + hi2c->XferSize = 255; + } + else + { + hi2c->XferSize = Size; + } + + /* Send Slave Address */ + /* Set NBYTES to write and reload if size > 255 and generate RESTART */ + if( (hi2c->XferSize == 255) && (hi2c->XferSize < hi2c->XferCount) ) + { + I2C_TransferConfig(hi2c,DevAddress,hi2c->XferSize, I2C_RELOAD_MODE, I2C_GENERATE_START_READ); + } + else + { + I2C_TransferConfig(hi2c,DevAddress,hi2c->XferSize, I2C_AUTOEND_MODE, I2C_GENERATE_START_READ); + } + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + /* Note : The I2C interrupts must be enabled after unlocking current process + to avoid the risk of I2C interrupt handle execution before current + process unlock */ + + /* Enable ERR, TC, STOP, NACK, RXI interrupt */ + /* possible to enable all of these */ + /* I2C_IT_ERRI | I2C_IT_TCI| I2C_IT_STOPI| I2C_IT_NACKI | I2C_IT_ADDRI | I2C_IT_RXI | I2C_IT_TXI */ + __HAL_I2C_ENABLE_IT(hi2c,I2C_IT_ERRI | I2C_IT_TCI | I2C_IT_STOPI | I2C_IT_NACKI | I2C_IT_ADDRI | I2C_IT_RXI ); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Transmit in slave mode an amount of data in no-blocking mode with Interrupt + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param pData: Pointer to data buffer + * @param Size: Amount of data to be sent + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2C_Slave_Transmit_IT(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size) +{ + if(hi2c->State == HAL_I2C_STATE_READY) + { + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(hi2c); + + hi2c->State = HAL_I2C_STATE_SLAVE_BUSY_TX; + hi2c->ErrorCode = HAL_I2C_ERROR_NONE; + + /* Enable Address Acknowledge */ + hi2c->Instance->CR2 &= ~I2C_CR2_NACK; + + hi2c->pBuffPtr = pData; + hi2c->XferSize = Size; + hi2c->XferCount = Size; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + /* Note : The I2C interrupts must be enabled after unlocking current process + to avoid the risk of I2C interrupt handle execution before current + process unlock */ + + /* Enable ERR, TC, STOP, NACK, TXI interrupt */ + /* possible to enable all of these */ + /* I2C_IT_ERRI | I2C_IT_TCI| I2C_IT_STOPI| I2C_IT_NACKI | I2C_IT_ADDRI | I2C_IT_RXI | I2C_IT_TXI */ + __HAL_I2C_ENABLE_IT(hi2c,I2C_IT_ERRI | I2C_IT_TCI| I2C_IT_STOPI | I2C_IT_NACKI | I2C_IT_ADDRI | I2C_IT_TXI ); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive in slave mode an amount of data in no-blocking mode with Interrupt + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param pData: Pointer to data buffer + * @param Size: Amount of data to be sent + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2C_Slave_Receive_IT(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size) +{ + if(hi2c->State == HAL_I2C_STATE_READY) + { + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(hi2c); + + hi2c->State = HAL_I2C_STATE_SLAVE_BUSY_RX; + hi2c->ErrorCode = HAL_I2C_ERROR_NONE; + + /* Enable Address Acknowledge */ + hi2c->Instance->CR2 &= ~I2C_CR2_NACK; + + hi2c->pBuffPtr = pData; + hi2c->XferSize = Size; + hi2c->XferCount = Size; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + /* Note : The I2C interrupts must be enabled after unlocking current process + to avoid the risk of I2C interrupt handle execution before current + process unlock */ + + /* Enable ERR, TC, STOP, NACK, RXI interrupt */ + /* possible to enable all of these */ + /* I2C_IT_ERRI | I2C_IT_TCI| I2C_IT_STOPI| I2C_IT_NACKI | I2C_IT_ADDRI | I2C_IT_RXI | I2C_IT_TXI */ + __HAL_I2C_ENABLE_IT(hi2c,I2C_IT_ERRI | I2C_IT_TCI | I2C_IT_STOPI | I2C_IT_NACKI | I2C_IT_ADDRI | I2C_IT_RXI); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Transmit in master mode an amount of data in no-blocking mode with DMA + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param DevAddress: Target device address + * @param pData: Pointer to data buffer + * @param Size: Amount of data to be sent + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2C_Master_Transmit_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size) +{ + if(hi2c->State == HAL_I2C_STATE_READY) + { + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) == SET) + { + return HAL_BUSY; + } + + /* Process Locked */ + __HAL_LOCK(hi2c); + + hi2c->State = HAL_I2C_STATE_MASTER_BUSY_TX; + hi2c->ErrorCode = HAL_I2C_ERROR_NONE; + + hi2c->pBuffPtr = pData; + hi2c->XferCount = Size; + if(Size > 255) + { + hi2c->XferSize = 255; + } + else + { + hi2c->XferSize = Size; + } + + /* Set the I2C DMA transfer complete callback */ + hi2c->hdmatx->XferCpltCallback = I2C_DMAMasterTransmitCplt; + + /* Set the DMA error callback */ + hi2c->hdmatx->XferErrorCallback = I2C_DMAError; + + /* Enable the DMA channel */ + HAL_DMA_Start_IT(hi2c->hdmatx, (uint32_t)pData, (uint32_t)&hi2c->Instance->TXDR, hi2c->XferSize); + + /* Send Slave Address */ + /* Set NBYTES to write and reload if size > 255 and generate RESTART */ + if( (hi2c->XferSize == 255) && (hi2c->XferSize < hi2c->XferCount) ) + { + I2C_TransferConfig(hi2c,DevAddress,hi2c->XferSize, I2C_RELOAD_MODE, I2C_GENERATE_START_WRITE); + } + else + { + I2C_TransferConfig(hi2c,DevAddress,hi2c->XferSize, I2C_AUTOEND_MODE, I2C_GENERATE_START_WRITE); + } + + /* Wait until TXIS flag is set */ + if(I2C_WaitOnTXISFlagUntilTimeout(hi2c, I2C_TIMEOUT_TXIS) != HAL_OK) + { + /* Disable Address Acknowledge */ + hi2c->Instance->CR2 |= I2C_CR2_NACK; + + if(hi2c->ErrorCode == HAL_I2C_ERROR_AF) + { + return HAL_ERROR; + } + else + { + return HAL_TIMEOUT; + } + } + + + /* Enable DMA Request */ + hi2c->Instance->CR1 |= I2C_CR1_TXDMAEN; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive in master mode an amount of data in no-blocking mode with DMA + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param DevAddress: Target device address + * @param pData: Pointer to data buffer + * @param Size: Amount of data to be sent + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2C_Master_Receive_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size) +{ + if(hi2c->State == HAL_I2C_STATE_READY) + { + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) == SET) + { + return HAL_BUSY; + } + + /* Process Locked */ + __HAL_LOCK(hi2c); + + hi2c->State = HAL_I2C_STATE_MASTER_BUSY_RX; + hi2c->ErrorCode = HAL_I2C_ERROR_NONE; + + hi2c->pBuffPtr = pData; + hi2c->XferCount = Size; + if(Size > 255) + { + hi2c->XferSize = 255; + } + else + { + hi2c->XferSize = Size; + } + + /* Set the I2C DMA transfer complete callback */ + hi2c->hdmarx->XferCpltCallback = I2C_DMAMasterReceiveCplt; + + /* Set the DMA error callback */ + hi2c->hdmarx->XferErrorCallback = I2C_DMAError; + + /* Enable the DMA channel */ + HAL_DMA_Start_IT(hi2c->hdmarx, (uint32_t)&hi2c->Instance->RXDR, (uint32_t)pData, hi2c->XferSize); + + /* Send Slave Address */ + /* Set NBYTES to write and reload if size > 255 and generate RESTART */ + if( (hi2c->XferSize == 255) && (hi2c->XferSize < hi2c->XferCount) ) + { + I2C_TransferConfig(hi2c,DevAddress,hi2c->XferSize, I2C_RELOAD_MODE, I2C_GENERATE_START_READ); + } + else + { + I2C_TransferConfig(hi2c,DevAddress,hi2c->XferSize, I2C_AUTOEND_MODE, I2C_GENERATE_START_READ); + } + + /* Wait until RXNE flag is set */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_RXNE, RESET, I2C_TIMEOUT_RXNE) != HAL_OK) + { + return HAL_TIMEOUT; + } + + + /* Enable DMA Request */ + hi2c->Instance->CR1 |= I2C_CR1_RXDMAEN; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Transmit in slave mode an amount of data in no-blocking mode with DMA + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param pData: Pointer to data buffer + * @param Size: Amount of data to be sent + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2C_Slave_Transmit_DMA(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size) +{ + if(hi2c->State == HAL_I2C_STATE_READY) + { + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + /* Process Locked */ + __HAL_LOCK(hi2c); + + hi2c->State = HAL_I2C_STATE_SLAVE_BUSY_TX; + hi2c->ErrorCode = HAL_I2C_ERROR_NONE; + + hi2c->pBuffPtr = pData; + hi2c->XferCount = Size; + hi2c->XferSize = Size; + + /* Set the I2C DMA transfer complete callback */ + hi2c->hdmatx->XferCpltCallback = I2C_DMASlaveTransmitCplt; + + /* Set the DMA error callback */ + hi2c->hdmatx->XferErrorCallback = I2C_DMAError; + + /* Enable the DMA channel */ + HAL_DMA_Start_IT(hi2c->hdmatx, (uint32_t)pData, (uint32_t)&hi2c->Instance->TXDR, hi2c->XferSize); + + /* Enable Address Acknowledge */ + hi2c->Instance->CR2 &= ~I2C_CR2_NACK; + + /* Wait until ADDR flag is set */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, RESET, I2C_TIMEOUT_ADDR) != HAL_OK) + { + /* Disable Address Acknowledge */ + hi2c->Instance->CR2 |= I2C_CR2_NACK; + return HAL_TIMEOUT; + } + + + /* Clear ADDR flag */ + __HAL_I2C_CLEAR_FLAG(hi2c,I2C_FLAG_ADDR); + + /* If 10bits addressing mode is selected */ + if(hi2c->Init.AddressingMode == I2C_ADDRESSINGMODE_10BIT) + { + /* Wait until ADDR flag is set */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, RESET, I2C_TIMEOUT_ADDR) != HAL_OK) + { + /* Disable Address Acknowledge */ + hi2c->Instance->CR2 |= I2C_CR2_NACK; + return HAL_TIMEOUT; + } + + /* Clear ADDR flag */ + __HAL_I2C_CLEAR_FLAG(hi2c,I2C_FLAG_ADDR); + } + + /* Wait until DIR flag is set Transmitter mode */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_DIR, RESET, I2C_TIMEOUT_BUSY) != HAL_OK) + { + /* Disable Address Acknowledge */ + hi2c->Instance->CR2 |= I2C_CR2_NACK; + return HAL_TIMEOUT; + } + + /* Enable DMA Request */ + hi2c->Instance->CR1 |= I2C_CR1_TXDMAEN; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive in slave mode an amount of data in no-blocking mode with DMA + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param pData: Pointer to data buffer + * @param Size: Amount of data to be sent + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2C_Slave_Receive_DMA(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size) +{ + if(hi2c->State == HAL_I2C_STATE_READY) + { + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + /* Process Locked */ + __HAL_LOCK(hi2c); + + hi2c->State = HAL_I2C_STATE_SLAVE_BUSY_RX; + hi2c->ErrorCode = HAL_I2C_ERROR_NONE; + + hi2c->pBuffPtr = pData; + hi2c->XferSize = Size; + hi2c->XferCount = Size; + + /* Set the I2C DMA transfer complete callback */ + hi2c->hdmarx->XferCpltCallback = I2C_DMASlaveReceiveCplt; + + /* Set the DMA error callback */ + hi2c->hdmarx->XferErrorCallback = I2C_DMAError; + + /* Enable the DMA channel */ + HAL_DMA_Start_IT(hi2c->hdmarx, (uint32_t)&hi2c->Instance->RXDR, (uint32_t)pData, Size); + + /* Enable Address Acknowledge */ + hi2c->Instance->CR2 &= ~I2C_CR2_NACK; + + /* Wait until ADDR flag is set */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, RESET, I2C_TIMEOUT_ADDR) != HAL_OK) + { + /* Disable Address Acknowledge */ + hi2c->Instance->CR2 |= I2C_CR2_NACK; + return HAL_TIMEOUT; + } + + + /* Clear ADDR flag */ + __HAL_I2C_CLEAR_FLAG(hi2c,I2C_FLAG_ADDR); + + /* Wait until DIR flag is set Receiver mode */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_DIR, SET, I2C_TIMEOUT_DIR) != HAL_OK) + { + /* Disable Address Acknowledge */ + hi2c->Instance->CR2 |= I2C_CR2_NACK; + return HAL_TIMEOUT; + } + + /* Enable DMA Request */ + hi2c->Instance->CR1 |= I2C_CR1_RXDMAEN; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} +/** + * @brief Write an amount of data in blocking mode to a specific memory address + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param DevAddress: Target device address + * @param MemAddress: Internal memory address + * @param MemAddSize: Size of internal memory address + * @param pData: Pointer to data buffer + * @param Size: Amount of data to be sent + * @param Timeout: Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2C_Mem_Write(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size, uint32_t Timeout) +{ + uint32_t Sizetmp = 0; + + /* Check the parameters */ + assert_param(IS_I2C_MEMADD_SIZE(MemAddSize)); + + if(hi2c->State == HAL_I2C_STATE_READY) + { + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) == SET) + { + return HAL_BUSY; + } + + /* Process Locked */ + __HAL_LOCK(hi2c); + + hi2c->State = HAL_I2C_STATE_MEM_BUSY_TX; + hi2c->ErrorCode = HAL_I2C_ERROR_NONE; + + /* Send Slave Address and Memory Address */ + if(I2C_RequestMemoryWrite(hi2c, DevAddress, MemAddress, MemAddSize, Timeout) != HAL_OK) + { + if(hi2c->ErrorCode == HAL_I2C_ERROR_AF) + { + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + return HAL_ERROR; + } + else + { + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + return HAL_TIMEOUT; + } + } + + /* Set NBYTES to write and reload if size > 255 and generate RESTART */ + /* Size > 255, need to set RELOAD bit */ + if(Size > 255) + { + I2C_TransferConfig(hi2c,DevAddress,255, I2C_RELOAD_MODE, I2C_NO_STARTSTOP); + Sizetmp = 255; + } + else + { + I2C_TransferConfig(hi2c,DevAddress,Size, I2C_AUTOEND_MODE, I2C_NO_STARTSTOP); + Sizetmp = Size; + } + + do + { + /* Wait until TXIS flag is set */ + if(I2C_WaitOnTXISFlagUntilTimeout(hi2c, Timeout) != HAL_OK) + { + if(hi2c->ErrorCode == HAL_I2C_ERROR_AF) + { + return HAL_ERROR; + } + else + { + return HAL_TIMEOUT; + } + } + + /* Write data to DR */ + hi2c->Instance->TXDR = (*pData++); + Sizetmp--; + Size--; + + if((Sizetmp == 0)&&(Size!=0)) + { + /* Wait until TCR flag is set */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_TCR, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + + if(Size > 255) + { + I2C_TransferConfig(hi2c,DevAddress,255, I2C_RELOAD_MODE, I2C_NO_STARTSTOP); + Sizetmp = 255; + } + else + { + I2C_TransferConfig(hi2c,DevAddress,Size, I2C_AUTOEND_MODE, I2C_NO_STARTSTOP); + Sizetmp = Size; + } + } + + }while(Size > 0); + + /* No need to Check TC flag, with AUTOEND mode the stop is automatically generated */ + /* Wait until STOPF flag is reset */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_STOPF, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + /* Clear STOP Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); + + /* Clear Configuration Register 2 */ + __HAL_I2C_RESET_CR2(hi2c); + + hi2c->State = HAL_I2C_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Read an amount of data in blocking mode from a specific memory address + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param DevAddress: Target device address + * @param MemAddress: Internal memory address + * @param MemAddSize: Size of internal memory address + * @param pData: Pointer to data buffer + * @param Size: Amount of data to be sent + * @param Timeout: Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2C_Mem_Read(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size, uint32_t Timeout) +{ + uint32_t Sizetmp = 0; + + /* Check the parameters */ + assert_param(IS_I2C_MEMADD_SIZE(MemAddSize)); + + if(hi2c->State == HAL_I2C_STATE_READY) + { + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) == SET) + { + return HAL_BUSY; + } + + /* Process Locked */ + __HAL_LOCK(hi2c); + + hi2c->State = HAL_I2C_STATE_MEM_BUSY_RX; + hi2c->ErrorCode = HAL_I2C_ERROR_NONE; + + /* Send Slave Address and Memory Address */ + if(I2C_RequestMemoryRead(hi2c, DevAddress, MemAddress, MemAddSize, Timeout) != HAL_OK) + { + if(hi2c->ErrorCode == HAL_I2C_ERROR_AF) + { + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + return HAL_ERROR; + } + else + { + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + return HAL_TIMEOUT; + } + } + + /* Send Slave Address */ + /* Set NBYTES to write and reload if size > 255 and generate RESTART */ + /* Size > 255, need to set RELOAD bit */ + if(Size > 255) + { + I2C_TransferConfig(hi2c,DevAddress,255, I2C_RELOAD_MODE, I2C_GENERATE_START_READ); + Sizetmp = 255; + } + else + { + I2C_TransferConfig(hi2c,DevAddress,Size, I2C_AUTOEND_MODE, I2C_GENERATE_START_READ); + Sizetmp = Size; + } + + do + { + /* Wait until RXNE flag is set */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_RXNE, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + /* Read data from RXDR */ + (*pData++) = hi2c->Instance->RXDR; + + /* Decrement the Size counter */ + Sizetmp--; + Size--; + + if((Sizetmp == 0)&&(Size!=0)) + { + /* Wait until TCR flag is set */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_TCR, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + if(Size > 255) + { + I2C_TransferConfig(hi2c,DevAddress,255, I2C_RELOAD_MODE, I2C_NO_STARTSTOP); + Sizetmp = 255; + } + else + { + I2C_TransferConfig(hi2c,DevAddress,Size, I2C_AUTOEND_MODE, I2C_NO_STARTSTOP); + Sizetmp = Size; + } + } + + }while(Size > 0); + + /* No need to Check TC flag, with AUTOEND mode the stop is automatically generated */ + /* Wait until STOPF flag is reset */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_STOPF, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + /* Clear STOP Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); + + /* Clear Configuration Register 2 */ + __HAL_I2C_RESET_CR2(hi2c); + + hi2c->State = HAL_I2C_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} +/** + * @brief Write an amount of data in no-blocking mode with Interrupt to a specific memory address + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param DevAddress: Target device address + * @param MemAddress: Internal memory address + * @param MemAddSize: Size of internal memory address + * @param pData: Pointer to data buffer + * @param Size: Amount of data to be sent + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2C_Mem_Write_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size) +{ + /* Check the parameters */ + assert_param(IS_I2C_MEMADD_SIZE(MemAddSize)); + + if(hi2c->State == HAL_I2C_STATE_READY) + { + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) == SET) + { + return HAL_BUSY; + } + + /* Process Locked */ + __HAL_LOCK(hi2c); + + hi2c->State = HAL_I2C_STATE_MEM_BUSY_TX; + hi2c->ErrorCode = HAL_I2C_ERROR_NONE; + + hi2c->pBuffPtr = pData; + hi2c->XferCount = Size; + if(Size > 255) + { + hi2c->XferSize = 255; + } + else + { + hi2c->XferSize = Size; + } + + /* Send Slave Address and Memory Address */ + if(I2C_RequestMemoryWrite(hi2c, DevAddress, MemAddress, MemAddSize, I2C_TIMEOUT_FLAG) != HAL_OK) + { + if(hi2c->ErrorCode == HAL_I2C_ERROR_AF) + { + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + return HAL_ERROR; + } + else + { + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + return HAL_TIMEOUT; + } + } + + /* Set NBYTES to write and reload if size > 255 and generate RESTART */ + /* Size > 255, need to set RELOAD bit */ + /* Set NBYTES to write and reload if size > 255 and generate RESTART */ + if( (hi2c->XferSize == 255) && (hi2c->XferSize < hi2c->XferCount) ) + { + I2C_TransferConfig(hi2c,DevAddress,hi2c->XferSize, I2C_RELOAD_MODE, I2C_NO_STARTSTOP); + } + else + { + I2C_TransferConfig(hi2c,DevAddress,hi2c->XferSize, I2C_AUTOEND_MODE, I2C_NO_STARTSTOP); + } + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + /* Note : The I2C interrupts must be enabled after unlocking current process + to avoid the risk of I2C interrupt handle execution before current + process unlock */ + + /* Enable ERR, TC, STOP, NACK, TXI interrupt */ + /* possible to enable all of these */ + /* I2C_IT_ERRI | I2C_IT_TCI| I2C_IT_STOPI| I2C_IT_NACKI | I2C_IT_ADDRI | I2C_IT_RXI | I2C_IT_TXI */ + __HAL_I2C_ENABLE_IT(hi2c,I2C_IT_ERRI | I2C_IT_TCI| I2C_IT_STOPI| I2C_IT_NACKI | I2C_IT_ADDRI | I2C_IT_TXI ); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Read an amount of data in no-blocking mode with Interrupt from a specific memory address + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param DevAddress: Target device address + * @param MemAddress: Internal memory address + * @param MemAddSize: Size of internal memory address + * @param pData: Pointer to data buffer + * @param Size: Amount of data to be sent + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2C_Mem_Read_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size) +{ + /* Check the parameters */ + assert_param(IS_I2C_MEMADD_SIZE(MemAddSize)); + + if(hi2c->State == HAL_I2C_STATE_READY) + { + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) == SET) + { + return HAL_BUSY; + } + + /* Process Locked */ + __HAL_LOCK(hi2c); + + hi2c->State = HAL_I2C_STATE_MEM_BUSY_RX; + + hi2c->pBuffPtr = pData; + hi2c->XferCount = Size; + if(Size > 255) + { + hi2c->XferSize = 255; + } + else + { + hi2c->XferSize = Size; + } + + /* Send Slave Address and Memory Address */ + if(I2C_RequestMemoryRead(hi2c, DevAddress, MemAddress, MemAddSize, I2C_TIMEOUT_FLAG) != HAL_OK) + { + if(hi2c->ErrorCode == HAL_I2C_ERROR_AF) + { + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + return HAL_ERROR; + } + else + { + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + return HAL_TIMEOUT; + } + } + + /* Set NBYTES to write and reload if size > 255 and generate RESTART */ + /* Size > 255, need to set RELOAD bit */ + /* Set NBYTES to read and reload if size > 255 and generate RESTART */ + if( (hi2c->XferSize == 255) && (hi2c->XferSize < hi2c->XferCount) ) + { + I2C_TransferConfig(hi2c,DevAddress,hi2c->XferSize, I2C_RELOAD_MODE, I2C_GENERATE_START_READ); + } + else + { + I2C_TransferConfig(hi2c,DevAddress,hi2c->XferSize, I2C_AUTOEND_MODE, I2C_GENERATE_START_READ); + } + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + /* Note : The I2C interrupts must be enabled after unlocking current process + to avoid the risk of I2C interrupt handle execution before current + process unlock */ + + /* Enable ERR, TC, STOP, NACK, RXI interrupt */ + /* possible to enable all of these */ + /* I2C_IT_ERRI | I2C_IT_TCI| I2C_IT_STOPI| I2C_IT_NACKI | I2C_IT_ADDRI | I2C_IT_RXI | I2C_IT_TXI */ + __HAL_I2C_ENABLE_IT(hi2c, I2C_IT_ERRI | I2C_IT_TCI| I2C_IT_STOPI| I2C_IT_NACKI | I2C_IT_ADDRI | I2C_IT_RXI ); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} +/** + * @brief Write an amount of data in no-blocking mode with DMA to a specific memory address + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param DevAddress: Target device address + * @param MemAddress: Internal memory address + * @param MemAddSize: Size of internal memory address + * @param pData: Pointer to data buffer + * @param Size: Amount of data to be sent + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2C_Mem_Write_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size) +{ + /* Check the parameters */ + assert_param(IS_I2C_MEMADD_SIZE(MemAddSize)); + + if(hi2c->State == HAL_I2C_STATE_READY) + { + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) == SET) + { + return HAL_BUSY; + } + + /* Process Locked */ + __HAL_LOCK(hi2c); + + hi2c->State = HAL_I2C_STATE_MEM_BUSY_TX; + hi2c->ErrorCode = HAL_I2C_ERROR_NONE; + + hi2c->pBuffPtr = pData; + hi2c->XferCount = Size; + if(Size > 255) + { + hi2c->XferSize = 255; + } + else + { + hi2c->XferSize = Size; + } + + /* Set the I2C DMA transfer complete callback */ + hi2c->hdmatx->XferCpltCallback = I2C_DMAMemTransmitCplt; + + /* Set the DMA error callback */ + hi2c->hdmatx->XferErrorCallback = I2C_DMAError; + + /* Enable the DMA channel */ + HAL_DMA_Start_IT(hi2c->hdmatx, (uint32_t)pData, (uint32_t)&hi2c->Instance->TXDR, hi2c->XferSize); + + /* Send Slave Address and Memory Address */ + if(I2C_RequestMemoryWrite(hi2c, DevAddress, MemAddress, MemAddSize, I2C_TIMEOUT_FLAG) != HAL_OK) + { + if(hi2c->ErrorCode == HAL_I2C_ERROR_AF) + { + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + return HAL_ERROR; + } + else + { + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + return HAL_TIMEOUT; + } + } + + /* Send Slave Address */ + /* Set NBYTES to write and reload if size > 255 and generate RESTART */ + if( (hi2c->XferSize == 255) && (hi2c->XferSize < hi2c->XferCount) ) + { + I2C_TransferConfig(hi2c,DevAddress,hi2c->XferSize, I2C_RELOAD_MODE, I2C_NO_STARTSTOP); + } + else + { + I2C_TransferConfig(hi2c,DevAddress,hi2c->XferSize, I2C_AUTOEND_MODE, I2C_NO_STARTSTOP); + } + + /* Wait until TXIS flag is set */ + if(I2C_WaitOnTXISFlagUntilTimeout(hi2c, I2C_TIMEOUT_TXIS) != HAL_OK) + { + if(hi2c->ErrorCode == HAL_I2C_ERROR_AF) + { + return HAL_ERROR; + } + else + { + return HAL_TIMEOUT; + } + } + + /* Enable DMA Request */ + hi2c->Instance->CR1 |= I2C_CR1_TXDMAEN; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Reads an amount of data in no-blocking mode with DMA from a specific memory address. + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param DevAddress: Target device address + * @param MemAddress: Internal memory address + * @param MemAddSize: Size of internal memory address + * @param pData: Pointer to data buffer + * @param Size: Amount of data to be read + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2C_Mem_Read_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size) +{ + /* Check the parameters */ + assert_param(IS_I2C_MEMADD_SIZE(MemAddSize)); + + if(hi2c->State == HAL_I2C_STATE_READY) + { + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) == SET) + { + return HAL_BUSY; + } + + /* Process Locked */ + __HAL_LOCK(hi2c); + + hi2c->State = HAL_I2C_STATE_MEM_BUSY_RX; + + hi2c->pBuffPtr = pData; + hi2c->XferCount = Size; + if(Size > 255) + { + hi2c->XferSize = 255; + } + else + { + hi2c->XferSize = Size; + } + + /* Set the I2C DMA transfer complete callback */ + hi2c->hdmarx->XferCpltCallback = I2C_DMAMemReceiveCplt; + + /* Set the DMA error callback */ + hi2c->hdmarx->XferErrorCallback = I2C_DMAError; + + /* Enable the DMA channel */ + HAL_DMA_Start_IT(hi2c->hdmarx, (uint32_t)&hi2c->Instance->RXDR, (uint32_t)pData, hi2c->XferSize); + + /* Send Slave Address and Memory Address */ + if(I2C_RequestMemoryRead(hi2c, DevAddress, MemAddress, MemAddSize, I2C_TIMEOUT_FLAG) != HAL_OK) + { + if(hi2c->ErrorCode == HAL_I2C_ERROR_AF) + { + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + return HAL_ERROR; + } + else + { + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + return HAL_TIMEOUT; + } + } + + /* Set NBYTES to write and reload if size > 255 and generate RESTART */ + if( (hi2c->XferSize == 255) && (hi2c->XferSize < hi2c->XferCount) ) + { + I2C_TransferConfig(hi2c,DevAddress,hi2c->XferSize, I2C_RELOAD_MODE, I2C_GENERATE_START_READ); + } + else + { + I2C_TransferConfig(hi2c,DevAddress,hi2c->XferSize, I2C_AUTOEND_MODE, I2C_GENERATE_START_READ); + } + + /* Wait until RXNE flag is set */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_RXNE, RESET, I2C_TIMEOUT_RXNE) != HAL_OK) + { + return HAL_TIMEOUT; + } + + /* Enable DMA Request */ + hi2c->Instance->CR1 |= I2C_CR1_RXDMAEN; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Checks if target device is ready for communication. + * @note This function is used with Memory devices + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param DevAddress: Target device address + * @param Trials: Number of trials + * @param Timeout: Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2C_IsDeviceReady(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint32_t Trials, uint32_t Timeout) +{ + uint32_t tickstart = 0; + + __IO uint32_t I2C_Trials = 0; + + if(hi2c->State == HAL_I2C_STATE_READY) + { + if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) == SET) + { + return HAL_BUSY; + } + + /* Process Locked */ + __HAL_LOCK(hi2c); + + hi2c->State = HAL_I2C_STATE_BUSY; + hi2c->ErrorCode = HAL_I2C_ERROR_NONE; + + do + { + /* Generate Start */ + hi2c->Instance->CR2 = __HAL_I2C_GENERATE_START(hi2c->Init.AddressingMode,DevAddress); + + /* No need to Check TC flag, with AUTOEND mode the stop is automatically generated */ + /* Wait until STOPF flag is set or a NACK flag is set*/ + tickstart = HAL_GetTick(); + while((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_STOPF) == RESET) && (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_AF) == RESET) && (hi2c->State != HAL_I2C_STATE_TIMEOUT)) + { + if(Timeout != HAL_MAX_DELAY) + { + if((HAL_GetTick() - tickstart) > Timeout) + { + /* Device is ready */ + hi2c->State = HAL_I2C_STATE_READY; + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + return HAL_TIMEOUT; + } + } + } + + /* Check if the NACKF flag has not been set */ + if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_AF) == RESET) + { + /* Wait until STOPF flag is reset */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_STOPF, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + /* Clear STOP Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); + + /* Device is ready */ + hi2c->State = HAL_I2C_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_OK; + } + else + { + /* Wait until STOPF flag is reset */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_STOPF, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + /* Clear NACK Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); + + /* Clear STOP Flag, auto generated with autoend*/ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); + } + + /* Check if the maximum allowed numbe of trials has bee reached */ + if (I2C_Trials == Trials) + { + /* Generate Stop */ + hi2c->Instance->CR2 |= I2C_CR2_STOP; + + /* Wait until STOPF flag is reset */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_STOPF, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + /* Clear STOP Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); + } + }while(I2C_Trials++ < Trials); + + hi2c->State = HAL_I2C_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_TIMEOUT; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief This function handles I2C event interrupt request. + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @retval None + */ +void HAL_I2C_EV_IRQHandler(I2C_HandleTypeDef *hi2c) +{ + /* I2C in mode Transmitter ---------------------------------------------------*/ + if (((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_TXIS) == SET) || (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_TCR) == SET) || (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_TC) == SET) || (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_STOPF) == SET) || (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_AF) == SET) || (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_ADDR) == SET)) && (__HAL_I2C_GET_IT_SOURCE(hi2c, (I2C_IT_TCI | I2C_IT_STOPI | I2C_IT_NACKI | I2C_IT_TXI | I2C_IT_ADDRI)) == SET)) + { + /* Slave mode selected */ + if (hi2c->State == HAL_I2C_STATE_SLAVE_BUSY_TX) + { + I2C_SlaveTransmit_ISR(hi2c); + } + /* Master mode selected */ + else + { + I2C_MasterTransmit_ISR(hi2c); + } + } + + /* I2C in mode Receiver ----------------------------------------------------*/ + if (((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_RXNE) == SET) || (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_TCR) == SET) || (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_TC) == SET) || (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_STOPF) == SET) || (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_AF) == SET) || (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_ADDR) == SET)) && (__HAL_I2C_GET_IT_SOURCE(hi2c, (I2C_IT_TCI| I2C_IT_STOPI| I2C_IT_NACKI | I2C_IT_RXI | I2C_IT_ADDRI)) == SET)) + { + /* Slave mode selected */ + if (hi2c->State == HAL_I2C_STATE_SLAVE_BUSY_RX) + { + I2C_SlaveReceive_ISR(hi2c); + } + /* Master mode selected */ + else + { + I2C_MasterReceive_ISR(hi2c); + } + } +} + +/** + * @brief This function handles I2C error interrupt request. + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @retval None + */ +void HAL_I2C_ER_IRQHandler(I2C_HandleTypeDef *hi2c) +{ + /* I2C Bus error interrupt occurred ------------------------------------*/ + if((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BERR) == SET) && (__HAL_I2C_GET_IT_SOURCE(hi2c, I2C_IT_ERRI) == SET)) + { + hi2c->ErrorCode |= HAL_I2C_ERROR_BERR; + + /* Clear BERR flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_BERR); + } + + /* I2C Over-Run/Under-Run interrupt occurred ----------------------------------------*/ + if((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_OVR) == SET) && (__HAL_I2C_GET_IT_SOURCE(hi2c, I2C_IT_ERRI) == SET)) + { + hi2c->ErrorCode |= HAL_I2C_ERROR_OVR; + + /* Clear OVR flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_OVR); + } + + /* I2C Arbitration Loss error interrupt occurred -------------------------------------*/ + if((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_ARLO) == SET) && (__HAL_I2C_GET_IT_SOURCE(hi2c, I2C_IT_ERRI) == SET)) + { + hi2c->ErrorCode |= HAL_I2C_ERROR_ARLO; + + /* Clear ARLO flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_ARLO); + } + + /* Call the Error Callback in case of Error detected */ + if(hi2c->ErrorCode != HAL_I2C_ERROR_NONE) + { + hi2c->State = HAL_I2C_STATE_READY; + + HAL_I2C_ErrorCallback(hi2c); + } +} + +/** + * @brief Master Tx Transfer completed callbacks. + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @retval None + */ + __weak void HAL_I2C_MasterTxCpltCallback(I2C_HandleTypeDef *hi2c) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_I2C_TxCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Master Rx Transfer completed callbacks. + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @retval None + */ +__weak void HAL_I2C_MasterRxCpltCallback(I2C_HandleTypeDef *hi2c) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_I2C_TxCpltCallback could be implemented in the user file + */ +} + +/** @brief Slave Tx Transfer completed callbacks. + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @retval None + */ + __weak void HAL_I2C_SlaveTxCpltCallback(I2C_HandleTypeDef *hi2c) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_I2C_TxCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Slave Rx Transfer completed callbacks. + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @retval None + */ +__weak void HAL_I2C_SlaveRxCpltCallback(I2C_HandleTypeDef *hi2c) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_I2C_TxCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Memory Tx Transfer completed callbacks. + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @retval None + */ + __weak void HAL_I2C_MemTxCpltCallback(I2C_HandleTypeDef *hi2c) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_I2C_TxCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Memory Rx Transfer completed callbacks. + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @retval None + */ +__weak void HAL_I2C_MemRxCpltCallback(I2C_HandleTypeDef *hi2c) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_I2C_TxCpltCallback could be implemented in the user file + */ +} + +/** + * @brief I2C error callbacks. + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @retval None + */ + __weak void HAL_I2C_ErrorCallback(I2C_HandleTypeDef *hi2c) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_I2C_ErrorCallback could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup I2C_Group3 Peripheral State and Errors functions + * @brief Peripheral State and Errors functions + * +@verbatim + =============================================================================== + ##### Peripheral State and Errors functions ##### + =============================================================================== + [..] + This subsection permit to get in run-time the status of the peripheral + and the data flow. + +@endverbatim + * @{ + */ + +/** + * @brief Returns the I2C state. + * @param hi2c : I2C handle + * @retval HAL state + */ +HAL_I2C_StateTypeDef HAL_I2C_GetState(I2C_HandleTypeDef *hi2c) +{ + return hi2c->State; +} + +/** +* @brief Return the I2C error code +* @param hi2c : pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. +* @retval I2C Error Code +*/ +uint32_t HAL_I2C_GetError(I2C_HandleTypeDef *hi2c) +{ + return hi2c->ErrorCode; +} + +/** + * @} + */ + +/** + * @brief Handle Interrupt Flags Master Transmit Mode + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @retval HAL status + */ +static HAL_StatusTypeDef I2C_MasterTransmit_ISR(I2C_HandleTypeDef *hi2c) +{ + uint16_t DevAddress; + + /* Process Locked */ + __HAL_LOCK(hi2c); + + if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_TXIS) == SET) + { + /* Write data to TXDR */ + hi2c->Instance->TXDR = (*hi2c->pBuffPtr++); + hi2c->XferSize--; + hi2c->XferCount--; + + } + else if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_TCR) == SET) + { + if((hi2c->XferSize == 0)&&(hi2c->XferCount!=0)) + { + DevAddress = (hi2c->Instance->CR2 & I2C_CR2_SADD); + + if(hi2c->XferCount > 255) + { + I2C_TransferConfig(hi2c,DevAddress,255, I2C_RELOAD_MODE, I2C_NO_STARTSTOP); + hi2c->XferSize = 255; + } + else + { + I2C_TransferConfig(hi2c,DevAddress,hi2c->XferCount, I2C_AUTOEND_MODE, I2C_NO_STARTSTOP); + hi2c->XferSize = hi2c->XferCount; + } + } + else + { + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + /* Wrong size Status regarding TCR flag event */ + hi2c->ErrorCode |= HAL_I2C_ERROR_SIZE; + HAL_I2C_ErrorCallback(hi2c); + } + } + else if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_TC) == SET) + { + if(hi2c->XferCount == 0) + { + /* Generate Stop */ + hi2c->Instance->CR2 |= I2C_CR2_STOP; + } + else + { + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + /* Wrong size Status regarding TCR flag event */ + hi2c->ErrorCode |= HAL_I2C_ERROR_SIZE; + HAL_I2C_ErrorCallback(hi2c); + } + } + else if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_STOPF) == SET) + { + /* Disable ERR, TC, STOP, NACK, TXI interrupt */ + __HAL_I2C_DISABLE_IT(hi2c,I2C_IT_ERRI | I2C_IT_TCI| I2C_IT_STOPI| I2C_IT_NACKI | I2C_IT_TXI ); + + /* Clear STOP Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); + + /* Clear Configuration Register 2 */ + __HAL_I2C_RESET_CR2(hi2c); + + hi2c->State = HAL_I2C_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + if(hi2c->State == HAL_I2C_STATE_MEM_BUSY_TX) + { + HAL_I2C_MemTxCpltCallback(hi2c); + } + else + { + HAL_I2C_MasterTxCpltCallback(hi2c); + } + } + else if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_AF) == SET) + { + /* Clear NACK Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); + + hi2c->State = HAL_I2C_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + hi2c->ErrorCode |= HAL_I2C_ERROR_AF; + HAL_I2C_ErrorCallback(hi2c); + } + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_OK; +} + +/** + * @brief Handle Interrupt Flags Master Receive Mode + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @retval HAL status + */ +static HAL_StatusTypeDef I2C_MasterReceive_ISR(I2C_HandleTypeDef *hi2c) +{ + uint16_t DevAddress; + + /* Process Locked */ + __HAL_LOCK(hi2c); + + if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_RXNE) == SET) + { + /* Read data from RXDR */ + (*hi2c->pBuffPtr++) = hi2c->Instance->RXDR; + hi2c->XferSize--; + hi2c->XferCount--; + } + else if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_TCR) == SET) + { + if((hi2c->XferSize == 0)&&(hi2c->XferCount!=0)) + { + DevAddress = (hi2c->Instance->CR2 & I2C_CR2_SADD); + + if(hi2c->XferCount > 255) + { + I2C_TransferConfig(hi2c,DevAddress,255, I2C_RELOAD_MODE, I2C_NO_STARTSTOP); + hi2c->XferSize = 255; + } + else + { + I2C_TransferConfig(hi2c,DevAddress,hi2c->XferCount, I2C_AUTOEND_MODE, I2C_NO_STARTSTOP); + hi2c->XferSize = hi2c->XferCount; + } + } + else + { + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + /* Wrong size Status regarding TCR flag event */ + hi2c->ErrorCode |= HAL_I2C_ERROR_SIZE; + HAL_I2C_ErrorCallback(hi2c); + } + } + else if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_TC) == SET) + { + if(hi2c->XferCount == 0) + { + /* Generate Stop */ + hi2c->Instance->CR2 |= I2C_CR2_STOP; + } + else + { + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + /* Wrong size Status regarding TCR flag event */ + hi2c->ErrorCode |= HAL_I2C_ERROR_SIZE; + HAL_I2C_ErrorCallback(hi2c); + } + } + else if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_STOPF) == SET) + { + /* Disable ERR, TC, STOP, NACK, TXI interrupt */ + __HAL_I2C_DISABLE_IT(hi2c,I2C_IT_ERRI | I2C_IT_TCI| I2C_IT_STOPI| I2C_IT_NACKI | I2C_IT_RXI ); + + /* Clear STOP Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); + + /* Clear Configuration Register 2 */ + __HAL_I2C_RESET_CR2(hi2c); + + hi2c->State = HAL_I2C_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + if(hi2c->State == HAL_I2C_STATE_MEM_BUSY_RX) + { + HAL_I2C_MemRxCpltCallback(hi2c); + } + else + { + HAL_I2C_MasterRxCpltCallback(hi2c); + } + } + else if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_AF) == SET) + { + /* Clear NACK Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); + + hi2c->State = HAL_I2C_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + hi2c->ErrorCode |= HAL_I2C_ERROR_AF; + HAL_I2C_ErrorCallback(hi2c); + } + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_OK; + +} + +/** + * @brief Handle Interrupt Flags Slave Transmit Mode + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @retval HAL status + */ +static HAL_StatusTypeDef I2C_SlaveTransmit_ISR(I2C_HandleTypeDef *hi2c) +{ + /* Process locked */ + __HAL_LOCK(hi2c); + + if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_ADDR) == SET) + { + /* Clear ADDR flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_ADDR); + } + /* Check first if STOPF is set */ + /* to prevent a Write Data in TX buffer */ + /* which is stuck in TXDR until next */ + /* communication with Master */ + else if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_STOPF) == SET) + { + /* Disable ERRI, TCI, STOPI, NACKI, ADDRI, RXI, TXI interrupt */ + __HAL_I2C_DISABLE_IT(hi2c,I2C_IT_ERRI | I2C_IT_TCI| I2C_IT_STOPI| I2C_IT_NACKI | I2C_IT_ADDRI | I2C_IT_RXI | I2C_IT_TXI ); + + /* Disable Address Acknowledge */ + hi2c->Instance->CR2 |= I2C_CR2_NACK; + + /* Clear STOP Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); + + hi2c->State = HAL_I2C_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + HAL_I2C_SlaveTxCpltCallback(hi2c); + } + else if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_TXIS) == SET) + { + /* Write data to TXDR only if XferCount not reach "0" */ + /* A TXIS flag can be set, during STOP treatment */ + if(hi2c->XferCount > 0) + { + /* Write data to TXDR */ + hi2c->Instance->TXDR = (*hi2c->pBuffPtr++); + hi2c->XferCount--; + } + } + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_OK; +} + +/** + * @brief Handle Interrupt Flags Slave Receive Mode + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @retval HAL status + */ +static HAL_StatusTypeDef I2C_SlaveReceive_ISR(I2C_HandleTypeDef *hi2c) +{ + /* Process Locked */ + __HAL_LOCK(hi2c); + + if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_ADDR) == SET) + { + /* Clear ADDR flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_ADDR); + } + else if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_RXNE) == SET) + { + /* Read data from RXDR */ + (*hi2c->pBuffPtr++) = hi2c->Instance->RXDR; + hi2c->XferSize--; + hi2c->XferCount--; + } + else if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_STOPF) == SET) + { + /* Disable ERRI, TCI, STOPI, NACKI, ADDRI, RXI, TXI interrupt */ + __HAL_I2C_DISABLE_IT(hi2c,I2C_IT_ERRI | I2C_IT_TCI| I2C_IT_STOPI| I2C_IT_NACKI | I2C_IT_ADDRI | I2C_IT_RXI | I2C_IT_RXI ); + + /* Disable Address Acknowledge */ + hi2c->Instance->CR2 |= I2C_CR2_NACK; + + /* Clear STOP Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); + + hi2c->State = HAL_I2C_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + HAL_I2C_SlaveRxCpltCallback(hi2c); + } + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_OK; +} + +/** + * @brief Master sends target device address followed by internal memory address for write request. + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param DevAddress: Target device address + * @param MemAddress: Internal memory address + * @param MemAddSize: Size of internal memory address + * @param Timeout: Timeout duration + * @retval HAL status + */ +static HAL_StatusTypeDef I2C_RequestMemoryWrite(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint32_t Timeout) +{ + I2C_TransferConfig(hi2c,DevAddress,MemAddSize, I2C_RELOAD_MODE, I2C_GENERATE_START_WRITE); + + /* Wait until TXIS flag is set */ + if(I2C_WaitOnTXISFlagUntilTimeout(hi2c, Timeout) != HAL_OK) + { + if(hi2c->ErrorCode == HAL_I2C_ERROR_AF) + { + return HAL_ERROR; + } + else + { + return HAL_TIMEOUT; + } + } + + /* If Memory address size is 8Bit */ + if(MemAddSize == I2C_MEMADD_SIZE_8BIT) + { + /* Send Memory Address */ + hi2c->Instance->TXDR = __HAL_I2C_MEM_ADD_LSB(MemAddress); + } + /* If Memory address size is 16Bit */ + else + { + /* Send MSB of Memory Address */ + hi2c->Instance->TXDR = __HAL_I2C_MEM_ADD_MSB(MemAddress); + + /* Wait until TXIS flag is set */ + if(I2C_WaitOnTXISFlagUntilTimeout(hi2c, Timeout) != HAL_OK) + { + if(hi2c->ErrorCode == HAL_I2C_ERROR_AF) + { + return HAL_ERROR; + } + else + { + return HAL_TIMEOUT; + } + } + + /* Send LSB of Memory Address */ + hi2c->Instance->TXDR = __HAL_I2C_MEM_ADD_LSB(MemAddress); + } + + /* Wait until TCR flag is set */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_TCR, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + +return HAL_OK; +} + +/** + * @brief Master sends target device address followed by internal memory address for read request. + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param DevAddress: Target device address + * @param MemAddress: Internal memory address + * @param MemAddSize: Size of internal memory address + * @param Timeout: Timeout duration + * @retval HAL status + */ +static HAL_StatusTypeDef I2C_RequestMemoryRead(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint32_t Timeout) +{ + I2C_TransferConfig(hi2c,DevAddress,MemAddSize, I2C_SOFTEND_MODE, I2C_GENERATE_START_WRITE); + + /* Wait until TXIS flag is set */ + if(I2C_WaitOnTXISFlagUntilTimeout(hi2c, Timeout) != HAL_OK) + { + if(hi2c->ErrorCode == HAL_I2C_ERROR_AF) + { + return HAL_ERROR; + } + else + { + return HAL_TIMEOUT; + } + } + + /* If Memory address size is 8Bit */ + if(MemAddSize == I2C_MEMADD_SIZE_8BIT) + { + /* Send Memory Address */ + hi2c->Instance->TXDR = __HAL_I2C_MEM_ADD_LSB(MemAddress); + } + /* If Mememory address size is 16Bit */ + else + { + /* Send MSB of Memory Address */ + hi2c->Instance->TXDR = __HAL_I2C_MEM_ADD_MSB(MemAddress); + + /* Wait until TXIS flag is set */ + if(I2C_WaitOnTXISFlagUntilTimeout(hi2c, Timeout) != HAL_OK) + { + if(hi2c->ErrorCode == HAL_I2C_ERROR_AF) + { + return HAL_ERROR; + } + else + { + return HAL_TIMEOUT; + } + } + + /* Send LSB of Memory Address */ + hi2c->Instance->TXDR = __HAL_I2C_MEM_ADD_LSB(MemAddress); + } + + /* Wait until TC flag is set */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_TC, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + return HAL_OK; +} + + +/** + * @brief DMA I2C master transmit process complete callback. + * @param hdma: DMA handle + * @retval None + */ +static void I2C_DMAMasterTransmitCplt(DMA_HandleTypeDef *hdma) +{ + uint16_t DevAddress; + I2C_HandleTypeDef* hi2c = (I2C_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent; + + /* Check if last DMA request was done with RELOAD */ + /* Set NBYTES to write and reload if size > 255 and generate RESTART */ + if( (hi2c->XferSize == 255) && (hi2c->XferSize < hi2c->XferCount) ) + { + /* Wait until TCR flag is set */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_TCR, RESET, I2C_TIMEOUT_TCR) != HAL_OK) + { + hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; + } + + /* Disable DMA Request */ + hi2c->Instance->CR1 &= ~I2C_CR1_TXDMAEN; + + /* Check if Errors has been detected during transfer */ + if(hi2c->ErrorCode != HAL_I2C_ERROR_NONE) + { + /* No need to Check TC flag, with AUTOEND mode the stop is automatically generated */ + /* Wait until STOPF flag is reset */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_STOPF, RESET, I2C_TIMEOUT_STOPF) != HAL_OK) + { + hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; + } + + /* Clear STOP Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); + + /* Clear Configuration Register 2 */ + __HAL_I2C_RESET_CR2(hi2c); + + hi2c->XferCount = 0; + + hi2c->State = HAL_I2C_STATE_READY; + HAL_I2C_ErrorCallback(hi2c); + } + else + { + hi2c->pBuffPtr += hi2c->XferSize; + hi2c->XferCount -= hi2c->XferSize; + if(hi2c->XferCount > 255) + { + hi2c->XferSize = 255; + } + else + { + hi2c->XferSize = hi2c->XferCount; + } + + DevAddress = (hi2c->Instance->CR2 & I2C_CR2_SADD); + + /* Enable the DMA channel */ + HAL_DMA_Start_IT(hi2c->hdmatx, (uint32_t)hi2c->pBuffPtr, (uint32_t)&hi2c->Instance->TXDR, hi2c->XferSize); + + /* Send Slave Address */ + /* Set NBYTES to write and reload if size > 255 and generate RESTART */ + if( (hi2c->XferSize == 255) && (hi2c->XferSize < hi2c->XferCount) ) + { + I2C_TransferConfig(hi2c,DevAddress,hi2c->XferSize, I2C_RELOAD_MODE, I2C_NO_STARTSTOP); + } + else + { + I2C_TransferConfig(hi2c,DevAddress,hi2c->XferSize, I2C_AUTOEND_MODE, I2C_NO_STARTSTOP); + } + + /* Wait until TXIS flag is set */ + if(I2C_WaitOnTXISFlagUntilTimeout(hi2c, I2C_TIMEOUT_TXIS) != HAL_OK) + { + /* No need to Check TC flag, with AUTOEND mode the stop is automatically generated */ + /* Wait until STOPF flag is reset */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_STOPF, RESET, I2C_TIMEOUT_STOPF) != HAL_OK) + { + hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; + } + + /* Clear STOP Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); + + /* Clear Configuration Register 2 */ + __HAL_I2C_RESET_CR2(hi2c); + + hi2c->XferCount = 0; + + hi2c->State = HAL_I2C_STATE_READY; + HAL_I2C_ErrorCallback(hi2c); + } + else + { + /* Enable DMA Request */ + hi2c->Instance->CR1 |= I2C_CR1_TXDMAEN; + } + } + } + else + { + /* No need to Check TC flag, with AUTOEND mode the stop is automatically generated */ + /* Wait until STOPF flag is reset */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_STOPF, RESET, I2C_TIMEOUT_STOPF) != HAL_OK) + { + hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; + } + + /* Clear STOP Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); + + /* Clear Configuration Register 2 */ + __HAL_I2C_RESET_CR2(hi2c); + + /* Disable DMA Request */ + hi2c->Instance->CR1 &= ~I2C_CR1_TXDMAEN; + + hi2c->XferCount = 0; + + hi2c->State = HAL_I2C_STATE_READY; + + /* Check if Errors has been detected during transfer */ + if(hi2c->ErrorCode != HAL_I2C_ERROR_NONE) + { + HAL_I2C_ErrorCallback(hi2c); + } + else + { + HAL_I2C_MasterTxCpltCallback(hi2c); + } + } +} + +/** + * @brief DMA I2C slave transmit process complete callback. + * @param hdma: DMA handle + * @retval None + */ +static void I2C_DMASlaveTransmitCplt(DMA_HandleTypeDef *hdma) +{ + I2C_HandleTypeDef* hi2c = (I2C_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent; + + /* Wait until STOP flag is set */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_STOPF, RESET, I2C_TIMEOUT_STOPF) != HAL_OK) + { + hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; + } + + /* Clear STOP flag */ + __HAL_I2C_CLEAR_FLAG(hi2c,I2C_FLAG_STOPF); + + /* Wait until BUSY flag is reset */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, I2C_TIMEOUT_BUSY) != HAL_OK) + { + hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; + } + + /* Disable DMA Request */ + hi2c->Instance->CR1 &= ~I2C_CR1_TXDMAEN; + + hi2c->XferCount = 0; + + hi2c->State = HAL_I2C_STATE_READY; + + /* Check if Errors has been detected during transfer */ + if(hi2c->ErrorCode != HAL_I2C_ERROR_NONE) + { + HAL_I2C_ErrorCallback(hi2c); + } + else + { + HAL_I2C_SlaveTxCpltCallback(hi2c); + } +} + +/** + * @brief DMA I2C master receive process complete callback + * @param hdma: DMA handle + * @retval None + */ +static void I2C_DMAMasterReceiveCplt(DMA_HandleTypeDef *hdma) +{ + I2C_HandleTypeDef* hi2c = (I2C_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent; + uint16_t DevAddress; + + /* Check if last DMA request was done with RELOAD */ + /* Set NBYTES to write and reload if size > 255 and generate RESTART */ + if( (hi2c->XferSize == 255) && (hi2c->XferSize < hi2c->XferCount) ) + { + /* Wait until TCR flag is set */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_TCR, RESET, I2C_TIMEOUT_TCR) != HAL_OK) + { + hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; + } + + /* Disable DMA Request */ + hi2c->Instance->CR1 &= ~I2C_CR1_RXDMAEN; + + /* Check if Errors has been detected during transfer */ + if(hi2c->ErrorCode != HAL_I2C_ERROR_NONE) + { + /* No need to Check TC flag, with AUTOEND mode the stop is automatically generated */ + /* Wait until STOPF flag is reset */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_STOPF, RESET, I2C_TIMEOUT_STOPF) != HAL_OK) + { + hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; + } + + /* Clear STOP Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); + + /* Clear Configuration Register 2 */ + __HAL_I2C_RESET_CR2(hi2c); + + hi2c->XferCount = 0; + + hi2c->State = HAL_I2C_STATE_READY; + HAL_I2C_ErrorCallback(hi2c); + } + else + { + hi2c->pBuffPtr += hi2c->XferSize; + hi2c->XferCount -= hi2c->XferSize; + if(hi2c->XferCount > 255) + { + hi2c->XferSize = 255; + } + else + { + hi2c->XferSize = hi2c->XferCount; + } + + DevAddress = (hi2c->Instance->CR2 & I2C_CR2_SADD); + + /* Enable the DMA channel */ + HAL_DMA_Start_IT(hi2c->hdmarx, (uint32_t)&hi2c->Instance->RXDR, (uint32_t)hi2c->pBuffPtr, hi2c->XferSize); + + /* Send Slave Address */ + /* Set NBYTES to write and reload if size > 255 and generate RESTART */ + if( (hi2c->XferSize == 255) && (hi2c->XferSize < hi2c->XferCount) ) + { + I2C_TransferConfig(hi2c,DevAddress,hi2c->XferSize, I2C_RELOAD_MODE, I2C_NO_STARTSTOP); + } + else + { + I2C_TransferConfig(hi2c,DevAddress,hi2c->XferSize, I2C_AUTOEND_MODE, I2C_NO_STARTSTOP); + } + + /* Wait until RXNE flag is set */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_RXNE, RESET, I2C_TIMEOUT_RXNE) != HAL_OK) + { + hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; + } + + /* Check if Errors has been detected during transfer */ + if(hi2c->ErrorCode != HAL_I2C_ERROR_NONE) + { + /* No need to Check TC flag, with AUTOEND mode the stop is automatically generated */ + /* Wait until STOPF flag is reset */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_STOPF, RESET, I2C_TIMEOUT_STOPF) != HAL_OK) + { + hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; + } + + /* Clear STOP Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); + + /* Clear Configuration Register 2 */ + __HAL_I2C_RESET_CR2(hi2c); + + hi2c->XferCount = 0; + + hi2c->State = HAL_I2C_STATE_READY; + + HAL_I2C_ErrorCallback(hi2c); + } + else + { + /* Enable DMA Request */ + hi2c->Instance->CR1 |= I2C_CR1_RXDMAEN; + } + } + } + else + { + /* No need to Check TC flag, with AUTOEND mode the stop is automatically generated */ + /* Wait until STOPF flag is reset */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_STOPF, RESET, I2C_TIMEOUT_STOPF) != HAL_OK) + { + hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; + } + + /* Clear STOP Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); + + /* Clear Configuration Register 2 */ + __HAL_I2C_RESET_CR2(hi2c); + + /* Disable DMA Request */ + hi2c->Instance->CR1 &= ~I2C_CR1_RXDMAEN; + + hi2c->XferCount = 0; + + hi2c->State = HAL_I2C_STATE_READY; + + /* Check if Errors has been detected during transfer */ + if(hi2c->ErrorCode != HAL_I2C_ERROR_NONE) + { + HAL_I2C_ErrorCallback(hi2c); + } + else + { + HAL_I2C_MasterRxCpltCallback(hi2c); + } + } +} + +/** + * @brief DMA I2C slave receive process complete callback. + * @param hdma: DMA handle + * @retval None + */ +static void I2C_DMASlaveReceiveCplt(DMA_HandleTypeDef *hdma) +{ + I2C_HandleTypeDef* hi2c = (I2C_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent; + + /* Wait until STOPF flag is reset */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_STOPF, RESET, I2C_TIMEOUT_STOPF) != HAL_OK) + { + hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; + } + + /* Clear STOPF flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); + + /* Wait until BUSY flag is reset */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, I2C_TIMEOUT_BUSY) != HAL_OK) + { + hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; + } + + /* Disable DMA Request */ + hi2c->Instance->CR1 &= ~I2C_CR1_RXDMAEN; + + /* Disable Address Acknowledge */ + hi2c->Instance->CR2 |= I2C_CR2_NACK; + + hi2c->XferCount = 0; + + hi2c->State = HAL_I2C_STATE_READY; + + /* Check if Errors has been detected during transfer */ + if(hi2c->ErrorCode != HAL_I2C_ERROR_NONE) + { + HAL_I2C_ErrorCallback(hi2c); + } + else + { + HAL_I2C_SlaveRxCpltCallback(hi2c); + } +} + +/** + * @brief DMA I2C Memory Write process complete callback + * @param hdma : DMA handle + * @retval None + */ +static void I2C_DMAMemTransmitCplt(DMA_HandleTypeDef *hdma) +{ + uint16_t DevAddress; + I2C_HandleTypeDef* hi2c = ( I2C_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + + /* Check if last DMA request was done with RELOAD */ + /* Set NBYTES to write and reload if size > 255 and generate RESTART */ + if( (hi2c->XferSize == 255) && (hi2c->XferSize < hi2c->XferCount) ) + { + /* Wait until TCR flag is set */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_TCR, RESET, I2C_TIMEOUT_TCR) != HAL_OK) + { + hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; + } + + /* Disable DMA Request */ + hi2c->Instance->CR1 &= ~I2C_CR1_TXDMAEN; + + /* Check if Errors has been detected during transfer */ + if(hi2c->ErrorCode != HAL_I2C_ERROR_NONE) + { + /* No need to Check TC flag, with AUTOEND mode the stop is automatically generated */ + /* Wait until STOPF flag is reset */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_STOPF, RESET, I2C_TIMEOUT_STOPF) != HAL_OK) + { + hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; + } + + /* Clear STOP Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); + + /* Clear Configuration Register 2 */ + __HAL_I2C_RESET_CR2(hi2c); + + hi2c->XferCount = 0; + + hi2c->State = HAL_I2C_STATE_READY; + HAL_I2C_ErrorCallback(hi2c); + } + else + { + hi2c->pBuffPtr += hi2c->XferSize; + hi2c->XferCount -= hi2c->XferSize; + if(hi2c->XferCount > 255) + { + hi2c->XferSize = 255; + } + else + { + hi2c->XferSize = hi2c->XferCount; + } + + DevAddress = (hi2c->Instance->CR2 & I2C_CR2_SADD); + + /* Enable the DMA channel */ + HAL_DMA_Start_IT(hi2c->hdmatx, (uint32_t)hi2c->pBuffPtr, (uint32_t)&hi2c->Instance->TXDR, hi2c->XferSize); + + /* Send Slave Address */ + /* Set NBYTES to write and reload if size > 255 and generate RESTART */ + if( (hi2c->XferSize == 255) && (hi2c->XferSize < hi2c->XferCount) ) + { + I2C_TransferConfig(hi2c,DevAddress,hi2c->XferSize, I2C_RELOAD_MODE, I2C_NO_STARTSTOP); + } + else + { + I2C_TransferConfig(hi2c,DevAddress,hi2c->XferSize, I2C_AUTOEND_MODE, I2C_NO_STARTSTOP); + } + + /* Wait until TXIS flag is set */ + if(I2C_WaitOnTXISFlagUntilTimeout(hi2c, I2C_TIMEOUT_TXIS) != HAL_OK) + { + /* No need to Check TC flag, with AUTOEND mode the stop is automatically generated */ + /* Wait until STOPF flag is reset */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_STOPF, RESET, I2C_TIMEOUT_STOPF) != HAL_OK) + { + hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; + } + + /* Clear STOP Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); + + /* Clear Configuration Register 2 */ + __HAL_I2C_RESET_CR2(hi2c); + + hi2c->XferCount = 0; + + hi2c->State = HAL_I2C_STATE_READY; + HAL_I2C_ErrorCallback(hi2c); + } + else + { + /* Enable DMA Request */ + hi2c->Instance->CR1 |= I2C_CR1_TXDMAEN; + } + } + } + else + { + /* No need to Check TC flag, with AUTOEND mode the stop is automatically generated */ + /* Wait until STOPF flag is reset */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_STOPF, RESET, I2C_TIMEOUT_STOPF) != HAL_OK) + { + hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; + } + + /* Clear STOP Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); + + /* Clear Configuration Register 2 */ + __HAL_I2C_RESET_CR2(hi2c); + + /* Disable DMA Request */ + hi2c->Instance->CR1 &= ~I2C_CR1_TXDMAEN; + + hi2c->XferCount = 0; + + hi2c->State = HAL_I2C_STATE_READY; + + /* Check if Errors has been detected during transfer */ + if(hi2c->ErrorCode != HAL_I2C_ERROR_NONE) + { + HAL_I2C_ErrorCallback(hi2c); + } + else + { + HAL_I2C_MemTxCpltCallback(hi2c); + } + } +} + +/** + * @brief DMA I2C Memory Read process complete callback + * @param hdma: DMA handle + * @retval None + */ +static void I2C_DMAMemReceiveCplt(DMA_HandleTypeDef *hdma) +{ + I2C_HandleTypeDef* hi2c = ( I2C_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + uint16_t DevAddress; + + /* Check if last DMA request was done with RELOAD */ + /* Set NBYTES to write and reload if size > 255 and generate RESTART */ + if( (hi2c->XferSize == 255) && (hi2c->XferSize < hi2c->XferCount) ) + { + /* Wait until TCR flag is set */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_TCR, RESET, I2C_TIMEOUT_TCR) != HAL_OK) + { + hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; + } + + /* Disable DMA Request */ + hi2c->Instance->CR1 &= ~I2C_CR1_RXDMAEN; + + /* Check if Errors has been detected during transfer */ + if(hi2c->ErrorCode != HAL_I2C_ERROR_NONE) + { + /* No need to Check TC flag, with AUTOEND mode the stop is automatically generated */ + /* Wait until STOPF flag is reset */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_STOPF, RESET, I2C_TIMEOUT_STOPF) != HAL_OK) + { + hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; + } + + /* Clear STOP Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); + + /* Clear Configuration Register 2 */ + __HAL_I2C_RESET_CR2(hi2c); + + hi2c->XferCount = 0; + + hi2c->State = HAL_I2C_STATE_READY; + HAL_I2C_ErrorCallback(hi2c); + } + else + { + hi2c->pBuffPtr += hi2c->XferSize; + hi2c->XferCount -= hi2c->XferSize; + if(hi2c->XferCount > 255) + { + hi2c->XferSize = 255; + } + else + { + hi2c->XferSize = hi2c->XferCount; + } + + DevAddress = (hi2c->Instance->CR2 & I2C_CR2_SADD); + + /* Enable the DMA channel */ + HAL_DMA_Start_IT(hi2c->hdmarx, (uint32_t)&hi2c->Instance->RXDR, (uint32_t)hi2c->pBuffPtr, hi2c->XferSize); + + /* Send Slave Address */ + /* Set NBYTES to write and reload if size > 255 and generate RESTART */ + if( (hi2c->XferSize == 255) && (hi2c->XferSize < hi2c->XferCount) ) + { + I2C_TransferConfig(hi2c,DevAddress,hi2c->XferSize, I2C_RELOAD_MODE, I2C_NO_STARTSTOP); + } + else + { + I2C_TransferConfig(hi2c,DevAddress,hi2c->XferSize, I2C_AUTOEND_MODE, I2C_NO_STARTSTOP); + } + + /* Wait until RXNE flag is set */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_RXNE, RESET, I2C_TIMEOUT_RXNE) != HAL_OK) + { + hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; + } + + /* Check if Errors has been detected during transfer */ + if(hi2c->ErrorCode != HAL_I2C_ERROR_NONE) + { + /* No need to Check TC flag, with AUTOEND mode the stop is automatically generated */ + /* Wait until STOPF flag is reset */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_STOPF, RESET, I2C_TIMEOUT_STOPF) != HAL_OK) + { + hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; + } + + /* Clear STOP Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); + + /* Clear Configuration Register 2 */ + __HAL_I2C_RESET_CR2(hi2c); + + hi2c->XferCount = 0; + + hi2c->State = HAL_I2C_STATE_READY; + HAL_I2C_ErrorCallback(hi2c); + } + else + { + /* Enable DMA Request */ + hi2c->Instance->CR1 |= I2C_CR1_RXDMAEN; + } + } + } + else + { + /* No need to Check TC flag, with AUTOEND mode the stop is automatically generated */ + /* Wait until STOPF flag is reset */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_STOPF, RESET, I2C_TIMEOUT_STOPF) != HAL_OK) + { + hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; + } + + /* Clear STOP Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); + + /* Clear Configuration Register 2 */ + __HAL_I2C_RESET_CR2(hi2c); + + /* Disable DMA Request */ + hi2c->Instance->CR1 &= ~I2C_CR1_RXDMAEN; + + hi2c->XferCount = 0; + + hi2c->State = HAL_I2C_STATE_READY; + + /* Check if Errors has been detected during transfer */ + if(hi2c->ErrorCode != HAL_I2C_ERROR_NONE) + { + HAL_I2C_ErrorCallback(hi2c); + } + else + { + HAL_I2C_MemRxCpltCallback(hi2c); + } + } +} + +/** + * @brief DMA I2C communication error callback. + * @param hdma : DMA handle + * @retval None + */ +static void I2C_DMAError(DMA_HandleTypeDef *hdma) +{ + I2C_HandleTypeDef* hi2c = ( I2C_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + + /* Disable Acknowledge */ + hi2c->Instance->CR2 |= I2C_CR2_NACK; + + hi2c->XferCount = 0; + + hi2c->State = HAL_I2C_STATE_READY; + + hi2c->ErrorCode |= HAL_I2C_ERROR_DMA; + + HAL_I2C_ErrorCallback(hi2c); +} + +/** + * @brief This function handles I2C Communication Timeout. + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param Flag: specifies the I2C flag to check. + * @param Status: The new Flag status (SET or RESET). + * @param Timeout: Timeout duration + * @retval HAL status + */ +static HAL_StatusTypeDef I2C_WaitOnFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Flag, FlagStatus Status, uint32_t Timeout) +{ + uint32_t tickstart = HAL_GetTick(); + + /* Wait until flag is set */ + if(Status == RESET) + { + while(__HAL_I2C_GET_FLAG(hi2c, Flag) == RESET) + { + /* Check for the Timeout */ + if(Timeout != HAL_MAX_DELAY) + { + if((HAL_GetTick() - tickstart) > Timeout) + { + hi2c->State= HAL_I2C_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_TIMEOUT; + } + } + } + } + else + { + while(__HAL_I2C_GET_FLAG(hi2c, Flag) != RESET) + { + /* Check for the Timeout */ + if(Timeout != HAL_MAX_DELAY) + { + if((HAL_GetTick() - tickstart) > Timeout) + { + hi2c->State= HAL_I2C_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_TIMEOUT; + } + } + } + } + return HAL_OK; +} + +/** + * @brief This function handles I2C Communication Timeout for specific usage of TXIS flag. + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param Timeout: Timeout duration + * @retval HAL status + */ +static HAL_StatusTypeDef I2C_WaitOnTXISFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Timeout) +{ + uint32_t tickstart = HAL_GetTick(); + + while(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_TXIS) == RESET) + { + if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_AF) == SET) + { + /* Clear NACKF Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); + + hi2c->ErrorCode |= HAL_I2C_ERROR_AF; + hi2c->State= HAL_I2C_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_ERROR; + } + + /* Check for the Timeout */ + if(Timeout != HAL_MAX_DELAY) + { + if((HAL_GetTick() - tickstart) > Timeout) + { + hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; + hi2c->State= HAL_I2C_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_TIMEOUT; + } + } + } + return HAL_OK; +} + +/** + * @brief Handles I2Cx communication when starting transfer or during transfer (TC or TCR flag are set). + * @param hi2c: I2C handle. + * @param DevAddress: specifies the slave address to be programmed. + * @param Size: specifies the number of bytes to be programmed. + * This parameter must be a value between 0 and 255. + * @param Mode: new state of the I2C START condition generation. + * This parameter can be one of the following values: + * @arg I2C_RELOAD_MODE: Enable Reload mode . + * @arg I2C_AUTOEND_MODE: Enable Automatic end mode. + * @arg I2C_SOFTEND_MODE: Enable Software end mode. + * @param Request: new state of the I2C START condition generation. + * This parameter can be one of the following values: + * @arg I2C_NO_STARTSTOP: Don't Generate stop and start condition. + * @arg I2C_GENERATE_STOP: Generate stop condition (Size should be set to 0). + * @arg I2C_GENERATE_START_READ: Generate Restart for read request. + * @arg I2C_GENERATE_START_WRITE: Generate Restart for write request. + * @retval None + */ +static void I2C_TransferConfig(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t Size, uint32_t Mode, uint32_t Request) +{ + uint32_t tmpreg = 0; + + /* Check the parameters */ + assert_param(IS_I2C_ALL_INSTANCE(hi2c->Instance)); + assert_param(IS_TRANSFER_MODE(Mode)); + assert_param(IS_TRANSFER_REQUEST(Request)); + + /* Get the CR2 register value */ + tmpreg = hi2c->Instance->CR2; + + /* clear tmpreg specific bits */ + tmpreg &= (uint32_t)~((uint32_t)(I2C_CR2_SADD | I2C_CR2_NBYTES | I2C_CR2_RELOAD | I2C_CR2_AUTOEND | I2C_CR2_RD_WRN | I2C_CR2_START | I2C_CR2_STOP)); + + /* update tmpreg */ + tmpreg |= (uint32_t)(((uint32_t)DevAddress & I2C_CR2_SADD) | (((uint32_t)Size << 16 ) & I2C_CR2_NBYTES) | \ + (uint32_t)Mode | (uint32_t)Request); + + /* update CR2 register */ + hi2c->Instance->CR2 = tmpreg; +} + +/** + * @} + */ + +/** + * @} + */ + +#endif /* HAL_I2C_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_i2c.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_i2c.h new file mode 100644 index 0000000000..11a5aedb0e --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_i2c.h @@ -0,0 +1,495 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_i2c.h + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief Header file of I2C HAL module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32F0xx_HAL_I2C_H +#define __STM32F0xx_HAL_I2C_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal_def.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @addtogroup I2C + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ + +/** + * @brief I2C Configuration Structure definition + */ +typedef struct +{ + uint32_t Timing; /*!< Specifies the I2C_TIMINGR_register value. + This parameter calculated by referring to I2C initialization + section in Reference manual */ + + uint32_t OwnAddress1; /*!< Specifies the first device own address. + This parameter can be a 7-bit or 10-bit address. */ + + uint32_t AddressingMode; /*!< Specifies if 7-bit or 10-bit addressing mode is selected. + This parameter can be a value of @ref I2C_addressing_mode */ + + uint32_t DualAddressMode; /*!< Specifies if dual addressing mode is selected. + This parameter can be a value of @ref I2C_dual_addressing_mode */ + + uint32_t OwnAddress2; /*!< Specifies the second device own address if dual addressing mode is selected + This parameter can be a 7-bit address. */ + + uint32_t OwnAddress2Masks; /*!< Specifies the acknoledge mask address second device own address if dual addressing mode is selected + This parameter can be a value of @ref I2C_own_address2_masks. */ + + uint32_t GeneralCallMode; /*!< Specifies if general call mode is selected. + This parameter can be a value of @ref I2C_general_call_addressing_mode. */ + + uint32_t NoStretchMode; /*!< Specifies if nostretch mode is selected. + This parameter can be a value of @ref I2C_nostretch_mode */ + +}I2C_InitTypeDef; + +/** + * @brief HAL State structures definition + */ +typedef enum +{ + HAL_I2C_STATE_RESET = 0x00, /*!< I2C not yet initialized or disabled */ + HAL_I2C_STATE_READY = 0x01, /*!< I2C initialized and ready for use */ + HAL_I2C_STATE_BUSY = 0x02, /*!< I2C internal process is ongoing */ + HAL_I2C_STATE_MASTER_BUSY_TX = 0x12, /*!< Master Data Transmission process is ongoing */ + HAL_I2C_STATE_MASTER_BUSY_RX = 0x22, /*!< Master Data Reception process is ongoing */ + HAL_I2C_STATE_SLAVE_BUSY_TX = 0x32, /*!< Slave Data Transmission process is ongoing */ + HAL_I2C_STATE_SLAVE_BUSY_RX = 0x42, /*!< Slave Data Reception process is ongoing */ + HAL_I2C_STATE_MEM_BUSY_TX = 0x52, /*!< Memory Data Transmission process is ongoing */ + HAL_I2C_STATE_MEM_BUSY_RX = 0x62, /*!< Memory Data Reception process is ongoing */ + HAL_I2C_STATE_TIMEOUT = 0x03, /*!< Timeout state */ + HAL_I2C_STATE_ERROR = 0x04 /*!< Reception process is ongoing */ + +}HAL_I2C_StateTypeDef; + +/** + * @brief HAL I2C Error Code structure definition + */ +typedef enum +{ + HAL_I2C_ERROR_NONE = 0x00, /*!< No error */ + HAL_I2C_ERROR_BERR = 0x01, /*!< BERR error */ + HAL_I2C_ERROR_ARLO = 0x02, /*!< ARLO error */ + HAL_I2C_ERROR_AF = 0x04, /*!< AF error */ + HAL_I2C_ERROR_OVR = 0x08, /*!< OVR error */ + HAL_I2C_ERROR_DMA = 0x10, /*!< DMA transfer error */ + HAL_I2C_ERROR_TIMEOUT = 0x20, /*!< Timeout error */ + HAL_I2C_ERROR_SIZE = 0x40 /*!< Size Management error */ +}HAL_I2C_ErrorTypeDef; + +/** + * @brief I2C handle Structure definition + */ +typedef struct +{ + I2C_TypeDef *Instance; /*!< I2C registers base address */ + + I2C_InitTypeDef Init; /*!< I2C communication parameters */ + + uint8_t *pBuffPtr; /*!< Pointer to I2C transfer buffer */ + + uint16_t XferSize; /*!< I2C transfer size */ + + __IO uint16_t XferCount; /*!< I2C transfer counter */ + + DMA_HandleTypeDef *hdmatx; /*!< I2C Tx DMA handle parameters */ + + DMA_HandleTypeDef *hdmarx; /*!< I2C Rx DMA handle parameters */ + + HAL_LockTypeDef Lock; /*!< I2C locking object */ + + __IO HAL_I2C_StateTypeDef State; /*!< I2C communication state */ + + __IO HAL_I2C_ErrorTypeDef ErrorCode; /* I2C Error code */ + +}I2C_HandleTypeDef; + +/* Exported constants --------------------------------------------------------*/ + +/** @defgroup I2C_Exported_Constants + * @{ + */ + +/** @defgroup I2C_addressing_mode + * @{ + */ +#define I2C_ADDRESSINGMODE_7BIT ((uint32_t)0x00000001) +#define I2C_ADDRESSINGMODE_10BIT ((uint32_t)0x00000002) + +#define IS_I2C_ADDRESSING_MODE(MODE) (((MODE) == I2C_ADDRESSINGMODE_7BIT) || \ + ((MODE) == I2C_ADDRESSINGMODE_10BIT)) +/** + * @} + */ + +/** @defgroup I2C_dual_addressing_mode + * @{ + */ + +#define I2C_DUALADDRESS_DISABLED ((uint32_t)0x00000000) +#define I2C_DUALADDRESS_ENABLED I2C_OAR2_OA2EN + +#define IS_I2C_DUAL_ADDRESS(ADDRESS) (((ADDRESS) == I2C_DUALADDRESS_DISABLED) || \ + ((ADDRESS) == I2C_DUALADDRESS_ENABLED)) +/** + * @} + */ + +/** @defgroup I2C_own_address2_masks + * @{ + */ + +#define I2C_OA2_NOMASK ((uint8_t)0x00) +#define I2C_OA2_MASK01 ((uint8_t)0x01) +#define I2C_OA2_MASK02 ((uint8_t)0x02) +#define I2C_OA2_MASK03 ((uint8_t)0x03) +#define I2C_OA2_MASK04 ((uint8_t)0x04) +#define I2C_OA2_MASK05 ((uint8_t)0x05) +#define I2C_OA2_MASK06 ((uint8_t)0x06) +#define I2C_OA2_MASK07 ((uint8_t)0x07) + +#define IS_I2C_OWN_ADDRESS2_MASK(MASK) (((MASK) == I2C_OA2_NOMASK) || \ + ((MASK) == I2C_OA2_MASK01) || \ + ((MASK) == I2C_OA2_MASK02) || \ + ((MASK) == I2C_OA2_MASK03) || \ + ((MASK) == I2C_OA2_MASK04) || \ + ((MASK) == I2C_OA2_MASK05) || \ + ((MASK) == I2C_OA2_MASK06) || \ + ((MASK) == I2C_OA2_MASK07)) +/** + * @} + */ + +/** @defgroup I2C_general_call_addressing_mode + * @{ + */ +#define I2C_GENERALCALL_DISABLED ((uint32_t)0x00000000) +#define I2C_GENERALCALL_ENABLED I2C_CR1_GCEN + +#define IS_I2C_GENERAL_CALL(CALL) (((CALL) == I2C_GENERALCALL_DISABLED) || \ + ((CALL) == I2C_GENERALCALL_ENABLED)) +/** + * @} + */ + +/** @defgroup I2C_nostretch_mode + * @{ + */ +#define I2C_NOSTRETCH_DISABLED ((uint32_t)0x00000000) +#define I2C_NOSTRETCH_ENABLED I2C_CR1_NOSTRETCH + +#define IS_I2C_NO_STRETCH(STRETCH) (((STRETCH) == I2C_NOSTRETCH_DISABLED) || \ + ((STRETCH) == I2C_NOSTRETCH_ENABLED)) +/** + * @} + */ + +/** @defgroup I2C_Memory_Address_Size + * @{ + */ +#define I2C_MEMADD_SIZE_8BIT ((uint32_t)0x00000001) +#define I2C_MEMADD_SIZE_16BIT ((uint32_t)0x00000002) + +#define IS_I2C_MEMADD_SIZE(SIZE) (((SIZE) == I2C_MEMADD_SIZE_8BIT) || \ + ((SIZE) == I2C_MEMADD_SIZE_16BIT)) +/** + * @} + */ + +/** @defgroup I2C_ReloadEndMode_definition + * @{ + */ + +#define I2C_RELOAD_MODE I2C_CR2_RELOAD +#define I2C_AUTOEND_MODE I2C_CR2_AUTOEND +#define I2C_SOFTEND_MODE ((uint32_t)0x00000000) + +#define IS_TRANSFER_MODE(MODE) (((MODE) == I2C_RELOAD_MODE) || \ + ((MODE) == I2C_AUTOEND_MODE) || \ + ((MODE) == I2C_SOFTEND_MODE)) +/** + * @} + */ + +/** @defgroup I2C_StartStopMode_definition + * @{ + */ + +#define I2C_NO_STARTSTOP ((uint32_t)0x00000000) +#define I2C_GENERATE_STOP I2C_CR2_STOP +#define I2C_GENERATE_START_READ (uint32_t)(I2C_CR2_START | I2C_CR2_RD_WRN) +#define I2C_GENERATE_START_WRITE I2C_CR2_START + +#define IS_TRANSFER_REQUEST(REQUEST) (((REQUEST) == I2C_GENERATE_STOP) || \ + ((REQUEST) == I2C_GENERATE_START_READ) || \ + ((REQUEST) == I2C_GENERATE_START_WRITE) || \ + ((REQUEST) == I2C_NO_STARTSTOP)) + +/** + * @} + */ + +/** @defgroup I2C_Interrupt_configuration_definition + * @brief I2C Interrupt definition + * Elements values convention: 0xXXXXXXXX + * - XXXXXXXX : Interrupt control mask + * @{ + */ +#define I2C_IT_ERRI I2C_CR1_ERRIE +#define I2C_IT_TCI I2C_CR1_TCIE +#define I2C_IT_STOPI I2C_CR1_STOPIE +#define I2C_IT_NACKI I2C_CR1_NACKIE +#define I2C_IT_ADDRI I2C_CR1_ADDRIE +#define I2C_IT_RXI I2C_CR1_RXIE +#define I2C_IT_TXI I2C_CR1_TXIE + +/** + * @} + */ + + +/** @defgroup I2C_Flag_definition + * @{ + */ + +#define I2C_FLAG_TXE I2C_ISR_TXE +#define I2C_FLAG_TXIS I2C_ISR_TXIS +#define I2C_FLAG_RXNE I2C_ISR_RXNE +#define I2C_FLAG_ADDR I2C_ISR_ADDR +#define I2C_FLAG_AF I2C_ISR_NACKF +#define I2C_FLAG_STOPF I2C_ISR_STOPF +#define I2C_FLAG_TC I2C_ISR_TC +#define I2C_FLAG_TCR I2C_ISR_TCR +#define I2C_FLAG_BERR I2C_ISR_BERR +#define I2C_FLAG_ARLO I2C_ISR_ARLO +#define I2C_FLAG_OVR I2C_ISR_OVR +#define I2C_FLAG_PECERR I2C_ISR_PECERR +#define I2C_FLAG_TIMEOUT I2C_ISR_TIMEOUT +#define I2C_FLAG_ALERT I2C_ISR_ALERT +#define I2C_FLAG_BUSY I2C_ISR_BUSY +#define I2C_FLAG_DIR I2C_ISR_DIR +/** + * @} + */ + +/** + * @} + */ + +/* Exported macros -----------------------------------------------------------*/ + +/** @brief Reset I2C handle state + * @param __HANDLE__: I2C handle. + * @retval None + */ +#define __HAL_I2C_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_I2C_STATE_RESET) + +/** @brief Enables or disables the specified I2C interrupts. + * @param __HANDLE__: specifies the I2C Handle. + * This parameter can be I2C where x: 1 or 2 to select the I2C peripheral. + * @param __INTERRUPT__: specifies the interrupt source to enable or disable. + * This parameter can be one of the following values: + * @arg I2C_IT_ERRI: Errors interrupt enable + * @arg I2C_IT_TCI: Transfer complete interrupt enable + * @arg I2C_IT_STOPI: STOP detection interrupt enable + * @arg I2C_IT_NACKI: NACK received interrupt enable + * @arg I2C_IT_ADDRI: Address match interrupt enable + * @arg I2C_IT_RXI: RX interrupt enable + * @arg I2C_IT_TXI: TX interrupt enable + * + * @retval None + */ + +#define __HAL_I2C_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR1 |= (__INTERRUPT__)) +#define __HAL_I2C_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR1 &= (~(__INTERRUPT__))) + +/** @brief Checks if the specified I2C interrupt source is enabled or disabled. + * @param __HANDLE__: specifies the I2C Handle. + * This parameter can be I2C where x: 1 or 2 to select the I2C peripheral. + * @param __INTERRUPT__: specifies the I2C interrupt source to check. + * This parameter can be one of the following values: + * @arg I2C_IT_ERRI: Errors interrupt enable + * @arg I2C_IT_TCI: Transfer complete interrupt enable + * @arg I2C_IT_STOPI: STOP detection interrupt enable + * @arg I2C_IT_NACKI: NACK received interrupt enable + * @arg I2C_IT_ADDRI: Address match interrupt enable + * @arg I2C_IT_RXI: RX interrupt enable + * @arg I2C_IT_TXI: TX interrupt enable + * + * @retval The new state of __IT__ (TRUE or FALSE). + */ +#define __HAL_I2C_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((((__HANDLE__)->Instance->CR1 & (__INTERRUPT__)) == (__INTERRUPT__)) ? SET : RESET) + +/** @brief Checks whether the specified I2C flag is set or not. + * @param __HANDLE__: specifies the I2C Handle. + * This parameter can be I2C where x: 1 or 2 to select the I2C peripheral. + * @param __FLAG__: specifies the flag to check. + * This parameter can be one of the following values: + * @arg I2C_FLAG_TXE: Transmit data register empty + * @arg I2C_FLAG_TXIS: Transmit interrupt status + * @arg I2C_FLAG_RXNE: Receive data register not empty + * @arg I2C_FLAG_ADDR: Address matched (slave mode) + * @arg I2C_FLAG_AF: Acknowledge failure received flag + * @arg I2C_FLAG_STOPF: STOP detection flag + * @arg I2C_FLAG_TC: Transfer complete (master mode) + * @arg I2C_FLAG_TCR: Transfer complete reload + * @arg I2C_FLAG_BERR: Bus error + * @arg I2C_FLAG_ARLO: Arbitration lost + * @arg I2C_FLAG_OVR: Overrun/Underrun + * @arg I2C_FLAG_PECERR: PEC error in reception + * @arg I2C_FLAG_TIMEOUT: Timeout or Tlow detection flag + * @arg I2C_FLAG_ALERT: SMBus alert + * @arg I2C_FLAG_BUSY: Bus busy + * @arg I2C_FLAG_DIR: Transfer direction (slave mode) + * + * @retval The new state of __FLAG__ (TRUE or FALSE). + */ +#define I2C_FLAG_MASK ((uint32_t)0x0001FFFF) +#define __HAL_I2C_GET_FLAG(__HANDLE__, __FLAG__) (((((__HANDLE__)->Instance->ISR) & ((__FLAG__) & I2C_FLAG_MASK)) == ((__FLAG__) & I2C_FLAG_MASK))) + +/** @brief Clears the I2C pending flags which are cleared by writing 1 in a specific bit. + * @param __HANDLE__: specifies the I2C Handle. + * This parameter can be I2C where x: 1 or 2 to select the I2C peripheral. + * @param __FLAG__: specifies the flag to clear. + * This parameter can be any combination of the following values: + * @arg I2C_FLAG_ADDR: Address matched (slave mode) + * @arg I2C_FLAG_AF: Acknowledge failure flag + * @arg I2C_FLAG_STOPF: STOP detection flag + * @arg I2C_FLAG_BERR: Bus error + * @arg I2C_FLAG_ARLO: Arbitration lost + * @arg I2C_FLAG_OVR: Overrun/Underrun + * @arg I2C_FLAG_PECERR: PEC error in reception + * @arg I2C_FLAG_TIMEOUT: Timeout or Tlow detection flag + * @arg I2C_FLAG_ALERT: SMBus alert + * + * @retval None + */ +#define __HAL_I2C_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->ICR |= ((__FLAG__) & I2C_FLAG_MASK)) + + +#define __HAL_I2C_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 |= I2C_CR1_PE) +#define __HAL_I2C_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 &= ~I2C_CR1_PE) + +#define __HAL_I2C_RESET_CR2(__HANDLE__) ((__HANDLE__)->Instance->CR2 &= (uint32_t)~((uint32_t)(I2C_CR2_SADD | I2C_CR2_HEAD10R | I2C_CR2_NBYTES | I2C_CR2_RELOAD | I2C_CR2_RD_WRN))) + +#define __HAL_I2C_MEM_ADD_MSB(__ADDRESS__) ((uint8_t)(((__ADDRESS__) & 0xFF00) >> 8)) +#define __HAL_I2C_MEM_ADD_LSB(__ADDRESS__) ((uint8_t)((__ADDRESS__) & 0x00FF)) + +#define __HAL_I2C_GENERATE_START(__ADDMODE__,__ADDRESS__) (((__ADDMODE__) == I2C_ADDRESSINGMODE_7BIT) ? (uint32_t)((((uint32_t)(__ADDRESS__) & (I2C_CR2_SADD)) | (I2C_CR2_START) | (I2C_CR2_AUTOEND)) & (~I2C_CR2_RD_WRN)) : \ + (uint32_t)((((uint32_t)(__ADDRESS__) & (I2C_CR2_SADD)) | (I2C_CR2_ADD10) | (I2C_CR2_START)) & (~I2C_CR2_RD_WRN))) + +#define IS_I2C_OWN_ADDRESS1(ADDRESS1) ((ADDRESS1) <= (uint32_t)0x000003FF) +#define IS_I2C_OWN_ADDRESS2(ADDRESS2) ((ADDRESS2) <= (uint16_t)0x00FF) + +/* Include I2C HAL Extension module */ +#include "stm32f0xx_hal_i2c_ex.h" + +/* Exported functions --------------------------------------------------------*/ +/* Initialization/de-initialization functions **********************************/ +HAL_StatusTypeDef HAL_I2C_Init(I2C_HandleTypeDef *hi2c); +HAL_StatusTypeDef HAL_I2C_DeInit (I2C_HandleTypeDef *hi2c); +void HAL_I2C_MspInit(I2C_HandleTypeDef *hi2c); +void HAL_I2C_MspDeInit(I2C_HandleTypeDef *hi2c); + +/* IO operation functions *****************************************************/ + /******* Blocking mode: Polling */ +HAL_StatusTypeDef HAL_I2C_Master_Transmit(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t Timeout); +HAL_StatusTypeDef HAL_I2C_Master_Receive(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t Timeout); +HAL_StatusTypeDef HAL_I2C_Slave_Transmit(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size, uint32_t Timeout); +HAL_StatusTypeDef HAL_I2C_Slave_Receive(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size, uint32_t Timeout); +HAL_StatusTypeDef HAL_I2C_Mem_Write(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size, uint32_t Timeout); +HAL_StatusTypeDef HAL_I2C_Mem_Read(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size, uint32_t Timeout); +HAL_StatusTypeDef HAL_I2C_IsDeviceReady(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint32_t Trials, uint32_t Timeout); + + /******* Non-Blocking mode: Interrupt */ +HAL_StatusTypeDef HAL_I2C_Master_Transmit_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size); +HAL_StatusTypeDef HAL_I2C_Master_Receive_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size); +HAL_StatusTypeDef HAL_I2C_Slave_Transmit_IT(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size); +HAL_StatusTypeDef HAL_I2C_Slave_Receive_IT(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size); +HAL_StatusTypeDef HAL_I2C_Mem_Write_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size); +HAL_StatusTypeDef HAL_I2C_Mem_Read_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size); + + /******* Non-Blocking mode: DMA */ +HAL_StatusTypeDef HAL_I2C_Master_Transmit_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size); +HAL_StatusTypeDef HAL_I2C_Master_Receive_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size); +HAL_StatusTypeDef HAL_I2C_Slave_Transmit_DMA(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size); +HAL_StatusTypeDef HAL_I2C_Slave_Receive_DMA(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size); +HAL_StatusTypeDef HAL_I2C_Mem_Write_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size); +HAL_StatusTypeDef HAL_I2C_Mem_Read_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size); + + /******* I2C IRQHandler and Callbacks used in non blocking modes (Interrupt and DMA) */ +void HAL_I2C_EV_IRQHandler(I2C_HandleTypeDef *hi2c); +void HAL_I2C_ER_IRQHandler(I2C_HandleTypeDef *hi2c); +void HAL_I2C_MasterTxCpltCallback(I2C_HandleTypeDef *hi2c); +void HAL_I2C_MasterRxCpltCallback(I2C_HandleTypeDef *hi2c); +void HAL_I2C_SlaveTxCpltCallback(I2C_HandleTypeDef *hi2c); +void HAL_I2C_SlaveRxCpltCallback(I2C_HandleTypeDef *hi2c); +void HAL_I2C_MemTxCpltCallback(I2C_HandleTypeDef *hi2c); +void HAL_I2C_MemRxCpltCallback(I2C_HandleTypeDef *hi2c); +void HAL_I2C_ErrorCallback(I2C_HandleTypeDef *hi2c); + +/* Peripheral State functions **************************************/ +HAL_I2C_StateTypeDef HAL_I2C_GetState(I2C_HandleTypeDef *hi2c); +uint32_t HAL_I2C_GetError(I2C_HandleTypeDef *hi2c); + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + + +#endif /* __STM32F0xx_HAL_I2C_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_i2c_ex.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_i2c_ex.c new file mode 100644 index 0000000000..3bdbae5b98 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_i2c_ex.c @@ -0,0 +1,292 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_i2c_ex.c + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief I2C Extension HAL module driver. + * This file provides firmware functions to manage the following + * functionalities of I2C extension peripheral: + * + Extension features functions + * + @verbatim + ============================================================================== + ##### I2C peripheral extension features ##### + ============================================================================== + + [..] Comparing to other previous devices, the I2C interface for STM32F0XX + devices contains the following additional features + + (+) Possibility to disable or enable Analog Noise Filter + (+) Use of a configured Digital Noise Filter + (+) Disable or enable wakeup from Stop mode + + ##### How to use this driver ##### + ============================================================================== + [..] This driver provides functions to configure Noise Filter + (#) Configure I2C Analog noise filter using the function HAL_I2CEx_AnalogFilter_Config() + (#) Configure I2C Digital noise filter using the function HAL_I2CEx_DigitalFilter_Config() + (#) Configure the enabling or disabling of I2C Wake Up Mode using the functions : + + HAL_I2CEx_EnableWakeUp() + + HAL_I2CEx_DisableWakeUp() + + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @defgroup I2CEx + * @brief I2C Extended HAL module driver + * @{ + */ + +#ifdef HAL_I2C_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup I2CEx_Private_Functions + * @{ + */ + + +/** @defgroup I2CEx_Group1 Extended features functions + * @brief Extended features functions + * +@verbatim + =============================================================================== + ##### Extension features functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Configure Noise Filters + +@endverbatim + * @{ + */ + +/** + * @brief Configures I2C Analog noise filter. + * @param hi2c : pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2Cx peripheral. + * @param AnalogFilter : new state of the Analog filter. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2CEx_AnalogFilter_Config(I2C_HandleTypeDef *hi2c, uint32_t AnalogFilter) +{ + /* Check the parameters */ + assert_param(IS_I2C_ALL_INSTANCE(hi2c->Instance)); + assert_param(IS_I2C_ANALOG_FILTER(AnalogFilter)); + + if((hi2c->State == HAL_I2C_STATE_BUSY) || (hi2c->State == HAL_I2C_STATE_MASTER_BUSY_TX) || (hi2c->State == HAL_I2C_STATE_MASTER_BUSY_RX) + || (hi2c->State == HAL_I2C_STATE_SLAVE_BUSY_TX) || (hi2c->State == HAL_I2C_STATE_SLAVE_BUSY_RX)) + { + return HAL_BUSY; + } + + /* Process Locked */ + __HAL_LOCK(hi2c); + + hi2c->State = HAL_I2C_STATE_BUSY; + + /* Disable the selected I2C peripheral */ + __HAL_I2C_DISABLE(hi2c); + + /* Reset I2Cx ANOFF bit */ + hi2c->Instance->CR1 &= ~(I2C_CR1_ANFOFF); + + /* Set analog filter bit*/ + hi2c->Instance->CR1 |= AnalogFilter; + + __HAL_I2C_ENABLE(hi2c); + + hi2c->State = HAL_I2C_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_OK; +} + +/** + * @brief Configures I2C Digital noise filter. + * @param hi2c : pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2Cx peripheral. + * @param DigitalFilter : Coefficient of digital noise filter between 0x00 and 0x0F. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2CEx_DigitalFilter_Config(I2C_HandleTypeDef *hi2c, uint32_t DigitalFilter) +{ + uint32_t tmpreg = 0; + + /* Check the parameters */ + assert_param(IS_I2C_ALL_INSTANCE(hi2c->Instance)); + assert_param(IS_I2C_DIGITAL_FILTER(DigitalFilter)); + + if((hi2c->State == HAL_I2C_STATE_BUSY) || (hi2c->State == HAL_I2C_STATE_MASTER_BUSY_TX) || (hi2c->State == HAL_I2C_STATE_MASTER_BUSY_RX) + || (hi2c->State == HAL_I2C_STATE_SLAVE_BUSY_TX) || (hi2c->State == HAL_I2C_STATE_SLAVE_BUSY_RX)) + { + return HAL_BUSY; + } + + /* Process Locked */ + __HAL_LOCK(hi2c); + + hi2c->State = HAL_I2C_STATE_BUSY; + + /* Disable the selected I2C peripheral */ + __HAL_I2C_DISABLE(hi2c); + + /* Get the old register value */ + tmpreg = hi2c->Instance->CR1; + + /* Reset I2Cx DNF bits [11:8] */ + tmpreg &= ~(I2C_CR1_DFN); + + /* Set I2Cx DNF coefficient */ + tmpreg |= DigitalFilter << 8; + + /* Store the new register value */ + hi2c->Instance->CR1 = tmpreg; + + __HAL_I2C_ENABLE(hi2c); + + hi2c->State = HAL_I2C_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_OK; +} + +/** + * @brief Enables I2C wakeup from stop mode. + * @param hi2c : pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2Cx peripheral. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2CEx_EnableWakeUp (I2C_HandleTypeDef *hi2c) +{ + /* Check the parameters */ + assert_param(IS_I2C_ALL_INSTANCE(hi2c->Instance)); + + if((hi2c->State == HAL_I2C_STATE_BUSY) || (hi2c->State == HAL_I2C_STATE_MASTER_BUSY_TX) || (hi2c->State == HAL_I2C_STATE_MASTER_BUSY_RX) + || (hi2c->State == HAL_I2C_STATE_SLAVE_BUSY_TX) || (hi2c->State == HAL_I2C_STATE_SLAVE_BUSY_RX)) + { + return HAL_BUSY; + } + + /* Process Locked */ + __HAL_LOCK(hi2c); + + hi2c->State = HAL_I2C_STATE_BUSY; + + /* Disable the selected I2C peripheral */ + __HAL_I2C_DISABLE(hi2c); + + /* Enable wakeup from stop mode */ + hi2c->Instance->CR1 |= I2C_CR1_WUPEN; + + __HAL_I2C_ENABLE(hi2c); + + hi2c->State = HAL_I2C_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_OK; +} + + +/** + * @brief Disables I2C wakeup from stop mode. + * @param hi2c : pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2Cx peripheral. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2CEx_DisableWakeUp (I2C_HandleTypeDef *hi2c) +{ + /* Check the parameters */ + assert_param(IS_I2C_ALL_INSTANCE(hi2c->Instance)); + + if((hi2c->State == HAL_I2C_STATE_BUSY) || (hi2c->State == HAL_I2C_STATE_MASTER_BUSY_TX) || (hi2c->State == HAL_I2C_STATE_MASTER_BUSY_RX) + || (hi2c->State == HAL_I2C_STATE_SLAVE_BUSY_TX) || (hi2c->State == HAL_I2C_STATE_SLAVE_BUSY_RX)) + { + return HAL_BUSY; + } + + /* Process Locked */ + __HAL_LOCK(hi2c); + + hi2c->State = HAL_I2C_STATE_BUSY; + + /* Disable the selected I2C peripheral */ + __HAL_I2C_DISABLE(hi2c); + + /* Enable wakeup from stop mode */ + hi2c->Instance->CR1 &= ~(I2C_CR1_WUPEN); + + __HAL_I2C_ENABLE(hi2c); + + hi2c->State = HAL_I2C_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_OK; +} + +/** + * @} + */ + +/** + * @} + */ + +#endif /* HAL_I2C_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_i2c_ex.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_i2c_ex.h new file mode 100644 index 0000000000..ea58203a60 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_i2c_ex.h @@ -0,0 +1,112 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_i2c_ex.h + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief Header file of I2C HAL Extension module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32F0xx_HAL_I2C_EX_H +#define __STM32F0xx_HAL_I2C_EX_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal_def.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @addtogroup I2CEx + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/* Exported constants --------------------------------------------------------*/ + +/** @defgroup I2CEx_Exported_Constants + * @{ + */ + +/** @defgroup I2CEx_Analog_Filter + * @{ + */ +#define I2C_ANALOGFILTER_ENABLED ((uint32_t)0x00000000) +#define I2C_ANALOGFILTER_DISABLED I2C_CR1_ANFOFF + +#define IS_I2C_ANALOG_FILTER(FILTER) (((FILTER) == I2C_ANALOGFILTER_ENABLED) || \ + ((FILTER) == I2C_ANALOGFILTER_DISABLED)) +/** + * @} + */ + +/** @defgroup I2CEx_Digital_Filter + * @{ + */ +#define IS_I2C_DIGITAL_FILTER(FILTER) ((FILTER) <= 0x0000000F) +/** + * @} + */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ +/* Exported functions --------------------------------------------------------*/ + +/* Peripheral Control functions ************************************************/ +HAL_StatusTypeDef HAL_I2CEx_AnalogFilter_Config(I2C_HandleTypeDef *hi2c, uint32_t AnalogFilter); +HAL_StatusTypeDef HAL_I2CEx_DigitalFilter_Config(I2C_HandleTypeDef *hi2c, uint32_t DigitalFilter); +HAL_StatusTypeDef HAL_I2CEx_EnableWakeUp (I2C_HandleTypeDef *hi2c); +HAL_StatusTypeDef HAL_I2CEx_DisableWakeUp (I2C_HandleTypeDef *hi2c); + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __STM32F0xx_HAL_I2C_EX_H */ + + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_i2s.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_i2s.c new file mode 100644 index 0000000000..1e8ca38247 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_i2s.c @@ -0,0 +1,1371 @@ +/** +****************************************************************************** +* @file stm32f0xx_hal_i2s.c +* @author MCD Application Team +* @version V1.0.0 +* @date 28-May-2014 +* @brief I2S HAL module driver. +* +* This file provides firmware functions to manage the following +* functionalities of the Integrated Interchip Sound (I2S) peripheral: +* + Initialization and de-initialization functions +* + IO operation functions +* + Peripheral State and Errors functions +@verbatim +=============================================================================== +##### How to use this driver ##### +=============================================================================== +[..] +The I2S HAL driver can be used as follows: + +(#) Declare a I2S_HandleTypeDef handle structure. +(#) Initialize the I2S low level resources by implement the HAL_I2S_MspInit() API: +(##) Enable the SPIx interface clock. +(##) I2S pins configuration: +(+++) Enable the clock for the I2S GPIOs. +(+++) Configure these I2S pins as alternate function pull-up. +(##) NVIC configuration if you need to use interrupt process (HAL_I2S_Transmit_IT() +and HAL_I2S_Receive_IT() APIs). +(+++) Configure the I2Sx interrupt priority. +(+++) Enable the NVIC I2S IRQ handle. +(##) DMA Configuration if you need to use DMA process (HAL_I2S_Transmit_DMA() +and HAL_I2S_Receive_DMA() APIs: +(+++) Declare a DMA handle structure for the Tx/Rx stream. +(+++) Enable the DMAx interface clock. +(+++) Configure the declared DMA handle structure with the required Tx/Rx parameters. +(+++) Configure the DMA Tx/Rx Channel. +(+++) Associate the initilalized DMA handle to the I2S DMA Tx/Rx handle. +(+++) Configure the priority and enable the NVIC for the transfer complete interrupt on the +DMA Tx/Rx Channel. + +(#) Program the Mode, Standard, Data Format, MCLK Output, Audio frequency and Polarity +using HAL_I2S_Init() function. + +-@- The specific I2S interrupts (Transmission complete interrupt, +RXNE interrupt and Error Interrupts) will be managed using the macros +__I2S_ENABLE_IT() and __I2S_DISABLE_IT() inside the transmit and receive process. +-@- Make sure that either: +(+@) External clock source is configured after setting correctly +the define constant EXTERNAL_CLOCK_VALUE in the stm32f0xx_hal_conf.h file. + +(#) Three mode of operations are available within this driver : + +*** Polling mode IO operation *** +================================= +[..] +(+) Send an amount of data in blocking mode using HAL_I2S_Transmit() +(+) Receive an amount of data in blocking mode using HAL_I2S_Receive() + +*** Interrupt mode IO operation *** +=================================== +[..] +(+) Send an amount of data in non blocking mode using HAL_I2S_Transmit_IT() +(+) At transmission end of half transfer HAL_I2S_TxHalfCpltCallback is executed and user can +add his own code by customization of function pointer HAL_I2S_TxHalfCpltCallback +(+) At transmission end of transfer HAL_I2S_TxCpltCallback is executed and user can +add his own code by customization of function pointer HAL_I2S_TxCpltCallback +(+) Receive an amount of data in non blocking mode using HAL_I2S_Receive_IT() +(+) At reception end of half transfer HAL_I2S_RxHalfCpltCallback is executed and user can +add his own code by customization of function pointer HAL_I2S_RxHalfCpltCallback +(+) At reception end of transfer HAL_I2S_RxCpltCallback is executed and user can +add his own code by customization of function pointer HAL_I2S_RxCpltCallback +(+) In case of transfer Error, HAL_I2S_ErrorCallback() function is executed and user can +add his own code by customization of function pointer HAL_I2S_ErrorCallback + +*** DMA mode IO operation *** +============================== +[..] +(+) Send an amount of data in non blocking mode (DMA) using HAL_I2S_Transmit_DMA() +(+) At transmission end of half transfer HAL_I2S_TxHalfCpltCallback is executed and user can +add his own code by customization of function pointer HAL_I2S_TxHalfCpltCallback +(+) At transmission end of transfer HAL_I2S_TxCpltCallback is executed and user can +add his own code by customization of function pointer HAL_I2S_TxCpltCallback +(+) Receive an amount of data in non blocking mode (DMA) using HAL_I2S_Receive_DMA() +(+) At reception end of half transfer HAL_I2S_RxHalfCpltCallback is executed and user can +add his own code by customization of function pointer HAL_I2S_RxHalfCpltCallback +(+) At reception end of transfer HAL_I2S_RxCpltCallback is executed and user can +add his own code by customization of function pointer HAL_I2S_RxCpltCallback +(+) In case of transfer Error, HAL_I2S_ErrorCallback() function is executed and user can +add his own code by customization of function pointer HAL_I2S_ErrorCallback +(+) Pause the DMA Transfer using HAL_I2S_DMAPause() +(+) Resume the DMA Transfer using HAL_I2S_DMAResume() +(+) Stop the DMA Transfer using HAL_I2S_DMAStop() + +*** I2S HAL driver macros list *** +============================================= +[..] +Below the list of most used macros in USART HAL driver. + +(+) __HAL_I2S_ENABLE: Enable the specified SPI peripheral (in I2S mode) +(+) __HAL_I2S_DISABLE: Disable the specified SPI peripheral (in I2S mode) +(+) __HAL_I2S_ENABLE_IT : Enable the specified I2S interrupts +(+) __HAL_I2S_DISABLE_IT : Disable the specified I2S interrupts +(+) __HAL_I2S_GET_FLAG: Check whether the specified I2S flag is set or not + +[..] +(@) You can refer to the I2S HAL driver header file for more useful macros + +@endverbatim +****************************************************************************** +* @attention +* +*

© COPYRIGHT(c) 2014 STMicroelectronics

+* +* Redistribution and use in source and binary forms, with or without modification, +* are permitted provided that the following conditions are met: +* 1. Redistributions of source code must retain the above copyright notice, +* this list of conditions and the following disclaimer. +* 2. Redistributions in binary form must reproduce the above copyright notice, +* this list of conditions and the following disclaimer in the documentation +* and/or other materials provided with the distribution. +* 3. Neither the name of STMicroelectronics nor the names of its contributors +* may be used to endorse or promote products derived from this software +* without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +****************************************************************************** +*/ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal.h" + +/** @addtogroup STM32F0xx_HAL_Driver +* @{ +*/ + +/** @defgroup I2S +* @brief I2S HAL module driver +* @{ +*/ + +#ifdef HAL_I2S_MODULE_ENABLED + +#if defined(STM32F031x6) || defined(STM32F038xx) || \ + defined(STM32F051x8) || defined(STM32F058xx) || \ + defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) || \ + defined(STM32F042x6) || defined(STM32F048xx) + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +static void I2S_DMATxCplt(DMA_HandleTypeDef *hdma); +static void I2S_DMATxHalfCplt(DMA_HandleTypeDef *hdma); +static void I2S_DMARxCplt(DMA_HandleTypeDef *hdma); +static void I2S_DMARxHalfCplt(DMA_HandleTypeDef *hdma); +static void I2S_DMAError(DMA_HandleTypeDef *hdma); +static void I2S_Transmit_IT(I2S_HandleTypeDef *hi2s); +static void I2S_Receive_IT(I2S_HandleTypeDef *hi2s); +static HAL_StatusTypeDef I2S_WaitFlagStateUntilTimeout(I2S_HandleTypeDef *hi2s, uint32_t Flag, uint32_t State, uint32_t Timeout); + +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup I2S_Private_Functions +* @{ +*/ + +/** @defgroup I2S_Group1 Initialization and de-initialization functions +* @brief Initialization and Configuration functions +* +@verbatim +=============================================================================== +##### Initialization and de-initialization functions ##### +=============================================================================== +[..] This subsection provides a set of functions allowing to initialize and +de-initialiaze the I2Sx peripheral in simplex mode: + +(+) User must Implement HAL_I2S_MspInit() function in which he configures +all related peripherals resources (CLOCK, GPIO, DMA, IT and NVIC ). + +(+) Call the function HAL_I2S_Init() to configure the selected device with +the selected configuration: +(++) Mode +(++) Standard +(++) Data Format +(++) MCLK Output +(++) Audio frequency +(++) Polarity + +(+) Call the function HAL_I2S_DeInit() to restore the default configuration +of the selected I2Sx periperal. +@endverbatim +* @{ +*/ + +/** +* @brief Initializes the I2S according to the specified parameters +* in the I2S_InitTypeDef and create the associated handle. +* @param hi2s: I2S handle +* @retval HAL status +*/ +HAL_StatusTypeDef HAL_I2S_Init(I2S_HandleTypeDef *hi2s) +{ + uint32_t tmpreg = 0, i2sdiv = 2, i2sodd = 0, packetlength = 1; + uint32_t tmp = 0, i2sclk = 0; + + /* Check the I2S handle allocation */ + if(hi2s == NULL) + { + return HAL_ERROR; + } + + /* Check the I2S parameters */ + assert_param(IS_I2S_MODE(hi2s->Init.Mode)); + assert_param(IS_I2S_STANDARD(hi2s->Init.Standard)); + assert_param(IS_I2S_DATA_FORMAT(hi2s->Init.DataFormat)); + assert_param(IS_I2S_MCLK_OUTPUT(hi2s->Init.MCLKOutput)); + assert_param(IS_I2S_AUDIO_FREQ(hi2s->Init.AudioFreq)); + assert_param(IS_I2S_CPOL(hi2s->Init.CPOL)); + assert_param(IS_I2S_CLOCKSOURCE(hi2s->Init.ClockSource)); + + if(hi2s->State == HAL_I2S_STATE_RESET) + { + /* Init the low level hardware : GPIO, CLOCK, CORTEX...etc */ + HAL_I2S_MspInit(hi2s); + } + + hi2s->State = HAL_I2S_STATE_BUSY; + + /*----------------------- SPIx I2SCFGR & I2SPR Configuration ---------------*/ + /* Clear I2SMOD, I2SE, I2SCFG, PCMSYNC, I2SSTD, CKPOL, DATLEN and CHLEN bits */ + hi2s->Instance->I2SCFGR &= (uint16_t)(~(SPI_I2SCFGR_CHLEN | SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CKPOL | \ + SPI_I2SCFGR_I2SSTD | SPI_I2SCFGR_PCMSYNC | SPI_I2SCFGR_I2SCFG | \ + SPI_I2SCFGR_I2SE | SPI_I2SCFGR_I2SMOD)); + hi2s->Instance->I2SPR = 0x0002; + + /* Get the I2SCFGR register value */ + tmpreg = hi2s->Instance->I2SCFGR; + + /* If the default value has to be written, reinitialize i2sdiv and i2sodd*/ + if(hi2s->Init.AudioFreq == I2S_AUDIOFREQ_DEFAULT) + { + i2sodd = (uint16_t)0; + i2sdiv = (uint16_t)2; + } + /* If the requested audio frequency is not the default, compute the prescaler */ + else + { + /* Check the frame length (For the Prescaler computing) *******************/ + if(hi2s->Init.DataFormat == I2S_DATAFORMAT_16B) + { + /* Packet length is 16 bits */ + packetlength = 1; + } + else + { + /* Packet length is 32 bits */ + packetlength = 2; + } + + /* Get I2S source Clock frequency ****************************************/ + i2sclk = HAL_RCC_GetSysClockFreq(); + + /* Compute the Real divider depending on the MCLK output state, with a floating point */ + if(hi2s->Init.MCLKOutput == I2S_MCLKOUTPUT_ENABLE) + { + /* MCLK output is enabled */ + tmp = (uint32_t)(((((i2sclk / 256) * 10) / hi2s->Init.AudioFreq)) + 5); + } + else + { + /* MCLK output is disabled */ + tmp = (uint32_t)(((((i2sclk / (32 * packetlength)) *10 ) / hi2s->Init.AudioFreq)) + 5); + } + + /* Remove the flatting point */ + tmp = tmp / 10; + + /* Check the parity of the divider */ + i2sodd = (uint32_t)(tmp & (uint32_t)1); + + /* Compute the i2sdiv prescaler */ + i2sdiv = (uint32_t)((tmp - i2sodd) / 2); + + /* Get the Mask for the Odd bit (SPI_I2SPR[8]) register */ + i2sodd = (uint32_t) (i2sodd << 8); + } + + /* Test if the divider is 1 or 0 or greater than 0xFF */ + if((i2sdiv < 2) || (i2sdiv > 0xFF)) + { + /* Set the default values */ + i2sdiv = 2; + i2sodd = 0; + } + + /* Write to SPIx I2SPR register the computed value */ + hi2s->Instance->I2SPR = (uint32_t)((uint32_t)i2sdiv | (uint32_t)(i2sodd | (uint32_t)hi2s->Init.MCLKOutput)); + + /* Configure the I2S with the I2S_InitStruct values */ + tmpreg |= (uint32_t)(SPI_I2SCFGR_I2SMOD | hi2s->Init.Mode | hi2s->Init.Standard | hi2s->Init.DataFormat | hi2s->Init.CPOL); + + /* Write to SPIx I2SCFGR */ + hi2s->Instance->I2SCFGR = tmpreg; + + hi2s->ErrorCode = HAL_I2S_ERROR_NONE; + hi2s->State= HAL_I2S_STATE_READY; + + return HAL_OK; +} + +/** +* @brief DeInitializes the I2S peripheral +* @param hi2s: I2S handle +* @retval HAL status +*/ +HAL_StatusTypeDef HAL_I2S_DeInit(I2S_HandleTypeDef *hi2s) +{ + /* Check the I2S handle allocation */ + if(hi2s == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_I2S_ALL_INSTANCE(hi2s->Instance)); + + hi2s->State = HAL_I2S_STATE_BUSY; + + /* Disable the I2S Peripheral Clock */ + __HAL_I2S_DISABLE(hi2s); + + /* DeInit the low level hardware: GPIO, CLOCK, NVIC... */ + HAL_I2S_MspDeInit(hi2s); + + hi2s->ErrorCode = HAL_I2S_ERROR_NONE; + hi2s->State = HAL_I2S_STATE_RESET; + + /* Release Lock */ + __HAL_UNLOCK(hi2s); + + return HAL_OK; +} + +/** +* @brief I2S MSP Init +* @param hi2s: I2S handle +* @retval None +*/ +__weak void HAL_I2S_MspInit(I2S_HandleTypeDef *hi2s) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_I2S_MspInit could be implemented in the user file + */ +} + +/** +* @brief I2S MSP DeInit +* @param hi2s: I2S handle +* @retval None +*/ +__weak void HAL_I2S_MspDeInit(I2S_HandleTypeDef *hi2s) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_I2S_MspDeInit could be implemented in the user file + */ +} + +/** +* @} +*/ + +/** @defgroup I2S_Group2 IO operation functions +* @brief Data transfers functions +* +@verbatim +=============================================================================== +##### IO operation functions ##### +=============================================================================== +[..] +This subsection provides a set of functions allowing to manage the I2S data +transfers. + +(#) There is two mode of transfer: +(++) Blocking mode : The communication is performed in the polling mode. +The status of all data processing is returned by the same function +after finishing transfer. +(++) No-Blocking mode : The communication is performed using Interrupts +or DMA. These functions return the status of the transfer startup. +The end of the data processing will be indicated through the +dedicated I2S IRQ when using Interrupt mode or the DMA IRQ when +using DMA mode. + +(#) Blocking mode functions are : +(++) HAL_I2S_Transmit() +(++) HAL_I2S_Receive() + +(#) No-Blocking mode functions with Interrupt are : +(++) HAL_I2S_Transmit_IT() +(++) HAL_I2S_Receive_IT() + +(#) No-Blocking mode functions with DMA are : +(++) HAL_I2S_Transmit_DMA() +(++) HAL_I2S_Receive_DMA() + +(#) A set of Transfer Complete Callbacks are provided in No_Blocking mode: +(++) HAL_I2S_TxCpltCallback() +(++) HAL_I2S_RxCpltCallback() +(++) HAL_I2S_ErrorCallback() + +@endverbatim +* @{ +*/ + +/** +* @brief Transmit an amount of data in blocking mode +* @param hi2s: I2S handle +* @param pData: a 16-bit pointer to data buffer. +* @param Size: number of data sample to be sent: +* @note When a 16-bit data frame or a 16-bit data frame extended is selected during the I2S +* configuration phase, the Size parameter means the number of 16-bit data length +* in the transaction and when a 24-bit data frame or a 32-bit data frame is selected +* the Size parameter means the number of 16-bit data length. +* @param Timeout: Timeout duration +* @note The I2S is kept enabled at the end of transaction to avoid the clock de-synchronization +* between Master and Slave(example: audio streaming). +* @retval HAL status +*/ +HAL_StatusTypeDef HAL_I2S_Transmit(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size, uint32_t Timeout) +{ + if((pData == NULL ) || (Size == 0)) + { + return HAL_ERROR; + } + + if(hi2s->State == HAL_I2S_STATE_READY) + { + if(((hi2s->Instance->I2SCFGR & (SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN)) == I2S_DATAFORMAT_24B)||\ + ((hi2s->Instance->I2SCFGR & (SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN)) == I2S_DATAFORMAT_32B)) + { + hi2s->TxXferSize = (Size << 1); + hi2s->TxXferCount = (Size << 1); + } + else + { + hi2s->TxXferSize = Size; + hi2s->TxXferCount = Size; + } + + /* Process Locked */ + __HAL_LOCK(hi2s); + + hi2s->ErrorCode = HAL_I2S_ERROR_NONE; + hi2s->State = HAL_I2S_STATE_BUSY_TX; + + /* Check if the I2S is already enabled */ + if((hi2s->Instance->I2SCFGR &SPI_I2SCFGR_I2SE) != SPI_I2SCFGR_I2SE) + { + /* Enable I2S peripheral */ + __HAL_I2S_ENABLE(hi2s); + } + + + /* Wait until TXE flag is set */ + if (I2S_WaitFlagStateUntilTimeout(hi2s, I2S_FLAG_TXE, RESET, Timeout) != HAL_OK) + { + /* Set the error code and execute error callback*/ + hi2s->ErrorCode |= HAL_I2S_ERROR_TIMEOUT; + HAL_I2S_ErrorCallback(hi2s); + return HAL_TIMEOUT; + } + + while(hi2s->TxXferCount > 0) + { + hi2s->Instance->DR = (*pData++); + hi2s->TxXferCount--; + + /* Wait until TXE flag is set */ + if(I2S_WaitFlagStateUntilTimeout(hi2s, I2S_FLAG_TXE, RESET, Timeout) != HAL_OK) + { + /* Set the error code and execute error callback*/ + hi2s->ErrorCode |= HAL_I2S_ERROR_TIMEOUT; + HAL_I2S_ErrorCallback(hi2s); + return HAL_TIMEOUT; + } + } + + /* Wait until Busy flag is reset */ + if (I2S_WaitFlagStateUntilTimeout(hi2s, I2S_FLAG_BSY, SET, Timeout) != HAL_OK) + { + /* Set the error code and execute error callback*/ + hi2s->ErrorCode |= HAL_I2S_ERROR_TIMEOUT; + HAL_I2S_ErrorCallback(hi2s); + return HAL_TIMEOUT; + } + + /* Disable I2S peripheral */ + __HAL_I2S_DISABLE(hi2s); + + hi2s->State = HAL_I2S_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2s); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** +* @brief Receive an amount of data in blocking mode +* @param hi2s: I2S handle +* @param pData: a 16-bit pointer to data buffer. +* @param Size: number of data sample to be sent: +* @note When a 16-bit data frame or a 16-bit data frame extended is selected during the I2S +* configuration phase, the Size parameter means the number of 16-bit data length +* in the transaction and when a 24-bit data frame or a 32-bit data frame is selected +* the Size parameter means the number of 16-bit data length. +* @param Timeout: Timeout duration +* @note The I2S is kept enabled at the end of transaction to avoid the clock de-synchronization +* between Master and Slave(example: audio streaming). +* @note In I2S Master Receiver mode, just after enabling the peripheral the clock will be generate +* in continouse way and as the I2S is not disabled at the end of the I2S transaction. +* @retval HAL status +*/ +HAL_StatusTypeDef HAL_I2S_Receive(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size, uint32_t Timeout) +{ + if((pData == NULL ) || (Size == 0)) + { + return HAL_ERROR; + } + + if(hi2s->State == HAL_I2S_STATE_READY) + { + if(((hi2s->Instance->I2SCFGR & (SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN)) == I2S_DATAFORMAT_24B)||\ + ((hi2s->Instance->I2SCFGR & (SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN)) == I2S_DATAFORMAT_32B)) + { + hi2s->RxXferSize = (Size << 1); + hi2s->RxXferCount = (Size << 1); + } + else + { + hi2s->RxXferSize = Size; + hi2s->RxXferCount = Size; + } + /* Process Locked */ + __HAL_LOCK(hi2s); + + hi2s->ErrorCode = HAL_I2S_ERROR_NONE; + hi2s->State = HAL_I2S_STATE_BUSY_RX; + + /* Check if the I2S is already enabled */ + if((hi2s->Instance->I2SCFGR & SPI_I2SCFGR_I2SE) != SPI_I2SCFGR_I2SE) + { + /* Enable I2S peripheral */ + __HAL_I2S_ENABLE(hi2s); + } + + /* Check if Master Receiver mode is selected */ + if((hi2s->Instance->I2SCFGR & SPI_I2SCFGR_I2SCFG) == I2S_MODE_MASTER_RX) + { + /* Clear the Overrun Flag by a read operation on the SPI_DR register followed by a read + access to the SPI_SR register. */ + __HAL_I2S_CLEAR_OVRFLAG(hi2s); + } + + /* Receive data */ + while(hi2s->RxXferCount > 0) + { + /* Wait until RXNE flag is set */ + if (I2S_WaitFlagStateUntilTimeout(hi2s, I2S_FLAG_RXNE, RESET, Timeout) != HAL_OK) + { + /* Set the error code and execute error callback*/ + hi2s->ErrorCode |= HAL_I2S_ERROR_TIMEOUT; + HAL_I2S_ErrorCallback(hi2s); + return HAL_TIMEOUT; + } + + (*pData++) = hi2s->Instance->DR; + hi2s->RxXferCount--; + + /* Check if an overrun occurs */ + if(__HAL_I2S_GET_FLAG(hi2s, I2S_FLAG_OVR) == SET) + { + /* Set the I2S State ready */ + hi2s->State = HAL_I2S_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2s); + + /* Set the error code and execute error callback*/ + hi2s->ErrorCode |= HAL_I2S_ERROR_OVR; + HAL_I2S_ErrorCallback(hi2s); + + return HAL_ERROR; + } + } + + /* Disable the I2S Peripheral Clock */ + __HAL_I2S_DISABLE(hi2s); + + hi2s->State = HAL_I2S_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2s); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** +* @brief Transmit an amount of data in non-blocking mode with Interrupt +* @param hi2s: I2S handle +* @param pData: a 16-bit pointer to data buffer. +* @param Size: number of data sample to be sent: +* @note When a 16-bit data frame or a 16-bit data frame extended is selected during the I2S +* configuration phase, the Size parameter means the number of 16-bit data length +* in the transaction and when a 24-bit data frame or a 32-bit data frame is selected +* the Size parameter means the number of 16-bit data length. +* @note The I2S is kept enabled at the end of transaction to avoid the clock de-synchronization +* between Master and Slave(example: audio streaming). +* @retval HAL status +*/ +HAL_StatusTypeDef HAL_I2S_Transmit_IT(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size) +{ + if(hi2s->State == HAL_I2S_STATE_READY) + { + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + hi2s->pTxBuffPtr = pData; + if(((hi2s->Instance->I2SCFGR & (SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN)) == I2S_DATAFORMAT_24B)||\ + ((hi2s->Instance->I2SCFGR & (SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN)) == I2S_DATAFORMAT_32B)) + { + hi2s->TxXferSize = (Size << 1); + hi2s->TxXferCount = (Size << 1); + } + else + { + hi2s->TxXferSize = Size; + hi2s->TxXferCount = Size; + } + + /* Process Locked */ + __HAL_LOCK(hi2s); + + hi2s->ErrorCode = HAL_I2S_ERROR_NONE; + hi2s->State = HAL_I2S_STATE_BUSY_TX; + + /* Enable TXE and ERR interrupt */ + __HAL_I2S_ENABLE_IT(hi2s, (I2S_IT_TXE | I2S_IT_ERR)); + + /* Check if the I2S is already enabled */ + if((hi2s->Instance->I2SCFGR &SPI_I2SCFGR_I2SE) != SPI_I2SCFGR_I2SE) + { + /* Enable I2S peripheral */ + __HAL_I2S_ENABLE(hi2s); + } + + /* Process Unlocked */ + __HAL_UNLOCK(hi2s); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** +* @brief Receive an amount of data in non-blocking mode with Interrupt +* @param hi2s: I2S handle +* @param pData: a 16-bit pointer to the Receive data buffer. +* @param Size: number of data sample to be sent: +* @note When a 16-bit data frame or a 16-bit data frame extended is selected during the I2S +* configuration phase, the Size parameter means the number of 16-bit data length +* in the transaction and when a 24-bit data frame or a 32-bit data frame is selected +* the Size parameter means the number of 16-bit data length. +* @note The I2S is kept enabled at the end of transaction to avoid the clock de-synchronization +* between Master and Slave(example: audio streaming). +* @note It is recommended to use DMA for the I2S receiver to avoid de-synchronisation +* between Master and Slave otherwise the I2S interrupt should be optimized. +* @retval HAL status +*/ +HAL_StatusTypeDef HAL_I2S_Receive_IT(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size) +{ + if(hi2s->State == HAL_I2S_STATE_READY) + { + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + hi2s->pRxBuffPtr = pData; + if(((hi2s->Instance->I2SCFGR & (SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN)) == I2S_DATAFORMAT_24B)||\ + ((hi2s->Instance->I2SCFGR & (SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN)) == I2S_DATAFORMAT_32B)) + { + hi2s->RxXferSize = (Size << 1); + hi2s->RxXferCount = (Size << 1); + } + else + { + hi2s->RxXferSize = Size; + hi2s->RxXferCount = Size; + } + /* Process Locked */ + __HAL_LOCK(hi2s); + + hi2s->ErrorCode = HAL_I2S_ERROR_NONE; + hi2s->State = HAL_I2S_STATE_BUSY_RX; + + /* Enable TXE and ERR interrupt */ + __HAL_I2S_ENABLE_IT(hi2s, (I2S_IT_RXNE | I2S_IT_ERR)); + + /* Check if the I2S is already enabled */ + if((hi2s->Instance->I2SCFGR &SPI_I2SCFGR_I2SE) != SPI_I2SCFGR_I2SE) + { + /* Enable I2S peripheral */ + __HAL_I2S_ENABLE(hi2s); + } + + /* Process Unlocked */ + __HAL_UNLOCK(hi2s); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** +* @brief Transmit an amount of data in non-blocking mode with DMA +* @param hi2s: I2S handle +* @param pData: a 16-bit pointer to the Transmit data buffer. +* @param Size: number of data sample to be sent: +* @note When a 16-bit data frame or a 16-bit data frame extended is selected during the I2S +* configuration phase, the Size parameter means the number of 16-bit data length +* in the transaction and when a 24-bit data frame or a 32-bit data frame is selected +* the Size parameter means the number of 16-bit data length. +* @note The I2S is kept enabled at the end of transaction to avoid the clock de-synchronization +* between Master and Slave(example: audio streaming). +* @retval HAL status +*/ +HAL_StatusTypeDef HAL_I2S_Transmit_DMA(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size) +{ + uint32_t *tmp; + + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + if(hi2s->State == HAL_I2S_STATE_READY) + { + hi2s->pTxBuffPtr = pData; + if(((hi2s->Instance->I2SCFGR & (SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN)) == I2S_DATAFORMAT_24B)||\ + ((hi2s->Instance->I2SCFGR & (SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN)) == I2S_DATAFORMAT_32B)) + { + hi2s->TxXferSize = (Size << 1); + hi2s->TxXferCount = (Size << 1); + } + else + { + hi2s->TxXferSize = Size; + hi2s->TxXferCount = Size; + } + + /* Process Locked */ + __HAL_LOCK(hi2s); + + hi2s->ErrorCode = HAL_I2S_ERROR_NONE; + hi2s->State = HAL_I2S_STATE_BUSY_TX; + + /* Set the I2S Tx DMA Half transfert complete callback */ + hi2s->hdmatx->XferHalfCpltCallback = I2S_DMATxHalfCplt; + + /* Set the I2S TxDMA transfert complete callback */ + hi2s->hdmatx->XferCpltCallback = I2S_DMATxCplt; + + /* Set the DMA error callback */ + hi2s->hdmatx->XferErrorCallback = I2S_DMAError; + + /* Enable the Tx DMA Channel */ + tmp = (uint32_t*)&pData; + HAL_DMA_Start_IT(hi2s->hdmatx, *(uint32_t*)tmp, (uint32_t)&hi2s->Instance->DR, hi2s->TxXferSize); + + /* Check if the I2S is already enabled */ + if((hi2s->Instance->I2SCFGR &SPI_I2SCFGR_I2SE) != SPI_I2SCFGR_I2SE) + { + /* Enable I2S peripheral */ + __HAL_I2S_ENABLE(hi2s); + } + + /* Enable Tx DMA Request */ + hi2s->Instance->CR2 |= SPI_CR2_TXDMAEN; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2s); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** +* @brief Receive an amount of data in non-blocking mode with DMA +* @param hi2s: I2S handle +* @param pData: a 16-bit pointer to the Receive data buffer. +* @param Size: number of data sample to be sent: +* @note When a 16-bit data frame or a 16-bit data frame extended is selected during the I2S +* configuration phase, the Size parameter means the number of 16-bit data length +* in the transaction and when a 24-bit data frame or a 32-bit data frame is selected +* the Size parameter means the number of 16-bit data length. +* @note The I2S is kept enabled at the end of transaction to avoid the clock de-synchronization +* between Master and Slave(example: audio streaming). +* @retval HAL status +*/ +HAL_StatusTypeDef HAL_I2S_Receive_DMA(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size) +{ + uint32_t *tmp; + + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + if(hi2s->State == HAL_I2S_STATE_READY) + { + hi2s->pRxBuffPtr = pData; + if(((hi2s->Instance->I2SCFGR & (SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN)) == I2S_DATAFORMAT_24B)||\ + ((hi2s->Instance->I2SCFGR & (SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN)) == I2S_DATAFORMAT_32B)) + { + hi2s->RxXferSize = (Size << 1); + hi2s->RxXferCount = (Size << 1); + } + else + { + hi2s->RxXferSize = Size; + hi2s->RxXferCount = Size; + } + /* Process Locked */ + __HAL_LOCK(hi2s); + + hi2s->ErrorCode = HAL_I2S_ERROR_NONE; + hi2s->State = HAL_I2S_STATE_BUSY_RX; + + /* Set the I2S Rx DMA Half transfert complete callback */ + hi2s->hdmarx->XferHalfCpltCallback = I2S_DMARxHalfCplt; + + /* Set the I2S Rx DMA transfert complete callback */ + hi2s->hdmarx->XferCpltCallback = I2S_DMARxCplt; + + /* Set the DMA error callback */ + hi2s->hdmarx->XferErrorCallback = I2S_DMAError; + + /* Check if Master Receiver mode is selected */ + if((hi2s->Instance->I2SCFGR & SPI_I2SCFGR_I2SCFG) == I2S_MODE_MASTER_RX) + { + /* Clear the Overrun Flag by a read operation to the SPI_DR register followed by a read + access to the SPI_SR register. */ + __HAL_I2S_CLEAR_OVRFLAG(hi2s); + } + + /* Enable the Rx DMA Channel */ + tmp = (uint32_t*)&pData; + HAL_DMA_Start_IT(hi2s->hdmarx, (uint32_t)&hi2s->Instance->DR, *(uint32_t*)tmp, hi2s->RxXferSize); + + /* Check if the I2S is already enabled */ + if((hi2s->Instance->I2SCFGR &SPI_I2SCFGR_I2SE) != SPI_I2SCFGR_I2SE) + { + /* Enable I2S peripheral */ + __HAL_I2S_ENABLE(hi2s); + } + + /* Enable Rx DMA Request */ + hi2s->Instance->CR2 |= SPI_CR2_RXDMAEN; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2s); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** +* @brief Pauses the audio stream playing from the Media. +* @param hi2s: I2S handle +* @retval None +*/ +HAL_StatusTypeDef HAL_I2S_DMAPause(I2S_HandleTypeDef *hi2s) +{ + /* Process Locked */ + __HAL_LOCK(hi2s); + + if(hi2s->State == HAL_I2S_STATE_BUSY_TX) + { + /* Disable the I2S DMA Tx request */ + hi2s->Instance->CR2 &= (uint16_t)(~SPI_CR2_TXDMAEN); + } + else if(hi2s->State == HAL_I2S_STATE_BUSY_RX) + { + /* Disable the I2S DMA Rx request */ + hi2s->Instance->CR2 &= (uint16_t)(~SPI_CR2_RXDMAEN); + } + + /* Process Unlocked */ + __HAL_UNLOCK(hi2s); + + return HAL_OK; +} + +/** +* @brief Resumes the audio stream playing from the Media. +* @param hi2s: I2S handle +* @retval None +*/ +HAL_StatusTypeDef HAL_I2S_DMAResume(I2S_HandleTypeDef *hi2s) +{ + /* Process Locked */ + __HAL_LOCK(hi2s); + + if(hi2s->State == HAL_I2S_STATE_BUSY_TX) + { + /* Enable the I2S DMA Tx request */ + hi2s->Instance->CR2 |= SPI_CR2_TXDMAEN; + } + else if(hi2s->State == HAL_I2S_STATE_BUSY_RX) + { + /* Enable the I2S DMA Rx request */ + hi2s->Instance->CR2 |= SPI_CR2_RXDMAEN; + } + + /* If the I2S peripheral is still not enabled, enable it */ + if ((hi2s->Instance->I2SCFGR & SPI_I2SCFGR_I2SE) == 0) + { + /* Enable I2S peripheral */ + __HAL_I2S_ENABLE(hi2s); + } + + /* Process Unlocked */ + __HAL_UNLOCK(hi2s); + + return HAL_OK; +} + +/** +* @brief Resumes the audio stream playing from the Media. +* @param hi2s: I2S handle +* @retval None +*/ +HAL_StatusTypeDef HAL_I2S_DMAStop(I2S_HandleTypeDef *hi2s) +{ + /* Process Locked */ + __HAL_LOCK(hi2s); + + /* Disable the I2S Tx/Rx DMA requests */ + hi2s->Instance->CR2 &= (uint16_t)(~SPI_CR2_TXDMAEN); + hi2s->Instance->CR2 &= (uint16_t)(~SPI_CR2_RXDMAEN); + + /* Disable the I2S DMA channel */ + __HAL_DMA_DISABLE(hi2s->hdmatx); + __HAL_DMA_DISABLE(hi2s->hdmarx); + + /* Disable I2S peripheral */ + __HAL_I2S_DISABLE(hi2s); + + hi2s->State = HAL_I2S_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2s); + + return HAL_OK; +} + +/** +* @brief This function handles I2S interrupt request. +* @param hi2s: I2S handle +* @retval HAL status +*/ +void HAL_I2S_IRQHandler(I2S_HandleTypeDef *hi2s) +{ + /* I2S in mode Receiver ------------------------------------------------*/ + if((__HAL_I2S_GET_FLAG(hi2s, I2S_FLAG_RXNE) != RESET) && (__HAL_I2S_GET_IT_SOURCE(hi2s, I2S_IT_RXNE) != RESET)) + { + I2S_Receive_IT(hi2s); + return; + } + + /* I2S in mode Tramitter -----------------------------------------------*/ + if((__HAL_I2S_GET_FLAG(hi2s, I2S_FLAG_TXE) != RESET) && (__HAL_I2S_GET_IT_SOURCE(hi2s, I2S_IT_TXE) != RESET)) + { + I2S_Transmit_IT(hi2s); + return; + } + + /* I2S Overrun error interrupt occured ---------------------------------*/ + if((__HAL_I2S_GET_FLAG(hi2s, I2S_FLAG_OVR) != RESET) && (__HAL_I2S_GET_IT_SOURCE(hi2s, I2S_IT_ERR) != RESET)) + { + /* Disable RXNE and ERR interrupt */ + __HAL_I2S_DISABLE_IT(hi2s, (I2S_IT_RXNE | I2S_IT_ERR)); + + /* Set the I2S State ready */ + hi2s->State = HAL_I2S_STATE_READY; + + /* Set the error code and execute error callback*/ + hi2s->ErrorCode |= HAL_I2S_ERROR_OVR; + HAL_I2S_ErrorCallback(hi2s); + } + + /* I2S Underrun error interrupt occured --------------------------------*/ + if((__HAL_I2S_GET_FLAG(hi2s, I2S_FLAG_UDR) != RESET) && (__HAL_I2S_GET_IT_SOURCE(hi2s, I2S_IT_ERR) != RESET)) + { + /* Disable TXE and ERR interrupt */ + __HAL_I2S_DISABLE_IT(hi2s, (I2S_IT_TXE | I2S_IT_ERR)); + + /* Set the I2S State ready */ + hi2s->State = HAL_I2S_STATE_READY; + + /* Set the error code and execute error callback*/ + hi2s->ErrorCode |= HAL_I2S_ERROR_UDR; + HAL_I2S_ErrorCallback(hi2s); + } +} + +/** +* @brief Tx Transfer Half completed callbacks +* @param hi2s: I2S handle +* @retval None +*/ +__weak void HAL_I2S_TxHalfCpltCallback(I2S_HandleTypeDef *hi2s) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_I2S_TxHalfCpltCallback could be implemented in the user file + */ +} + +/** +* @brief Tx Transfer completed callbacks +* @param hi2s: I2S handle +* @retval None +*/ +__weak void HAL_I2S_TxCpltCallback(I2S_HandleTypeDef *hi2s) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_I2S_TxCpltCallback could be implemented in the user file + */ +} + +/** +* @brief Rx Transfer half completed callbacks +* @param hi2s: I2S handle +* @retval None +*/ +__weak void HAL_I2S_RxHalfCpltCallback(I2S_HandleTypeDef *hi2s) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_I2S_RxCpltCallback could be implemented in the user file + */ +} + +/** +* @brief Rx Transfer completed callbacks +* @param hi2s: I2S handle +* @retval None +*/ +__weak void HAL_I2S_RxCpltCallback(I2S_HandleTypeDef *hi2s) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_I2S_RxCpltCallback could be implemented in the user file + */ +} + +/** +* @brief I2S error callbacks +* @param hi2s: I2S handle +* @retval None +*/ +__weak void HAL_I2S_ErrorCallback(I2S_HandleTypeDef *hi2s) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_I2S_ErrorCallback could be implemented in the user file + */ +} + +/** +* @} +*/ + +/** @defgroup I2S_Group3 Peripheral State and Errors functions +* @brief Peripheral State functions +* +@verbatim +=============================================================================== +##### Peripheral State and Errors functions ##### +=============================================================================== +[..] +This subsection permit to get in run-time the status of the peripheral +and the data flow. + +@endverbatim +* @{ +*/ + +/** +* @brief Return the I2S state +* @param hi2s : I2S handle +* @retval HAL state +*/ +HAL_I2S_StateTypeDef HAL_I2S_GetState(I2S_HandleTypeDef *hi2s) +{ + return hi2s->State; +} + +/** +* @brief Return the I2S error code +* @param hi2s : I2S handle +* @retval I2S Error Code +*/ +HAL_I2S_ErrorTypeDef HAL_I2S_GetError(I2S_HandleTypeDef *hi2s) +{ + return hi2s->ErrorCode; +} + +/** +* @} +*/ + +/** +* @brief DMA I2S transmit process complete callback +* @param hdma : DMA handle +* @retval None +*/ +static void I2S_DMATxCplt(DMA_HandleTypeDef *hdma) +{ + I2S_HandleTypeDef* hi2s = ( I2S_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + + /* Disable Tx DMA Request */ + hi2s->Instance->CR2 &= (uint16_t)(~SPI_CR2_TXDMAEN); + + hi2s->TxXferCount = 0; + hi2s->State = HAL_I2S_STATE_READY; + + HAL_I2S_TxCpltCallback(hi2s); +} + +/** +* @brief DMA I2S transmit process half complete callback +* @param hdma : DMA handle +* @retval None +*/ +static void I2S_DMATxHalfCplt(DMA_HandleTypeDef *hdma) +{ + I2S_HandleTypeDef* hi2s = (I2S_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent; + + HAL_I2S_TxHalfCpltCallback(hi2s); +} + +/** +* @brief DMA I2S receive process complete callback +* @param hdma : DMA handle +* @retval None +*/ +static void I2S_DMARxCplt(DMA_HandleTypeDef *hdma) +{ + I2S_HandleTypeDef* hi2s = ( I2S_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + + /* Disable Rx DMA Request */ + hi2s->Instance->CR2 &= (uint16_t)(~SPI_CR2_RXDMAEN); + hi2s->RxXferCount = 0; + + hi2s->State = HAL_I2S_STATE_READY; + HAL_I2S_RxCpltCallback(hi2s); +} + +/** +* @brief DMA I2S receive process half complete callback +* @param hdma : DMA handle +* @retval None +*/ +static void I2S_DMARxHalfCplt(DMA_HandleTypeDef *hdma) +{ + I2S_HandleTypeDef* hi2s = (I2S_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent; + + HAL_I2S_RxHalfCpltCallback(hi2s); +} + +/** +* @brief DMA I2S communication error callback +* @param hdma : DMA handle +* @retval None +*/ +static void I2S_DMAError(DMA_HandleTypeDef *hdma) +{ + I2S_HandleTypeDef* hi2s = ( I2S_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + + /* Disable Rx and Tx DMA Request */ + hi2s->Instance->CR2 &= (uint16_t)(~(SPI_CR2_RXDMAEN | SPI_CR2_TXDMAEN)); + hi2s->TxXferCount = 0; + hi2s->RxXferCount = 0; + + hi2s->State= HAL_I2S_STATE_READY; + + /* Set the error code and execute error callback*/ + hi2s->ErrorCode |= HAL_I2S_ERROR_DMA; + HAL_I2S_ErrorCallback(hi2s); +} + +/** +* @brief Transmit an amount of data in non-blocking mode with Interrupt +* @param hi2s: I2S handle + * @retval None +*/ +static void I2S_Transmit_IT(I2S_HandleTypeDef *hi2s) +{ + /* Transmit data */ + hi2s->Instance->DR = (*hi2s->pTxBuffPtr++); + hi2s->TxXferCount--; + + if(hi2s->TxXferCount == 0) + { + /* Disable TXE and ERR interrupt */ + __HAL_I2S_DISABLE_IT(hi2s, (I2S_IT_TXE | I2S_IT_ERR)); + + while(__HAL_I2S_GET_FLAG(hi2s, I2S_FLAG_TXE) == RESET) {}; + + while(__HAL_I2S_GET_FLAG(hi2s, I2S_FLAG_BSY) != RESET) {}; + + /* Disable I2S peripheral */ + __HAL_I2S_DISABLE(hi2s); + + hi2s->State = HAL_I2S_STATE_READY; + HAL_I2S_TxCpltCallback(hi2s); + } +} + +/** +* @brief Receive an amount of data in non-blocking mode with Interrupt +* @param hi2s: I2S handle + * @retval None +*/ +static void I2S_Receive_IT(I2S_HandleTypeDef *hi2s) +{ + /* Receive data */ + (*hi2s->pRxBuffPtr++) = hi2s->Instance->DR; + hi2s->RxXferCount--; + + /* Check if Master Receiver mode is selected */ + if((hi2s->Init.Mode == I2S_MODE_MASTER_RX) && \ + (__HAL_I2S_GET_FLAG(hi2s, I2S_FLAG_OVR) != RESET)) + { + /* Clear the Overrun Flag by a read operation on the SPI_DR register followed by a read + access to the SPI_SR register. */ + __HAL_I2S_CLEAR_OVRFLAG(hi2s); + } + + + if(hi2s->RxXferCount == 0) + { + /* Disable the I2S Peripheral Clock */ + __HAL_I2S_DISABLE(hi2s); + + /* Disable RXNE and ERR interrupt */ + __HAL_I2S_DISABLE_IT(hi2s, (I2S_IT_RXNE | I2S_IT_ERR)); + hi2s->State = HAL_I2S_STATE_READY; + HAL_I2S_RxCpltCallback(hi2s); + } +} + + +/** +* @brief This function handles I2S Communication Timeout. +* @param hi2s: I2S handle +* @param Flag: Flag checked +* @param State: Value of the flag expected +* @param Timeout: Duration of the timeout +* @retval HAL status +*/ +static HAL_StatusTypeDef I2S_WaitFlagStateUntilTimeout(I2S_HandleTypeDef *hi2s, uint32_t Flag, uint32_t State, uint32_t Timeout) +{ + uint32_t tickstart = HAL_GetTick(); + + /* Wait until flag is set */ + if(State == RESET) + { + while(__HAL_I2S_GET_FLAG(hi2s, Flag) == RESET) + { + if(Timeout != HAL_MAX_DELAY) + { + if((HAL_GetTick() - tickstart) > Timeout) + { + /* Set the I2S State ready */ + hi2s->State= HAL_I2S_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2s); + + return HAL_TIMEOUT; + } + } + } + } + else + { + while(__HAL_I2S_GET_FLAG(hi2s, Flag) != RESET) + { + if(Timeout != HAL_MAX_DELAY) + { + if((HAL_GetTick() - tickstart) > Timeout) + { + /* Set the I2S State ready */ + hi2s->State= HAL_I2S_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2s); + + return HAL_TIMEOUT; + } + } + } + } + return HAL_OK; +} + +/** +* @} +*/ + +#endif /* defined(STM32F031x6) || defined(STM32F038xx) || */ + /* defined(STM32F051x8) || defined(STM32F058xx) || */ + /* defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) || */ + /* defined(STM32F042x6) || defined(STM32F048xx) */ + +#endif /* HAL_I2S_MODULE_ENABLED */ +/** +* @} +*/ + +/** +* @} +*/ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_i2s.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_i2s.h new file mode 100644 index 0000000000..4c53280d4c --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_i2s.h @@ -0,0 +1,418 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_i2s.h + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief Header file of I2S HAL module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32F0xx_HAL_I2S_H +#define __STM32F0xx_HAL_I2S_H + +#ifdef __cplusplus + extern "C" { +#endif + +#if defined(STM32F031x6) || defined(STM32F038xx) || \ + defined(STM32F051x8) || defined(STM32F058xx) || \ + defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) || \ + defined(STM32F042x6) || defined(STM32F048xx) + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal_def.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @addtogroup I2S + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/** + * @brief I2S Init structure definition + */ +typedef struct +{ + uint32_t Mode; /*!< Specifies the I2S operating mode. + This parameter can be a value of @ref I2S_Mode */ + + uint32_t Standard; /*!< Specifies the standard used for the I2S communication. + This parameter can be a value of @ref I2S_Standard */ + + uint32_t DataFormat; /*!< Specifies the data format for the I2S communication. + This parameter can be a value of @ref I2S_Data_Format */ + + uint32_t MCLKOutput; /*!< Specifies whether the I2S MCLK output is enabled or not. + This parameter can be a value of @ref I2S_MCLK_Output */ + + uint32_t AudioFreq; /*!< Specifies the frequency selected for the I2S communication. + This parameter can be a value of @ref I2S_Audio_Frequency */ + + uint32_t CPOL; /*!< Specifies the idle state of the I2S clock. + This parameter can be a value of @ref I2S_Clock_Polarity */ + + uint32_t ClockSource; /*!< Specifies the I2S Clock Source. + This parameter can be a value of @ref I2S_Clock_Source */ + +}I2S_InitTypeDef; + +/** + * @brief HAL State structures definition + */ +typedef enum +{ + HAL_I2S_STATE_RESET = 0x00, /*!< I2S not yet initialized or disabled */ + HAL_I2S_STATE_READY = 0x01, /*!< I2S initialized and ready for use */ + HAL_I2S_STATE_BUSY = 0x02, /*!< I2S internal process is ongoing */ + HAL_I2S_STATE_BUSY_TX = 0x03, /*!< Data Transmission process is ongoing */ + HAL_I2S_STATE_BUSY_RX = 0x04, /*!< Data Reception process is ongoing */ + HAL_I2S_STATE_PAUSE = 0x06, /*!< I2S pause state: used in case of DMA */ + HAL_I2S_STATE_TIMEOUT = 0x07, /*!< I2S timeout state */ + HAL_I2S_STATE_ERROR = 0x08 /*!< I2S error state */ +}HAL_I2S_StateTypeDef; + +/** + * @brief HAL I2S Error Code structure definition + */ +typedef enum +{ + HAL_I2S_ERROR_NONE = 0x00, /*!< No error */ + HAL_I2S_ERROR_TIMEOUT = 0x01, /*!< Timeout error */ + HAL_I2S_ERROR_OVR = 0x02, /*!< OVR error */ + HAL_I2S_ERROR_UDR = 0x04, /*!< UDR error */ + HAL_I2S_ERROR_DMA = 0x08, /*!< DMA transfer error */ + HAL_I2S_ERROR_UNKNOW = 0x10 /*!< Unknow Error error */ +}HAL_I2S_ErrorTypeDef; + +/** + * @brief I2S handle Structure definition + */ +typedef struct +{ + SPI_TypeDef *Instance; /* I2S registers base address */ + + I2S_InitTypeDef Init; /* I2S communication parameters */ + + uint16_t *pTxBuffPtr; /* Pointer to I2S Tx transfer buffer */ + + __IO uint16_t TxXferSize; /* I2S Tx transfer size */ + + __IO uint16_t TxXferCount; /* I2S Tx transfer Counter */ + + uint16_t *pRxBuffPtr; /* Pointer to I2S Rx transfer buffer */ + + __IO uint16_t RxXferSize; /* I2S Rx transfer size */ + + __IO uint16_t RxXferCount; /* I2S Rx transfer counter */ + + DMA_HandleTypeDef *hdmatx; /* I2S Tx DMA handle parameters */ + + DMA_HandleTypeDef *hdmarx; /* I2S Rx DMA handle parameters */ + + __IO HAL_LockTypeDef Lock; /* I2S locking object */ + + __IO HAL_I2S_StateTypeDef State; /* I2S communication state */ + + __IO HAL_I2S_ErrorTypeDef ErrorCode; /* I2S Error code */ + +}I2S_HandleTypeDef; + +/* Exported constants --------------------------------------------------------*/ + +/** @defgroup I2S_Exported_Constants + * @{ + */ + +/** @defgroup I2S_Clock_Source + * @{ + */ +#define I2S_CLOCK_PLL ((uint32_t)0x00000000) +#define I2S_CLOCK_EXTERNAL ((uint32_t)0x00000001) + +#define IS_I2S_CLOCKSOURCE(CLOCK) (((CLOCK) == I2S_CLOCK_EXTERNAL) || \ + ((CLOCK) == I2S_CLOCK_PLL)) +/** + * @} + */ + +/** @defgroup I2S_Mode + * @{ + */ +#define I2S_MODE_SLAVE_TX ((uint32_t)0x00000000) +#define I2S_MODE_SLAVE_RX ((uint32_t)0x00000100) +#define I2S_MODE_MASTER_TX ((uint32_t)0x00000200) +#define I2S_MODE_MASTER_RX ((uint32_t)0x00000300) + +#define IS_I2S_MODE(MODE) (((MODE) == I2S_MODE_SLAVE_TX) || \ + ((MODE) == I2S_MODE_SLAVE_RX) || \ + ((MODE) == I2S_MODE_MASTER_TX)|| \ + ((MODE) == I2S_MODE_MASTER_RX)) +/** + * @} + */ + +/** @defgroup I2S_Standard + * @{ + */ +#define I2S_STANDARD_PHILIPS ((uint32_t)0x00000000) +#define I2S_STANDARD_MSB ((uint32_t)0x00000010) +#define I2S_STANDARD_LSB ((uint32_t)0x00000020) +#define I2S_STANDARD_PCM_SHORT ((uint32_t)0x00000030) +#define I2S_STANDARD_PCM_LONG ((uint32_t)0x000000B0) + +#define IS_I2S_STANDARD(STANDARD) (((STANDARD) == I2S_STANDARD_PHILIPS) || \ + ((STANDARD) == I2S_STANDARD_MSB) || \ + ((STANDARD) == I2S_STANDARD_LSB) || \ + ((STANDARD) == I2S_STANDARD_PCM_SHORT) || \ + ((STANDARD) == I2S_STANDARD_PCM_LONG)) +/** + * @} + */ + +/** @defgroup I2S_Data_Format + * @{ + */ +#define I2S_DATAFORMAT_16B ((uint32_t)0x00000000) +#define I2S_DATAFORMAT_16B_EXTENDED ((uint32_t)0x00000001) +#define I2S_DATAFORMAT_24B ((uint32_t)0x00000003) +#define I2S_DATAFORMAT_32B ((uint32_t)0x00000005) + +#define IS_I2S_DATA_FORMAT(FORMAT) (((FORMAT) == I2S_DATAFORMAT_16B) || \ + ((FORMAT) == I2S_DATAFORMAT_16B_EXTENDED) || \ + ((FORMAT) == I2S_DATAFORMAT_24B) || \ + ((FORMAT) == I2S_DATAFORMAT_32B)) +/** + * @} + */ + +/** @defgroup I2S_MCLK_Output + * @{ + */ +#define I2S_MCLKOUTPUT_ENABLE ((uint32_t)SPI_I2SPR_MCKOE) +#define I2S_MCLKOUTPUT_DISABLE ((uint32_t)0x00000000) + +#define IS_I2S_MCLK_OUTPUT(OUTPUT) (((OUTPUT) == I2S_MCLKOUTPUT_ENABLE) || \ + ((OUTPUT) == I2S_MCLKOUTPUT_DISABLE)) +/** + * @} + */ + +/** @defgroup I2S_Audio_Frequency + * @{ + */ +#define I2S_AUDIOFREQ_192K ((uint32_t)192000) +#define I2S_AUDIOFREQ_96K ((uint32_t)96000) +#define I2S_AUDIOFREQ_48K ((uint32_t)48000) +#define I2S_AUDIOFREQ_44K ((uint32_t)44100) +#define I2S_AUDIOFREQ_32K ((uint32_t)32000) +#define I2S_AUDIOFREQ_22K ((uint32_t)22050) +#define I2S_AUDIOFREQ_16K ((uint32_t)16000) +#define I2S_AUDIOFREQ_11K ((uint32_t)11025) +#define I2S_AUDIOFREQ_8K ((uint32_t)8000) +#define I2S_AUDIOFREQ_DEFAULT ((uint32_t)2) + +#define IS_I2S_AUDIO_FREQ(FREQ) ((((FREQ) >= I2S_AUDIOFREQ_8K) && \ + ((FREQ) <= I2S_AUDIOFREQ_192K)) || \ + ((FREQ) == I2S_AUDIOFREQ_DEFAULT)) +/** + * @} + */ + +/** @defgroup I2S_Clock_Polarity + * @{ + */ +#define I2S_CPOL_LOW ((uint32_t)0x00000000) +#define I2S_CPOL_HIGH ((uint32_t)SPI_I2SCFGR_CKPOL) + +#define IS_I2S_CPOL(CPOL) (((CPOL) == I2S_CPOL_LOW) || \ + ((CPOL) == I2S_CPOL_HIGH)) +/** + * @} + */ + +/** @defgroup I2S_Interrupt_configuration_definition + * @{ + */ +#define I2S_IT_TXE SPI_CR2_TXEIE +#define I2S_IT_RXNE SPI_CR2_RXNEIE +#define I2S_IT_ERR SPI_CR2_ERRIE +/** + * @} + */ + +/** @defgroup I2S_Flag_definition + * @{ + */ +#define I2S_FLAG_TXE SPI_SR_TXE +#define I2S_FLAG_RXNE SPI_SR_RXNE + +#define I2S_FLAG_UDR SPI_SR_UDR +#define I2S_FLAG_OVR SPI_SR_OVR +#define I2S_FLAG_FRE SPI_SR_FRE + +#define I2S_FLAG_CHSIDE SPI_SR_CHSIDE +#define I2S_FLAG_BSY SPI_SR_BSY +/** + * @} + */ + +/** + * @} + */ + +/* Exported macros -----------------------------------------------------------*/ + +/** @brief Reset I2S handle state + * @param __HANDLE__: I2S handle. + * @retval None + */ +#define __HAL_I2S_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_I2S_STATE_RESET) + +/** @brief Enable or disable the specified SPI peripheral (in I2S mode). + * @param __HANDLE__: specifies the I2S Handle. + * @retval None + */ +#define __HAL_I2S_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->I2SCFGR |= SPI_I2SCFGR_I2SE) +#define __HAL_I2S_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->I2SCFGR &= (uint16_t)(~SPI_I2SCFGR_I2SE)) + +/** @brief Enable or disable the specified I2S interrupts. + * @param __HANDLE__: specifies the I2S Handle. + * @param __INTERRUPT__: specifies the interrupt source to enable or disable. + * This parameter can be one of the following values: + * @arg I2S_IT_TXE: Tx buffer empty interrupt enable + * @arg I2S_IT_RXNE: RX buffer not empty interrupt enable + * @arg I2S_IT_ERR: Error interrupt enable + * @retval None + */ +#define __HAL_I2S_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR2 |= (__INTERRUPT__)) +#define __HAL_I2S_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR2 &= (uint16_t)(~(__INTERRUPT__))) + +/** @brief Checks if the specified I2S interrupt source is enabled or disabled. + * @param __HANDLE__: specifies the I2S Handle. + * This parameter can be I2S where x: 1, 2, or 3 to select the I2S peripheral. + * @param __INTERRUPT__: specifies the I2S interrupt source to check. + * This parameter can be one of the following values: + * @arg I2S_IT_TXE: Tx buffer empty interrupt enable + * @arg I2S_IT_RXNE: RX buffer not empty interrupt enable + * @arg I2S_IT_ERR: Error interrupt enable + * @retval The new state of __IT__ (TRUE or FALSE). + */ +#define __HAL_I2S_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((((__HANDLE__)->Instance->CR2 & (__INTERRUPT__)) == (__INTERRUPT__)) ? SET : RESET) + +/** @brief Checks whether the specified I2S flag is set or not. + * @param __HANDLE__: specifies the I2S Handle. + * @param __FLAG__: specifies the flag to check. + * This parameter can be one of the following values: + * @arg I2S_FLAG_RXNE: Receive buffer not empty flag + * @arg I2S_FLAG_TXE: Transmit buffer empty flag + * @arg I2S_FLAG_UDR: Underrun flag + * @arg I2S_FLAG_OVR: Overrun flag + * @arg I2S_FLAG_FRE: Frame error flag + * @arg I2S_FLAG_CHSIDE: Channel Side flag + * @arg I2S_FLAG_BSY: Busy flag + * @retval The new state of __FLAG__ (TRUE or FALSE). + */ +#define __HAL_I2S_GET_FLAG(__HANDLE__, __FLAG__) ((((__HANDLE__)->Instance->SR) & (__FLAG__)) == (__FLAG__)) + +/** @brief Clears the I2S OVR pending flag. + * @param __HANDLE__: specifies the I2S Handle. + * @retval None + */ +#define __HAL_I2S_CLEAR_OVRFLAG(__HANDLE__) do{__IO uint32_t tmpreg = (__HANDLE__)->Instance->DR;\ + tmpreg = (__HANDLE__)->Instance->SR;}while(0) +/** @brief Clears the I2S UDR pending flag. + * @param __HANDLE__: specifies the I2S Handle. + * @retval None + */ +#define __HAL_I2S_CLEAR_UDRFLAG(__HANDLE__)((__HANDLE__)->Instance->SR) + +/* Exported functions --------------------------------------------------------*/ + +/* Initialization/de-initialization functions **********************************/ +__weak HAL_StatusTypeDef HAL_I2S_Init(I2S_HandleTypeDef *hi2s); +HAL_StatusTypeDef HAL_I2S_DeInit (I2S_HandleTypeDef *hi2s); +void HAL_I2S_MspInit(I2S_HandleTypeDef *hi2s); +void HAL_I2S_MspDeInit(I2S_HandleTypeDef *hi2s); + +/* I/O operation functions ***************************************************/ + /* Blocking mode: Polling */ +HAL_StatusTypeDef HAL_I2S_Transmit(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size, uint32_t Timeout); +HAL_StatusTypeDef HAL_I2S_Receive(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size, uint32_t Timeout); + + /* Non-Blocking mode: Interrupt */ +HAL_StatusTypeDef HAL_I2S_Transmit_IT(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size); +HAL_StatusTypeDef HAL_I2S_Receive_IT(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size); +void HAL_I2S_IRQHandler(I2S_HandleTypeDef *hi2s); + +/* Non-Blocking mode: DMA */ +HAL_StatusTypeDef HAL_I2S_Transmit_DMA(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size); +HAL_StatusTypeDef HAL_I2S_Receive_DMA(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size); + +HAL_StatusTypeDef HAL_I2S_DMAPause(I2S_HandleTypeDef *hi2s); +HAL_StatusTypeDef HAL_I2S_DMAResume(I2S_HandleTypeDef *hi2s); +HAL_StatusTypeDef HAL_I2S_DMAStop(I2S_HandleTypeDef *hi2s); + +/* Peripheral Control and State functions **************************************/ +HAL_I2S_StateTypeDef HAL_I2S_GetState(I2S_HandleTypeDef *hi2s); +HAL_I2S_ErrorTypeDef HAL_I2S_GetError(I2S_HandleTypeDef *hi2s); + +/* Callbacks used in non blocking modes (Interrupt and DMA) *******************/ +void HAL_I2S_TxHalfCpltCallback(I2S_HandleTypeDef *hi2s); +void HAL_I2S_TxCpltCallback(I2S_HandleTypeDef *hi2s); +void HAL_I2S_RxHalfCpltCallback(I2S_HandleTypeDef *hi2s); +void HAL_I2S_RxCpltCallback(I2S_HandleTypeDef *hi2s); +void HAL_I2S_ErrorCallback(I2S_HandleTypeDef *hi2s); + +/** + * @} + */ + +/** + * @} + */ + +#endif /* defined(STM32F031x6) || defined(STM32F038xx) || */ + /* defined(STM32F051x8) || defined(STM32F058xx) || */ + /* defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) ||*/ + /* defined(STM32F042x6) || defined(STM32F048xx) */ + +#ifdef __cplusplus +} +#endif + + +#endif /* __STM32F0xx_HAL_I2S_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_irda.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_irda.c new file mode 100644 index 0000000000..a18021af80 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_irda.c @@ -0,0 +1,1266 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_irda.c + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief IRDA HAL module driver. + * + * This file provides firmware functions to manage the following + * functionalities of the IrDA (Infrared Data Association) Peripheral + * (IRDA) + * + Initialization and de-initialization function + * + IO operation function + * + Peripheral Control function + * + * + @verbatim + =============================================================================== + ##### How to use this driver ##### + =============================================================================== + [..] + The IRDA HAL driver can be used as follows: + + (#) Declare a IRDA_HandleTypeDef handle structure. + (#) Initialize the IRDA low level resources by implementing the HAL_IRDA_MspInit() API + in setting the associated USART or UART in IRDA mode: + (##) Enable the USARTx/UARTx interface clock. + (##) USARTx/UARTx pins configuration: + (+) Enable the clock for the USARTx/UARTx GPIOs. + (+) Configure these USARTx/UARTx pins as alternate function pull-up. + (##) NVIC configuration if you need to use interrupt process (HAL_IRDA_Transmit_IT() + and HAL_IRDA_Receive_IT() APIs): + (+) Configure the USARTx/UARTx interrupt priority. + (+) Enable the NVIC IRDA IRQ handle. + (@) The specific IRDA interrupts (Transmission complete interrupt, + RXNE interrupt and Error Interrupts) will be managed using the macros + __HAL_IRDA_ENABLE_IT() and __HAL_IRDA_DISABLE_IT() inside the transmit and receive process. + (##) DMA Configuration if you need to use DMA process (HAL_IRDA_Transmit_DMA() + and HAL_IRDA_Receive_DMA() APIs): + (+) Declare a DMA handle structure for the Tx/Rx stream. + (+) Enable the DMAx interface clock. + (+) Configure the declared DMA handle structure with the required Tx/Rx parameters. + (+) Configure the DMA Tx/Rx Stream. + (+) Associate the initilalized DMA handle to the IRDA DMA Tx/Rx handle. + (+) Configure the priority and enable the NVIC for the transfer complete interrupt on the DMA Tx/Rx Stream. + + (#) Program the Baud Rate, Word Length and Parity and Mode(Receiver/Transmitter), + the normal or low power mode and the clock prescaler in the hirda Init structure. + + (#) Initialize the IRDA registers by calling + the HAL_IRDA_Init() API. + + (@) This API (HAL_IRDA_Init()) configures also the low level Hardware (GPIO, CLOCK, CORTEX...etc) + by calling the customized HAL_IRDA_MspInit() API. + + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @defgroup IRDA + * @brief HAL IRDA module driver + * @{ + */ +#ifdef HAL_IRDA_MODULE_ENABLED + +#if !defined(STM32F030x6) && !defined(STM32F030x8) + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +#define TEACK_REACK_TIMEOUT 1000 +#define HAL_IRDA_TXDMA_TIMEOUTVALUE 22000 +#define IRDA_CR1_FIELDS ((uint32_t)(USART_CR1_M | USART_CR1_PCE \ + | USART_CR1_PS | USART_CR1_TE | USART_CR1_RE)) +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +static void IRDA_DMATransmitCplt(DMA_HandleTypeDef *hdma); +static void IRDA_DMAReceiveCplt(DMA_HandleTypeDef *hdma); +static void IRDA_DMAError(DMA_HandleTypeDef *hdma); +static HAL_StatusTypeDef IRDA_SetConfig(IRDA_HandleTypeDef *hirda); +static HAL_StatusTypeDef IRDA_CheckIdleState(IRDA_HandleTypeDef *hirda); +static HAL_StatusTypeDef IRDA_WaitOnFlagUntilTimeout(IRDA_HandleTypeDef *hirda, uint32_t Flag, FlagStatus Status, uint32_t Timeout); +static HAL_StatusTypeDef IRDA_Transmit_IT(IRDA_HandleTypeDef *hirda); +static HAL_StatusTypeDef IRDA_Receive_IT(IRDA_HandleTypeDef *hirda); +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup IRDA_Private_Functions + * @{ + */ + +/** @defgroup HAL_IRDA_Group1 Initialization/de-initialization functions + * @brief Initialization and Configuration functions + * +@verbatim +=============================================================================== + ##### Initialization and Configuration functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to initialize the USARTx + in asynchronous IRDA mode. + (+) For the asynchronous mode only these parameters can be configured: + (++) Baud Rate + (++) Word Length + (++) Parity: If the parity is enabled, then the MSB bit of the data written + in the data register is transmitted but is changed by the parity bit. + Depending on the frame length defined by the M bit (8-bits or 9-bits) + or by the M1 and M0 bits (7-bit, 8-bit or 9-bit), + the possible IRDA frame formats are as listed in the following table: + +---------------------------------------------------------------+ + | M bit | PCE bit | IRDA frame | + |-----------|-----------|---------------------------------------| + | 0 | 0 | | SB | 8-bit data | STB | | + |-----------|-----------|---------------------------------------| + | 0 | 1 | | SB | 7-bit data | PB | STB | | + |-----------|-----------|---------------------------------------| + | 1 | 0 | | SB | 9-bit data | STB | | + |-----------|-----------|---------------------------------------| + | 1 | 1 | | SB | 8-bit data | PB | STB | | + +---------------------------------------------------------------+ + | M1M0 bits | PCE bit | IRDA frame | + |-----------------------|---------------------------------------| + | 10 | 0 | | SB | 7-bit data | STB | | + |-----------|-----------|---------------------------------------| + | 10 | 1 | | SB | 6-bit data | PB | STB | | + +---------------------------------------------------------------+ + + (++) Power mode + (++) Prescaler setting + (++) Receiver/transmitter modes + + [..] + The HAL_IRDA_Init() API follows the USART asynchronous configuration procedures + (details for the procedures are available in reference manual). + +@endverbatim + * @{ + */ + +/** + * @brief Initializes the IRDA mode according to the specified + * parameters in the IRDA_InitTypeDef and creates the associated handle . + * @param hirda: IRDA handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_IRDA_Init(IRDA_HandleTypeDef *hirda) +{ + /* Check the IRDA handle allocation */ + if(hirda == NULL) + { + return HAL_ERROR; + } + + /* Check the USART/UART associated to the IRDA handle */ + assert_param(IS_IRDA_INSTANCE(hirda->Instance)); + + if(hirda->State == HAL_IRDA_STATE_RESET) + { + /* Init the low level hardware : GPIO, CLOCK */ + HAL_IRDA_MspInit(hirda); + } + + hirda->State = HAL_IRDA_STATE_BUSY; + + /* Disable the Peripheral to update the configuration registers */ + __HAL_IRDA_DISABLE(hirda); + + /* Set the IRDA Communication parameters */ + if (IRDA_SetConfig(hirda) == HAL_ERROR) + { + return HAL_ERROR; + } + + /* In IRDA mode, the following bits must be kept cleared: + - LINEN, STOP and CLKEN bits in the USART_CR2 register, + - SCEN and HDSEL bits in the USART_CR3 register.*/ + hirda->Instance->CR2 &= ~(USART_CR2_LINEN | USART_CR2_CLKEN | USART_CR2_STOP); + hirda->Instance->CR3 &= ~(USART_CR3_SCEN | USART_CR3_HDSEL); + + /* set the UART/USART in IRDA mode */ + hirda->Instance->CR3 |= USART_CR3_IREN; + + /* Enable the Peripheral */ + __HAL_IRDA_ENABLE(hirda); + + /* TEACK and/or REACK to check before moving hirda->State to Ready */ + return (IRDA_CheckIdleState(hirda)); +} + + + + + + +/** + * @brief DeInitializes the IRDA peripheral + * @param hirda: IRDA handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_IRDA_DeInit(IRDA_HandleTypeDef *hirda) +{ + /* Check the IRDA handle allocation */ + if(hirda == NULL) + { + return HAL_ERROR; + } + + /* Check the USART/UART associated to the IRDA handle */ + assert_param(IS_IRDA_INSTANCE(hirda->Instance)); + + hirda->State = HAL_IRDA_STATE_BUSY; + + /* DeInit the low level hardware */ + HAL_IRDA_MspDeInit(hirda); + /* Disable the Peripheral */ + __HAL_IRDA_DISABLE(hirda); + + hirda->ErrorCode = HAL_IRDA_ERROR_NONE; + hirda->State = HAL_IRDA_STATE_RESET; + + /* Process Unlock */ + __HAL_UNLOCK(hirda); + + return HAL_OK; +} + +/** + * @brief IRDA MSP Init + * @param hirda: IRDA handle + * @retval None + */ + __weak void HAL_IRDA_MspInit(IRDA_HandleTypeDef *hirda) +{ + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_IRDA_MspInit can be implemented in the user file + */ +} + +/** + * @brief IRDA MSP DeInit + * @param hirda: IRDA handle + * @retval None + */ + __weak void HAL_IRDA_MspDeInit(IRDA_HandleTypeDef *hirda) +{ + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_IRDA_MspDeInit can be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup HAL_IRDA_Group2 IO operation functions + * @brief IRDA Transmit/Receive functions + * +@verbatim + =============================================================================== + ##### I/O operation functions ##### + =============================================================================== + This subsection provides a set of functions allowing to manage the IRDA asynchronous + data transfers. + + (#) There are two modes of transfer: + (+) Blocking mode: the communication is performed in polling mode. + The HAL status of all data processing is returned by the same function + after finishing transfer. + (+) No-Blocking mode: the communication is performed using Interrupts + or DMA, these API's return the HAL status. + The end of the data processing will be indicated through the + dedicated IRDA IRQ when using Interrupt mode or the DMA IRQ when + using DMA mode. + The HAL_IRDA_TxCpltCallback(), HAL_IRDA_RxCpltCallback() user callbacks + will be executed respectivelly at the end of the Transmit or Receive process + The HAL_IRDA_ErrorCallback() user callback will be executed when a communication error is detected + + (#) Blocking mode API's are : + (+) HAL_IRDA_Transmit() + (+) HAL_IRDA_Receive() + + (#) Non-Blocking mode API's with Interrupt are : + (+) HAL_IRDA_Transmit_IT() + (+) HAL_IRDA_Receive_IT() + (+) HAL_IRDA_IRQHandler() + (+) IRDA_Transmit_IT() + (+) IRDA_Receive_IT() + + (#) Non-Blocking mode functions with DMA are : + (+) HAL_IRDA_Transmit_DMA() + (+) HAL_IRDA_Receive_DMA() + + (#) A set of Transfer Complete Callbacks are provided in No_Blocking mode: + (+) HAL_IRDA_TxCpltCallback() + (+) HAL_IRDA_RxCpltCallback() + (+) HAL_IRDA_ErrorCallback() + +@endverbatim + * @{ + */ + +/** + * @brief Send an amount of data in blocking mode + * @param hirda: IRDA handle + * @param pData: pointer to data buffer + * @param Size: amount of data to be sent + * @param Timeout: Duration of the timeout + * @retval HAL status + */ +HAL_StatusTypeDef HAL_IRDA_Transmit(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size, uint32_t Timeout) +{ + uint16_t* tmp; + + if ((hirda->State == HAL_IRDA_STATE_READY) || (hirda->State == HAL_IRDA_STATE_BUSY_RX)) + { + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(hirda); + hirda->ErrorCode = HAL_IRDA_ERROR_NONE; + + if(hirda->State == HAL_IRDA_STATE_BUSY_RX) + { + hirda->State = HAL_IRDA_STATE_BUSY_TX_RX; + } + else + { + hirda->State = HAL_IRDA_STATE_BUSY_TX; + } + + hirda->TxXferSize = Size; + hirda->TxXferCount = Size; + while(hirda->TxXferCount > 0) + { + hirda->TxXferCount--; + + if(IRDA_WaitOnFlagUntilTimeout(hirda, IRDA_FLAG_TXE, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + if ((hirda->Init.WordLength == IRDA_WORDLENGTH_9B) && (hirda->Init.Parity == IRDA_PARITY_NONE)) + { + tmp = (uint16_t*) pData; + hirda->Instance->TDR = (*tmp & (uint16_t)0x01FF); + pData += 2; + } + else + { + hirda->Instance->TDR = (*pData++ & (uint8_t)0xFF); + } + } + + if(IRDA_WaitOnFlagUntilTimeout(hirda, IRDA_FLAG_TC, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + if(hirda->State == HAL_IRDA_STATE_BUSY_TX_RX) + { + hirda->State = HAL_IRDA_STATE_BUSY_RX; + } + else + { + hirda->State = HAL_IRDA_STATE_READY; + } + + /* Process Unlocked */ + __HAL_UNLOCK(hirda); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive an amount of data in blocking mode + * @param hirda: IRDA handle + * @param pData: pointer to data buffer + * @param Size: amount of data to be received + * @param Timeout: Duration of the timeout + * @retval HAL status + */ +HAL_StatusTypeDef HAL_IRDA_Receive(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size, uint32_t Timeout) +{ + uint16_t* tmp; + uint16_t uhMask; + + if ((hirda->State == HAL_IRDA_STATE_READY) || (hirda->State == HAL_IRDA_STATE_BUSY_TX)) + { + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(hirda); + hirda->ErrorCode = HAL_IRDA_ERROR_NONE; + + if(hirda->State == HAL_IRDA_STATE_BUSY_TX) + { + hirda->State = HAL_IRDA_STATE_BUSY_TX_RX; + } + else + { + hirda->State = HAL_IRDA_STATE_BUSY_RX; + } + + hirda->RxXferSize = Size; + hirda->RxXferCount = Size; + + /* Computation of the mask to apply to the RDR register + of the UART associated to the IRDA */ + __HAL_IRDA_MASK_COMPUTATION(hirda); + uhMask = hirda->Mask; + + /* Check data remaining to be received */ + while(hirda->RxXferCount > 0) + { + hirda->RxXferCount--; + + if(IRDA_WaitOnFlagUntilTimeout(hirda, IRDA_FLAG_RXNE, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + if ((hirda->Init.WordLength == IRDA_WORDLENGTH_9B) && (hirda->Init.Parity == IRDA_PARITY_NONE)) + { + tmp = (uint16_t*) pData ; + *tmp = (uint16_t)(hirda->Instance->RDR & uhMask); + pData +=2; + } + else + { + *pData++ = (uint8_t)(hirda->Instance->RDR & (uint8_t)uhMask); + } + } + + if(hirda->State == HAL_IRDA_STATE_BUSY_TX_RX) + { + hirda->State = HAL_IRDA_STATE_BUSY_TX; + } + else + { + hirda->State = HAL_IRDA_STATE_READY; + } + + /* Process Unlocked */ + __HAL_UNLOCK(hirda); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Send an amount of data in interrupt mode + * @param hirda: IRDA handle + * @param pData: pointer to data buffer + * @param Size: amount of data to be sent + * @retval HAL status + */ +HAL_StatusTypeDef HAL_IRDA_Transmit_IT(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size) +{ + if ((hirda->State == HAL_IRDA_STATE_READY) || (hirda->State == HAL_IRDA_STATE_BUSY_RX)) + { + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(hirda); + + hirda->pTxBuffPtr = pData; + hirda->TxXferSize = Size; + hirda->TxXferCount = Size; + + hirda->ErrorCode = HAL_IRDA_ERROR_NONE; + if(hirda->State == HAL_IRDA_STATE_BUSY_RX) + { + hirda->State = HAL_IRDA_STATE_BUSY_TX_RX; + } + else + { + hirda->State = HAL_IRDA_STATE_BUSY_TX; + } + + /* Enable the IRDA Error Interrupt: (Frame error, noise error, overrun error) */ + __HAL_IRDA_ENABLE_IT(hirda, IRDA_IT_ERR); + + /* Process Unlocked */ + __HAL_UNLOCK(hirda); + + /* Enable the IRDA Transmit Complete Interrupt */ + __HAL_IRDA_ENABLE_IT(hirda, IRDA_IT_TC); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive an amount of data in interrupt mode + * @param hirda: IRDA handle + * @param pData: pointer to data buffer + * @param Size: amount of data to be received + * @retval HAL status + */ +HAL_StatusTypeDef HAL_IRDA_Receive_IT(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size) +{ + if ((hirda->State == HAL_IRDA_STATE_READY) || (hirda->State == HAL_IRDA_STATE_BUSY_TX)) + { + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(hirda); + + hirda->pRxBuffPtr = pData; + hirda->RxXferSize = Size; + hirda->RxXferCount = Size; + + /* Computation of the mask to apply to the RDR register + of the UART associated to the IRDA */ + __HAL_IRDA_MASK_COMPUTATION(hirda); + + hirda->ErrorCode = HAL_IRDA_ERROR_NONE; + if(hirda->State == HAL_IRDA_STATE_BUSY_TX) + { + hirda->State = HAL_IRDA_STATE_BUSY_TX_RX; + } + else + { + hirda->State = HAL_IRDA_STATE_BUSY_RX; + } + + /* Enable the IRDA Parity Error Interrupt */ + __HAL_IRDA_ENABLE_IT(hirda, IRDA_IT_PE); + + /* Enable the IRDA Error Interrupt: (Frame error, noise error, overrun error) */ + __HAL_IRDA_ENABLE_IT(hirda, IRDA_IT_ERR); + + /* Process Unlocked */ + __HAL_UNLOCK(hirda); + + /* Enable the IRDA Data Register not empty Interrupt */ + __HAL_IRDA_ENABLE_IT(hirda, IRDA_IT_RXNE); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Send an amount of data in DMA mode + * @param hirda: IRDA handle + * @param pData: pointer to data buffer + * @param Size: amount of data to be sent + * @retval HAL status + */ +HAL_StatusTypeDef HAL_IRDA_Transmit_DMA(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size) +{ + uint32_t *tmp; + + if ((hirda->State == HAL_IRDA_STATE_READY) || (hirda->State == HAL_IRDA_STATE_BUSY_RX)) + { + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(hirda); + + hirda->pTxBuffPtr = pData; + hirda->TxXferSize = Size; + hirda->TxXferCount = Size; + + hirda->ErrorCode = HAL_IRDA_ERROR_NONE; + + if(hirda->State == HAL_IRDA_STATE_BUSY_RX) + { + hirda->State = HAL_IRDA_STATE_BUSY_TX_RX; + } + else + { + hirda->State = HAL_IRDA_STATE_BUSY_TX; + } + + /* Set the IRDA DMA transfer complete callback */ + hirda->hdmatx->XferCpltCallback = IRDA_DMATransmitCplt; + + /* Set the DMA error callback */ + hirda->hdmatx->XferErrorCallback = IRDA_DMAError; + + /* Enable the IRDA transmit DMA channel */ + tmp = (uint32_t*)&pData; + HAL_DMA_Start_IT(hirda->hdmatx, *(uint32_t*)tmp, (uint32_t)&hirda->Instance->TDR, Size); + + /* Enable the DMA transfer for transmit request by setting the DMAT bit + in the IRDA CR3 register */ + hirda->Instance->CR3 |= USART_CR3_DMAT; + + /* Process Unlocked */ + __HAL_UNLOCK(hirda); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive an amount of data in DMA mode + * @param hirda: IRDA handle + * @param pData: pointer to data buffer + * @param Size: amount of data to be received + * @note When the IRDA parity is enabled (PCE = 1), the received data contain + * the parity bit (MSB position) + * @retval HAL status + */ +HAL_StatusTypeDef HAL_IRDA_Receive_DMA(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size) +{ + uint32_t *tmp; + + if ((hirda->State == HAL_IRDA_STATE_READY) || (hirda->State == HAL_IRDA_STATE_BUSY_TX)) + { + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(hirda); + + hirda->pRxBuffPtr = pData; + hirda->RxXferSize = Size; + + hirda->ErrorCode = HAL_IRDA_ERROR_NONE; + if(hirda->State == HAL_IRDA_STATE_BUSY_TX) + { + hirda->State = HAL_IRDA_STATE_BUSY_TX_RX; + } + else + { + hirda->State = HAL_IRDA_STATE_BUSY_RX; + } + + /* Set the IRDA DMA transfer complete callback */ + hirda->hdmarx->XferCpltCallback = IRDA_DMAReceiveCplt; + + /* Set the DMA error callback */ + hirda->hdmarx->XferErrorCallback = IRDA_DMAError; + + /* Enable the DMA channel */ + tmp = (uint32_t*)&pData; + HAL_DMA_Start_IT(hirda->hdmarx, (uint32_t)&hirda->Instance->RDR, *(uint32_t*)tmp, Size); + + /* Enable the DMA transfer for the receiver request by setting the DMAR bit + in the IRDA CR3 register */ + hirda->Instance->CR3 |= USART_CR3_DMAR; + + /* Process Unlocked */ + __HAL_UNLOCK(hirda); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief This function handles IRDA interrupt request. + * @param hirda: IRDA handle + * @retval None + */ +void HAL_IRDA_IRQHandler(IRDA_HandleTypeDef *hirda) +{ + /* IRDA parity error interrupt occurred -------------------------------------*/ + if((__HAL_IRDA_GET_IT(hirda, IRDA_IT_PE) != RESET) && (__HAL_IRDA_GET_IT_SOURCE(hirda, IRDA_IT_PE) != RESET)) + { + __HAL_IRDA_CLEAR_IT(hirda, IRDA_CLEAR_PEF); + + hirda->ErrorCode |= HAL_IRDA_ERROR_PE; + /* Set the IRDA state ready to be able to start again the process */ + hirda->State = HAL_IRDA_STATE_READY; + } + + /* IRDA frame error interrupt occured --------------------------------------*/ + if((__HAL_IRDA_GET_IT(hirda, IRDA_IT_FE) != RESET) && (__HAL_IRDA_GET_IT_SOURCE(hirda, IRDA_IT_ERR) != RESET)) + { + __HAL_IRDA_CLEAR_IT(hirda, IRDA_CLEAR_FEF); + + hirda->ErrorCode |= HAL_IRDA_ERROR_FE; + /* Set the IRDA state ready to be able to start again the process */ + hirda->State = HAL_IRDA_STATE_READY; + } + + /* IRDA noise error interrupt occured --------------------------------------*/ + if((__HAL_IRDA_GET_IT(hirda, IRDA_IT_NE) != RESET) && (__HAL_IRDA_GET_IT_SOURCE(hirda, IRDA_IT_ERR) != RESET)) + { + __HAL_IRDA_CLEAR_IT(hirda, IRDA_CLEAR_NEF); + + hirda->ErrorCode |= HAL_IRDA_ERROR_NE; + /* Set the IRDA state ready to be able to start again the process */ + hirda->State = HAL_IRDA_STATE_READY; + } + + /* IRDA Over-Run interrupt occured -----------------------------------------*/ + if((__HAL_IRDA_GET_IT(hirda, IRDA_IT_ORE) != RESET) && (__HAL_IRDA_GET_IT_SOURCE(hirda, IRDA_IT_ERR) != RESET)) + { + __HAL_IRDA_CLEAR_IT(hirda, IRDA_CLEAR_OREF); + + hirda->ErrorCode |= HAL_IRDA_ERROR_ORE; + /* Set the IRDA state ready to be able to start again the process */ + hirda->State = HAL_IRDA_STATE_READY; + } + + /* Call IRDA Error Call back function if need be --------------------------*/ + if(hirda->ErrorCode != HAL_IRDA_ERROR_NONE) + { + HAL_IRDA_ErrorCallback(hirda); + } + + /* IRDA in mode Receiver ---------------------------------------------------*/ + if((__HAL_IRDA_GET_IT(hirda, IRDA_IT_RXNE) != RESET) && (__HAL_IRDA_GET_IT_SOURCE(hirda, IRDA_IT_RXNE) != RESET)) + { + IRDA_Receive_IT(hirda); + /* Clear RXNE interrupt flag */ + __HAL_IRDA_SEND_REQ(hirda, IRDA_RXDATA_FLUSH_REQUEST); + } + + + /* IRDA in mode Transmitter ------------------------------------------------*/ + if((__HAL_IRDA_GET_IT(hirda, IRDA_IT_TC) != RESET) &&(__HAL_IRDA_GET_IT_SOURCE(hirda, IRDA_IT_TC) != RESET)) + { + IRDA_Transmit_IT(hirda); + } + +} + +/** + * @brief DMA IRDA Tx transfer completed callback + * @param hdma: DMA handle + * @retval None + */ +static void IRDA_DMATransmitCplt(DMA_HandleTypeDef *hdma) +{ + IRDA_HandleTypeDef* hirda = ( IRDA_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + hirda->TxXferCount = 0; + + /* Disable the DMA transfer for transmit request by setting the DMAT bit + in the IRDA CR3 register */ + hirda->Instance->CR3 &= (uint16_t)~((uint16_t)USART_CR3_DMAT); + + /* Wait for IRDA TC Flag */ + if(IRDA_WaitOnFlagUntilTimeout(hirda, IRDA_FLAG_TC, RESET, HAL_IRDA_TXDMA_TIMEOUTVALUE) != HAL_OK) + { + /* Timeout Occured */ + HAL_IRDA_ErrorCallback(hirda); + } + else + { + /* No Timeout */ + if(hirda->State == HAL_IRDA_STATE_BUSY_TX_RX) + { + hirda->State = HAL_IRDA_STATE_BUSY_RX; + } + else + { + hirda->State = HAL_IRDA_STATE_READY; + } + HAL_IRDA_TxCpltCallback(hirda); + } +} + +/** + * @brief DMA IRDA Rx Transfer completed callback + * @param hdma: DMA handle + * @retval None + */ +static void IRDA_DMAReceiveCplt(DMA_HandleTypeDef *hdma) +{ + IRDA_HandleTypeDef* hirda = ( IRDA_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + hirda->RxXferCount = 0; + + /* Disable the DMA transfer for the receiver request by setting the DMAR bit + in the IRDA CR3 register */ + hirda->Instance->CR3 &= (uint16_t)~((uint16_t)USART_CR3_DMAR); + + if(hirda->State == HAL_IRDA_STATE_BUSY_TX_RX) + { + hirda->State = HAL_IRDA_STATE_BUSY_TX; + } + else + { + hirda->State = HAL_IRDA_STATE_READY; + } + + HAL_IRDA_RxCpltCallback(hirda); +} + +/** + * @brief DMA IRDA communication error callback + * @param hdma: DMA handle + * @retval None + */ +static void IRDA_DMAError(DMA_HandleTypeDef *hdma) +{ + IRDA_HandleTypeDef* hirda = ( IRDA_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + hirda->RxXferCount = 0; + hirda->TxXferCount = 0; + hirda->State= HAL_IRDA_STATE_READY; + hirda->ErrorCode |= HAL_IRDA_ERROR_DMA; + HAL_IRDA_ErrorCallback(hirda); +} + +/** + * @brief Tx Transfer completed callback + * @param hirda: irda handle + * @retval None + */ + __weak void HAL_IRDA_TxCpltCallback(IRDA_HandleTypeDef *hirda) +{ + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_IRDA_TxCpltCallback can be implemented in the user file + */ +} + +/** + * @brief Rx Transfer completed callback + * @param hirda: irda handle + * @retval None + */ +__weak void HAL_IRDA_RxCpltCallback(IRDA_HandleTypeDef *hirda) +{ + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_IRDA_TxCpltCallback can be implemented in the user file + */ +} + +/** + * @brief IRDA error callback + * @param hirda: IRDA handle + * @retval None + */ + __weak void HAL_IRDA_ErrorCallback(IRDA_HandleTypeDef *hirda) +{ + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_IRDA_ErrorCallback can be implemented in the user file + */ +} + +/** + * @brief Receive an amount of data in non blocking mode. + * Function called under interruption only, once + * interruptions have been enabled by HAL_IRDA_Transmit_IT() + * @param hirda: IRDA handle + * @retval HAL status + */ +static HAL_StatusTypeDef IRDA_Transmit_IT(IRDA_HandleTypeDef *hirda) +{ + uint16_t* tmp; + + if((hirda->State == HAL_IRDA_STATE_BUSY_TX) || (hirda->State == HAL_IRDA_STATE_BUSY_TX_RX)) + { + __HAL_LOCK(hirda); + + if(hirda->TxXferCount == 0) + { + /* Disable the IRDA Transmit Complete Interrupt */ + __HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_TC); + + if(hirda->State == HAL_IRDA_STATE_BUSY_TX_RX) + { + hirda->State = HAL_IRDA_STATE_BUSY_RX; + } + else + { + /* Disable the IRDA Error Interrupt: (Frame error, noise error, overrun error) */ + __HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_ERR); + + hirda->State = HAL_IRDA_STATE_READY; + } + + /* Call the Process Unlocked before calling the Tx call back API to give the possibiity to + start again the Transmission under the Tx call back API */ + __HAL_UNLOCK(hirda); + + HAL_IRDA_TxCpltCallback(hirda); + + return HAL_OK; + } + else + { + if ((hirda->Init.WordLength == IRDA_WORDLENGTH_9B) && (hirda->Init.Parity == IRDA_PARITY_NONE)) + { + tmp = (uint16_t*) hirda->pTxBuffPtr; + hirda->Instance->TDR = (*tmp & (uint16_t)0x01FF); + hirda->pTxBuffPtr += 2; + } + else + { + hirda->Instance->TDR = (uint8_t)(*hirda->pTxBuffPtr++ & (uint8_t)0xFF); + } + hirda->TxXferCount--; + + /* Process Unlocked */ + __HAL_UNLOCK(hirda); + + return HAL_OK; + } + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive an amount of data in non blocking mode. + * Function called under interruption only, once + * interruptions have been enabled by HAL_IRDA_Receive_IT() + * @param hirda: IRDA handle + * @retval HAL status + */ +static HAL_StatusTypeDef IRDA_Receive_IT(IRDA_HandleTypeDef *hirda) +{ + uint16_t* tmp; + uint16_t uhMask = hirda->Mask; + + if ((hirda->State == HAL_IRDA_STATE_BUSY_RX) || (hirda->State == HAL_IRDA_STATE_BUSY_TX_RX)) + { + /* Process Locked */ + __HAL_LOCK(hirda); + + if ((hirda->Init.WordLength == IRDA_WORDLENGTH_9B) && (hirda->Init.Parity == IRDA_PARITY_NONE)) + { + tmp = (uint16_t*) hirda->pRxBuffPtr ; + *tmp = (uint16_t)(hirda->Instance->RDR & uhMask); + hirda->pRxBuffPtr +=2; + } + else + { + *hirda->pRxBuffPtr++ = (uint8_t)(hirda->Instance->RDR & (uint8_t)uhMask); + } + + if(--hirda->RxXferCount == 0) + { + __HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_RXNE); + + if(hirda->State == HAL_IRDA_STATE_BUSY_TX_RX) + { + hirda->State = HAL_IRDA_STATE_BUSY_TX; + } + else + { + /* Disable the IRDA Parity Error Interrupt */ + __HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_PE); + + /* Disable the IRDA Error Interrupt: (Frame error, noise error, overrun error) */ + __HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_ERR); + + hirda->State = HAL_IRDA_STATE_READY; + } + + /* Call the Process Unlocked before calling the Rx call back API to give the possibiity to + start again the receiption under the Rx call back API */ + __HAL_UNLOCK(hirda); + + HAL_IRDA_RxCpltCallback(hirda); + + return HAL_OK; + } + /* Process Unlocked */ + __HAL_UNLOCK(hirda); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @} + */ + +/** @defgroup HAL_IRDA_Group3 Peripheral Control functions + * @brief IRDA control functions + * +@verbatim + =============================================================================== + ##### Peripheral Control functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to control the IRDA. + (+) HAL_IRDA_GetState() API can be helpful to check in run-time the state of the IRDA peripheral. + (+) IRDA_SetConfig() API is used to configure the IRDA communications parameters. +@endverbatim + * @{ + */ + +/** + * @brief return the IRDA state + * @param hirda: irda handle + * @retval HAL state + */ +HAL_IRDA_StateTypeDef HAL_IRDA_GetState(IRDA_HandleTypeDef *hirda) +{ + return hirda->State; +} + +/** +* @brief Return the IRDA error code +* @param hirda : pointer to a IRDA_HandleTypeDef structure that contains + * the configuration information for the specified IRDA. +* @retval IRDA Error Code +*/ +uint32_t HAL_IRDA_GetError(IRDA_HandleTypeDef *hirda) +{ + return hirda->ErrorCode; +} + +/** + * @} + */ + +/** + * @brief Configure the IRDA peripheral + * @param hirda: irda handle + * @retval None + */ +static HAL_StatusTypeDef IRDA_SetConfig(IRDA_HandleTypeDef *hirda) +{ + uint32_t tmpreg = 0x00000000; + UART_ClockSourceTypeDef clocksource = UART_CLOCKSOURCE_UNDEFINED; + HAL_StatusTypeDef ret = HAL_OK; + + /* Check the communication parameters */ + assert_param(IS_IRDA_BAUDRATE(hirda->Init.BaudRate)); + assert_param(IS_IRDA_WORD_LENGTH(hirda->Init.WordLength)); + assert_param(IS_IRDA_PARITY(hirda->Init.Parity)); + assert_param(IS_IRDA_TX_RX_MODE(hirda->Init.Mode)); + assert_param(IS_IRDA_PRESCALER(hirda->Init.Prescaler)); + assert_param(IS_IRDA_POWERMODE(hirda->Init.PowerMode)); + + + + + /*-------------------------- USART CR1 Configuration -----------------------*/ + /* Configure the IRDA Word Length, Parity and transfer Mode: + Set the M bits according to hirda->Init.WordLength value + Set PCE and PS bits according to hirda->Init.Parity value + Set TE and RE bits according to hirda->Init.Mode value */ + tmpreg = (uint32_t)hirda->Init.WordLength | hirda->Init.Parity | hirda->Init.Mode ; + + MODIFY_REG(hirda->Instance->CR1, IRDA_CR1_FIELDS, tmpreg); + + /*-------------------------- USART CR3 Configuration -----------------------*/ + MODIFY_REG(hirda->Instance->CR3, USART_CR3_IRLP, hirda->Init.PowerMode); + + /*-------------------------- USART GTPR Configuration ----------------------*/ + MODIFY_REG(hirda->Instance->GTPR, USART_GTPR_PSC, hirda->Init.Prescaler); + + /*-------------------------- USART BRR Configuration -----------------------*/ + __HAL_UART_GETCLOCKSOURCE(hirda, clocksource); + switch (clocksource) + { + case UART_CLOCKSOURCE_PCLK1: + hirda->Instance->BRR = (uint16_t)(HAL_RCC_GetPCLK1Freq() / hirda->Init.BaudRate); + break; + case UART_CLOCKSOURCE_HSI: + hirda->Instance->BRR = (uint16_t)(HSI_VALUE / hirda->Init.BaudRate); + break; + case UART_CLOCKSOURCE_SYSCLK: + hirda->Instance->BRR = (uint16_t)(HAL_RCC_GetSysClockFreq() / hirda->Init.BaudRate); + break; + case UART_CLOCKSOURCE_LSE: + hirda->Instance->BRR = (uint16_t)(LSE_VALUE / hirda->Init.BaudRate); + break; + case UART_CLOCKSOURCE_UNDEFINED: + default: + ret = HAL_ERROR; + break; + } + + return ret; +} + +/** + * @brief Check the IRDA Idle State + * @param hirda: IRDA handle + * @retval HAL status + */ +static HAL_StatusTypeDef IRDA_CheckIdleState(IRDA_HandleTypeDef *hirda) +{ + + /* Initialize the IRDA ErrorCode */ + hirda->ErrorCode = HAL_IRDA_ERROR_NONE; + + /* Check if the Transmitter is enabled */ + if((hirda->Instance->CR1 & USART_CR1_TE) == USART_CR1_TE) + { + /* Wait until TEACK flag is set */ + if(IRDA_WaitOnFlagUntilTimeout(hirda, USART_ISR_TEACK, RESET, TEACK_REACK_TIMEOUT) != HAL_OK) + { + /* Timeout Occured */ + return HAL_TIMEOUT; + } + } + /* Check if the Receiver is enabled */ + if((hirda->Instance->CR1 & USART_CR1_RE) == USART_CR1_RE) + { + if(IRDA_WaitOnFlagUntilTimeout(hirda, USART_ISR_REACK, RESET, TEACK_REACK_TIMEOUT) != HAL_OK) + { + /* Timeout Occured */ + return HAL_TIMEOUT; + } + } + /* Initialize the IRDA state*/ + hirda->State= HAL_IRDA_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hirda); + + return HAL_OK; +} + + +/** + * @brief Handle IRDA Communication Timeout. + * @param hirda: IRDA handle + * @param Flag: specifies the IRDA flag to check. + * @param Status: the flag status (SET or RESET). The function is locked in a while loop as long as the flag remains set to Status. + * @param Timeout: Timeout duration + * @retval HAL status + */ +static HAL_StatusTypeDef IRDA_WaitOnFlagUntilTimeout(IRDA_HandleTypeDef *hirda, uint32_t Flag, FlagStatus Status, uint32_t Timeout) +{ + uint32_t tickstart = HAL_GetTick(); + + /* Wait until flag is set */ + if(Status == RESET) + { + while(__HAL_IRDA_GET_FLAG(hirda, Flag) == RESET) + { + /* Check for the Timeout */ + if(Timeout != HAL_MAX_DELAY) + { + if((HAL_GetTick() - tickstart) >= Timeout) + { + /* Disable TXE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts for the interrupt process */ + __HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_TXE); + __HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_RXNE); + __HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_PE); + __HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_ERR); + + hirda->State= HAL_IRDA_STATE_TIMEOUT; + + /* Process Unlocked */ + __HAL_UNLOCK(hirda); + + return HAL_TIMEOUT; + } + } + } + } + else + { + while(__HAL_IRDA_GET_FLAG(hirda, Flag) != RESET) + { + /* Check for the Timeout */ + if(Timeout != HAL_MAX_DELAY) + { + if((HAL_GetTick() - tickstart) >= Timeout) + { + /* Disable TXE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts for the interrupt process */ + __HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_TXE); + __HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_RXNE); + __HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_PE); + __HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_ERR); + + hirda->State= HAL_IRDA_STATE_TIMEOUT; + + /* Process Unlocked */ + __HAL_UNLOCK(hirda); + + return HAL_TIMEOUT; + } + } + } + } + return HAL_OK; +} + +/** + * @} + */ + +#endif /* !defined(STM32F030x6) && !defined(STM32F030x8) */ + +#endif /* HAL_IRDA_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_irda.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_irda.h new file mode 100644 index 0000000000..817b9388a0 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_irda.h @@ -0,0 +1,581 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_irda.h + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief Header file of IRDA HAL module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32F0xx_HAL_IRDA_H +#define __STM32F0xx_HAL_IRDA_H + +#ifdef __cplusplus + extern "C" { +#endif + +#if !defined(STM32F030x6) && !defined(STM32F030x8) + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal_def.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @addtogroup IRDA + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ + +/** + * @brief IRDA Init Structure definition + */ +typedef struct +{ + uint32_t BaudRate; /*!< This member configures the IRDA communication baud rate. + The baud rate register is computed using the following formula: + Baud Rate Register = ((PCLKx) / ((hirda->Init.BaudRate))) */ + + uint32_t WordLength; /*!< Specifies the number of data bits transmitted or received in a frame. + This parameter can be a value of @ref IRDAEx_Word_Length */ + + uint16_t Parity; /*!< Specifies the parity mode. + This parameter can be a value of @ref IRDA_Parity + @note When parity is enabled, the computed parity is inserted + at the MSB position of the transmitted data (9th bit when + the word length is set to 9 data bits; 8th bit when the + word length is set to 8 data bits). */ + + uint16_t Mode; /*!< Specifies wether the Receive or Transmit mode is enabled or disabled. + This parameter can be a value of @ref IRDA_Mode */ + + uint8_t Prescaler; /*!< Specifies the Prescaler value for dividing the UART/USART source clock + to achieve low-power frequency. + @note Prescaler value 0 is forbidden */ + + uint16_t PowerMode; /*!< Specifies the IRDA power mode. + This parameter can be a value of @ref IRDA_Low_Power */ +}IRDA_InitTypeDef; + +/** + * @brief HAL IRDA State structures definition + */ +typedef enum +{ + HAL_IRDA_STATE_RESET = 0x00, /*!< Peripheral is not initialized */ + HAL_IRDA_STATE_READY = 0x01, /*!< Peripheral Initialized and ready for use */ + HAL_IRDA_STATE_BUSY = 0x02, /*!< an internal process is ongoing */ + HAL_IRDA_STATE_BUSY_TX = 0x12, /*!< Data Transmission process is ongoing */ + HAL_IRDA_STATE_BUSY_RX = 0x22, /*!< Data Reception process is ongoing */ + HAL_IRDA_STATE_BUSY_TX_RX = 0x32, /*!< Data Transmission and Reception process is ongoing */ + HAL_IRDA_STATE_TIMEOUT = 0x03, /*!< Timeout state */ + HAL_IRDA_STATE_ERROR = 0x04 /*!< Error */ +}HAL_IRDA_StateTypeDef; + +/** + * @brief HAL IRDA Error Code structure definition + */ +typedef enum +{ + HAL_IRDA_ERROR_NONE = 0x00, /*!< No error */ + HAL_IRDA_ERROR_PE = 0x01, /*!< Parity error */ + HAL_IRDA_ERROR_NE = 0x02, /*!< Noise error */ + HAL_IRDA_ERROR_FE = 0x04, /*!< frame error */ + HAL_IRDA_ERROR_ORE = 0x08, /*!< Overrun error */ + HAL_IRDA_ERROR_DMA = 0x10 /*!< DMA transfer error */ +}HAL_IRDA_ErrorTypeDef; + +/** + * @brief IRDA handle Structure definition + */ +typedef struct +{ + USART_TypeDef *Instance; /* USART registers base address */ + + IRDA_InitTypeDef Init; /* IRDA communication parameters */ + + uint8_t *pTxBuffPtr; /* Pointer to IRDA Tx transfer Buffer */ + + uint16_t TxXferSize; /* IRDA Tx Transfer size */ + + uint16_t TxXferCount; /* IRDA Tx Transfer Counter */ + + uint8_t *pRxBuffPtr; /* Pointer to IRDA Rx transfer Buffer */ + + uint16_t RxXferSize; /* IRDA Rx Transfer size */ + + uint16_t RxXferCount; /* IRDA Rx Transfer Counter */ + + uint16_t Mask; /* USART RX RDR register mask */ + + DMA_HandleTypeDef *hdmatx; /* IRDA Tx DMA Handle parameters */ + + DMA_HandleTypeDef *hdmarx; /* IRDA Rx DMA Handle parameters */ + + HAL_LockTypeDef Lock; /* Locking object */ + + HAL_IRDA_StateTypeDef State; /* IRDA communication state */ + + HAL_IRDA_ErrorTypeDef ErrorCode; /* IRDA Error code */ + +}IRDA_HandleTypeDef; + +/** + * @brief IRDA Configuration enumeration values definition + */ +typedef enum +{ + IRDA_BAUDRATE = 0x00, + IRDA_PARITY = 0x01, + IRDA_WORDLENGTH = 0x02, + IRDA_MODE = 0x03, + IRDA_PRESCALER = 0x04, + IRDA_POWERMODE = 0x05 +}IRDA_ControlTypeDef; + +/* Exported constants --------------------------------------------------------*/ +/** @defgroup IRDA_Exported_Constants IRDA Exported Constants + * @{ + */ + +/** @defgroup IRDA_Parity IRDA Parity + * @{ + */ +#define IRDA_PARITY_NONE ((uint16_t)0x0000) +#define IRDA_PARITY_EVEN ((uint16_t)USART_CR1_PCE) +#define IRDA_PARITY_ODD ((uint16_t)(USART_CR1_PCE | USART_CR1_PS)) +#define IS_IRDA_PARITY(PARITY) (((PARITY) == IRDA_PARITY_NONE) || \ + ((PARITY) == IRDA_PARITY_EVEN) || \ + ((PARITY) == IRDA_PARITY_ODD)) +/** + * @} + */ + + +/** @defgroup IRDA_Transfer_Mode IRDA Transfer Mode + * @{ + */ +#define IRDA_MODE_RX ((uint16_t)USART_CR1_RE) +#define IRDA_MODE_TX ((uint16_t)USART_CR1_TE) +#define IRDA_MODE_TX_RX ((uint16_t)(USART_CR1_TE |USART_CR1_RE)) +#define IS_IRDA_TX_RX_MODE(MODE) ((((MODE) & (~((uint16_t)(IRDA_MODE_TX_RX)))) == (uint16_t)0x00) && ((MODE) != (uint16_t)0x00)) +/** + * @} + */ + +/** @defgroup IRDA_Low_Power IRDA Low Power + * @{ + */ +#define IRDA_POWERMODE_NORMAL ((uint16_t)0x0000) +#define IRDA_POWERMODE_LOWPOWER ((uint16_t)USART_CR3_IRLP) +#define IS_IRDA_POWERMODE(MODE) (((MODE) == IRDA_POWERMODE_LOWPOWER) || \ + ((MODE) == IRDA_POWERMODE_NORMAL)) +/** + * @} + */ + + /** @defgroup IRDA_State IRDA State + * @{ + */ +#define IRDA_STATE_DISABLE ((uint16_t)0x0000) +#define IRDA_STATE_ENABLE ((uint16_t)USART_CR1_UE) +#define IS_IRDA_STATE(STATE) (((STATE) == IRDA_STATE_DISABLE) || \ + ((STATE) == IRDA_STATE_ENABLE)) +/** + * @} + */ + + /** @defgroup IRDA_Mode IRDA Mode + * @{ + */ +#define IRDA_MODE_DISABLE ((uint16_t)0x0000) +#define IRDA_MODE_ENABLE ((uint16_t)USART_CR3_IREN) +#define IS_IRDA_MODE(STATE) (((STATE) == IRDA_MODE_DISABLE) || \ + ((STATE) == IRDA_MODE_ENABLE)) +/** + * @} + */ + +/** @defgroup IRDA_One_Bit IRDA One Bit Sampling + * @{ + */ +#define IRDA_ONE_BIT_SAMPLE_DISABLED ((uint16_t)0x00000000) +#define IRDA_ONE_BIT_SAMPLE_ENABLED ((uint16_t)USART_CR3_ONEBIT) +#define IS_IRDA_ONEBIT_SAMPLE(ONEBIT) (((ONEBIT) == IRDA_ONE_BIT_SAMPLE_DISABLED) || \ + ((ONEBIT) == IRDA_ONE_BIT_SAMPLE_ENABLED)) +/** + * @} + */ + +/** @defgroup IRDA_DMA_Tx IRDA DMA Tx + * @{ + */ +#define IRDA_DMA_TX_DISABLE ((uint16_t)0x00000000) +#define IRDA_DMA_TX_ENABLE ((uint16_t)USART_CR3_DMAT) +#define IS_IRDA_DMA_TX(DMATX) (((DMATX) == IRDA_DMA_TX_DISABLE) || \ + ((DMATX) == IRDA_DMA_TX_ENABLE)) +/** + * @} + */ + +/** @defgroup IRDA_DMA_Rx IRDA DMA Rx + * @{ + */ +#define IRDA_DMA_RX_DISABLE ((uint16_t)0x0000) +#define IRDA_DMA_RX_ENABLE ((uint16_t)USART_CR3_DMAR) +#define IS_IRDA_DMA_RX(DMARX) (((DMARX) == IRDA_DMA_RX_DISABLE) || \ + ((DMARX) == IRDA_DMA_RX_ENABLE)) +/** + * @} + */ + +/** @defgroup IRDA_Flags IRDA Flags + * Elements values convention: 0xXXXX + * - 0xXXXX : Flag mask in the ISR register + * @{ + */ +#define IRDA_FLAG_REACK ((uint32_t)0x00400000) +#define IRDA_FLAG_TEACK ((uint32_t)0x00200000) +#define IRDA_FLAG_BUSY ((uint32_t)0x00010000) +#define IRDA_FLAG_ABRF ((uint32_t)0x00008000) +#define IRDA_FLAG_ABRE ((uint32_t)0x00004000) +#define IRDA_FLAG_TXE ((uint32_t)0x00000080) +#define IRDA_FLAG_TC ((uint32_t)0x00000040) +#define IRDA_FLAG_RXNE ((uint32_t)0x00000020) +#define IRDA_FLAG_ORE ((uint32_t)0x00000008) +#define IRDA_FLAG_NE ((uint32_t)0x00000004) +#define IRDA_FLAG_FE ((uint32_t)0x00000002) +#define IRDA_FLAG_PE ((uint32_t)0x00000001) +/** + * @} + */ + +/** @defgroup IRDA_Interrupt_definition IRDA Interrupts Definition + * Elements values convention: 0000ZZZZ0XXYYYYYb + * - YYYYY : Interrupt source position in the XX register (5bits) + * - XX : Interrupt source register (2bits) + * - 01: CR1 register + * - 10: CR2 register + * - 11: CR3 register + * - ZZZZ : Flag position in the ISR register(4bits) + * @{ + */ +#define IRDA_IT_PE ((uint16_t)0x0028) +#define IRDA_IT_TXE ((uint16_t)0x0727) +#define IRDA_IT_TC ((uint16_t)0x0626) +#define IRDA_IT_RXNE ((uint16_t)0x0525) +#define IRDA_IT_IDLE ((uint16_t)0x0424) + + + +/** Elements values convention: 000000000XXYYYYYb + * - YYYYY : Interrupt source position in the XX register (5bits) + * - XX : Interrupt source register (2bits) + * - 01: CR1 register + * - 10: CR2 register + * - 11: CR3 register + */ +#define IRDA_IT_ERR ((uint16_t)0x0060) + +/** Elements values convention: 0000ZZZZ00000000b + * - ZZZZ : Flag position in the ISR register(4bits) + */ +#define IRDA_IT_ORE ((uint16_t)0x0300) +#define IRDA_IT_NE ((uint16_t)0x0200) +#define IRDA_IT_FE ((uint16_t)0x0100) +/** + * @} + */ + +/** @defgroup IRDA_IT_CLEAR_Flags IRDA Interruption Clear Flags + * @{ + */ +#define IRDA_CLEAR_PEF USART_ICR_PECF /*!< Parity Error Clear Flag */ +#define IRDA_CLEAR_FEF USART_ICR_FECF /*!< Framing Error Clear Flag */ +#define IRDA_CLEAR_NEF USART_ICR_NCF /*!< Noise detected Clear Flag */ +#define IRDA_CLEAR_OREF USART_ICR_ORECF /*!< OverRun Error Clear Flag */ +#define IRDA_CLEAR_TCF USART_ICR_TCCF /*!< Transmission Complete Clear Flag */ +/** + * @} + */ + + + +/** @defgroup IRDA_Request_Parameters IRDA Request Parameters + * @{ + */ +#define IRDA_AUTOBAUD_REQUEST ((uint16_t)USART_RQR_ABRRQ) /*!< Auto-Baud Rate Request */ +#define IRDA_RXDATA_FLUSH_REQUEST ((uint16_t)USART_RQR_RXFRQ) /*!< Receive Data flush Request */ +#define IRDA_TXDATA_FLUSH_REQUEST ((uint16_t)USART_RQR_TXFRQ) /*!< Transmit data flush Request */ +#define IS_IRDA_REQUEST_PARAMETER(PARAM) (((PARAM) == IRDA_AUTOBAUD_REQUEST) || \ + ((PARAM) == IRDA_SENDBREAK_REQUEST) || \ + ((PARAM) == IRDA_MUTE_MODE_REQUEST) || \ + ((PARAM) == IRDA_RXDATA_FLUSH_REQUEST) || \ + ((PARAM) == IRDA_TXDATA_FLUSH_REQUEST)) +/** + * @} + */ + +/** @defgroup IRDA_Interruption_Mask IRDA interruptions flag mask + * @{ + */ +#define IRDA_IT_MASK ((uint16_t)0x001F) +/** + * @} + */ + +/** + * @} + */ + + +/* Exported macros -----------------------------------------------------------*/ +/** @defgroup IRDA_Exported_Macros + * @{ + */ + +/** @brief Reset IRDA handle state + * @param __HANDLE__: IRDA handle. + * @retval None + */ +#define __HAL_IRDA_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_IRDA_STATE_RESET) + +/** @brief Checks whether the specified IRDA flag is set or not. + * @param __HANDLE__: specifies the IRDA Handle. + * The Handle Instance can be UARTx where x: 1, 2, 3, 4, 5 to select the USART or + * UART peripheral + * @param __FLAG__: specifies the flag to check. + * This parameter can be one of the following values: + * @arg IRDA_FLAG_REACK: Receive enable ackowledge flag + * @arg IRDA_FLAG_TEACK: Transmit enable ackowledge flag + * @arg IRDA_FLAG_BUSY: Busy flag + * @arg IRDA_FLAG_ABRF: Auto Baud rate detection flag + * @arg IRDA_FLAG_ABRE: Auto Baud rate detection error flag + * @arg IRDA_FLAG_TXE: Transmit data register empty flag + * @arg IRDA_FLAG_TC: Transmission Complete flag + * @arg IRDA_FLAG_RXNE: Receive data register not empty flag + * @arg IRDA_FLAG_IDLE: Idle Line detection flag + * @arg IRDA_FLAG_ORE: OverRun Error flag + * @arg IRDA_FLAG_NE: Noise Error flag + * @arg IRDA_FLAG_FE: Framing Error flag + * @arg IRDA_FLAG_PE: Parity Error flag + * @retval The new state of __FLAG__ (TRUE or FALSE). + */ +#define __HAL_IRDA_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->ISR & (__FLAG__)) == (__FLAG__)) + + +/** @brief Enables the specified IRDA interrupt. + * @param __HANDLE__: specifies the IRDA Handle. + * The Handle Instance can be UARTx where x: 1, 2, 3, 4, 5 to select the USART or + * UART peripheral + * @param __INTERRUPT__: specifies the IRDA interrupt source to enable. + * This parameter can be one of the following values: + * @arg IRDA_IT_TXE: Transmit Data Register empty interrupt + * @arg IRDA_IT_TC: Transmission complete interrupt + * @arg IRDA_IT_RXNE: Receive Data register not empty interrupt + * @arg IRDA_IT_IDLE: Idle line detection interrupt + * @arg IRDA_IT_PE: Parity Error interrupt + * @arg IRDA_IT_ERR: Error interrupt(Frame error, noise error, overrun error) + * @retval None + */ +#define __HAL_IRDA_ENABLE_IT(__HANDLE__, __INTERRUPT__) (((((uint8_t)(__INTERRUPT__)) >> 5U) == 1)? ((__HANDLE__)->Instance->CR1 |= (1U << ((__INTERRUPT__) & IRDA_IT_MASK))): \ + ((((uint8_t)(__INTERRUPT__)) >> 5U) == 2)? ((__HANDLE__)->Instance->CR2 |= (1U << ((__INTERRUPT__) & IRDA_IT_MASK))): \ + ((__HANDLE__)->Instance->CR3 |= (1U << ((__INTERRUPT__) & IRDA_IT_MASK)))) + +/** @brief Disables the specified IRDA interrupt. + * @param __HANDLE__: specifies the IRDA Handle. + * The Handle Instance can be UARTx where x: 1, 2, 3, 4, 5 to select the USART or + * UART peripheral + * @param __INTERRUPT__: specifies the IRDA interrupt source to disable. + * This parameter can be one of the following values: + * @arg IRDA_IT_TXE: Transmit Data Register empty interrupt + * @arg IRDA_IT_TC: Transmission complete interrupt + * @arg IRDA_IT_RXNE: Receive Data register not empty interrupt + * @arg IRDA_IT_IDLE: Idle line detection interrupt + * @arg IRDA_IT_PE: Parity Error interrupt + * @arg IRDA_IT_ERR: Error interrupt(Frame error, noise error, overrun error) + * @retval None + */ +#define __HAL_IRDA_DISABLE_IT(__HANDLE__, __INTERRUPT__) (((((uint8_t)(__INTERRUPT__)) >> 5U) == 1)? ((__HANDLE__)->Instance->CR1 &= ~ (1U << ((__INTERRUPT__) & IRDA_IT_MASK))): \ + ((((uint8_t)(__INTERRUPT__)) >> 5U) == 2)? ((__HANDLE__)->Instance->CR2 &= ~ (1U << ((__INTERRUPT__) & IRDA_IT_MASK))): \ + ((__HANDLE__)->Instance->CR3 &= ~ (1U << ((__INTERRUPT__) & IRDA_IT_MASK)))) + + +/** @brief Checks whether the specified IRDA interrupt has occurred or not. + * @param __HANDLE__: specifies the IRDA Handle. + * The Handle Instance can be UARTx where x: 1, 2, 3, 4, 5 to select the USART or + * UART peripheral + * @param __IT__: specifies the IRDA interrupt source to check. + * This parameter can be one of the following values: + * @arg IRDA_IT_TXE: Transmit Data Register empty interrupt + * @arg IRDA_IT_TC: Transmission complete interrupt + * @arg IRDA_IT_RXNE: Receive Data register not empty interrupt + * @arg IRDA_IT_IDLE: Idle line detection interrupt + * @arg IRDA_IT_ORE: OverRun Error interrupt + * @arg IRDA_IT_NE: Noise Error interrupt + * @arg IRDA_IT_FE: Framing Error interrupt + * @arg IRDA_IT_PE: Parity Error interrupt + * @retval The new state of __IT__ (TRUE or FALSE). + */ +#define __HAL_IRDA_GET_IT(__HANDLE__, __IT__) ((__HANDLE__)->Instance->ISR & ((uint32_t)1U << ((__IT__)>> 0x08))) + +/** @brief Checks whether the specified IRDA interrupt source is enabled. + * @param __HANDLE__: specifies the IRDA Handle. + * The Handle Instance can be UARTx where x: 1, 2, 3, 4, 5 to select the USART or + * UART peripheral + * @param __IT__: specifies the IRDA interrupt source to check. + * This parameter can be one of the following values: + * @arg IRDA_IT_TXE: Transmit Data Register empty interrupt + * @arg IRDA_IT_TC: Transmission complete interrupt + * @arg IRDA_IT_RXNE: Receive Data register not empty interrupt + * @arg IRDA_IT_IDLE: Idle line detection interrupt + * @arg IRDA_IT_ORE: OverRun Error interrupt + * @arg IRDA_IT_NE: Noise Error interrupt + * @arg IRDA_IT_FE: Framing Error interrupt + * @arg IRDA_IT_PE: Parity Error interrupt + * @retval The new state of __IT__ (TRUE or FALSE). + */ +#define __HAL_IRDA_GET_IT_SOURCE(__HANDLE__, __IT__) ((((((uint8_t)(__IT__)) >> 5U) == 1)? (__HANDLE__)->Instance->CR1:(((((uint8_t)(__IT__)) >> 5U) == 2)? \ + (__HANDLE__)->Instance->CR2 : (__HANDLE__)->Instance->CR3)) & ((uint32_t)1 << (((uint16_t)(__IT__)) & IRDA_IT_MASK))) + + +/** @brief Clears the specified IRDA ISR flag, in setting the proper ICR register flag. + * @param __HANDLE__: specifies the IRDA Handle. + * The Handle Instance can be UARTx where x: 1, 2, 3, 4, 5 to select the USART or + * UART peripheral + * @param __IT_CLEAR__: specifies the interrupt clear register flag that needs to be set + * to clear the corresponding interrupt + * This parameter can be one of the following values: + * @arg IRDA_CLEAR_PEF: Parity Error Clear Flag + * @arg IRDA_CLEAR_FEF: Framing Error Clear Flag + * @arg IRDA_CLEAR_NEF: Noise detected Clear Flag + * @arg IRDA_CLEAR_OREF: OverRun Error Clear Flag + * @arg IRDA_CLEAR_TCF: Transmission Complete Clear Flag + * @retval None + */ +#define __HAL_IRDA_CLEAR_IT(__HANDLE__, __IT_CLEAR__) ((__HANDLE__)->Instance->ICR |= (uint32_t)(__IT_CLEAR__)) + + +/** @brief Set a specific IRDA request flag. + * @param __HANDLE__: specifies the IRDA Handle. + * The Handle Instance can be UARTx where x: 1, 2, 3, 4, 5 to select the USART or + * UART peripheral + * @param __REQ__: specifies the request flag to set + * This parameter can be one of the following values: + * @arg IRDA_AUTOBAUD_REQUEST: Auto-Baud Rate Request + * @arg IRDA_RXDATA_FLUSH_REQUEST: Receive Data flush Request + * @arg IRDA_TXDATA_FLUSH_REQUEST: Transmit data flush Request + * + * @retval None + */ +#define __HAL_IRDA_SEND_REQ(__HANDLE__, __REQ__) ((__HANDLE__)->Instance->RQR |= (uint16_t)(__REQ__)) + + + +/** @brief Enable UART/USART associated to IRDA Handle + * @param __HANDLE__: specifies the IRDA Handle. + * The Handle Instance can be UARTx where x: 1, 2, 3, 4, 5 to select the USART or + * UART peripheral + * @retval None + */ +#define __HAL_IRDA_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 |= USART_CR1_UE) + +/** @brief Disable UART/USART associated to IRDA Handle + * @param __HANDLE__: specifies the IRDA Handle. + * The Handle Instance can be UARTx where x: 1, 2, 3, 4, 5 to select the USART or + * UART peripheral + * @retval None + */ +#define __HAL_IRDA_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 &= ~USART_CR1_UE) + +/** @brief Ensure that IRDA Baud rate is less or equal to maximum value + * @param __BAUDRATE__: specifies the IRDA Baudrate set by the user. + * @retval True or False + */ +#define IS_IRDA_BAUDRATE(__BAUDRATE__) ((__BAUDRATE__) < 115201) + +/** @brief Ensure that IRDA prescaler value is strictly larger than 0 + * @param __PRESCALER__: specifies the IRDA prescaler value set by the user. + * @retval True or False + */ +#define IS_IRDA_PRESCALER(__PRESCALER__) ((__PRESCALER__) > 0) + +/** + * @} + */ + +/* Include IRDA HAL Extension module */ +#include "stm32f0xx_hal_irda_ex.h" + +/* Exported functions --------------------------------------------------------*/ +/* Initialization and de-initialization functions ****************************/ +HAL_StatusTypeDef HAL_IRDA_Init(IRDA_HandleTypeDef *hirda); +HAL_StatusTypeDef HAL_IRDA_DeInit(IRDA_HandleTypeDef *hirda); +void HAL_IRDA_MspInit(IRDA_HandleTypeDef *hirda); +void HAL_IRDA_MspDeInit(IRDA_HandleTypeDef *hirda); + + +/* IO operation functions *****************************************************/ +HAL_StatusTypeDef HAL_IRDA_Transmit(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size, uint32_t Timeout); +HAL_StatusTypeDef HAL_IRDA_Receive(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size, uint32_t Timeout); +HAL_StatusTypeDef HAL_IRDA_Transmit_IT(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size); +HAL_StatusTypeDef HAL_IRDA_Receive_IT(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size); +HAL_StatusTypeDef HAL_IRDA_Transmit_DMA(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size); +HAL_StatusTypeDef HAL_IRDA_Receive_DMA(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size); +void HAL_IRDA_IRQHandler(IRDA_HandleTypeDef *hirda); +void HAL_IRDA_TxCpltCallback(IRDA_HandleTypeDef *hirda); +void HAL_IRDA_RxCpltCallback(IRDA_HandleTypeDef *hirda); +void HAL_IRDA_ErrorCallback(IRDA_HandleTypeDef *hirda); + +/* Peripheral State and Error functions ***************************************/ +HAL_IRDA_StateTypeDef HAL_IRDA_GetState(IRDA_HandleTypeDef *hirda); +uint32_t HAL_IRDA_GetError(IRDA_HandleTypeDef *hirda); + +/** + * @} + */ + +/** + * @} + */ + +#endif /* !defined(STM32F030x6) && !defined(STM32F030x8) */ + +#ifdef __cplusplus +} +#endif + +#endif /* __STM32F0xx_HAL_IRDA_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_irda_ex.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_irda_ex.h new file mode 100644 index 0000000000..4ad7e116de --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_irda_ex.h @@ -0,0 +1,196 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_irda_ex.h + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief Header file of IRDA HAL Extension module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32F0xx_HAL_IRDA_EX_H +#define __STM32F0xx_HAL_IRDA_EX_H + +#ifdef __cplusplus + extern "C" { +#endif + +#if !defined(STM32F030x6) && !defined(STM32F030x8) + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal_def.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @addtogroup IRDAEx + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/* Exported constants --------------------------------------------------------*/ +/** @defgroup IRDAEx_Exported_Constants + * @{ + */ + +/** @defgroup IRDAEx_Word_Length IRDA Word Length + * @{ + */ +#if defined (STM32F042x6) || defined (STM32F048xx) || \ + defined (STM32F071xB) || defined (STM32F072xB) || defined (STM32F078xx) +#define IRDA_WORDLENGTH_7B ((uint32_t)USART_CR1_M1) +#define IRDA_WORDLENGTH_8B ((uint32_t)0x00000000) +#define IRDA_WORDLENGTH_9B ((uint32_t)USART_CR1_M0) +#define IS_IRDA_WORD_LENGTH(LENGTH) (((LENGTH) == IRDA_WORDLENGTH_7B) || \ + ((LENGTH) == IRDA_WORDLENGTH_8B) || \ + ((LENGTH) == IRDA_WORDLENGTH_9B)) +#else +#define IRDA_WORDLENGTH_8B ((uint32_t)0x00000000) +#define IRDA_WORDLENGTH_9B ((uint32_t)USART_CR1_M) +#define IS_IRDA_WORD_LENGTH(LENGTH) (((LENGTH) == IRDA_WORDLENGTH_8B) || \ + ((LENGTH) == IRDA_WORDLENGTH_9B)) +#endif /* defined (STM32F042x6) || defined (STM32F048xx) || \ + defined (STM32F071xB) || defined (STM32F072xB) || defined (STM32F078xx) */ +/** + * @} + */ + + +/** + * @} + */ + +/* Exported macros -----------------------------------------------------------*/ + +/** @defgroup IRDAEx_Exported_Macros + * @{ + */ + +/** @brief Computes the mask to apply to retrieve the received data + * according to the word length and to the parity bits activation. + * @param __HANDLE__: specifies the IRDA Handle + * @retval none + */ +#if defined (STM32F042x6) || defined (STM32F048xx) || \ + defined (STM32F071xB) || defined (STM32F072xB) || defined (STM32F078xx) +#define __HAL_IRDA_MASK_COMPUTATION(__HANDLE__) \ + do { \ + if ((__HANDLE__)->Init.WordLength == IRDA_WORDLENGTH_9B) \ + { \ + if ((__HANDLE__)->Init.Parity == IRDA_PARITY_NONE) \ + { \ + (__HANDLE__)->Mask = 0x01FF ; \ + } \ + else \ + { \ + (__HANDLE__)->Mask = 0x00FF ; \ + } \ + } \ + else if ((__HANDLE__)->Init.WordLength == IRDA_WORDLENGTH_8B) \ + { \ + if ((__HANDLE__)->Init.Parity == IRDA_PARITY_NONE) \ + { \ + (__HANDLE__)->Mask = 0x00FF ; \ + } \ + else \ + { \ + (__HANDLE__)->Mask = 0x007F ; \ + } \ + } \ + else if ((__HANDLE__)->Init.WordLength == IRDA_WORDLENGTH_7B) \ + { \ + if ((__HANDLE__)->Init.Parity == IRDA_PARITY_NONE) \ + { \ + (__HANDLE__)->Mask = 0x007F ; \ + } \ + else \ + { \ + (__HANDLE__)->Mask = 0x003F ; \ + } \ + } \ +} while(0) +#else +#define __HAL_IRDA_MASK_COMPUTATION(__HANDLE__) \ + do { \ + if ((__HANDLE__)->Init.WordLength == IRDA_WORDLENGTH_9B) \ + { \ + if ((__HANDLE__)->Init.Parity == IRDA_PARITY_NONE) \ + { \ + (__HANDLE__)->Mask = 0x01FF ; \ + } \ + else \ + { \ + (__HANDLE__)->Mask = 0x00FF ; \ + } \ + } \ + else if ((__HANDLE__)->Init.WordLength == IRDA_WORDLENGTH_8B) \ + { \ + if ((__HANDLE__)->Init.Parity == IRDA_PARITY_NONE) \ + { \ + (__HANDLE__)->Mask = 0x00FF ; \ + } \ + else \ + { \ + (__HANDLE__)->Mask = 0x007F ; \ + } \ + } \ +} while(0) +#endif /* defined (STM32F042x6) || defined (STM32F048xx) || \ + defined (STM32F071xB) || defined (STM32F072xB) || defined (STM32F078xx) */ +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/* Initialization and de-initialization functions ****************************/ +/* IO operation functions *****************************************************/ +/* Peripheral Control functions ***********************************************/ +/* Peripheral State and Error functions ***************************************/ + + +/** + * @} + */ + +/** + * @} + */ + +#endif /* !defined(STM32F030x6) && !defined(STM32F030x8) */ + +#ifdef __cplusplus +} +#endif + +#endif /* __STM32F0xx_HAL_IRDA_EX_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_iwdg.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_iwdg.c new file mode 100644 index 0000000000..27c0ccc218 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_iwdg.c @@ -0,0 +1,401 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_iwdg.c + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief IWDG HAL module driver. + * + * This file provides firmware functions to manage the following + * functionalities of the IWDG peripheral: + * + Initialization and Configuration functions + * + IO operation functions + * + Peripheral State functions + * + @verbatim + +================================================================================ + ##### IWDG specific features ##### +================================================================================ + [..] + (+) The IWDG can be started by either software or hardware (configurable + through option byte). + (+) The IWDG is clocked by its own dedicated Low-Speed clock (LSI) and + thus stays active even if the main clock fails. + (+) Once the IWDG is started, the LSI is forced ON and cannot be disabled + (LSI cannot be disabled too), and the counter starts counting down from + the reset value of 0xFFF. When it reaches the end of count value (0x000) + a system reset is generated. + (+) The IWDG counter should be refreshed at regular intervals, otherwise the + watchdog generates an MCU reset when the counter reaches 0. + (+) The IWDG is implemented in the VDD voltage domain that is still functional + in STOP and STANDBY mode (IWDG reset can wake-up from STANDBY). + (+) IWDGRST flag in RCC_CSR register can be used to inform when an IWDG + reset occurs. + (+) Min-max timeout value @41KHz (LSI): ~0.1ms / ~25.5s + The IWDG timeout may vary due to LSI frequency dispersion. STM32F0x + devices provide the capability to measure the LSI frequency (LSI clock + connected internally to TIM16 CH1 input capture). The measured value + can be used to have an IWDG timeout with an acceptable accuracy. + For more information, please refer to the STM32F0x Reference manual. + + ##### How to use this driver ##### + ============================================================================== + [..] + (#) if Window option is disabled + (+) Use IWDG using HAL_IWDG_Init() function to : + (++) Enable write access to IWDG_PR, IWDG_RLR. + (++) Configure the IWDG prescaler, counter reload value. + This reload value will be loaded in the IWDG counter each time the counter + is reloaded, then the IWDG will start counting down from this value. + (+) Use IWDG using HAL_IWDG_Start() function to : + (++) Reload IWDG counter with value defined in the IWDG_RLR register. + (++) Start the IWDG, when the IWDG is used in software mode (no need + to enable the LSI, it will be enabled by hardware). + (+) Then the application program must refresh the IWDG counter at regular + intervals during normal operation to prevent an MCU reset, using + HAL_IWDG_Refresh() function. + (#) if Window option is enabled: + (+) Use IWDG using HAL_IWDG_Start() function to enable IWDG downcounter + (+) Use IWDG using HAL_IWDG_Init() function to : + (++) Enable write access to IWDG_PR, IWDG_RLR and IWDG_WINR registers. + (++) Configure the IWDG prescaler, reload value and window value. + (+) Then the application program must refresh the IWDG counter at regular + intervals during normal operation to prevent an MCU reset, using + HAL_IWDG_Refresh() function. + + *** IWDG HAL driver macros list *** + ==================================== + [..] + Below the list of most used macros in IWDG HAL driver. + + (+) __HAL_IWDG_START: Enable the IWDG peripheral + (+) __HAL_IWDG_RELOAD_COUNTER: Reloads IWDG counter with value defined in the reload register + (+) __HAL_IWDG_ENABLE_WRITE_ACCESS : Enable write access to IWDG_PR and IWDG_RLR registers + (+) __HAL_IWDG_DISABLE_WRITE_ACCESS : Disable write access to IWDG_PR and IWDG_RLR registers + (+) __HAL_IWDG_GET_FLAG: Get the selected IWDG's flag status + + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @defgroup IWDG + * @brief IWDG HAL module driver. + * @{ + */ + +#ifdef HAL_IWDG_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +#define HAL_IWDG_DEFAULT_TIMEOUT 1000 +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup IWDG_Private_Functions + * @{ + */ + +/** @defgroup HAL_IWDG_Group1 Initialization functions + * @brief Initialization and Configuration functions. + * +@verbatim + =============================================================================== + ##### Initialization functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Initialize the IWDG according to the specified parameters + in the IWDG_InitTypeDef and create the associated handle + (+) Manage Window option + (+) Initialize the IWDG MSP + +@endverbatim + * @{ + */ + +/** + * @brief Initializes the IWDG according to the specified + * parameters in the IWDG_InitTypeDef and creates the associated handle. + * @param hiwdg: IWDG handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_IWDG_Init(IWDG_HandleTypeDef *hiwdg) +{ + uint32_t tickstart = 0; + + /* Check the IWDG handle allocation */ + if(hiwdg == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_IWDG_ALL_INSTANCE(hiwdg->Instance)); + assert_param(IS_IWDG_PRESCALER(hiwdg->Init.Prescaler)); + assert_param(IS_IWDG_RELOAD(hiwdg->Init.Reload)); + assert_param(IS_IWDG_WINDOW(hiwdg->Init.Window)); + + /* Check pending flag, if previous update not done, return error */ + if((__HAL_IWDG_GET_FLAG(hiwdg, IWDG_FLAG_PVU) != RESET) + &&(__HAL_IWDG_GET_FLAG(hiwdg, IWDG_FLAG_RVU) != RESET) + &&(__HAL_IWDG_GET_FLAG(hiwdg, IWDG_FLAG_WVU) != RESET)) + { + return HAL_ERROR; + } + + if(hiwdg->State == HAL_IWDG_STATE_RESET) + { + /* Init the low level hardware */ + HAL_IWDG_MspInit(hiwdg); + } + + /* Change IWDG peripheral state */ + hiwdg->State = HAL_IWDG_STATE_BUSY; + + /* Enable write access to IWDG_PR, IWDG_RLR and IWDG_WINR registers */ + /* by writing 0x5555 in KR */ + __HAL_IWDG_ENABLE_WRITE_ACCESS(hiwdg); + + /* Write to IWDG registers the IWDG_Prescaler & IWDG_Reload values to work with */ + MODIFY_REG(hiwdg->Instance->PR, IWDG_PR_PR, hiwdg->Init.Prescaler); + MODIFY_REG(hiwdg->Instance->RLR, IWDG_RLR_RL, hiwdg->Init.Reload); + + /* check if window option is enabled */ + if (((hiwdg->Init.Window) != IWDG_WINDOW_DISABLE) || ((hiwdg->Instance->WINR) != IWDG_WINDOW_DISABLE)) + { + tickstart = HAL_GetTick(); + + /* Wait for register to be updated */ + while((uint32_t)(hiwdg->Instance->SR) != RESET) + { + if((HAL_GetTick() - tickstart) >= HAL_IWDG_DEFAULT_TIMEOUT) + { + /* Set IWDG state */ + hiwdg->State = HAL_IWDG_STATE_TIMEOUT; + return HAL_TIMEOUT; + } + } + + /* Write to IWDG WINR the IWDG_Window value to compare with */ + MODIFY_REG(hiwdg->Instance->WINR, IWDG_WINR_WIN, hiwdg->Init.Window); + + } + /* Change IWDG peripheral state */ + hiwdg->State = HAL_IWDG_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Initializes the IWDG MSP. + * @param hiwdg: IWDG handle + * @retval None + */ +__weak void HAL_IWDG_MspInit(IWDG_HandleTypeDef *hiwdg) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_IWDG_MspInit could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup IWDG_Group2 IO operation functions + * @brief IO operation functions + * +@verbatim + =============================================================================== + ##### IO operation functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Start the IWDG. + (+) Refresh the IWDG. + +@endverbatim + * @{ + */ + +/** + * @brief Starts the IWDG. + * @param hiwdg: IWDG handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_IWDG_Start(IWDG_HandleTypeDef *hiwdg) +{ + uint32_t tickstart = 0; + + /* Process Locked */ + __HAL_LOCK(hiwdg); + + /* Change IWDG peripheral state */ + hiwdg->State = HAL_IWDG_STATE_BUSY; + + /* Reload IWDG counter with value defined in the RLR register */ + if ((hiwdg->Init.Window) == IWDG_WINDOW_DISABLE) + { + __HAL_IWDG_RELOAD_COUNTER(hiwdg); + } + + /* Enable the IWDG peripheral */ + __HAL_IWDG_START(hiwdg); + + tickstart = HAL_GetTick(); + + /* Wait until PVU, RVU, WVU flag are RESET */ + while( (__HAL_IWDG_GET_FLAG(hiwdg, IWDG_FLAG_PVU) != RESET) + &&(__HAL_IWDG_GET_FLAG(hiwdg, IWDG_FLAG_RVU) != RESET) + &&(__HAL_IWDG_GET_FLAG(hiwdg, IWDG_FLAG_WVU) != RESET) ) + { + if((HAL_GetTick() - tickstart) >= HAL_IWDG_DEFAULT_TIMEOUT) + { + /* Set IWDG state */ + hiwdg->State = HAL_IWDG_STATE_TIMEOUT; + + /* Process unlocked */ + __HAL_UNLOCK(hiwdg); + + return HAL_TIMEOUT; + } + } + + /* Change IWDG peripheral state */ + hiwdg->State = HAL_IWDG_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hiwdg); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Refreshes the IWDG. + * @param hiwdg: IWDG handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_IWDG_Refresh(IWDG_HandleTypeDef *hiwdg) + { + uint32_t tickstart = 0; + + /* Process Locked */ + __HAL_LOCK(hiwdg); + + /* Change IWDG peripheral state */ + hiwdg->State = HAL_IWDG_STATE_BUSY; + + tickstart = HAL_GetTick(); + + /* Wait until RVU flag is RESET */ + while(__HAL_IWDG_GET_FLAG(hiwdg, IWDG_FLAG_RVU) != RESET) + { + if((HAL_GetTick() - tickstart) >= HAL_IWDG_DEFAULT_TIMEOUT) + { + /* Set IWDG state */ + hiwdg->State = HAL_IWDG_STATE_TIMEOUT; + + /* Process unlocked */ + __HAL_UNLOCK(hiwdg); + + return HAL_TIMEOUT; + } + } + + /* Reload IWDG counter with value defined in the reload register */ + __HAL_IWDG_RELOAD_COUNTER(hiwdg); + + /* Change IWDG peripheral state */ + hiwdg->State = HAL_IWDG_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hiwdg); + + /* Return function status */ + return HAL_OK; +} + +/** + * @} + */ + +/** @defgroup IWDG_Group3 Peripheral State functions + * @brief Peripheral State functions. + * +@verbatim + =============================================================================== + ##### Peripheral State functions ##### + =============================================================================== + [..] + This subsection permits to get in run-time the status of the peripheral + and the data flow. + +@endverbatim + * @{ + */ + +/** + * @brief Returns the IWDG state. + * @param hiwdg: IWDG handle + * @retval HAL state + */ +HAL_IWDG_StateTypeDef HAL_IWDG_GetState(IWDG_HandleTypeDef *hiwdg) +{ + return hiwdg->State; +} + +/** + * @} + */ + +/** + * @} + */ + +#endif /* HAL_IWDG_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_iwdg.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_iwdg.h new file mode 100644 index 0000000000..aa3ca77ad3 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_iwdg.h @@ -0,0 +1,275 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_iwdg.h + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief Header file of IWDG HAL module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32F0xx_HAL_IWDG_H +#define __STM32F0xx_HAL_IWDG_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal_def.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @addtogroup IWDG + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ + +/** + * @brief IWDG HAL State Structure definition + */ +typedef enum +{ + HAL_IWDG_STATE_RESET = 0x00, /*!< IWDG not yet initialized or disabled */ + HAL_IWDG_STATE_READY = 0x01, /*!< IWDG initialized and ready for use */ + HAL_IWDG_STATE_BUSY = 0x02, /*!< IWDG internal process is ongoing */ + HAL_IWDG_STATE_TIMEOUT = 0x03, /*!< IWDG timeout state */ + HAL_IWDG_STATE_ERROR = 0x04 /*!< IWDG error state */ + +}HAL_IWDG_StateTypeDef; + +/** + * @brief IWDG Init structure definition + */ +typedef struct +{ + uint32_t Prescaler; /*!< Select the prescaler of the IWDG. + This parameter can be a value of @ref IWDG_Prescaler */ + + uint32_t Reload; /*!< Specifies the IWDG down-counter reload value. + This parameter must be a number between Min_Data = 0 and Max_Data = 0x0FFF */ + + uint32_t Window; /*!< Specifies the window value to be compared to the down-counter. + This parameter must be a number between Min_Data = 0 and Max_Data = 0x0FFF */ + +} IWDG_InitTypeDef; + +/** + * @brief IWDG Handle Structure definition + */ +typedef struct +{ + IWDG_TypeDef *Instance; /*!< Register base address */ + + IWDG_InitTypeDef Init; /*!< IWDG required parameters */ + + HAL_LockTypeDef Lock; /*!< IWDG Locking object */ + + __IO HAL_IWDG_StateTypeDef State; /*!< IWDG communication state */ + +}IWDG_HandleTypeDef; + +/* Exported constants --------------------------------------------------------*/ +/** @defgroup IWDG_Exported_Constants + * @{ + */ + +/** @defgroup IWDG_Registers_BitMask + * @brief IWDG registers bit mask + * @{ + */ +/* --- KR Register ---*/ +/* KR register bit mask */ +#define KR_KEY_RELOAD ((uint32_t)0xAAAA) /*!< IWDG Reload Counter Enable */ +#define KR_KEY_ENABLE ((uint32_t)0xCCCC) /*!< IWDG Peripheral Enable */ +#define KR_KEY_EWA ((uint32_t)0x5555) /*!< IWDG KR Write Access Enable */ +#define KR_KEY_DWA ((uint32_t)0x0000) /*!< IWDG KR Write Access Disable */ + +#define IS_IWDG_KR(KR) (((KR) == KR_KEY_RELOAD) || \ + ((KR) == KR_KEY_ENABLE))|| \ + ((KR) == KR_KEY_EWA)) || \ + ((KR) == KR_KEY_DWA)) +/** + * @} + */ + +/** @defgroup IWDG_Flag_definition + * @{ + */ +#define IWDG_FLAG_PVU ((uint32_t)0x0001) /*!< Watchdog counter prescaler value update Flag */ +#define IWDG_FLAG_RVU ((uint32_t)0x0002) /*!< Watchdog counter reload value update Flag */ +#define IWDG_FLAG_WVU ((uint32_t)0x0004) /*!< Watchdog counter window value update Flag */ + +#define IS_IWDG_FLAG(FLAG) (((FLAG) == IWDG_FLAG_PVU) || \ + ((FLAG) == IWDG_FLAG_RVU) || \ + ((FLAG) == IWDG_FLAG_WVU)) +/** + * @} + */ + +/** @defgroup IWDG_Prescaler + * @{ + */ +#define IWDG_PRESCALER_4 ((uint8_t)0x00) /*!< IWDG prescaler set to 4 */ +#define IWDG_PRESCALER_8 ((uint8_t)0x01) /*!< IWDG prescaler set to 8 */ +#define IWDG_PRESCALER_16 ((uint8_t)0x02) /*!< IWDG prescaler set to 16 */ +#define IWDG_PRESCALER_32 ((uint8_t)0x03) /*!< IWDG prescaler set to 32 */ +#define IWDG_PRESCALER_64 ((uint8_t)0x04) /*!< IWDG prescaler set to 64 */ +#define IWDG_PRESCALER_128 ((uint8_t)0x05) /*!< IWDG prescaler set to 128 */ +#define IWDG_PRESCALER_256 ((uint8_t)0x06) /*!< IWDG prescaler set to 256 */ + +#define IS_IWDG_PRESCALER(PRESCALER) (((PRESCALER) == IWDG_PRESCALER_4) || \ + ((PRESCALER) == IWDG_PRESCALER_8) || \ + ((PRESCALER) == IWDG_PRESCALER_16) || \ + ((PRESCALER) == IWDG_PRESCALER_32) || \ + ((PRESCALER) == IWDG_PRESCALER_64) || \ + ((PRESCALER) == IWDG_PRESCALER_128)|| \ + ((PRESCALER) == IWDG_PRESCALER_256)) + +/** + * @} + */ + +/** @defgroup IWDG_Reload_Value + * @{ + */ +#define IS_IWDG_RELOAD(RELOAD) ((RELOAD) <= 0xFFF) +/** + * @} + */ + +/** @defgroup IWDG_CounterWindow_Value + * @{ + */ +#define IS_IWDG_WINDOW(VALUE) ((VALUE) <= 0xFFF) +/** + * @} + */ +/** @defgroup IWDG_Window option disable + * @{ + */ +#define IWDG_WINDOW_DISABLE 0xFFF +/** + * @} + */ + +/** + * @} + */ + +/* Exported macros -----------------------------------------------------------*/ + +/** @defgroup IWDG_Exported_Macros + * @{ + */ + +/** @brief Reset IWDG handle state + * @param __HANDLE__: IWDG handle. + * @retval None + */ +#define __HAL_IWDG_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_IWDG_STATE_RESET) + +/** + * @brief Enables the IWDG peripheral. + * @param __HANDLE__: IWDG handle + * @retval None + */ +#define __HAL_IWDG_START(__HANDLE__) ((__HANDLE__)->Instance->KR |= KR_KEY_ENABLE) + +/** + * @brief Reloads IWDG counter with value defined in the reload register + * (write access to IWDG_PR and IWDG_RLR registers disabled). + * @param __HANDLE__: IWDG handle + * @retval None + */ +#define __HAL_IWDG_RELOAD_COUNTER(__HANDLE__) (((__HANDLE__)->Instance->KR) |= KR_KEY_RELOAD) + +/** + * @brief Enable write access to IWDG_PR, IWDG_RLR and IWDG_WINR registers. + * @param __HANDLE__: IWDG handle + * @retval None + */ +#define __HAL_IWDG_ENABLE_WRITE_ACCESS(__HANDLE__) (((__HANDLE__)->Instance->KR) |= KR_KEY_EWA) + +/** + * @brief Disable write access to IWDG_PR, IWDG_RLR and IWDG_WINR registers. + * @param __HANDLE__: IWDG handle + * @retval None + */ +#define __HAL_IWDG_DISABLE_WRITE_ACCESS(__HANDLE__) (((__HANDLE__)->Instance->KR) |= KR_KEY_DWA) + +/** + * @brief Gets the selected IWDG's flag status. + * @param __HANDLE__: IWDG handle + * @param __FLAG__: specifies the flag to check. + * This parameter can be one of the following values: + * @arg IWDG_FLAG_PVU: Watchdog counter reload value update flag + * @arg IWDG_FLAG_RVU: Watchdog counter prescaler value flag + * @arg IWDG_FLAG_WVU: Watchdog counter window value flag + * @retval The new state of __FLAG__ (TRUE or FALSE). + */ +#define __HAL_IWDG_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->SR & (__FLAG__)) == (__FLAG__)) + +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ + +/* Initialization and de-initialization functions ****************************/ +HAL_StatusTypeDef HAL_IWDG_Init(IWDG_HandleTypeDef *hiwdg); +void HAL_IWDG_MspInit(IWDG_HandleTypeDef *hiwdg); + +/* I/O operation functions ****************************************************/ +HAL_StatusTypeDef HAL_IWDG_Start(IWDG_HandleTypeDef *hiwdg); +HAL_StatusTypeDef HAL_IWDG_Refresh(IWDG_HandleTypeDef *hiwdg); + +/* Peripheral State functions ************************************************/ +HAL_IWDG_StateTypeDef HAL_IWDG_GetState(IWDG_HandleTypeDef *hiwdg); + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __STM32F0xx_HAL_IWDG_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_pcd.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_pcd.c new file mode 100644 index 0000000000..c476bb7fff --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_pcd.c @@ -0,0 +1,1312 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_pcd.c + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief PCD HAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the USB Peripheral Controller: + * + Initialization and de-initialization functions + * + IO operation functions + * + Peripheral Control functions + * + Peripheral State functions + * + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + The PCD HAL driver can be used as follows: + + (#) Declare a PCD_HandleTypeDef handle structure, for example: + PCD_HandleTypeDef hpcd; + + (#) Fill parameters of Init structure in HCD handle + + (#) Call HAL_PCD_Init() API to initialize the HCD peripheral (Core, Device core, ...) + + (#) Initialize the PCD low level resources through the HAL_PCD_MspInit() API: + (##) Enable the PCD/USB Low Level interface clock using + (+++) __USB_CLK_ENABLE); + + (##) Initialize the related GPIO clocks + (##) Configure PCD pin-out + (##) Configure PCD NVIC interrupt + + (#)Associate the Upper USB device stack to the HAL PCD Driver: + (##) hpcd.pData = pdev; + + (#)Enable HCD transmission and reception: + (##) HAL_PCD_Start(); + + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @defgroup PCD + * @brief PCD HAL module driver + * @{ + */ + +#ifdef HAL_PCD_MODULE_ENABLED + +#if defined(STM32F042x6) || defined(STM32F048xx) || defined(STM32F072xB) || defined(STM32F078xx) + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +#define BTABLE_ADDRESS (0x000) +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +static HAL_StatusTypeDef PCD_EP_ISR_Handler(PCD_HandleTypeDef *hpcd); +void PCD_WritePMA(USB_TypeDef *USBx, uint8_t *pbUsrBuf, uint16_t wPMABufAddr, uint16_t wNBytes); +void PCD_ReadPMA(USB_TypeDef *USBx, uint8_t *pbUsrBuf, uint16_t wPMABufAddr, uint16_t wNBytes); +/* Private functions ---------------------------------------------------------*/ + + +/** @defgroup PCD_Private_Functions + * @{ + */ + +/** @defgroup PCD_Group1 Initialization and de-initialization functions + * @brief Initialization and Configuration functions + * +@verbatim + =============================================================================== + ##### Initialization and de-initialization functions ##### + =============================================================================== + [..] This section provides functions allowing to: + +@endverbatim + * @{ + */ + +/** + * @brief Initializes the PCD according to the specified + * parameters in the PCD_InitTypeDef and create the associated handle. + * @param hpcd: PCD handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_Init(PCD_HandleTypeDef *hpcd) +{ + uint32_t i = 0; + + uint32_t wInterrupt_Mask = 0; + + /* Check the PCD handle allocation */ + if(hpcd == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_PCD_ALL_INSTANCE(hpcd->Instance)); + + hpcd->State = PCD_BUSY; + + /* Init the low level hardware : GPIO, CLOCK, NVIC... */ + HAL_PCD_MspInit(hpcd); + + /* Init endpoints structures */ + for (i = 0; i < hpcd->Init.dev_endpoints ; i++) + { + /* Init ep structure */ + hpcd->IN_ep[i].is_in = 1; + hpcd->IN_ep[i].num = i; + /* Control until ep is actvated */ + hpcd->IN_ep[i].type = PCD_EP_TYPE_CTRL; + hpcd->IN_ep[i].maxpacket = 0; + hpcd->IN_ep[i].xfer_buff = 0; + hpcd->IN_ep[i].xfer_len = 0; + } + + for (i = 0; i < hpcd->Init.dev_endpoints ; i++) + { + hpcd->OUT_ep[i].is_in = 0; + hpcd->OUT_ep[i].num = i; + /* Control until ep is activated */ + hpcd->OUT_ep[i].type = PCD_EP_TYPE_CTRL; + hpcd->OUT_ep[i].maxpacket = 0; + hpcd->OUT_ep[i].xfer_buff = 0; + hpcd->OUT_ep[i].xfer_len = 0; + } + + /* Init Device */ + /*CNTR_FRES = 1*/ + hpcd->Instance->CNTR = USB_CNTR_FRES; + + /*CNTR_FRES = 0*/ + hpcd->Instance->CNTR = 0; + + /*Clear pending interrupts*/ + hpcd->Instance->ISTR = 0; + + /*Set Btable Adress*/ + hpcd->Instance->BTABLE = BTABLE_ADDRESS; + + /*set wInterrupt_Mask global variable*/ + wInterrupt_Mask = USB_CNTR_CTRM | USB_CNTR_WKUPM | USB_CNTR_SUSPM | USB_CNTR_ERRM \ + | USB_CNTR_ESOFM | USB_CNTR_RESETM; + + /*Set interrupt mask*/ + hpcd->Instance->CNTR = wInterrupt_Mask; + + hpcd->USB_Address = 0; + hpcd->State= PCD_READY; + + return HAL_OK; +} + +/** + * @brief DeInitializes the PCD peripheral + * @param hpcd: PCD handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_DeInit(PCD_HandleTypeDef *hpcd) +{ + /* Check the PCD handle allocation */ + if(hpcd == NULL) + { + return HAL_ERROR; + } + + hpcd->State = PCD_BUSY; + + /* Stop Device */ + HAL_PCD_Stop(hpcd); + + /* DeInit the low level hardware */ + HAL_PCD_MspDeInit(hpcd); + + hpcd->State = PCD_READY; + + return HAL_OK; +} + +/** + * @brief Initializes the PCD MSP. + * @param hpcd: PCD handle + * @retval None + */ +__weak void HAL_PCD_MspInit(PCD_HandleTypeDef *hpcd) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_PCD_MspInit could be implemented in the user file + */ +} + +/** + * @brief DeInitializes PCD MSP. + * @param hpcd: PCD handle + * @retval None + */ +__weak void HAL_PCD_MspDeInit(PCD_HandleTypeDef *hpcd) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_PCD_MspDeInit could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup PCD_Group2 IO operation functions + * @brief Data transfers functions + * +@verbatim + =============================================================================== + ##### IO operation functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to manage the PCD data + transfers. + +@endverbatim + * @{ + */ + +/** + * @brief Start The USB OTG Device. + * @param hpcd: PCD handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_Start(PCD_HandleTypeDef *hpcd) +{ + /* Enabling DP Pull-Down bit to Connect internal pull-up on USB DP line */ + hpcd->Instance->BCDR |= USB_BCDR_DPPU; + + return HAL_OK; +} + +/** + * @brief Stop The USB OTG Device. + * @param hpcd: PCD handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_Stop(PCD_HandleTypeDef *hpcd) +{ + __HAL_LOCK(hpcd); + + /* disable all interrupts and force USB reset */ + hpcd->Instance->CNTR = USB_CNTR_FRES; + + /* clear interrupt status register */ + hpcd->Instance->ISTR = 0; + + /* switch-off device */ + hpcd->Instance->CNTR = (USB_CNTR_FRES | USB_CNTR_PDWN); + + __HAL_UNLOCK(hpcd); + return HAL_OK; +} + +/** + * @brief This function handles PCD Endpoint interrupt request. + * @param hpcd: PCD handle + * @retval HAL status + */ +static HAL_StatusTypeDef PCD_EP_ISR_Handler(PCD_HandleTypeDef *hpcd) +{ + PCD_EPTypeDef *ep; + uint16_t count=0; + uint8_t EPindex; + __IO uint16_t wIstr; + __IO uint16_t wEPVal = 0; + + /* stay in loop while pending interrupts */ + while (((wIstr = hpcd->Instance->ISTR) & USB_ISTR_CTR) != 0) + { + /* extract highest priority endpoint number */ + EPindex = (uint8_t)(wIstr & USB_ISTR_EP_ID); + + if (EPindex == 0) + { + /* Decode and service control endpoint interrupt */ + + /* DIR bit = origin of the interrupt */ + if ((wIstr & USB_ISTR_DIR) == 0) + { + /* DIR = 0 */ + + /* DIR = 0 => IN int */ + /* DIR = 0 implies that (EP_CTR_TX = 1) always */ + PCD_CLEAR_TX_EP_CTR(hpcd->Instance, PCD_ENDP0); + ep = &hpcd->IN_ep[0]; + + ep->xfer_count = PCD_GET_EP_TX_CNT(hpcd->Instance, ep->num); + ep->xfer_buff += ep->xfer_count; + + /* TX COMPLETE */ + HAL_PCD_DataInStageCallback(hpcd, 0); + + + if((hpcd->USB_Address > 0)&& ( ep->xfer_len == 0)) + { + hpcd->Instance->DADDR = (hpcd->USB_Address | USB_DADDR_EF); + hpcd->USB_Address = 0; + } + + } + else + { + /* DIR = 1 */ + + /* DIR = 1 & CTR_RX => SETUP or OUT int */ + /* DIR = 1 & (CTR_TX | CTR_RX) => 2 int pending */ + ep = &hpcd->OUT_ep[0]; + wEPVal = PCD_GET_ENDPOINT(hpcd->Instance, PCD_ENDP0); + + if ((wEPVal & USB_EP_SETUP) != 0) + { + /* Get SETUP Packet*/ + ep->xfer_count = PCD_GET_EP_RX_CNT(hpcd->Instance, ep->num); + PCD_ReadPMA(hpcd->Instance, (uint8_t*)hpcd->Setup ,ep->pmaadress , ep->xfer_count); + /* SETUP bit kept frozen while CTR_RX = 1*/ + PCD_CLEAR_RX_EP_CTR(hpcd->Instance, PCD_ENDP0); + + /* Process SETUP Packet*/ + HAL_PCD_SetupStageCallback(hpcd); + } + + else if ((wEPVal & USB_EP_CTR_RX) != 0) + { + PCD_CLEAR_RX_EP_CTR(hpcd->Instance, PCD_ENDP0); + /* Get Control Data OUT Packet*/ + ep->xfer_count = PCD_GET_EP_RX_CNT(hpcd->Instance, ep->num); + + if (ep->xfer_count != 0) + { + PCD_ReadPMA(hpcd->Instance, ep->xfer_buff, ep->pmaadress, ep->xfer_count); + ep->xfer_buff+=ep->xfer_count; + } + + /* Process Control Data OUT Packet*/ + HAL_PCD_DataOutStageCallback(hpcd, 0); + + PCD_SET_EP_RX_CNT(hpcd->Instance, PCD_ENDP0, ep->maxpacket); + PCD_SET_EP_RX_STATUS(hpcd->Instance, PCD_ENDP0, USB_EP_RX_VALID); + } + } + } + else + { + + /* Decode and service non control endpoints interrupt */ + + /* process related endpoint register */ + wEPVal = PCD_GET_ENDPOINT(hpcd->Instance, EPindex); + if ((wEPVal & USB_EP_CTR_RX) != 0) + { + /* clear int flag */ + PCD_CLEAR_RX_EP_CTR(hpcd->Instance, EPindex); + ep = &hpcd->OUT_ep[EPindex]; + + /* OUT double Buffering*/ + if (ep->doublebuffer == 0) + { + count = PCD_GET_EP_RX_CNT(hpcd->Instance, ep->num); + if (count != 0) + { + PCD_ReadPMA(hpcd->Instance, ep->xfer_buff, ep->pmaadress, count); + } + } + else + { + if (PCD_GET_ENDPOINT(hpcd->Instance, ep->num) & USB_EP_DTOG_RX) + { + /*read from endpoint BUF0Addr buffer*/ + count = PCD_GET_EP_DBUF0_CNT(hpcd->Instance, ep->num); + if (count != 0) + { + PCD_ReadPMA(hpcd->Instance, ep->xfer_buff, ep->pmaaddr0, count); + } + } + else + { + /*read from endpoint BUF1Addr buffer*/ + count = PCD_GET_EP_DBUF1_CNT(hpcd->Instance, ep->num); + if (count != 0) + { + PCD_ReadPMA(hpcd->Instance, ep->xfer_buff, ep->pmaaddr1, count); + } + } + PCD_FreeUserBuffer(hpcd->Instance, ep->num, PCD_EP_DBUF_OUT); + } + /*multi-packet on the NON control OUT endpoint*/ + ep->xfer_count+=count; + ep->xfer_buff+=count; + + if ((ep->xfer_len == 0) || (count < ep->maxpacket)) + { + /* RX COMPLETE */ + HAL_PCD_DataOutStageCallback(hpcd, ep->num); + } + else + { + HAL_PCD_EP_Receive(hpcd, ep->num, ep->xfer_buff, ep->xfer_len); + } + + } /* if((wEPVal & EP_CTR_RX) */ + + if ((wEPVal & USB_EP_CTR_TX) != 0) + { + ep = &hpcd->IN_ep[EPindex]; + + /* clear int flag */ + PCD_CLEAR_TX_EP_CTR(hpcd->Instance, EPindex); + + /* IN double Buffering*/ + if (ep->doublebuffer == 0) + { + ep->xfer_count = PCD_GET_EP_TX_CNT(hpcd->Instance, ep->num); + if (ep->xfer_count != 0) + { + PCD_WritePMA(hpcd->Instance, ep->xfer_buff, ep->pmaadress, ep->xfer_count); + } + } + else + { + if (PCD_GET_ENDPOINT(hpcd->Instance, ep->num) & USB_EP_DTOG_TX) + { + /*read from endpoint BUF0Addr buffer*/ + ep->xfer_count = PCD_GET_EP_DBUF0_CNT(hpcd->Instance, ep->num); + if (ep->xfer_count != 0) + { + PCD_WritePMA(hpcd->Instance, ep->xfer_buff, ep->pmaaddr0, ep->xfer_count); + } + } + else + { + /*read from endpoint BUF1Addr buffer*/ + ep->xfer_count = PCD_GET_EP_DBUF1_CNT(hpcd->Instance, ep->num); + if (ep->xfer_count != 0) + { + PCD_WritePMA(hpcd->Instance, ep->xfer_buff, ep->pmaaddr1, ep->xfer_count); + } + } + PCD_FreeUserBuffer(hpcd->Instance, ep->num, PCD_EP_DBUF_IN); + } + /*multi-packet on the NON control IN endpoint*/ + ep->xfer_count = PCD_GET_EP_TX_CNT(hpcd->Instance, ep->num); + ep->xfer_buff+=ep->xfer_count; + + /* Zero Length Packet? */ + if (ep->xfer_len == 0) + { + /* TX COMPLETE */ + HAL_PCD_DataInStageCallback(hpcd, ep->num); + } + else + { + HAL_PCD_EP_Transmit(hpcd, ep->num, ep->xfer_buff, ep->xfer_len); + } + } + } + } + return HAL_OK; +} +/** + * @brief This function handles PCD interrupt request. + * @param hpcd: PCD handle + * @retval HAL status + */ +void HAL_PCD_IRQHandler(PCD_HandleTypeDef *hpcd) +{ + uint32_t wInterrupt_Mask = 0; + + if (__HAL_PCD_GET_FLAG (hpcd, USB_ISTR_CTR)) + { + /* servicing of the endpoint correct transfer interrupt */ + /* clear of the CTR flag into the sub */ + PCD_EP_ISR_Handler(hpcd); + } + + if (__HAL_PCD_GET_FLAG (hpcd, USB_ISTR_RESET)) + { + __HAL_PCD_CLEAR_FLAG(hpcd, USB_ISTR_RESET); + HAL_PCD_ResetCallback(hpcd); + HAL_PCD_SetAddress(hpcd, 0); + } + + if (__HAL_PCD_GET_FLAG (hpcd, USB_ISTR_PMAOVR)) + { + __HAL_PCD_CLEAR_FLAG(hpcd, USB_ISTR_PMAOVR); + } + + if (__HAL_PCD_GET_FLAG (hpcd, USB_ISTR_ERR)) + { + __HAL_PCD_CLEAR_FLAG(hpcd, USB_ISTR_ERR); + } + + if (__HAL_PCD_GET_FLAG (hpcd, USB_ISTR_WKUP)) + { + + hpcd->Instance->CNTR &= ~(USB_CNTR_LPMODE); + + /*set wInterrupt_Mask global variable*/ + wInterrupt_Mask = USB_CNTR_CTRM | USB_CNTR_WKUPM | USB_CNTR_SUSPM | USB_CNTR_ERRM \ + | USB_CNTR_ESOFM | USB_CNTR_RESETM; + + /*Set interrupt mask*/ + hpcd->Instance->CNTR = wInterrupt_Mask; + + HAL_PCD_ResumeCallback(hpcd); + + __HAL_PCD_CLEAR_FLAG(hpcd, USB_ISTR_WKUP); + } + + if (__HAL_PCD_GET_FLAG (hpcd, USB_ISTR_SUSP)) + { + /* clear of the ISTR bit must be done after setting of CNTR_FSUSP */ + __HAL_PCD_CLEAR_FLAG(hpcd, USB_ISTR_SUSP); + + /* Force low-power mode in the macrocell */ + hpcd->Instance->CNTR |= USB_CNTR_FSUSP; + hpcd->Instance->CNTR |= USB_CNTR_LPMODE; + + if (__HAL_PCD_GET_FLAG (hpcd, USB_ISTR_WKUP) == 0) + { + HAL_PCD_SuspendCallback(hpcd); + } + } + + if (__HAL_PCD_GET_FLAG (hpcd, USB_ISTR_SOF)) + { + __HAL_PCD_CLEAR_FLAG(hpcd, USB_ISTR_SOF); + HAL_PCD_SOFCallback(hpcd); + } + + if (__HAL_PCD_GET_FLAG (hpcd, USB_ISTR_ESOF)) + { + /* clear ESOF flag in ISTR */ + __HAL_PCD_CLEAR_FLAG(hpcd, USB_ISTR_ESOF); + } +} + +/** + * @brief Data out stage callbacks + * @param hpcd: PCD handle + * @param epnum: endpoint number + * @retval None + */ + __weak void HAL_PCD_DataOutStageCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_PCD_DataOutStageCallback could be implemented in the user file + */ +} + +/** + * @brief Data IN stage callbacks + * @param hpcd: PCD handle + * @param epnum: endpoint number + * @retval None + */ + __weak void HAL_PCD_DataInStageCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_PCD_DataInStageCallback could be implemented in the user file + */ +} +/** + * @brief Setup stage callback + * @param hpcd: ppp handle + * @retval None + */ + __weak void HAL_PCD_SetupStageCallback(PCD_HandleTypeDef *hpcd) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_PCD_SetupStageCallback could be implemented in the user file + */ +} + +/** + * @brief USB Start Of Frame callbacks + * @param hpcd: PCD handle + * @retval None + */ + __weak void HAL_PCD_SOFCallback(PCD_HandleTypeDef *hpcd) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_PCD_SOFCallback could be implemented in the user file + */ +} + +/** + * @brief USB Reset callbacks + * @param hpcd: PCD handle + * @retval None + */ + __weak void HAL_PCD_ResetCallback(PCD_HandleTypeDef *hpcd) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_PCD_ResetCallback could be implemented in the user file + */ +} + + +/** + * @brief Suspend event callbacks + * @param hpcd: PCD handle + * @retval None + */ + __weak void HAL_PCD_SuspendCallback(PCD_HandleTypeDef *hpcd) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_PCD_SuspendCallback could be implemented in the user file + */ +} + +/** + * @brief Resume event callbacks + * @param hpcd: PCD handle + * @retval None + */ + __weak void HAL_PCD_ResumeCallback(PCD_HandleTypeDef *hpcd) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_PCD_ResumeCallback could be implemented in the user file + */ +} + +/** + * @brief Incomplete ISO OUT callbacks + * @param hpcd: PCD handle + * @param epnum: endpoint number + * @retval None + */ + __weak void HAL_PCD_ISOOUTIncompleteCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_PCD_ISOOUTIncompleteCallback could be implemented in the user file + */ +} + +/** + * @brief Incomplete ISO IN callbacks + * @param hpcd: PCD handle + * @param epnum: endpoint number + * @retval None + */ + __weak void HAL_PCD_ISOINIncompleteCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_PCD_ISOINIncompleteCallback could be implemented in the user file + */ +} + +/** + * @brief Connection event callbacks + * @param hpcd: PCD handle + * @retval None + */ + __weak void HAL_PCD_ConnectCallback(PCD_HandleTypeDef *hpcd) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_PCD_ConnectCallback could be implemented in the user file + */ +} + +/** + * @brief Disconnection event callbacks + * @param hpcd: ppp handle + * @retval None + */ + __weak void HAL_PCD_DisconnectCallback(PCD_HandleTypeDef *hpcd) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_PCD_DisconnectCallback could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup PCD_Group3 Peripheral Control functions + * @brief management functions + * +@verbatim + =============================================================================== + ##### Peripheral Control functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to control the PCD data + transfers. + +@endverbatim + * @{ + */ + +/** + * @brief Send an amount of data in blocking mode + * @param hpcd: PCD handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_DevConnect(PCD_HandleTypeDef *hpcd) +{ + __HAL_LOCK(hpcd); + + /* Enabling DP Pull-Down bit to Connect internal pull-up on USB DP line */ + hpcd->Instance->BCDR |= USB_BCDR_DPPU; + + __HAL_UNLOCK(hpcd); + return HAL_OK; +} + +/** + * @brief Send an amount of data in blocking mode + * @param hpcd: PCD handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_DevDisconnect(PCD_HandleTypeDef *hpcd) +{ + __HAL_LOCK(hpcd); + + /* Disable DP Pull-Down bit*/ + hpcd->Instance->BCDR &= ~(USB_BCDR_DPPU); + + __HAL_UNLOCK(hpcd); + return HAL_OK; +} + +/** + * @brief Set the USB Device address + * @param hpcd: PCD handle + * @param address: new device address + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_SetAddress(PCD_HandleTypeDef *hpcd, uint8_t address) +{ + __HAL_LOCK(hpcd); + + if(address == 0) + { + /* set device address and enable function */ + hpcd->Instance->DADDR = USB_DADDR_EF; + } + else /* USB Address will be applied later */ + { + hpcd->USB_Address = address; + } + + __HAL_UNLOCK(hpcd); + return HAL_OK; +} +/** + * @brief Open and configure an endpoint + * @param hpcd: PCD handle + * @param ep_addr: endpoint address + * @param ep_mps: endpoint max packert size + * @param ep_type: endpoint type + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_EP_Open(PCD_HandleTypeDef *hpcd, uint8_t ep_addr, uint16_t ep_mps, uint8_t ep_type) +{ + HAL_StatusTypeDef ret = HAL_OK; + PCD_EPTypeDef *ep; + + if ((ep_addr & 0x80) == 0x80) + { + ep = &hpcd->IN_ep[ep_addr & 0x7F]; + } + else + { + ep = &hpcd->OUT_ep[ep_addr & 0x7F]; + } + ep->num = ep_addr & 0x7F; + + ep->is_in = (0x80 & ep_addr) != 0; + ep->maxpacket = ep_mps; + ep->type = ep_type; + + __HAL_LOCK(hpcd); + +/* initialize Endpoint */ + switch (ep->type) + { + case PCD_EP_TYPE_CTRL: + PCD_SET_EPTYPE(hpcd->Instance, ep->num, USB_EP_CONTROL); + break; + case PCD_EP_TYPE_BULK: + PCD_SET_EPTYPE(hpcd->Instance, ep->num, USB_EP_BULK); + break; + case PCD_EP_TYPE_INTR: + PCD_SET_EPTYPE(hpcd->Instance, ep->num, USB_EP_INTERRUPT); + break; + case PCD_EP_TYPE_ISOC: + PCD_SET_EPTYPE(hpcd->Instance, ep->num, USB_EP_ISOCHRONOUS); + break; + } + + PCD_SET_EP_ADDRESS(hpcd->Instance, ep->num, ep->num); + + if (ep->doublebuffer == 0) + { + if (ep->is_in) + { + /*Set the endpoint Transmit buffer address */ + PCD_SET_EP_TX_ADDRESS(hpcd->Instance, ep->num, ep->pmaadress); + PCD_CLEAR_TX_DTOG(hpcd->Instance, ep->num); + /* Configure NAK status for the Endpoint*/ + PCD_SET_EP_TX_STATUS(hpcd->Instance, ep->num, USB_EP_TX_NAK); + } + else + { + /*Set the endpoint Receive buffer address */ + PCD_SET_EP_RX_ADDRESS(hpcd->Instance, ep->num, ep->pmaadress); + /*Set the endpoint Receive buffer counter*/ + PCD_SET_EP_RX_CNT(hpcd->Instance, ep->num, ep->maxpacket); + PCD_CLEAR_RX_DTOG(hpcd->Instance, ep->num); + /* Configure VALID status for the Endpoint*/ + PCD_SET_EP_RX_STATUS(hpcd->Instance, ep->num, USB_EP_RX_VALID); + } + } + /*Double Buffer*/ + else + { + /*Set the endpoint as double buffered*/ + PCD_SET_EP_DBUF(hpcd->Instance, ep->num); + /*Set buffer address for double buffered mode*/ + PCD_SET_EP_DBUF_ADDR(hpcd->Instance, ep->num,ep->pmaaddr0, ep->pmaaddr1); + + if (ep->is_in==0) + { + /* Clear the data toggle bits for the endpoint IN/OUT*/ + PCD_CLEAR_RX_DTOG(hpcd->Instance, ep->num); + PCD_CLEAR_TX_DTOG(hpcd->Instance, ep->num); + + /* Reset value of the data toggle bits for the endpoint out*/ + PCD_TX_DTOG(hpcd->Instance, ep->num); + + PCD_SET_EP_RX_STATUS(hpcd->Instance, ep->num, USB_EP_RX_VALID); + PCD_SET_EP_TX_STATUS(hpcd->Instance, ep->num, USB_EP_TX_DIS); + } + else + { + /* Clear the data toggle bits for the endpoint IN/OUT*/ + PCD_CLEAR_RX_DTOG(hpcd->Instance, ep->num); + PCD_CLEAR_TX_DTOG(hpcd->Instance, ep->num); + PCD_RX_DTOG(hpcd->Instance, ep->num); + /* Configure DISABLE status for the Endpoint*/ + PCD_SET_EP_TX_STATUS(hpcd->Instance, ep->num, USB_EP_TX_DIS); + PCD_SET_EP_RX_STATUS(hpcd->Instance, ep->num, USB_EP_RX_DIS); + } + } + + __HAL_UNLOCK(hpcd); + return ret; +} + + +/** + * @brief Deactivate an endpoint + * @param hpcd: PCD handle + * @param ep_addr: endpoint address + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_EP_Close(PCD_HandleTypeDef *hpcd, uint8_t ep_addr) +{ + PCD_EPTypeDef *ep; + + if ((ep_addr & 0x80) == 0x80) + { + ep = &hpcd->IN_ep[ep_addr & 0x7F]; + } + else + { + ep = &hpcd->OUT_ep[ep_addr & 0x7F]; + } + ep->num = ep_addr & 0x7F; + + ep->is_in = (0x80 & ep_addr) != 0; + + __HAL_LOCK(hpcd); + + if (ep->doublebuffer == 0) + { + if (ep->is_in) + { + PCD_CLEAR_TX_DTOG(hpcd->Instance, ep->num); + /* Configure DISABLE status for the Endpoint*/ + PCD_SET_EP_TX_STATUS(hpcd->Instance, ep->num, USB_EP_TX_DIS); + } + else + { + PCD_CLEAR_RX_DTOG(hpcd->Instance, ep->num); + /* Configure DISABLE status for the Endpoint*/ + PCD_SET_EP_RX_STATUS(hpcd->Instance, ep->num, USB_EP_RX_DIS); + } + } + /*Double Buffer*/ + else + { + if (ep->is_in==0) + { + /* Clear the data toggle bits for the endpoint IN/OUT*/ + PCD_CLEAR_RX_DTOG(hpcd->Instance, ep->num); + PCD_CLEAR_TX_DTOG(hpcd->Instance, ep->num); + + /* Reset value of the data toggle bits for the endpoint out*/ + PCD_TX_DTOG(hpcd->Instance, ep->num); + + PCD_SET_EP_RX_STATUS(hpcd->Instance, ep->num, USB_EP_RX_DIS); + PCD_SET_EP_TX_STATUS(hpcd->Instance, ep->num, USB_EP_TX_DIS); + } + else + { + /* Clear the data toggle bits for the endpoint IN/OUT*/ + PCD_CLEAR_RX_DTOG(hpcd->Instance, ep->num); + PCD_CLEAR_TX_DTOG(hpcd->Instance, ep->num); + PCD_RX_DTOG(hpcd->Instance, ep->num); + /* Configure DISABLE status for the Endpoint*/ + PCD_SET_EP_TX_STATUS(hpcd->Instance, ep->num, USB_EP_TX_DIS); + PCD_SET_EP_RX_STATUS(hpcd->Instance, ep->num, USB_EP_RX_DIS); + } + } + + __HAL_UNLOCK(hpcd); + return HAL_OK; +} + + +/** + * @brief Receive an amount of data + * @param hpcd: PCD handle + * @param ep_addr: endpoint address + * @param pBuf: pointer to the reception buffer + * @param len: amount of data to be received + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_EP_Receive(PCD_HandleTypeDef *hpcd, uint8_t ep_addr, uint8_t *pBuf, uint32_t len) +{ + + PCD_EPTypeDef *ep; + + ep = &hpcd->OUT_ep[ep_addr & 0x7F]; + + /*setup and start the Xfer */ + ep->xfer_buff = pBuf; + ep->xfer_len = len; + ep->xfer_count = 0; + ep->is_in = 0; + ep->num = ep_addr & 0x7F; + + __HAL_LOCK(hpcd); + + /* Multi packet transfer*/ + if (ep->xfer_len > ep->maxpacket) + { + len=ep->maxpacket; + ep->xfer_len-=len; + } + else + { + len=ep->xfer_len; + ep->xfer_len =0; + } + + /* configure and validate Rx endpoint */ + if (ep->doublebuffer == 0) + { + /*Set RX buffer count*/ + PCD_SET_EP_RX_CNT(hpcd->Instance, ep->num, len); + } + else + { + /*Set the Double buffer counter*/ + PCD_SET_EP_DBUF1_CNT(hpcd->Instance, ep->num, ep->is_in, len); + } + + PCD_SET_EP_RX_STATUS(hpcd->Instance, ep->num, USB_EP_RX_VALID); + + __HAL_UNLOCK(hpcd); + + return HAL_OK; +} + +/** + * @brief Get Received Data Size + * @param hpcd: PCD handle + * @param ep_addr: endpoint address + * @retval Data Size + */ +uint16_t HAL_PCD_EP_GetRxCount(PCD_HandleTypeDef *hpcd, uint8_t ep_addr) +{ + return hpcd->OUT_ep[ep_addr & 0x7F].xfer_count; +} +/** + * @brief Send an amount of data + * @param hpcd: PCD handle + * @param ep_addr: endpoint address + * @param pBuf: pointer to the transmission buffer + * @param len: amount of data to be sent + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_EP_Transmit(PCD_HandleTypeDef *hpcd, uint8_t ep_addr, uint8_t *pBuf, uint32_t len) +{ + PCD_EPTypeDef *ep; + uint16_t pmabuffer = 0; + + ep = &hpcd->IN_ep[ep_addr & 0x7F]; + + /*setup and start the Xfer */ + ep->xfer_buff = pBuf; + ep->xfer_len = len; + ep->xfer_count = 0; + ep->is_in = 1; + ep->num = ep_addr & 0x7F; + + __HAL_LOCK(hpcd); + + /*Multi packet transfer*/ + if (ep->xfer_len > ep->maxpacket) + { + len=ep->maxpacket; + ep->xfer_len-=len; + } + else + { + len=ep->xfer_len; + ep->xfer_len =0; + } + + /* configure and validate Tx endpoint */ + if (ep->doublebuffer == 0) + { + PCD_WritePMA(hpcd->Instance, ep->xfer_buff, ep->pmaadress, len); + PCD_SET_EP_TX_CNT(hpcd->Instance, ep->num, len); + } + else + { + /*Set the Double buffer counter*/ + PCD_SET_EP_DBUF1_CNT(hpcd->Instance, ep->num, ep->is_in, len); + + /*Write the data to the USB endpoint*/ + if (PCD_GET_ENDPOINT(hpcd->Instance, ep->num)& USB_EP_DTOG_TX) + { + pmabuffer = ep->pmaaddr1; + } + else + { + pmabuffer = ep->pmaaddr0; + } + PCD_WritePMA(hpcd->Instance, ep->xfer_buff, pmabuffer, len); + PCD_FreeUserBuffer(hpcd->Instance, ep->num, ep->is_in); + } + + PCD_SET_EP_TX_STATUS(hpcd->Instance, ep->num, USB_EP_TX_VALID); + + __HAL_UNLOCK(hpcd); + + return HAL_OK; +} + +/** + * @brief Set a STALL condition over an endpoint + * @param hpcd: PCD handle + * @param ep_addr: endpoint address + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_EP_SetStall(PCD_HandleTypeDef *hpcd, uint8_t ep_addr) +{ + PCD_EPTypeDef *ep; + + __HAL_LOCK(hpcd); + + if ((0x80 & ep_addr) == 0x80) + { + ep = &hpcd->IN_ep[ep_addr & 0x7F]; + } + else + { + ep = &hpcd->OUT_ep[ep_addr]; + } + + ep->is_stall = 1; + ep->num = ep_addr & 0x7F; + ep->is_in = ((ep_addr & 0x80) == 0x80); + + if (ep->num == 0) + { + /* This macro sets STALL status for RX & TX*/ + PCD_SET_EP_TXRX_STATUS(hpcd->Instance, ep->num, USB_EP_RX_STALL, USB_EP_TX_STALL); + } + else + { + if (ep->is_in) + { + PCD_SET_EP_TX_STATUS(hpcd->Instance, ep->num , USB_EP_TX_STALL); + } + else + { + PCD_SET_EP_RX_STATUS(hpcd->Instance, ep->num , USB_EP_RX_STALL); + } + } + __HAL_UNLOCK(hpcd); + + return HAL_OK; +} + +/** + * @brief Clear a STALL condition over in an endpoint + * @param hpcd: PCD handle + * @param ep_addr: endpoint address + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_EP_ClrStall(PCD_HandleTypeDef *hpcd, uint8_t ep_addr) +{ + PCD_EPTypeDef *ep; + + if ((0x80 & ep_addr) == 0x80) + { + ep = &hpcd->IN_ep[ep_addr & 0x7F]; + } + else + { + ep = &hpcd->OUT_ep[ep_addr]; + } + + ep->is_stall = 0; + ep->num = ep_addr & 0x7F; + ep->is_in = ((ep_addr & 0x80) == 0x80); + + __HAL_LOCK(hpcd); + + if (ep->is_in) + { + PCD_CLEAR_TX_DTOG(hpcd->Instance, ep->num); + PCD_SET_EP_TX_STATUS(hpcd->Instance, ep->num, USB_EP_TX_VALID); + } + else + { + PCD_CLEAR_RX_DTOG(hpcd->Instance, ep->num); + PCD_SET_EP_RX_STATUS(hpcd->Instance, ep->num, USB_EP_RX_VALID); + } + __HAL_UNLOCK(hpcd); + + return HAL_OK; +} + +/** + * @brief Flush an endpoint + * @param hpcd: PCD handle + * @param ep_addr: endpoint address + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_EP_Flush(PCD_HandleTypeDef *hpcd, uint8_t ep_addr) +{ + return HAL_OK; +} + +/** + * @brief HAL_PCD_ActiveRemoteWakeup : active remote wakeup signalling + * @param hpcd: PCD handle + * @retval status + */ +HAL_StatusTypeDef HAL_PCD_ActiveRemoteWakeup(PCD_HandleTypeDef *hpcd) +{ + hpcd->Instance->CNTR |= USB_CNTR_RESUME; + return HAL_OK; +} + +/** + * @brief HAL_PCD_DeActiveRemoteWakeup : de-active remote wakeup signalling + * @param hpcd: PCD handle + * @retval status + */ +HAL_StatusTypeDef HAL_PCD_DeActiveRemoteWakeup(PCD_HandleTypeDef *hpcd) +{ + hpcd->Instance->CNTR &= ~(USB_CNTR_RESUME); + return HAL_OK; +} +/** + * @brief Copy a buffer from user memory area to packet memory area (PMA) + * @param USBx: USB peripheral instance register address. + * @param pbUsrBuf: pointer to user memory area. + * @param wPMABufAddr: address into PMA. + * @param wNBytes: no. of bytes to be copied. + * @retval None + */ +void PCD_WritePMA(USB_TypeDef *USBx, uint8_t *pbUsrBuf, uint16_t wPMABufAddr, uint16_t wNBytes) +{ + uint32_t n = (wNBytes + 1) >> 1; + uint32_t i; + uint16_t temp1, temp2; + uint16_t *pdwVal; + pdwVal = (uint16_t *)(wPMABufAddr + (uint32_t)USBx + 0x400); + + for (i = n; i != 0; i--) + { + temp1 = (uint16_t) * pbUsrBuf; + pbUsrBuf++; + temp2 = temp1 | (uint16_t) * pbUsrBuf << 8; + *pdwVal++ = temp2; + pbUsrBuf++; + } +} + +/** + * @brief Copy a buffer from user memory area to packet memory area (PMA) + * @param USBx: USB peripheral instance register address. + * @param pbUsrBuf = pointer to user memory area. + * @param wPMABufAddr: address into PMA. + * @param wNBytes: no. of bytes to be copied. + * @retval None + */ +void PCD_ReadPMA(USB_TypeDef *USBx, uint8_t *pbUsrBuf, uint16_t wPMABufAddr, uint16_t wNBytes) +{ + uint32_t n = (wNBytes + 1) >> 1; + uint32_t i; + uint16_t *pdwVal; + pdwVal = (uint16_t *)(wPMABufAddr + (uint32_t)USBx + 0x400); + for (i = n; i != 0; i--) + { + *(uint16_t*)pbUsrBuf++ = *pdwVal++; + pbUsrBuf++; + } +} +/** + * @} + */ + +/** @defgroup PCD_Group4 Peripheral State functions + * @brief Peripheral State functions + * +@verbatim + =============================================================================== + ##### Peripheral State functions ##### + =============================================================================== + [..] + This subsection permit to get in run-time the status of the peripheral + and the data flow. + +@endverbatim + * @{ + */ + +/** + * @brief Return the PCD state + * @param hpcd : PCD handle + * @retval HAL state + */ +PCD_StateTypeDef HAL_PCD_GetState(PCD_HandleTypeDef *hpcd) +{ + return hpcd->State; +} +/** + * @} + */ + +/** + * @} + */ + +#endif /* STM32F042x6 || STM32F072xB || STM32F078xx */ + +#endif /* HAL_PCD_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_pcd.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_pcd.h new file mode 100644 index 0000000000..57b9ff2414 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_pcd.h @@ -0,0 +1,722 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_pcd.h + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief Header file of PCD HAL module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32F0xx_HAL_PCD_H +#define __STM32F0xx_HAL_PCD_H + +#ifdef __cplusplus + extern "C" { +#endif + +#if defined(STM32F042x6) || defined(STM32F048xx) || defined(STM32F072xB) || defined(STM32F078xx) + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal_def.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @addtogroup PCD + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ + + /** + * @brief PCD State structures definition + */ +typedef enum +{ + PCD_READY = 0x00, + PCD_ERROR = 0x01, + PCD_BUSY = 0x02, + PCD_TIMEOUT = 0x03 +} PCD_StateTypeDef; + +typedef enum +{ + /* double buffered endpoint direction */ + PCD_EP_DBUF_OUT, + PCD_EP_DBUF_IN, + PCD_EP_DBUF_ERR, +}PCD_EP_DBUF_DIR; + +/* endpoint buffer number */ +typedef enum +{ + PCD_EP_NOBUF, + PCD_EP_BUF0, + PCD_EP_BUF1 +}PCD_EP_BUF_NUM; + +/** + * @brief PCD Initialization Structure definition + */ +typedef struct +{ + uint32_t dev_endpoints; /*!< Device Endpoints number. + This parameter depends on the used USB core. + This parameter must be a number between Min_Data = 1 and Max_Data = 15 */ + + uint32_t speed; /*!< USB Core speed. + This parameter can be any value of @ref USB_Core_Speed */ + + uint32_t ep0_mps; /*!< Set the Endpoint 0 Max Packet size. + This parameter can be any value of @ref USB_EP0_MPS */ + + uint32_t phy_itface; /*!< Select the used PHY interface. + This parameter can be any value of @ref USB_Core_PHY */ + + uint32_t Sof_enable; /*!< Enable or disable the output of the SOF signal. + This parameter can be set to ENABLE or DISABLE */ + + uint32_t low_power_enable; /*!< Enable or disable Low Power mode + This parameter can be set to ENABLE or DISABLE */ + + uint32_t lpm_enable; /*!< Enable or disable the Link Power Management . + This parameter can be set to ENABLE or DISABLE */ + + uint32_t battery_charging_enable; /*!< Enable or disable Battery charging. + This parameter can be set to ENABLE or DISABLE */ + +}PCD_InitTypeDef; + +typedef struct +{ + uint8_t num; /*!< Endpoint number + This parameter must be a number between Min_Data = 1 and Max_Data = 15 */ + + uint8_t is_in; /*!< Endpoint direction + This parameter must be a number between Min_Data = 0 and Max_Data = 1 */ + + uint8_t is_stall; /*!< Endpoint stall condition + This parameter must be a number between Min_Data = 0 and Max_Data = 1 */ + + uint8_t type; /*!< Endpoint type + This parameter can be any value of @ref USB_EP_Type */ + + uint16_t pmaadress; /*!< PMA Address + This parameter can be any value between Min_addr = 0 and Max_addr = 1K */ + + + uint16_t pmaaddr0; /*!< PMA Address0 + This parameter can be any value between Min_addr = 0 and Max_addr = 1K */ + + + uint16_t pmaaddr1; /*!< PMA Address1 + This parameter can be any value between Min_addr = 0 and Max_addr = 1K */ + + + uint8_t doublebuffer; /*!< Double buffer enable + This parameter can be 0 or 1 */ + + uint32_t maxpacket; /*!< Endpoint Max packet size + This parameter must be a number between Min_Data = 0 and Max_Data = 64KB */ + + uint8_t *xfer_buff; /*!< Pointer to transfer buffer */ + + + uint32_t xfer_len; /*!< Current transfer length */ + + uint32_t xfer_count; /*!< Partial transfer length in case of multi packet transfer */ + +}PCD_EPTypeDef; + +typedef USB_TypeDef PCD_TypeDef; + +/** + * @brief PCD Handle Structure definition + */ +typedef struct +{ + PCD_TypeDef *Instance; /*!< Register base address */ + PCD_InitTypeDef Init; /*!< PCD required parameters */ + __IO uint8_t USB_Address; /*!< USB Address */ + PCD_EPTypeDef IN_ep[5]; /*!< IN endpoint parameters */ + PCD_EPTypeDef OUT_ep[5]; /*!< OUT endpoint parameters */ + HAL_LockTypeDef Lock; /*!< PCD peripheral status */ + __IO PCD_StateTypeDef State; /*!< PCD communication state */ + uint32_t Setup[12]; /*!< Setup packet buffer */ + void *pData; /*!< Pointer to upper stack Handler */ + +} PCD_HandleTypeDef; + +#include "stm32f0xx_hal_pcd_ex.h" +/* Exported constants --------------------------------------------------------*/ +/** @defgroup PCD_Exported_Constants + * @{ + */ + +/** @defgroup USB_Core_Speed + * @{ + */ +#define PCD_SPEED_HIGH 0 /* Not Supported */ +#define PCD_SPEED_FULL 2 +/** + * @} + */ + +/** @defgroup USB_Core_PHY + * @{ + */ +#define PCD_PHY_EMBEDDED 2 +/** + * @} + */ + +/** @defgroup USB_EP0_MPS + * @{ + */ +#define DEP0CTL_MPS_64 0 +#define DEP0CTL_MPS_32 1 +#define DEP0CTL_MPS_16 2 +#define DEP0CTL_MPS_8 3 + +#define PCD_EP0MPS_64 DEP0CTL_MPS_64 +#define PCD_EP0MPS_32 DEP0CTL_MPS_32 +#define PCD_EP0MPS_16 DEP0CTL_MPS_16 +#define PCD_EP0MPS_08 DEP0CTL_MPS_8 +/** + * @} + */ + +/** @defgroup USB_EP_Type + * @{ + */ +#define PCD_EP_TYPE_CTRL 0 +#define PCD_EP_TYPE_ISOC 1 +#define PCD_EP_TYPE_BULK 2 +#define PCD_EP_TYPE_INTR 3 +/** + * @} + */ + +#define PCD_ENDP0 ((uint8_t)0) +#define PCD_ENDP1 ((uint8_t)1) +#define PCD_ENDP2 ((uint8_t)2) +#define PCD_ENDP3 ((uint8_t)3) +#define PCD_ENDP4 ((uint8_t)4) +#define PCD_ENDP5 ((uint8_t)5) +#define PCD_ENDP6 ((uint8_t)6) +#define PCD_ENDP7 ((uint8_t)7) + +/* Endpoint Kind */ +#define PCD_SNG_BUF 0 +#define PCD_DBL_BUF 1 + +#define IS_PCD_ALL_INSTANCE IS_USB_ALL_INSTANCE +/** + * @} + */ + +/* Exported macros -----------------------------------------------------------*/ + +/** @defgroup PCD_Interrupt_Clock + * @brief macros to handle interrupts and specific clock configurations + * @{ + */ +#define __HAL_PCD_GET_FLAG(__HANDLE__, __INTERRUPT__) ((((__HANDLE__)->Instance->ISTR) & (__INTERRUPT__)) == (__INTERRUPT__)) +#define __HAL_PCD_CLEAR_FLAG(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->ISTR) &= ~(__INTERRUPT__)) + +#define USB_EXTI_LINE_WAKEUP ((uint32_t)0x00040000) /*!< External interrupt line 18 Connected to the USB FS EXTI Line */ + +#define __HAL_USB_EXTI_ENABLE_IT() EXTI->IMR |= USB_EXTI_LINE_WAKEUP +#define __HAL_USB_EXTI_DISABLE_IT() EXTI->IMR &= ~(USB_EXTI_LINE_WAKEUP) + +/* Internal macros -----------------------------------------------------------*/ + +/* SetENDPOINT */ +#define PCD_SET_ENDPOINT(USBx, bEpNum,wRegValue) (*(&USBx->EP0R + bEpNum * 2)= (uint16_t)wRegValue) + +/* GetENDPOINT */ +#define PCD_GET_ENDPOINT(USBx, bEpNum) (*(&USBx->EP0R + bEpNum * 2)) + + + +/** + * @brief sets the type in the endpoint register(bits EP_TYPE[1:0]) + * @param USBx: USB peripheral instance register address. + * @param bEpNum: Endpoint Number. + * @param wType: Endpoint Type. + * @retval None + */ +#define PCD_SET_EPTYPE(USBx, bEpNum,wType) (PCD_SET_ENDPOINT(USBx, bEpNum,\ + ((PCD_GET_ENDPOINT(USBx, bEpNum) & USB_EP_T_MASK) | wType ))) + +/** + * @brief gets the type in the endpoint register(bits EP_TYPE[1:0]) + * @param USBx: USB peripheral instance register address. + * @param bEpNum: Endpoint Number. + * @retval Endpoint Type + */ +#define PCD_GET_EPTYPE(USBx, bEpNum) (PCD_GET_ENDPOINT(USBx, bEpNum) & USB_EP_T_FIELD) + + +/** + * @brief free buffer used from the application realizing it to the line + toggles bit SW_BUF in the double buffered endpoint register + * @param USBx: USB peripheral instance register address. + * @param bEpNum: Endpoint Number. + * @param bDir: Direction + * @retval None + */ +#define PCD_FreeUserBuffer(USBx, bEpNum, bDir)\ +{\ + if (bDir == PCD_EP_DBUF_OUT)\ + { /* OUT double buffered endpoint */\ + PCD_TX_DTOG(USBx, bEpNum);\ + }\ + else if (bDir == PCD_EP_DBUF_IN)\ + { /* IN double buffered endpoint */\ + PCD_RX_DTOG(USBx, bEpNum);\ + }\ +} + +/** + * @brief gets direction of the double buffered endpoint + * @param USBx: USB peripheral instance register address. + * @param bEpNum: Endpoint Number. + * @retval EP_DBUF_OUT, EP_DBUF_IN, + * EP_DBUF_ERR if the endpoint counter not yet programmed. + */ +#define PCD_GET_DB_DIR(USBx, bEpNum)\ +{\ + if ((uint16_t)(*PCD_EP_RX_CNT(USBx, bEpNum) & 0xFC00) != 0)\ + return(PCD_EP_DBUF_OUT);\ + else if (((uint16_t)(*PCD_EP_TX_CNT(USBx, bEpNum)) & 0x03FF) != 0)\ + return(PCD_EP_DBUF_IN);\ + else\ + return(PCD_EP_DBUF_ERR);\ +} + +/** + * @brief sets the status for tx transfer (bits STAT_TX[1:0]). + * @param USBx: USB peripheral instance register address. + * @param bEpNum: Endpoint Number. + * @param wState: new state + * @retval None + */ +#define PCD_SET_EP_TX_STATUS(USBx, bEpNum, wState) {\ + register uint16_t _wRegVal; \ + \ + _wRegVal = PCD_GET_ENDPOINT(USBx, bEpNum) & USB_EPTX_DTOGMASK;\ + /* toggle first bit ? */ \ + if((USB_EPTX_DTOG1 & wState)!= 0) \ + _wRegVal ^= USB_EPTX_DTOG1; \ + /* toggle second bit ? */ \ + if((USB_EPTX_DTOG2 & wState)!= 0) \ + _wRegVal ^= USB_EPTX_DTOG2; \ + PCD_SET_ENDPOINT(USBx, bEpNum, (_wRegVal | USB_EP_CTR_RX|USB_EP_CTR_TX)); \ + } /* PCD_SET_EP_TX_STATUS */ + +/** + * @brief sets the status for rx transfer (bits STAT_TX[1:0]) + * @param USBx: USB peripheral instance register address. + * @param bEpNum: Endpoint Number. + * @param wState: new state + * @retval None + */ +#define PCD_SET_EP_RX_STATUS(USBx, bEpNum,wState) {\ + register uint16_t _wRegVal; \ + \ + _wRegVal = PCD_GET_ENDPOINT(USBx, bEpNum) & USB_EPRX_DTOGMASK;\ + /* toggle first bit ? */ \ + if((USB_EPRX_DTOG1 & wState)!= 0) \ + _wRegVal ^= USB_EPRX_DTOG1; \ + /* toggle second bit ? */ \ + if((USB_EPRX_DTOG2 & wState)!= 0) \ + _wRegVal ^= USB_EPRX_DTOG2; \ + PCD_SET_ENDPOINT(USBx, bEpNum, (_wRegVal | USB_EP_CTR_RX|USB_EP_CTR_TX)); \ + } /* PCD_SET_EP_RX_STATUS */ + +/** + * @brief sets the status for rx & tx (bits STAT_TX[1:0] & STAT_RX[1:0]) + * @param USBx: USB peripheral instance register address. + * @param bEpNum: Endpoint Number. + * @param wStaterx: new state. + * @param wStatetx: new state. + * @retval None + */ +#define PCD_SET_EP_TXRX_STATUS(USBx,bEpNum,wStaterx,wStatetx) {\ + register uint32_t _wRegVal; \ + \ + _wRegVal = PCD_GET_ENDPOINT(USBx, bEpNum) & (USB_EPRX_DTOGMASK |USB_EPTX_STAT) ;\ + /* toggle first bit ? */ \ + if((USB_EPRX_DTOG1 & wStaterx)!= 0) \ + _wRegVal ^= USB_EPRX_DTOG1; \ + /* toggle second bit ? */ \ + if((USB_EPRX_DTOG2 & wStaterx)!= 0) \ + _wRegVal ^= USB_EPRX_DTOG2; \ + /* toggle first bit ? */ \ + if((USB_EPTX_DTOG1 & wStatetx)!= 0) \ + _wRegVal ^= USB_EPTX_DTOG1; \ + /* toggle second bit ? */ \ + if((USB_EPTX_DTOG2 & wStatetx)!= 0) \ + _wRegVal ^= USB_EPTX_DTOG2; \ + PCD_SET_ENDPOINT(USBx, bEpNum, _wRegVal | USB_EP_CTR_RX|USB_EP_CTR_TX); \ + } /* PCD_SET_EP_TXRX_STATUS */ + +/** + * @brief gets the status for tx/rx transfer (bits STAT_TX[1:0] + * /STAT_RX[1:0]) + * @param USBx: USB peripheral instance register address. + * @param bEpNum: Endpoint Number. + * @retval status + */ +#define PCD_GET_EP_TX_STATUS(USBx, bEpNum) ((uint16_t)PCD_GET_ENDPOINT(USBx, bEpNum) & USB_EPTX_STAT) + +#define PCD_GET_EP_RX_STATUS(USBx, bEpNum) ((uint16_t)PCD_GET_ENDPOINT(USBx, bEpNum) & USB_EPRX_STAT) + +/** + * @brief sets directly the VALID tx/rx-status into the endpoint register + * @param USBx: USB peripheral instance register address. + * @param bEpNum: Endpoint Number. + * @retval None + */ +#define PCD_SET_EP_TX_VALID(USBx, bEpNum) (PCD_SET_EP_TX_STATUS(USBx, bEpNum, USB_EP_TX_VALID)) + +#define PCD_SET_EP_RX_VALID(USBx, bEpNum) (PCD_SET_EP_RX_STATUS(USBx, bEpNum, USB_EP_RX_VALID)) + +/** + * @brief checks stall condition in an endpoint. + * @param USBx: USB peripheral instance register address. + * @param bEpNum: Endpoint Number. + * @retval TRUE = endpoint in stall condition. + */ +#define PCD_GET_EP_TX_STALL_STATUS(USBx, bEpNum) (PCD_GET_EP_TX_STATUS(USBx, bEpNum) \ + == USB_EP_TX_STALL) +#define PCD_GET_EP_RX_STALL_STATUS(USBx, bEpNum) (PCD_GET_EP_RX_STATUS(USBx, bEpNum) \ + == USB_EP_RX_STALL) + +/** + * @brief set & clear EP_KIND bit. + * @param USBx: USB peripheral instance register address. + * @param bEpNum: Endpoint Number. + * @retval None + */ +#define PCD_SET_EP_KIND(USBx, bEpNum) (PCD_SET_ENDPOINT(USBx, bEpNum, \ + (USB_EP_CTR_RX|USB_EP_CTR_TX|((PCD_GET_ENDPOINT(USBx, bEpNum) | USB_EP_KIND) & USB_EPREG_MASK)))) +#define PCD_CLEAR_EP_KIND(USBx, bEpNum) (PCD_SET_ENDPOINT(USBx, bEpNum, \ + (USB_EP_CTR_RX|USB_EP_CTR_TX|(PCD_GET_ENDPOINT(USBx, bEpNum) & USB_EPKIND_MASK)))) + +/** + * @brief Sets/clears directly STATUS_OUT bit in the endpoint register. + * @param USBx: USB peripheral instance register address. + * @param bEpNum: Endpoint Number. + * @retval None + */ +#define PCD_SET_OUT_STATUS(USBx, bEpNum) PCD_SET_EP_KIND(USBx, bEpNum) +#define PCD_CLEAR_OUT_STATUS(USBx, bEpNum) PCD_CLEAR_EP_KIND(USBx, bEpNum) + +/** + * @brief Sets/clears directly EP_KIND bit in the endpoint register. + * @param USBx: USB peripheral instance register address. + * @param bEpNum: Endpoint Number. + * @retval None + */ +#define PCD_SET_EP_DBUF(USBx, bEpNum) PCD_SET_EP_KIND(USBx, bEpNum) +#define PCD_CLEAR_EP_DBUF(USBx, bEpNum) PCD_CLEAR_EP_KIND(USBx, bEpNum) + +/** + * @brief Clears bit CTR_RX / CTR_TX in the endpoint register. + * @param USBx: USB peripheral instance register address. + * @param bEpNum: Endpoint Number. + * @retval None + */ +#define PCD_CLEAR_RX_EP_CTR(USBx, bEpNum) (PCD_SET_ENDPOINT(USBx, bEpNum,\ + PCD_GET_ENDPOINT(USBx, bEpNum) & 0x7FFF & USB_EPREG_MASK)) +#define PCD_CLEAR_TX_EP_CTR(USBx, bEpNum) (PCD_SET_ENDPOINT(USBx, bEpNum,\ + PCD_GET_ENDPOINT(USBx, bEpNum) & 0xFF7F & USB_EPREG_MASK)) + +/** + * @brief Toggles DTOG_RX / DTOG_TX bit in the endpoint register. + * @param USBx: USB peripheral instance register address. + * @param bEpNum: Endpoint Number. + * @retval None + */ +#define PCD_RX_DTOG(USBx, bEpNum) (PCD_SET_ENDPOINT(USBx, bEpNum, \ + USB_EP_CTR_RX|USB_EP_CTR_TX|USB_EP_DTOG_RX | (PCD_GET_ENDPOINT(USBx, bEpNum) & USB_EPREG_MASK))) +#define PCD_TX_DTOG(USBx, bEpNum) (PCD_SET_ENDPOINT(USBx, bEpNum, \ + USB_EP_CTR_RX|USB_EP_CTR_TX|USB_EP_DTOG_TX | (PCD_GET_ENDPOINT(USBx, bEpNum) & USB_EPREG_MASK))) + +/** + * @brief Clears DTOG_RX / DTOG_TX bit in the endpoint register. + * @param USBx: USB peripheral instance register address. + * @param bEpNum: Endpoint Number. + * @retval None + */ +#define PCD_CLEAR_RX_DTOG(USBx, bEpNum) if((PCD_GET_ENDPOINT(USBx, bEpNum) & USB_EP_DTOG_RX) != 0)\ + PCD_RX_DTOG(USBx, bEpNum) +#define PCD_CLEAR_TX_DTOG(USBx, bEpNum) if((PCD_GET_ENDPOINT(USBx, bEpNum) & USB_EP_DTOG_TX) != 0)\ + PCD_TX_DTOG(USBx, bEpNum) + +/** + * @brief Sets address in an endpoint register. + * @param USBx: USB peripheral instance register address. + * @param bEpNum: Endpoint Number. + * @param bAddr: Address. + * @retval None + */ +#define PCD_SET_EP_ADDRESS(USBx, bEpNum,bAddr) PCD_SET_ENDPOINT(USBx, bEpNum,\ + USB_EP_CTR_RX|USB_EP_CTR_TX|(PCD_GET_ENDPOINT(USBx, bEpNum) & USB_EPREG_MASK) | bAddr) + +/** + * @brief Gets address in an endpoint register. + * @param USBx: USB peripheral instance register address. + * @param bEpNum: Endpoint Number. + * @retval None + */ +#define PCD_GET_EP_ADDRESS(USBx, bEpNum) ((uint8_t)(PCD_GET_ENDPOINT(USBx, bEpNum) & USB_EPADDR_FIELD)) + +#define PCD_EP_TX_ADDRESS(USBx, bEpNum) ((uint16_t *)((USBx->BTABLE+bEpNum*8)+ ((uint32_t)USBx + 0x400))) +#define PCD_EP_TX_CNT(USBx, bEpNum) ((uint16_t *)((USBx->BTABLE+bEpNum*8+2)+ ((uint32_t)USBx + 0x400))) +#define PCD_EP_RX_ADDRESS(USBx, bEpNum) ((uint16_t *)((USBx->BTABLE+bEpNum*8+4)+ ((uint32_t)USBx + 0x400))) +#define PCD_EP_RX_CNT(USBx, bEpNum) ((uint16_t *)((USBx->BTABLE+bEpNum*8+6)+ ((uint32_t)USBx + 0x400))) + +/** + * @brief sets address of the tx/rx buffer. + * @param USBx: USB peripheral instance register address. + * @param bEpNum: Endpoint Number. + * @param wAddr: address to be set (must be word aligned). + * @retval None + */ +#define PCD_SET_EP_TX_ADDRESS(USBx, bEpNum,wAddr) (*PCD_EP_TX_ADDRESS(USBx, bEpNum) = ((wAddr >> 1) << 1)) +#define PCD_SET_EP_RX_ADDRESS(USBx, bEpNum,wAddr) (*PCD_EP_RX_ADDRESS(USBx, bEpNum) = ((wAddr >> 1) << 1)) + +/** + * @brief Gets address of the tx/rx buffer. + * @param USBx: USB peripheral instance register address. + * @param bEpNum: Endpoint Number. + * @retval address of the buffer. + */ +#define PCD_GET_EP_TX_ADDRESS(USBx, bEpNum) ((uint16_t)*PCD_EP_TX_ADDRESS(USBx, bEpNum)) +#define PCD_GET_EP_RX_ADDRESS(USBx, bEpNum) ((uint16_t)*PCD_EP_RX_ADDRESS(USBx, bEpNum)) + +/** + * @brief Sets counter of rx buffer with no. of blocks. + * @param dwReg: Register + * @param wCount: Counter. + * @param wNBlocks: no. of Blocks. + * @retval None + */ +#define PCD_CALC_BLK32(dwReg,wCount,wNBlocks) {\ + wNBlocks = wCount >> 5;\ + if((wCount & 0x1f) == 0)\ + wNBlocks--;\ + *pdwReg = (uint16_t)((wNBlocks << 10) | 0x8000);\ + }/* PCD_CALC_BLK32 */ + +#define PCD_CALC_BLK2(dwReg,wCount,wNBlocks) {\ + wNBlocks = wCount >> 1;\ + if((wCount & 0x1) != 0)\ + wNBlocks++;\ + *pdwReg = (uint16_t)(wNBlocks << 10);\ + }/* PCD_CALC_BLK2 */ + +#define PCD_SET_EP_CNT_RX_REG(dwReg,wCount) {\ + uint16_t wNBlocks;\ + if(wCount > 62){PCD_CALC_BLK32(dwReg,wCount,wNBlocks);}\ + else {PCD_CALC_BLK2(dwReg,wCount,wNBlocks);}\ + }/* PCD_SET_EP_CNT_RX_REG */ + +#define PCD_SET_EP_RX_DBUF0_CNT(USBx, bEpNum,wCount) {\ + uint16_t *pdwReg = PCD_EP_TX_CNT(USBx, bEpNum); \ + PCD_SET_EP_CNT_RX_REG(pdwReg, wCount);\ + } +/** + * @brief sets counter for the tx/rx buffer. + * @param USBx: USB peripheral instance register address. + * @param bEpNum: Endpoint Number. + * @param wCount: Counter value. + * @retval None + */ +#define PCD_SET_EP_TX_CNT(USBx, bEpNum,wCount) (*PCD_EP_TX_CNT(USBx, bEpNum) = wCount) +#define PCD_SET_EP_RX_CNT(USBx, bEpNum,wCount) {\ + uint16_t *pdwReg = PCD_EP_RX_CNT(USBx, bEpNum); \ + PCD_SET_EP_CNT_RX_REG(pdwReg, wCount);\ + } + +/** + * @brief gets counter of the tx buffer. + * @param USBx: USB peripheral instance register address. + * @param bEpNum: Endpoint Number. + * @retval Counter value + */ +#define PCD_GET_EP_TX_CNT(USBx, bEpNum)((uint16_t)(*PCD_EP_TX_CNT(USBx, bEpNum)) & 0x3ff) +#define PCD_GET_EP_RX_CNT(USBx, bEpNum)((uint16_t)(*PCD_EP_RX_CNT(USBx, bEpNum)) & 0x3ff) + +/** + * @brief Sets buffer 0/1 address in a double buffer endpoint. + * @param USBx: USB peripheral instance register address. + * @param bEpNum: Endpoint Number. + * @param wBuf0Addr: buffer 0 address. + * @retval Counter value + */ +#define PCD_SET_EP_DBUF0_ADDR(USBx, bEpNum,wBuf0Addr) {PCD_SET_EP_TX_ADDRESS(USBx, bEpNum, wBuf0Addr);} +#define PCD_SET_EP_DBUF1_ADDR(USBx, bEpNum,wBuf1Addr) {PCD_SET_EP_RX_ADDRESS(USBx, bEpNum, wBuf1Addr);} + +/** + * @brief Sets addresses in a double buffer endpoint. + * @param USBx: USB peripheral instance register address. + * @param bEpNum: Endpoint Number. + * @param wBuf0Addr: buffer 0 address. + * @param wBuf1Addr = buffer 1 address. + * @retval None + */ +#define PCD_SET_EP_DBUF_ADDR(USBx, bEpNum,wBuf0Addr,wBuf1Addr) { \ + PCD_SET_EP_DBUF0_ADDR(USBx, bEpNum, wBuf0Addr);\ + PCD_SET_EP_DBUF1_ADDR(USBx, bEpNum, wBuf1Addr);\ + } /* PCD_SET_EP_DBUF_ADDR */ + +/** + * @brief Gets buffer 0/1 address of a double buffer endpoint. + * @param USBx: USB peripheral instance register address. + * @param bEpNum: Endpoint Number. + * @retval None + */ +#define PCD_GET_EP_DBUF0_ADDR(USBx, bEpNum) (PCD_GET_EP_TX_ADDRESS(USBx, bEpNum)) +#define PCD_GET_EP_DBUF1_ADDR(USBx, bEpNum) (PCD_GET_EP_RX_ADDRESS(USBx, bEpNum)) + +/** + * @brief Gets buffer 0/1 address of a double buffer endpoint. + * @param USBx: USB peripheral instance register address. + * @param bEpNum: Endpoint Number. + * @param bDir: endpoint dir EP_DBUF_OUT = OUT + * EP_DBUF_IN = IN + * @param wCount: Counter value + * @retval None + */ +#define PCD_SET_EP_DBUF0_CNT(USBx, bEpNum, bDir, wCount) { \ + if(bDir == PCD_EP_DBUF_OUT)\ + /* OUT endpoint */ \ + {PCD_SET_EP_RX_DBUF0_CNT(USBx, bEpNum,wCount);} \ + else if(bDir == PCD_EP_DBUF_IN)\ + /* IN endpoint */ \ + *PCD_EP_TX_CNT(USBx, bEpNum) = (uint32_t)wCount; \ + } /* SetEPDblBuf0Count*/ + +#define PCD_SET_EP_DBUF1_CNT(USBx, bEpNum, bDir, wCount) { \ + if(bDir == PCD_EP_DBUF_OUT)\ + /* OUT endpoint */ \ + {PCD_SET_EP_RX_CNT(USBx, bEpNum,wCount);}\ + else if(bDir == PCD_EP_DBUF_IN)\ + /* IN endpoint */\ + *PCD_EP_RX_CNT(USBx, bEpNum) = (uint32_t)wCount; \ + } /* SetEPDblBuf1Count */ + +#define PCD_SET_EP_DBUF_CNT(USBx, bEpNum, bDir, wCount) {\ + PCD_SET_EP_DBUF0_CNT(USBx, bEpNum, bDir, wCount); \ + PCD_SET_EP_DBUF1_CNT(USBx, bEpNum, bDir, wCount); \ + } /* PCD_SET_EP_DBUF_CNT */ + +/** + * @brief Gets buffer 0/1 rx/tx counter for double buffering. + * @param USBx: USB peripheral instance register address. + * @param bEpNum: Endpoint Number. + * @retval None + */ +#define PCD_GET_EP_DBUF0_CNT(USBx, bEpNum) (PCD_GET_EP_TX_CNT(USBx, bEpNum)) +#define PCD_GET_EP_DBUF1_CNT(USBx, bEpNum) (PCD_GET_EP_RX_CNT(USBx, bEpNum)) + + +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ + +/* Initialization/de-initialization functions **********************************/ +HAL_StatusTypeDef HAL_PCD_Init(PCD_HandleTypeDef *hpcd); +HAL_StatusTypeDef HAL_PCD_DeInit (PCD_HandleTypeDef *hpcd); +void HAL_PCD_MspInit(PCD_HandleTypeDef *hpcd); +void HAL_PCD_MspDeInit(PCD_HandleTypeDef *hpcd); + +/* I/O operation functions *****************************************************/ + /* Non-Blocking mode: Interrupt */ +HAL_StatusTypeDef HAL_PCD_Start(PCD_HandleTypeDef *hpcd); +HAL_StatusTypeDef HAL_PCD_Stop(PCD_HandleTypeDef *hpcd); +void HAL_PCD_IRQHandler(PCD_HandleTypeDef *hpcd); + +void HAL_PCD_DataOutStageCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum); +void HAL_PCD_DataInStageCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum); +void HAL_PCD_SetupStageCallback(PCD_HandleTypeDef *hpcd); +void HAL_PCD_SOFCallback(PCD_HandleTypeDef *hpcd); +void HAL_PCD_ResetCallback(PCD_HandleTypeDef *hpcd); +void HAL_PCD_SuspendCallback(PCD_HandleTypeDef *hpcd); +void HAL_PCD_ResumeCallback(PCD_HandleTypeDef *hpcd); +void HAL_PCD_ISOOUTIncompleteCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum); +void HAL_PCD_ISOINIncompleteCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum); +void HAL_PCD_ConnectCallback(PCD_HandleTypeDef *hpcd); +void HAL_PCD_DisconnectCallback(PCD_HandleTypeDef *hpcd); + +/* Peripheral Control functions ************************************************/ +HAL_StatusTypeDef HAL_PCD_DevConnect(PCD_HandleTypeDef *hpcd); +HAL_StatusTypeDef HAL_PCD_DevDisconnect(PCD_HandleTypeDef *hpcd); +HAL_StatusTypeDef HAL_PCD_SetAddress(PCD_HandleTypeDef *hpcd, uint8_t address); +HAL_StatusTypeDef HAL_PCD_EP_Open(PCD_HandleTypeDef *hpcd, uint8_t ep_addr, uint16_t ep_mps, uint8_t ep_type); +HAL_StatusTypeDef HAL_PCD_EP_Close(PCD_HandleTypeDef *hpcd, uint8_t ep_addr); +HAL_StatusTypeDef HAL_PCD_EP_Receive(PCD_HandleTypeDef *hpcd, uint8_t ep_addr, uint8_t *pBuf, uint32_t len); +HAL_StatusTypeDef HAL_PCD_EP_Transmit(PCD_HandleTypeDef *hpcd, uint8_t ep_addr, uint8_t *pBuf, uint32_t len); +uint16_t HAL_PCD_EP_GetRxCount(PCD_HandleTypeDef *hpcd, uint8_t ep_addr); +HAL_StatusTypeDef HAL_PCD_EP_SetStall(PCD_HandleTypeDef *hpcd, uint8_t ep_addr); +HAL_StatusTypeDef HAL_PCD_EP_ClrStall(PCD_HandleTypeDef *hpcd, uint8_t ep_addr); +HAL_StatusTypeDef HAL_PCD_EP_Flush(PCD_HandleTypeDef *hpcd, uint8_t ep_addr); +HAL_StatusTypeDef HAL_PCD_ActiveRemoteWakeup(PCD_HandleTypeDef *hpcd); +HAL_StatusTypeDef HAL_PCD_DeActiveRemoteWakeup(PCD_HandleTypeDef *hpcd); +/* Peripheral State functions **************************************************/ +PCD_StateTypeDef HAL_PCD_GetState(PCD_HandleTypeDef *hpcd); + +/** + * @} + */ + +/** + * @} + */ + +#endif /* STM32F042x6 || STM32F072xB || STM32F078xx */ + +#ifdef __cplusplus +} +#endif + + +#endif /* __STM32F0xx_HAL_PCD_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_pcd_ex.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_pcd_ex.c new file mode 100644 index 0000000000..65cfeae552 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_pcd_ex.c @@ -0,0 +1,154 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_pcd_ex.c + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief Extended PCD HAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the USB Peripheral Controller: + * + Configuration of the PMA for EP + * + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @defgroup PCDEx + * @brief PCDEx HAL module driver + * @{ + */ + +#ifdef HAL_PCD_MODULE_ENABLED + +#if defined(STM32F042x6) || defined(STM32F048xx) || defined(STM32F072xB) || defined(STM32F078xx) + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ + + +/** @defgroup PCDEx_Private_Functions + * @{ + */ + +/** @defgroup PCDEx_Group1 Initialization and de-initialization functions + * @brief Initialization and Configuration functions + * +@verbatim + =============================================================================== + ##### Peripheral extended features methods ##### + =============================================================================== +@endverbatim + * @{ + */ + +/** + * @brief Configure PMA for EP + * @param hpcd: PCD handle + * @param ep_addr: endpoint address + * @param ep_kind: endpoint Kind + * @arg USB_SNG_BUF: Single Buffer used + * @arg USB_DBL_BUF: Double Buffer used + * @param pmaadress: EP address in The PMA: In case of single buffer endpoint + * this parameter is 16-bit value providing the address + * in PMA allocated to endpoint. + * In case of double buffer endpoint this parameter + * is a 32-bit value providing the endpoint buffer 0 address + * in the LSB part of 32-bit value and endpoint buffer 1 address + * in the MSB part of 32-bit value. + * @retval : status + */ + +HAL_StatusTypeDef HAL_PCDEx_PMAConfig(PCD_HandleTypeDef *hpcd, + uint16_t ep_addr, + uint16_t ep_kind, + uint32_t pmaadress) + +{ + PCD_EPTypeDef *ep; + + /* initialize ep structure*/ + if ((0x80 & ep_addr) == 0x80) + { + ep = &hpcd->IN_ep[ep_addr & 0x7F]; + } + else + { + ep = &hpcd->OUT_ep[ep_addr]; + } + + /* Here we check if the endpoint is single or double Buffer*/ + if (ep_kind == PCD_SNG_BUF) + { + /*Single Buffer*/ + ep->doublebuffer = 0; + /*Configure te PMA*/ + ep->pmaadress = (uint16_t)pmaadress; + } + else /*USB_DBL_BUF*/ + { + /*Double Buffer Endpoint*/ + ep->doublebuffer = 1; + /*Configure the PMA*/ + ep->pmaaddr0 = pmaadress & 0xFFFF; + ep->pmaaddr1 = (pmaadress & 0xFFFF0000) >> 16; + } + + return HAL_OK; +} +/** + * @} + */ + +/** + * @} + */ + +#endif /* STM32F042x6 || STM32F072xB || STM32F078xx */ + +#endif /* HAL_PCD_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_pcd_ex.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_pcd_ex.h new file mode 100644 index 0000000000..2fb76c6ae3 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_pcd_ex.h @@ -0,0 +1,86 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_pcd_ex.h + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief Header file of PCD HAL Extension module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32L0xx_HAL_PCD_EX_H +#define __STM32L0xx_HAL_PCD_EX_H + +#ifdef __cplusplus + extern "C" { +#endif + +#if defined(STM32F042x6) || defined(STM32F048xx) || defined(STM32F072xB) || defined(STM32F078xx) + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal_def.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @addtogroup PCDEx + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/* Exported constants --------------------------------------------------------*/ +/* Exported macros -----------------------------------------------------------*/ +/* Internal macros -----------------------------------------------------------*/ +/* Exported functions --------------------------------------------------------*/ +HAL_StatusTypeDef HAL_PCDEx_PMAConfig(PCD_HandleTypeDef *hpcd, + uint16_t ep_addr, + uint16_t ep_kind, + uint32_t pmaadress); + +/** + * @} + */ + +/** + * @} + */ + +#endif /* STM32F042x6 || STM32F072xB || STM32F078xx */ + +#ifdef __cplusplus +} +#endif + + +#endif /* __STM32F0xx_HAL_PCD_EX_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_pwr.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_pwr.c new file mode 100644 index 0000000000..94dd758a35 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_pwr.c @@ -0,0 +1,436 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_pwr.c + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief PWR HAL module driver. + * + * This file provides firmware functions to manage the following + * functionalities of the Power Controller (PWR) peripheral: + * + Initialization/de-initialization function + * + Peripheral Control function + * + @verbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @defgroup PWR + * @brief PWR HAL module driver + * @{ + */ + +#ifdef HAL_PWR_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup PWR_Private_Functions + * @{ + */ + +/** @defgroup HAL_PWR_Group1 Initialization and de-initialization functions + * @brief Initialization and de-initialization functions + * +@verbatim + =============================================================================== + ##### Initialization and de-initialization functions ##### + =============================================================================== + [..] + After reset, the backup domain (RTC registers, RTC backup data + registers) is protected against possible unwanted + write accesses. + To enable access to the RTC Domain and RTC registers, proceed as follows: + (+) Enable the Power Controller (PWR) APB1 interface clock using the + __PWR_CLK_ENABLE() macro. + (+) Enable access to RTC domain using the HAL_PWR_EnableBkUpAccess() function. + +@endverbatim + * @{ + */ + +/** + * @brief Deinitializes the HAL PWR peripheral registers to their default reset values. + * @param None + * @retval None + */ +void HAL_PWR_DeInit(void) +{ + __PWR_FORCE_RESET(); + __PWR_RELEASE_RESET(); +} + +/** + * @brief Enables access to the backup domain (RTC registers, RTC + * backup data registers). + * @note If the HSE divided by 32 is used as the RTC clock, the + * Backup Domain Access should be kept enabled. + * @param None + * @retval None + */ +void HAL_PWR_EnableBkUpAccess(void) +{ + PWR->CR |= (uint32_t)PWR_CR_DBP; +} + +/** + * @brief Disables access to the backup domain (RTC registers, RTC + * backup data registers). + * @note If the HSE divided by 32 is used as the RTC clock, the + * Backup Domain Access should be kept enabled. + * @param None + * @retval None + */ +void HAL_PWR_DisableBkUpAccess(void) +{ + PWR->CR &= ~((uint32_t)PWR_CR_DBP); +} + +/** + * @} + */ + +/** @defgroup HAL_PWR_Group2 Peripheral Control function + * @brief Low Power modes configuration functions + * +@verbatim + + =============================================================================== + ##### Peripheral Control function ##### + =============================================================================== + + *** WakeUp pin configuration *** + ================================ + [..] + (+) WakeUp pin is used to wakeup the system from Standby mode. This pin is + forced in input pull down configuration and is active on rising edges. + (+) There are two WakeUp pins, and up to eight Wakeup pins on STM32F07x devices. + WakeUp Pin 1 on PA.00. + WakeUp Pin 2 on PC.13. + WakeUp Pin 3 on PE.06.(STM32F07x) + WakeUp Pin 4 on PA.02.(STM32F07x) + WakeUp Pin 5 on PC.05.(STM32F07x) + WakeUp Pin 6 on PB.05.(STM32F07x) + WakeUp Pin 7 on PB.15.(STM32F07x) + WakeUp Pin 8 on PF.02.(STM32F07x) + + *** Low Power modes configuration *** + ===================================== + [..] + The devices feature 3 low-power modes: + (+) Sleep mode: Cortex-M0 core stopped, peripherals kept running. + (+) Stop mode: All clocks are stopped, regulator running, regulator + in low power mode + (+) Standby mode: 1.8V domain powered off + Note: Standby mode is not available on STM32F0x8 devices. + + *** Sleep mode *** + ================== + [..] + (+) Entry: + The Sleep mode is entered by using the HAL_PWR_EnterSLEEPMode(PWR_MAINREGULATOR_ON, PWR_SLEEPENTRY_WFx) + functions with + (++) PWR_SLEEPENTRY_WFI: enter SLEEP mode with WFI instruction + (++) PWR_SLEEPENTRY_WFE: enter SLEEP mode with WFE instruction + + (+) Exit: + (++) Any peripheral interrupt acknowledged by the nested vectored interrupt + controller (NVIC) can wake up the device from Sleep mode. + + *** Stop mode *** + ================= + [..] + In Stop mode, all clocks in the 1.8V domain are stopped, the PLL, the HSI, + and the HSE RC oscillators are disabled. Internal SRAM and register contents + are preserved. + The voltage regulator can be configured either in normal or low-power mode. + To minimize the consumption. + + (+) Entry: + The Stop mode is entered using the HAL_PWR_EnterSTOPMode(PWR_MAINREGULATOR_ON, PWR_STOPENTRY_WFI ) + function with: + (++) Main regulator ON. + (++) Low Power regulator ON. + (++) PWR_STOPENTRY_WFI: enter STOP mode with WFI instruction + (++) PWR_STOPENTRY_WFE: enter STOP mode with WFE instruction + (+) Exit: + (++) Any EXTI Line (Internal or External) configured in Interrupt/Event mode. + (++) Some specific communication peripherals (CEC, USART, I2C) interrupts, + when programmed in wakeup mode (the peripheral must be + programmed in wakeup mode and the corresponding interrupt vector + must be enabled in the NVIC) + + *** Standby mode *** + ==================== + [..] + The Standby mode allows to achieve the lowest power consumption. It is based + on the Cortex-M0 deep sleep mode, with the voltage regulator disabled. + The 1.8V domain is consequently powered off. The PLL, the HSI oscillator and + the HSE oscillator are also switched off. SRAM and register contents are lost + except for the RTC registers, RTC backup registers and Standby + circuitry. + The voltage regulator is OFF. + + (+) Entry: + (++) The Standby mode is entered using the HAL_PWR_EnterSTANDBYMode() function. + (+) Exit: + (++) WKUP pin rising edge, RTC alarm (Alarm A), RTC wakeup, + tamper event, time-stamp event, external reset in NRST pin, IWDG reset. + + + *** Auto-wakeup (AWU) from low-power mode *** + ============================================= + [..] + The MCU can be woken up from low-power mode by an RTC Alarm event, an RTC + Wakeup event, a tamper event or a time-stamp event, without depending on + an external interrupt (Auto-wakeup mode). + + (#) RTC auto-wakeup (AWU) from the Stop and Standby modes + + (+++) To wake up from the Stop mode with an RTC alarm event, it is necessary to + configure the RTC to generate the RTC alarm using the HAL_RTC_SetAlarm_IT() function. + + (+++) To wake up from the Stop mode with an RTC Tamper or time stamp event, it + is necessary to configure the RTC to detect the tamper or time stamp event using the + HAL_RTC_SetTimeStamp_IT() or HAL_RTC_SetTamper_IT() functions. + + (+++) To wake up from the Stop mode with an RTC WakeUp event, it is necessary to + configure the RTC to generate the RTC WakeUp event using the HAL_RTC_SetWakeUpTimer_IT() function. + +@endverbatim + * @{ + */ + + +/** + * @brief Enables the WakeUp PINx functionality. + * @param WakeUpPinx: Specifies the Power Wake-Up pin to enable. + * This parameter can be value of : + * @ref PWREx_WakeUp_Pins + * @retval None + */ +void HAL_PWR_EnableWakeUpPin(uint32_t WakeUpPinx) +{ + /* Check the parameters */ + assert_param(IS_PWR_WAKEUP_PIN(WakeUpPinx)); + PWR->CSR |= (PWR_CSR_EWUP1 << (uint8_t)WakeUpPinx); +} + +/** + * @brief Disables the WakeUp PINx functionality. + * @param WakeUpPinx: Specifies the Power Wake-Up pin to disable. + * This parameter can be values of : + * @ref PWREx_WakeUp_Pins + * @retval None + */ +void HAL_PWR_DisableWakeUpPin(uint32_t WakeUpPinx) +{ + /* Check the parameters */ + assert_param(IS_PWR_WAKEUP_PIN(WakeUpPinx)); + PWR->CSR &= ~(PWR_CSR_EWUP1 << (uint8_t)WakeUpPinx); +} + +/** + * @brief Enters Sleep mode. + * @note In Sleep mode, all I/O pins keep the same state as in Run mode. + * @param Regulator: Specifies the regulator state in SLEEP mode. + * This parameter can be one of the following values: + * @arg PWR_MAINREGULATOR_ON: SLEEP mode with regulator ON + * @arg PWR_LOWPOWERREGULATOR_ON: SLEEP mode with low power regulator ON + * @param SLEEPEntry: Specifies if SLEEP mode is entered with WFI or WFE instruction. + * When WFI entry is used, tick interrupt have to be disabled if not desired as + * the interrupt wake up source. + * This parameter can be one of the following values: + * @arg PWR_SLEEPENTRY_WFI: enter SLEEP mode with WFI instruction + * @arg PWR_SLEEPENTRY_WFE: enter SLEEP mode with WFE instruction + * @retval None + */ +void HAL_PWR_EnterSLEEPMode(uint32_t Regulator, uint8_t SLEEPEntry) +{ + uint32_t tmpreg = 0; + + /* Check the parameters */ + assert_param(IS_PWR_REGULATOR(Regulator)); + assert_param(IS_PWR_SLEEP_ENTRY(SLEEPEntry)); + + /* Select the regulator state in SLEEP mode ---------------------------------*/ + tmpreg = PWR->CR; + + /* Clear PDDS and LPDS bits */ + tmpreg &= (uint32_t)~(PWR_CR_PDDS | PWR_CR_LPDS); + + /* Set LPDS bit according to Regulator value */ + tmpreg |= Regulator; + + /* Store the new value */ + PWR->CR = tmpreg; + + /* Clear SLEEPDEEP bit of Cortex System Control Register */ + SCB->SCR &= (uint32_t)~((uint32_t)SCB_SCR_SLEEPDEEP_Msk); + + /* Select SLEEP mode entry -------------------------------------------------*/ + if(SLEEPEntry == PWR_SLEEPENTRY_WFI) + { + /* Request Wait For Interrupt */ + __WFI(); + } + else + { + /* Request Wait For Event */ + __SEV(); + __WFE(); + __WFE(); + } + +} + +/** + * @brief Enters STOP mode. + * @note In Stop mode, all I/O pins keep the same state as in Run mode. + * @note When exiting Stop mode by issuing an interrupt or a wakeup event, + * the HSI RC oscillator is selected as system clock. + * @note When the voltage regulator operates in low power mode, an additional + * startup delay is incurred when waking up from Stop mode. + * By keeping the internal regulator ON during Stop mode, the consumption + * is higher although the startup time is reduced. + * @param Regulator: Specifies the regulator state in STOP mode. + * This parameter can be one of the following values: + * @arg PWR_MAINREGULATOR_ON: STOP mode with regulator ON + * @arg PWR_LOWPOWERREGULATOR_ON: STOP mode with low power regulator ON + * @param STOPEntry: specifies if STOP mode in entered with WFI or WFE instruction. + * This parameter can be one of the following values: + * @arg PWR_STOPENTRY_WFI:Enter STOP mode with WFI instruction + * @arg PWR_STOPENTRY_WFE: Enter STOP mode with WFE instruction + * @retval None + */ +void HAL_PWR_EnterSTOPMode(uint32_t Regulator, uint8_t STOPEntry) +{ + uint32_t tmpreg = 0; + + /* Check the parameters */ + assert_param(IS_PWR_REGULATOR(Regulator)); + assert_param(IS_PWR_STOP_ENTRY(STOPEntry)); + + /* Select the regulator state in STOP mode ---------------------------------*/ + tmpreg = PWR->CR; + + /* Clear PDDS and LPDS bits */ + tmpreg &= (uint32_t)~(PWR_CR_PDDS | PWR_CR_LPDS); + + /* Set LPDS bit according to Regulator value */ + tmpreg |= Regulator; + + /* Store the new value */ + PWR->CR = tmpreg; + + /* Set SLEEPDEEP bit of Cortex System Control Register */ + SCB->SCR |= SCB_SCR_SLEEPDEEP_Msk; + + /* Select STOP mode entry --------------------------------------------------*/ + if(STOPEntry == PWR_STOPENTRY_WFI) + { + /* Request Wait For Interrupt */ + __WFI(); + } + else + { + /* Request Wait For Event */ + __SEV(); + __WFE(); + __WFE(); + } + + /* Reset SLEEPDEEP bit of Cortex System Control Register */ + SCB->SCR &= (uint32_t)~((uint32_t)SCB_SCR_SLEEPDEEP_Msk); +} + +/** + * @brief Enters STANDBY mode. + * @note In Standby mode, all I/O pins are high impedance except for: + * - Reset pad (still available) + * - RTC alternate function pins if configured for tamper, time-stamp, RTC + * Alarm out, or RTC clock calibration out. + * - WKUP pins if enabled. + * STM32F0x8 devices, the Stop mode is available, but it is + * aningless to distinguish between voltage regulator in Low power + * mode and voltage regulator in Run mode because the regulator + * not used and the core is supplied directly from an external source. + * Consequently, the Standby mode is not available on those devices. + * @param None + * @retval None + */ +void HAL_PWR_EnterSTANDBYMode(void) +{ + /* Clear Wakeup flag */ + PWR->CR |= (uint32_t)PWR_CR_CWUF; + + /* Select STANDBY mode */ + PWR->CR |= (uint32_t)PWR_CR_PDDS; + + /* Set SLEEPDEEP bit of Cortex System Control Register */ + SCB->SCR |= SCB_SCR_SLEEPDEEP_Msk; + + /* This option is used to ensure that store operations are completed */ +#if defined ( __CC_ARM) + __force_stores(); +#endif + /* Request Wait For Interrupt */ + __WFI(); +} + +/** + * @} + */ + +/** + * @} + */ + +#endif /* HAL_PWR_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_pwr.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_pwr.h new file mode 100644 index 0000000000..0cfb15d39f --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_pwr.h @@ -0,0 +1,173 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_pwr.h + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief Header file of PWR HAL module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32F0xx_HAL_PWR_H +#define __STM32F0xx_HAL_PWR_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal_def.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @addtogroup PWR + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/* Exported constants --------------------------------------------------------*/ +/** @defgroup PWR_Exported_Constants + * @{ + */ + +/** @defgroup PWR_Regulator_state_in_STOP_mode + * @{ + */ +#define PWR_MAINREGULATOR_ON ((uint32_t)0x00000000) +#define PWR_LOWPOWERREGULATOR_ON PWR_CR_LPDS + +#define IS_PWR_REGULATOR(REGULATOR) (((REGULATOR) == PWR_MAINREGULATOR_ON) || \ + ((REGULATOR) == PWR_LOWPOWERREGULATOR_ON)) +/** + * @} + */ + +/** @defgroup PWR_SLEEP_mode_entry + * @{ + */ +#define PWR_SLEEPENTRY_WFI ((uint8_t)0x01) +#define PWR_SLEEPENTRY_WFE ((uint8_t)0x02) +#define IS_PWR_SLEEP_ENTRY(ENTRY) (((ENTRY) == PWR_SLEEPENTRY_WFI) || ((ENTRY) == PWR_SLEEPENTRY_WFE)) +/** + * @} + */ + +/** @defgroup PWR_STOP_mode_entry + * @{ + */ +#define PWR_STOPENTRY_WFI ((uint8_t)0x01) +#define PWR_STOPENTRY_WFE ((uint8_t)0x02) +#define IS_PWR_STOP_ENTRY(ENTRY) (((ENTRY) == PWR_STOPENTRY_WFI) || ((ENTRY) == PWR_STOPENTRY_WFE)) +/** + * @} + */ + + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ +/** @defgroup PWR_Exported_Macros + * @{ + */ + +/** @brief Check PWR flag is set or not. + * @param __FLAG__: specifies the flag to check. + * This parameter can be one of the following values: + * @arg PWR_FLAG_WU: Wake Up flag. This flag indicates that a wakeup event + * was received from the WKUP pin or from the RTC alarm (Alarm A), + * RTC Tamper event, RTC TimeStamp event or RTC Wakeup. + * An additional wakeup event is detected if the WKUP pin is enabled + * (by setting the EWUP bit) when the WKUP pin level is already high. + * @arg PWR_FLAG_SB: StandBy flag. This flag indicates that the system was + * resumed from StandBy mode. + * @arg PWR_FLAG_PVDO: PVD Output. This flag is valid only if PVD is enabled + * by the HAL_PWR_EnablePVD() function. The PVD is stopped by Standby mode + * For this reason, this bit is equal to 0 after Standby or reset + * until the PVDE bit is set. + * Warning: this Flag is not available on STM32F030x8 products + * @arg PWR_FLAG_VREFINTRDY: This flag indicates that the internal reference + * voltage VREFINT is ready. + * Warning: this Flag is not available on STM32F030x8 products + * @retval The new state of __FLAG__ (TRUE or FALSE). + */ +#define __HAL_PWR_GET_FLAG(__FLAG__) ((PWR->CSR & (__FLAG__)) == (__FLAG__)) + +/** @brief Clear the PWR's pending flags. + * @param __FLAG__: specifies the flag to clear. + * This parameter can be one of the following values: + * @arg PWR_FLAG_WU: Wake Up flag + * @arg PWR_FLAG_SB: StandBy flag + */ +#define __HAL_PWR_CLEAR_FLAG(__FLAG__) (PWR->CR |= (__FLAG__) << 2) + + +/** + * @} + */ + +/* Include PWR HAL Extension module */ +#include "stm32f0xx_hal_pwr_ex.h" + +/* Exported functions --------------------------------------------------------*/ + +/* Initialization and de-initialization functions *****************************/ +void HAL_PWR_DeInit(void); + +/* Peripheral Control functions **********************************************/ +void HAL_PWR_EnableBkUpAccess(void); +void HAL_PWR_DisableBkUpAccess(void); +void HAL_PWR_EnableWakeUpPin(uint32_t WakeUpPinx); +void HAL_PWR_DisableWakeUpPin(uint32_t WakeUpPinx); + +void HAL_PWR_EnterSTOPMode(uint32_t Regulator, uint8_t STOPEntry); +void HAL_PWR_EnterSLEEPMode(uint32_t Regulator, uint8_t SLEEPEntry); +void HAL_PWR_EnterSTANDBYMode(void); + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + + +#endif /* __STM32F0xx_HAL_PWR_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_pwr_ex.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_pwr_ex.c new file mode 100644 index 0000000000..d9c5148537 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_pwr_ex.c @@ -0,0 +1,210 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_pwr_ex.c + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief Extended PWR HAL module driver. + * + * This file provides firmware functions to manage the following + * functionalities of the Power Controller (PWR) peripheral: + * + Extended Initialization and de-initialization function + * + Extended Peripheral Control function + * + @verbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @defgroup PWREx + * @brief PWR Extended HAL module driver + * @{ + */ + +#ifdef HAL_PWR_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup PWREx_Private_Functions + * @{ + */ + +/** @defgroup PWREx_Group1 Extended Peripheral Control functions + * @brief Extended Peripheral Control functions + * +@verbatim + + =============================================================================== + ##### Peripheral Control function ##### + =============================================================================== + + *** PVD configuration *** + ========================= + [..] + (+) The PVD is used to monitor the VDD power supply by comparing it to a + threshold selected by the PVD Level (PLS[2:0] bits in the PWR_CR). + (+) A PVDO flag is available to indicate if VDD/VDDA is higher or lower + than the PVD threshold. This event is internally connected to the EXTI + line16 and can generate an interrupt if enabled. This is done through + __HAL_PVD_EXTI_ENABLE_IT() macro + (+) The PVD is stopped in Standby mode. + Note: PVD is not available on STM32F030x4/x6/x8 + +@endverbatim + * @{ + */ + +#if defined (STM32F031x6) || defined (STM32F042x6) || defined (STM32F051x8) || \ + defined (STM32F071xB) || defined (STM32F072xB) + +/** + * @brief Configures the voltage threshold detected by the Power Voltage Detector(PVD). + * @param sConfigPVD: pointer to an PWR_PVDTypeDef structure that contains the configuration + * information for the PVD. + * @note Refer to the electrical characteristics of your device datasheet for + * more details about the voltage threshold corresponding to each + * detection level. + * @retval None + */ +void HAL_PWR_PVDConfig(PWR_PVDTypeDef *sConfigPVD) +{ + /* Check the parameters */ + assert_param(IS_PWR_PVD_LEVEL(sConfigPVD->PVDLevel)); + assert_param(IS_PWR_PVD_MODE(sConfigPVD->Mode)); + + /* Set PLS[7:5] bits according to PVDLevel value */ + MODIFY_REG(PWR->CR, PWR_CR_PLS, sConfigPVD->PVDLevel); + + /* Configure the EXTI 16 interrupt */ + if((sConfigPVD->Mode == PWR_MODE_IT_RISING_FALLING) ||\ + (sConfigPVD->Mode == PWR_MODE_IT_FALLING) ||\ + (sConfigPVD->Mode == PWR_MODE_IT_RISING)) + { + __HAL_PVD_EXTI_ENABLE_IT(PWR_EXTI_LINE_PVD); + } + /* Configure the rising edge */ + if((sConfigPVD->Mode == PWR_MODE_IT_RISING_FALLING) ||\ + (sConfigPVD->Mode == PWR_MODE_IT_RISING)) + { + EXTI->RTSR |= PWR_EXTI_LINE_PVD; + } + /* Configure the falling edge */ + if((sConfigPVD->Mode == PWR_MODE_IT_RISING_FALLING) ||\ + (sConfigPVD->Mode == PWR_MODE_IT_FALLING)) + { + EXTI->FTSR |= PWR_EXTI_LINE_PVD; + } +} + +/** + * @brief Enables the Power Voltage Detector(PVD). + * @param None + * @retval None + */ +void HAL_PWR_EnablePVD(void) +{ + PWR->CR |= (uint32_t)PWR_CR_PVDE; +} + +/** + * @brief Disables the Power Voltage Detector(PVD). + * @param None + * @retval None + */ +void HAL_PWR_DisablePVD(void) +{ + PWR->CR &= ~((uint32_t)PWR_CR_PVDE); +} + +/** + * @brief This function handles the PWR PVD interrupt request. + * @note This API should be called under the PVD_IRQHandler(). + * @param None + * @retval None + */ +void HAL_PWR_PVD_IRQHandler(void) +{ + /* Check PWR exti flag */ + if(__HAL_PVD_EXTI_GET_FLAG(PWR_EXTI_LINE_PVD) != RESET) + { + /* PWR PVD interrupt user callback */ + HAL_PWR_PVDCallback(); + + /* Clear PWR Exti pending bit */ + __HAL_PVD_EXTI_CLEAR_FLAG(PWR_EXTI_LINE_PVD); + } +} + +/** + * @brief PWR PVD interrupt callback + * @param None + * @retval None + */ +__weak void HAL_PWR_PVDCallback(void) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_PWR_PVDCallback could be implemented in the user file + */ +} + +#endif /* defined (STM32F031x6) || defined (STM32F042x6) || defined (STM32F051x8) || */ + /* defined (STM32F071xB) || defined (STM32F072xB) */ + + +/** + * @} + */ + +/** + * @} + */ + + +#endif /* HAL_PWR_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_pwr_ex.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_pwr_ex.h new file mode 100644 index 0000000000..0c3cbf1ee9 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_pwr_ex.h @@ -0,0 +1,269 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_pwr_ex.h + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief Header file of PWR HAL Extension module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32F0xx_HAL_PWR_EX_H +#define __STM32F0xx_HAL_PWR_EX_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal_def.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @addtogroup PWREx + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ + +#if defined (STM32F031x6) || defined (STM32F042x6) || defined (STM32F051x8) || \ + defined (STM32F071xB) || defined (STM32F072xB) + +/** + * @brief PWR PVD configuration structure definition + */ +typedef struct +{ + uint32_t PVDLevel; /*!< PVDLevel: Specifies the PVD detection level + This parameter can be a value of @ref PWREx_PVD_detection_level */ + + uint32_t Mode; /*!< Mode: Specifies the operating mode for the selected pins. + This parameter can be a value of @ref PWREx_PVD_Mode */ +}PWR_PVDTypeDef; + +#endif /* defined (STM32F031x6) || defined (STM32F042x6) || defined (STM32F051x8) || */ + /* defined (STM32F071xB) || defined (STM32F072xB) */ + +/* Exported constants --------------------------------------------------------*/ +/** @defgroup PWREx_Exported_Constants + * @{ + */ + +/** @defgroup PWREx_WakeUp_Pins + * @{ + */ +#if defined (STM32F071xB) || defined (STM32F072xB) || defined (STM32F078xx) +#define PWR_WAKEUP_PIN1 ((uint32_t)0x00) +#define PWR_WAKEUP_PIN2 ((uint32_t)0x01) +#define PWR_WAKEUP_PIN3 ((uint32_t)0x02) +#define PWR_WAKEUP_PIN4 ((uint32_t)0x03) +#define PWR_WAKEUP_PIN5 ((uint32_t)0x04) +#define PWR_WAKEUP_PIN6 ((uint32_t)0x05) +#define PWR_WAKEUP_PIN7 ((uint32_t)0x06) +#define PWR_WAKEUP_PIN8 ((uint32_t)0x07) + +#define IS_PWR_WAKEUP_PIN(PIN) (((PIN) == PWR_WAKEUP_PIN1) || \ + ((PIN) == PWR_WAKEUP_PIN2) || \ + ((PIN) == PWR_WAKEUP_PIN3) || \ + ((PIN) == PWR_WAKEUP_PIN4) || \ + ((PIN) == PWR_WAKEUP_PIN5) || \ + ((PIN) == PWR_WAKEUP_PIN6) || \ + ((PIN) == PWR_WAKEUP_PIN7) || \ + ((PIN) == PWR_WAKEUP_PIN8)) +#else +#define PWR_WAKEUP_PIN1 ((uint32_t)0x00) +#define PWR_WAKEUP_PIN2 ((uint32_t)0x01) + +#define IS_PWR_WAKEUP_PIN(PIN) (((PIN) == PWR_WAKEUP_PIN1) || \ + ((PIN) == PWR_WAKEUP_PIN2)) +#endif /* defined (STM32F071xB) || defined (STM32F072xB) || defined (STM32F078xx) */ +/** + * @} + */ + +#if defined (STM32F031x6) || defined (STM32F042x6) || defined (STM32F051x8) || \ + defined (STM32F071xB) || defined (STM32F072xB) + +#define PWR_EXTI_LINE_PVD ((uint32_t)0x00010000) /*!< External interrupt line 16 Connected to the PVD EXTI Line */ + +/** @defgroup PWREx_PVD_detection_level + * @{ + */ +#define PWR_PVDLEVEL_0 PWR_CR_PLS_LEV0 +#define PWR_PVDLEVEL_1 PWR_CR_PLS_LEV1 +#define PWR_PVDLEVEL_2 PWR_CR_PLS_LEV2 +#define PWR_PVDLEVEL_3 PWR_CR_PLS_LEV3 +#define PWR_PVDLEVEL_4 PWR_CR_PLS_LEV4 +#define PWR_PVDLEVEL_5 PWR_CR_PLS_LEV5 +#define PWR_PVDLEVEL_6 PWR_CR_PLS_LEV6 +#define PWR_PVDLEVEL_7 PWR_CR_PLS_LEV7 +#define IS_PWR_PVD_LEVEL(LEVEL) (((LEVEL) == PWR_PVDLEVEL_0) || ((LEVEL) == PWR_PVDLEVEL_1)|| \ + ((LEVEL) == PWR_PVDLEVEL_2) || ((LEVEL) == PWR_PVDLEVEL_3)|| \ + ((LEVEL) == PWR_PVDLEVEL_4) || ((LEVEL) == PWR_PVDLEVEL_5)|| \ + ((LEVEL) == PWR_PVDLEVEL_6) || ((LEVEL) == PWR_PVDLEVEL_7)) +/** + * @} + */ + +/** @defgroup PWREx_PVD_Mode + * @{ + */ +#define PWR_MODE_EVT ((uint32_t)0x00000000) /*!< No Interrupt */ +#define PWR_MODE_IT_RISING ((uint32_t)0x00000001) /*!< External Interrupt Mode with Rising edge trigger detection */ +#define PWR_MODE_IT_FALLING ((uint32_t)0x00000002) /*!< External Interrupt Mode with Falling edge trigger detection */ +#define PWR_MODE_IT_RISING_FALLING ((uint32_t)0x00000003) /*!< External Interrupt Mode with Rising/Falling edge trigger detection */ +#define IS_PWR_PVD_MODE(MODE) (((MODE) == PWR_MODE_EVT) || ((MODE) == PWR_MODE_IT_RISING)|| \ + ((MODE) == PWR_MODE_IT_FALLING) || ((MODE) == PWR_MODE_IT_RISING_FALLING)) +/** + * @} + */ +#endif /* defined (STM32F031x6) || defined (STM32F042x6) || defined (STM32F051x8) || */ + /* defined (STM32F071xB) || defined (STM32F072xB) */ + +/** @defgroup PWREx_Flag + * @{ + */ +#if defined (STM32F031x6) || defined (STM32F042x6) || defined (STM32F051x8) || \ + defined (STM32F071xB) || defined (STM32F072xB) + +#define PWR_FLAG_WU PWR_CSR_WUF +#define PWR_FLAG_SB PWR_CSR_SBF +#define PWR_FLAG_PVDO PWR_CSR_PVDO +#define PWR_FLAG_VREFINTRDY PWR_CSR_VREFINTRDYF +#define IS_PWR_GET_FLAG(FLAG) (((FLAG) == PWR_FLAG_WU) || ((FLAG) == PWR_FLAG_SB) || \ + ((FLAG) == PWR_FLAG_PVDO) || ((FLAG) == PWR_FLAG_VREFINTRDY)) +#else +#define PWR_FLAG_WU PWR_CSR_WUF +#define PWR_FLAG_SB PWR_CSR_SBF +#define IS_PWR_GET_FLAG(FLAG) (((FLAG) == PWR_FLAG_WU) || ((FLAG) == PWR_FLAG_SB)) + +#endif /* defined (STM32F031x6) || defined (STM32F042x6) || defined (STM32F051x8) || */ + /* defined (STM32F071xB) || defined (STM32F072xB) */ +/** + * @} + */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ +/** @defgroup PWREx_Exported_Macros + * @{ + */ +#if defined (STM32F031x6) || defined (STM32F042x6) || defined (STM32F051x8) || \ + defined (STM32F071xB) || defined (STM32F072xB) +/** + * @brief Enable the PVD Exti Line. + * @param __EXTILINE__: specifies the PVD EXTI sources to be enabled. + * This parameter can be: + * @arg PWR_EXTI_LINE_PVD + * @retval None. + */ +#define __HAL_PVD_EXTI_ENABLE_IT(__EXTILINE__) (EXTI->IMR |= (__EXTILINE__)) + +/** + * @brief Disable the PVD EXTI Line. + * @param __EXTILINE__: specifies the PVD EXTI sources to be disabled. + * This parameter can be: + * @arg PWR_EXTI_LINE_PVD + * @retval None. + */ +#define __HAL_PVD_EXTI_DISABLE_IT(__EXTILINE__) (EXTI->IMR &= ~(__EXTILINE__)) + +/** + * @brief Generate a Software interrupt on selected EXTI line. + * @param __EXTILINE__: specifies the PVD EXTI sources to be disabled. + * This parameter can be: + * @arg PWR_EXTI_LINE_PVD + * @retval None + */ +#define __HAL_PVD_EXTI_GENERATE_SWIT(__EXTILINE__) (EXTI->SWIER |= (__EXTILINE__)) + +/** + * @brief Check whether the specified PVD EXTI interrupt flag is set or not. + * @param __EXTILINE__: specifies the PVD EXTI sources to be cleared. + * This parameter can be: + * @arg PWR_EXTI_LINE_PVD + * @retval EXTI PVD Line Status. + */ +#define __HAL_PVD_EXTI_GET_FLAG(__EXTILINE__) (EXTI->PR & (__EXTILINE__)) + +/** + * @brief Clear the PVD EXTI flag. + * @param __EXTILINE__: specifies the PVD EXTI sources to be cleared. + * This parameter can be: + * @arg PWR_EXTI_LINE_PVD + * @retval None. + */ +#define __HAL_PVD_EXTI_CLEAR_FLAG(__EXTILINE__) (EXTI->PR = (__EXTILINE__)) + +#endif /* defined (STM32F031x6) || defined (STM32F042x6) || defined (STM32F051x8) || */ + /* defined (STM32F071xB) || defined (STM32F072xB) */ +/** + * @} + */ + + +/* Exported functions --------------------------------------------------------*/ +/* I/O operation functions ***************************************************/ + +#if defined (STM32F031x6) || defined (STM32F042x6) || defined (STM32F051x8) || \ + defined (STM32F071xB) || defined (STM32F072xB) + +void HAL_PWR_PVD_IRQHandler(void); +void HAL_PWR_PVDCallback(void); + +/* Peripheral Control functions **********************************************/ +void HAL_PWR_PVDConfig(PWR_PVDTypeDef *sConfigPVD); +void HAL_PWR_EnablePVD(void); +void HAL_PWR_DisablePVD(void); + +#endif /* defined (STM32F031x6) || defined (STM32F042x6) || defined (STM32F051x8) || */ + /* defined (STM32F071xB) || defined (STM32F072xB) */ + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __STM32F0xx_HAL_PWR_EX_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_rcc.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_rcc.c new file mode 100644 index 0000000000..b03d242496 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_rcc.c @@ -0,0 +1,601 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_rcc.c + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief RCC HAL module driver. + * + * This file provides firmware functions to manage the following + * functionalities of the Reset and Clock Control (RCC) peripheral: + * + Initialization/de-initialization function + * + Peripheral Control function + * + @verbatim + ============================================================================== + ##### RCC specific features ##### + ============================================================================== + [..] + After reset the device is running from Internal High Speed oscillator + (HSI 8MHz) with Flash 0 wait state, Flash prefetch buffer is disabled, + and all peripherals are off except internal SRAM, Flash and JTAG. + (+) There is no prescaler on High speed (AHB) and Low speed (APB) busses; + all peripherals mapped on these busses are running at HSI speed. + (+) The clock for all peripherals is switched off, except the SRAM and FLASH. + (+) All GPIOs are in input floating state, except the JTAG pins which + are assigned to be used for debug purpose. + + [..] + Once the device started from reset, the user application has to: + (+) Configure the clock source to be used to drive the System clock + (if the application needs higher frequency/performance) + (+) Configure the System clock frequency and Flash settings + (+) Configure the AHB and APB busses prescalers + (+) Enable the clock for the peripheral(s) to be used + (+) Configure the clock source(s) for peripherals which clocks are not + derived from the System clock (RTC, ADC, I2C, USART, TIM, USB FS, etc..) + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @defgroup RCC + * @brief RCC HAL module driver + * @{ + */ + +#ifdef HAL_RCC_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +#define RCC_CFGR_HPRE_BITNUMBER 4 +#define RCC_CFGR_PPRE_BITNUMBER 8 + +/* Private macro -------------------------------------------------------------*/ +#define __MCO_CLK_ENABLE() __GPIOA_CLK_ENABLE() +#define MCO_GPIO_PORT GPIOA +#define MCO_PIN GPIO_PIN_8 + +/* Private variables ---------------------------------------------------------*/ +const uint8_t APBAHBPrescTable[16] = {0, 0, 0, 0, 1, 2, 3, 4, 1, 2, 3, 4, 6, 7, 8, 9}; + +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup RCC_Private_Functions + * @{ + */ + +/** @defgroup HAL_RCC_Group1 Initialization/de-initialization function + * @brief Initialization and Configuration functions + * +@verbatim + =============================================================================== + ##### Initialization and de-initialization function ##### + =============================================================================== + [..] + This section provide functions allowing to configure the internal/external oscillators + (HSE, HSI, HSI14, HSI48, LSE, LSI, PLL, CSS and MCO) and the System busses clocks (SYSCLK, + AHB and APB1). + + [..] Internal/external clock and PLL configuration + (#) HSI (high-speed internal), 8 MHz factory-trimmed RC used directly or through + the PLL as System clock source. + The HSI clock can be used also to clock the USART and I2C peripherals. + + (#) HSI14 (high-speed internal), 14 MHz factory-trimmed RC used directly to clock + the ADC peripheral. + + (#) LSI (low-speed internal), 40 KHz low consumption RC used as IWDG and/or RTC + clock source. + + (#) HSE (high-speed external), 4 to 32 MHz crystal oscillator used directly or + through the PLL as System clock source. Can be used also as RTC clock source. + + (#) LSE (low-speed external), 32 KHz oscillator used as RTC clock source. + + (#) PLL (clocked by HSI, HSI48 or HSE), featuring different output clocks: + (+@) The first output is used to generate the high speed system clock (up to 48 MHz) + (+@) The second output is used to generate the clock for the USB FS (48 MHz) + (+@) The third output may be used to generate the clock for the TIM, I2C and USART + peripherals (up to 48 MHz) + + (#) CSS (Clock security system), once enable using the macro __HAL_RCC_CSS_ENABLE() + and if a HSE clock failure occurs(HSE used directly or through PLL as System + clock source), the System clockis automatically switched to HSI and an interrupt + is generated if enabled. The interrupt is linked to the Cortex-M0 NMI + (Non-Maskable Interrupt) exception vector. + + (#) MCO (microcontroller clock output), used to output SYSCLK, HSI, HSE, LSI, LSE or PLL + clock (divided by 2) output on pin (such as PA8 pin). + + [..] System, AHB and APB busses clocks configuration + (#) Several clock sources can be used to drive the System clock (SYSCLK): HSI, + HSE and PLL. + The AHB clock (HCLK) is derived from System clock through configurable + prescaler and used to clock the CPU, memory and peripherals mapped + on AHB bus (DMA, GPIO...). APB1 (PCLK1) clock is derived + from AHB clock through configurable prescalers and used to clock + the peripherals mapped on these busses. You can use + "HAL_RCC_GetSysClockFreq()" function to retrieve the frequencies of these clocks. + + (#) All the peripheral clocks are derived from the System clock (SYSCLK) except: + (+@) The FLASH program/erase clock which is always HSI 8MHz clock. + (+@) The USB 48 MHz clock which is derived from the PLL VCO clock. + (+@) The USART clock which can be derived as well from HSI 8MHz, LSI or LSE. + (+@) The I2C clock which can be derived as well from HSI 8MHz clock. + (+@) The ADC clock which is derived from PLL output. + (+@) The RTC clock which is derived from the LSE, LSI or 1 MHz HSE_RTC + (HSE divided by a programmable prescaler). The System clock (SYSCLK) + frequency must be higher or equal to the RTC clock frequency. + (+@) IWDG clock which is always the LSI clock. + + (#) For the STM32F0xx devices, the maximum frequency of the SYSCLK, HCLK and PCLK1 is 48 MHz, + Depending on the SYSCLK frequency, the flash latency should be adapted accordingly: + +-----------------------------------------------+ + | Latency | SYSCLK clock frequency (MHz) | + |---------------|-------------------------------| + |0WS(1CPU cycle)| 0 < SYSCLK <= 24 | + |---------------|-------------------------------| + |1WS(2CPU cycle)| 24 < SYSCLK <= 48 | + +-----------------------------------------------+ + + (#) After reset, the System clock source is the HSI (8 MHz) with 0 WS and + prefetch is disabled. + +@endverbatim + * @{ + */ + +/** + * @brief Resets the RCC clock configuration to the default reset state. + * @note The default reset state of the clock configuration is given below: + * - HSI ON and used as system clock source + * - HSE and PLL OFF + * - AHB, APB1 prescaler set to 1. + * - CSS, MCO OFF + * - All interrupts disabled + * @note This function doesn't modify the configuration of the + * - Peripheral clocks + * - LSI, LSE and RTC clocks + * @param None + * @retval None + */ +void HAL_RCC_DeInit(void) +{ + /* Set HSION bit, HSITRIM[4:0] bits to the reset value*/ + SET_BIT(RCC->CR, RCC_CR_HSION | RCC_CR_HSITRIM_4); + + /* Reset SW[1:0], HPRE[3:0], PPRE[2:0] and MCOSEL[2:0] bits */ + CLEAR_BIT(RCC->CFGR, RCC_CFGR_SW | RCC_CFGR_HPRE | RCC_CFGR_PPRE | RCC_CFGR_MCO); + + /* Reset HSEON, CSSON, PLLON bits */ + CLEAR_BIT(RCC->CR, RCC_CR_PLLON | RCC_CR_CSSON | RCC_CR_HSEON); + + /* Reset HSEBYP bit */ + CLEAR_BIT(RCC->CR, RCC_CR_HSEBYP); + + /* Reset CFGR register */ + CLEAR_REG(RCC->CFGR); + + /* Reset CFGR2 register */ + CLEAR_REG(RCC->CFGR2); + + /* Reset CFGR3 register */ + CLEAR_REG(RCC->CFGR3); + + /* Disable all interrupts */ + CLEAR_REG(RCC->CIR); +} + +/** + * @brief Initializes the RCC Oscillators according to the specified parameters in the + * RCC_OscInitTypeDef. + * @param RCC_OscInitStruct: pointer to an RCC_OscInitTypeDef structure that + * contains the configuration information for the RCC Oscillators. + * @note The PLL is not disabled when used as system clock. + * @retval HAL status + */ +__weak HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct) +{ + /* Note : This function is defined into this file for library reference. */ + /* Function content is located into file stm32f0xx_hal_rcc_ex.c to */ + /* handle the possible oscillators present in STM32F0xx devices */ + + /* Return error status as not implemented here */ + return HAL_ERROR; +} + +/** + * @brief Initializes the CPU, AHB and APB busses clocks according to the specified + * parameters in the RCC_ClkInitStruct. + * @param RCC_ClkInitStruct: pointer to an RCC_OscInitTypeDef structure that + * contains the configuration information for the RCC peripheral. + * @param FLatency: FLASH Latency + * This parameter can be one of the following values: + * @arg FLASH_LATENCY_0: FLASH 0 Latency cycle + * @arg FLASH_LATENCY_1: FLASH 1 Latency cycle + * + * @note The SystemCoreClock CMSIS variable is used to store System Clock Frequency + * and updated by HAL_RCC_GetHCLKFreq() function called within this function + * + * @note The HSI is used (enabled by hardware) as system clock source after + * startup from Reset, wake-up from STOP and STANDBY mode, or in case + * of failure of the HSE used directly or indirectly as system clock + * (if the Clock Security System CSS is enabled). + * + * @note A switch from one clock source to another occurs only if the target + * clock source is ready (clock stable after startup delay or PLL locked). + * If a clock source which is not yet ready is selected, the switch will + * occur when the clock source will be ready. + * @retval HAL status + */ +__weak HAL_StatusTypeDef HAL_RCC_ClockConfig(RCC_ClkInitTypeDef *RCC_ClkInitStruct, uint32_t FLatency) +{ + /* Note : This function is defined into this file for library reference. */ + /* Function content is located into file stm32f0xx_hal_rcc_ex.c to */ + /* handle the possible oscillators present in STM32F0xx devices */ + + /* Return error status as not implemented here */ + return HAL_ERROR; +} + +/** + * @} + */ + +/** @defgroup HAL_RCC_Group2 Peripheral Control function + * @brief RCC clocks control functions + * +@verbatim + =============================================================================== + ##### Peripheral Control function ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to control the RCC Clocks + frequencies. + +@endverbatim + * @{ + */ + +/** + * @brief Selects the clock source to output on MCO pin(such as PA8). + * @note MCO pin (such as PA8) should be configured in alternate function mode. + * @param RCC_MCOx: specifies the output direction for the clock source. + * This parameter can be one of the following values: + * @arg RCC_MCO: Clock source to output on MCO pin(such as PA8). + * @param RCC_MCOSource: specifies the clock source to output. + * This parameter can be one of the following values: + * @arg RCC_MCOSOURCE_LSI: LSI clock selected as MCO source + * @arg RCC_MCOSOURCE_HSI: HSI clock selected as MCO source + * @arg RCC_MCOSOURCE_LSE: LSE clock selected as MCO source + * @arg RCC_MCOSOURCE_HSE: HSE clock selected as MCO source + * @arg RCC_MCOSOURCE_PLLCLK_NODIV: main PLL clock not divided selected as MCO source (not applicable to STM32F05x devices) + * @arg RCC_MCOSOURCE_PLLCLK_DIV2: main PLL clock divided by 2 selected as MCO source + * @arg RCC_MCOSOURCE_SYSCLK: System clock (SYSCLK) selected as MCO source + * @param RCC_MCODiv: specifies the MCOx prescaler. + * This parameter can be one of the following values: + * @arg RCC_MCO_NODIV: no division applied to MCO clock + * @retval None + */ +void HAL_RCC_MCOConfig(uint32_t RCC_MCOx, uint32_t RCC_MCOSource, uint32_t RCC_MCODiv) +{ + GPIO_InitTypeDef gpio; + /* Check the parameters */ + assert_param(IS_RCC_MCO(RCC_MCOx)); + assert_param(IS_RCC_MCODIV(RCC_MCODiv)); + /* RCC_MCO */ + assert_param(IS_RCC_MCOSOURCE(RCC_MCOSource)); + + /* MCO Clock Enable */ + __MCO_CLK_ENABLE(); + + /* Configue the MCO pin in alternate function mode */ + gpio.Pin = MCO_PIN; + gpio.Mode = GPIO_MODE_AF_PP; + gpio.Speed = GPIO_SPEED_HIGH; + gpio.Pull = GPIO_NOPULL; + gpio.Alternate = GPIO_AF0_MCO; + HAL_GPIO_Init(MCO_GPIO_PORT, &gpio); + + /* Configure the MCO clock source */ + __HAL_RCC_MCO_CONFIG(RCC_MCOSource, RCC_MCODiv); +} + +/** + * @brief Enables the Clock Security System. + * @note If a failure is detected on the HSE oscillator clock, this oscillator + * is automatically disabled and an interrupt is generated to inform the + * software about the failure (Clock Security System Interrupt, CSSI), + * allowing the MCU to perform rescue operations. The CSSI is linked to + * the Cortex-M4 NMI (Non-Maskable Interrupt) exception vector. + * @param None + * @retval None + */ +void HAL_RCC_EnableCSS(void) +{ + SET_BIT(RCC->CR, RCC_CR_CSSON); +} + +/** + * @brief Disables the Clock Security System. + * @param None + * @retval None + */ +void HAL_RCC_DisableCSS(void) +{ + CLEAR_BIT(RCC->CR, RCC_CR_CSSON); +} + +/** + * @brief Returns the SYSCLK frequency + * @note The system frequency computed by this function is not the real + * frequency in the chip. It is calculated based on the predefined + * constant and the selected clock source: + * @note If SYSCLK source is HSI, function returns a value based on HSI_VALUE(*) + * @note If SYSCLK source is HSI48, function returns a value based on HSI48_VALUE(*) + * @note If SYSCLK source is HSE, function returns a value based on HSE_VALUE + * divided by PREDIV factor(**) + * @note If SYSCLK source is PLL, function returns a value based on HSE_VALUE + * divided by PREDIV factor(**) or depending on STM32F0xx devices either a value based + * on HSI_VALUE divided by 2 or HSI_VALUE divided by PREDIV factor(*) multiplied by the + * PLL factor . + * @note (*) HSI_VALUE & HSI48_VALUE are constants defined in stm32f0xx_hal_conf.h file + * (default values 8 MHz and 48MHz). + * @note (**) HSE_VALUE is a constant defined in stm32f0xx_hal_conf.h file (default value + * 8 MHz), user has to ensure that HSE_VALUE is same as the real + * frequency of the crystal used. Otherwise, this function may + * have wrong result. + * + * @note The result of this function could be not correct when using fractional + * value for HSE crystal. + * + * @note This function can be used by the user application to compute the + * baudrate for the communication peripherals or configure other parameters. + * + * @note Each time SYSCLK changes, this function must be called to update the + * right SYSCLK value. Otherwise, any configuration based on this function will be incorrect. + * + * @param None + * @retval SYSCLK frequency + */ +__weak uint32_t HAL_RCC_GetSysClockFreq(void) +{ + /* Note : This function is defined into this file for library reference. */ + /* Function content is located into file stm32f0xx_hal_rcc_ex.c to */ + /* handle the possible oscillators present in STM32F0xx devices */ + + /* Return current SYSCLK frequency without computation */ + return SystemCoreClock; +} + +/** + * @brief Returns the HCLK frequency + * @note Each time HCLK changes, this function must be called to update the + * right HCLK value. Otherwise, any configuration based on this function will be incorrect. + * + * @note The SystemCoreClock CMSIS variable is used to store System Clock Frequency + * and updated within this function + * + * @param None + * @retval HCLK frequency + */ +uint32_t HAL_RCC_GetHCLKFreq(void) +{ + SystemCoreClock = HAL_RCC_GetSysClockFreq() >> APBAHBPrescTable[(RCC->CFGR & RCC_CFGR_HPRE)>> RCC_CFGR_HPRE_BITNUMBER]; + return SystemCoreClock; +} + +/** + * @brief Returns the PCLK1 frequency + * @note Each time PCLK1 changes, this function must be called to update the + * right PCLK1 value. Otherwise, any configuration based on this function will be incorrect. + * @param None + * @retval PCLK1 frequency + */ +uint32_t HAL_RCC_GetPCLK1Freq(void) +{ + /* Get HCLK source and Compute PCLK1 frequency ---------------------------*/ + return (HAL_RCC_GetHCLKFreq() >> APBAHBPrescTable[(RCC->CFGR & RCC_CFGR_PPRE)>> RCC_CFGR_PPRE_BITNUMBER]); +} + +/** + * @brief Configures the RCC_OscInitStruct according to the internal + * RCC configuration registers. + * @param RCC_OscInitStruct: pointer to an RCC_OscInitTypeDef structure that + * will be configured. + * @retval None + */ +void HAL_RCC_GetOscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct) +{ + /* Set all possible values for the Oscillator type parameter ---------------*/ + RCC_OscInitStruct->OscillatorType = RCC_OSCILLATORTYPE_HSE | RCC_OSCILLATORTYPE_HSI | RCC_OSCILLATORTYPE_LSE | RCC_OSCILLATORTYPE_LSI; + + /* Get the HSE configuration -----------------------------------------------*/ + if((RCC->CR & RCC_CR_HSEBYP) == RCC_CR_HSEBYP) + { + RCC_OscInitStruct->HSEState = RCC_HSE_BYPASS; + } + else if((RCC->CR & RCC_CR_HSEON) == RCC_CR_HSEON) + { + RCC_OscInitStruct->HSEState = RCC_HSE_ON; + } + else + { + RCC_OscInitStruct->HSEState = RCC_HSE_OFF; + } + + /* Get the HSI configuration -----------------------------------------------*/ + if((RCC->CR & RCC_CR_HSION) == RCC_CR_HSION) + { + RCC_OscInitStruct->HSIState = RCC_HSI_ON; + } + else + { + RCC_OscInitStruct->HSIState = RCC_HSI_OFF; + } + + RCC_OscInitStruct->HSICalibrationValue = (uint32_t)((RCC->CR &RCC_CR_HSITRIM) >> RCC_CR_HSITRIM_BitNumber); + + /* Get the LSE configuration -----------------------------------------------*/ + if((RCC->BDCR & RCC_BDCR_LSEBYP) == RCC_BDCR_LSEBYP) + { + RCC_OscInitStruct->LSEState = RCC_LSE_BYPASS; + } + else if((RCC->BDCR & RCC_BDCR_LSEON) == RCC_BDCR_LSEON) + { + RCC_OscInitStruct->LSEState = RCC_LSE_ON; + } + else + { + RCC_OscInitStruct->LSEState = RCC_LSE_OFF; + } + + /* Get the LSI configuration -----------------------------------------------*/ + if((RCC->CSR & RCC_CSR_LSION) == RCC_CSR_LSION) + { + RCC_OscInitStruct->LSIState = RCC_LSI_ON; + } + else + { + RCC_OscInitStruct->LSIState = RCC_LSI_OFF; + } + + /* Get the PLL configuration -----------------------------------------------*/ + if((RCC->CR & RCC_CR_PLLON) == RCC_CR_PLLON) + { + RCC_OscInitStruct->PLL.PLLState = RCC_PLL_ON; + } + else + { + RCC_OscInitStruct->PLL.PLLState = RCC_PLL_OFF; + } + RCC_OscInitStruct->PLL.PLLSource = (uint32_t)(RCC->CFGR & RCC_CFGR_PLLSRC); + RCC_OscInitStruct->PLL.PLLMUL = (uint32_t)(RCC->CFGR & RCC_CFGR_PLLMUL); + RCC_OscInitStruct->PLL.PREDIV = (uint32_t)(RCC->CFGR2 & RCC_CFGR2_PREDIV); + + /* Get the HSI14 configuration -----------------------------------------------*/ + if((RCC->CR2 & RCC_CR2_HSI14ON) == RCC_CR2_HSI14ON) + { + RCC_OscInitStruct->HSI14State = RCC_HSI_ON; + } + else + { + RCC_OscInitStruct->HSI14State = RCC_HSI_OFF; + } + + RCC_OscInitStruct->HSI14CalibrationValue = (uint32_t)((RCC->CR2 & RCC_CR2_HSI14TRIM) >> RCC_CR2_HSI14TRIM_BitNumber); + + /* Get the HSI48 configuration if any-----------------------------------------*/ + RCC_OscInitStruct->HSI48State = __HAL_RCC_GET_HSI48_STATE(); +} + +/** + * @brief Get the RCC_ClkInitStruct according to the internal + * RCC configuration registers. + * @param RCC_ClkInitStruct: pointer to an RCC_ClkInitTypeDef structure that + * contains the current clock configuration. + * @param pFLatency: Pointer on the Flash Latency. + * @retval None + */ +void HAL_RCC_GetClockConfig(RCC_ClkInitTypeDef *RCC_ClkInitStruct, uint32_t *pFLatency) +{ + /* Set all possible values for the Clock type parameter --------------------*/ + RCC_ClkInitStruct->ClockType = RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_PCLK1; + + /* Get the SYSCLK configuration --------------------------------------------*/ + RCC_ClkInitStruct->SYSCLKSource = (uint32_t)(RCC->CFGR & RCC_CFGR_SW); + + /* Get the HCLK configuration ----------------------------------------------*/ + RCC_ClkInitStruct->AHBCLKDivider = (uint32_t)(RCC->CFGR & RCC_CFGR_HPRE); + + /* Get the APB1 configuration ----------------------------------------------*/ + RCC_ClkInitStruct->APB1CLKDivider = (uint32_t)(RCC->CFGR & RCC_CFGR_PPRE); + + /* Get the Flash Wait State (Latency) configuration ------------------------*/ + *pFLatency = (uint32_t)(FLASH->ACR & FLASH_ACR_LATENCY); +} + +/** + * @brief This function handles the RCC CSS interrupt request. + * @note This API should be called under the NMI_Handler(). + * @param None + * @retval None + */ +void HAL_RCC_NMI_IRQHandler(void) +{ + /* Check RCC CSSF flag */ + if(__HAL_RCC_GET_IT(RCC_IT_CSS)) + { + /* RCC Clock Security System interrupt user callback */ + HAL_RCC_CCSCallback(); + + /* Clear RCC CSS pending bit */ + __HAL_RCC_CLEAR_IT(RCC_IT_CSS); + } +} + +/** + * @brief RCC Clock Security System interrupt callback + * @param none + * @retval none + */ +__weak void HAL_RCC_CCSCallback(void) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_RCC_CCSCallback could be implemented in the user file + */ +} + +/** + * @} + */ + +/** + * @} + */ + +#endif /* HAL_RCC_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_rcc.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_rcc.h new file mode 100644 index 0000000000..cd1584cb9e --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_rcc.h @@ -0,0 +1,1110 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_rcc.h + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief Header file of RCC HAL module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32F0xx_HAL_RCC_H +#define __STM32F0xx_HAL_RCC_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal_def.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @addtogroup RCC + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ + +/** + * @brief RCC PLL configuration structure definition + */ +typedef struct +{ + uint32_t PLLState; /*!< PLLState: The new state of the PLL. + This parameter can be a value of @ref RCC_PLL_Config */ + + uint32_t PLLSource; /*!< PLLSource: PLL entry clock source. + This parameter must be a value of @ref RCC_PLL_Clock_Source */ + + uint32_t PREDIV; /*!< PREDIV: Predivision factor for PLL VCO input clock + This parameter must be a value of @ref RCC_PLL_Prediv_Factor */ + + uint32_t PLLMUL; /*!< PLLMUL: Multiplication factor for PLL VCO input clock + This parameter must be a value of @ref RCC_PLL_Multiplication_Factor */ + +}RCC_PLLInitTypeDef; + +/** + * @brief RCC Internal/External Oscillator (HSE, HSI, LSE and LSI) configuration structure definition + */ +typedef struct +{ + uint32_t OscillatorType; /*!< The Oscillators to be configured. + This parameter can be a value of @ref RCC_Oscillator_Type */ + + uint32_t HSEState; /*!< The new state of the HSE. + This parameter can be a value of @ref RCC_HSE_Config */ + + uint32_t LSEState; /*!< The new state of the LSE. + This parameter can be a value of @ref RCC_LSE_Config */ + + uint32_t HSIState; /*!< The new state of the HSI. + This parameter can be a value of @ref RCC_HSI_Config */ + + uint32_t HSICalibrationValue; /*!< The HSI calibration trimming value (default is RCC_HSICALIBRATION_DEFAULT). + This parameter must be a number between Min_Data = 0x00 and Max_Data = 0x1F */ + + uint32_t HSI14State; /*!< The new state of the HSI14. + This parameter can be a value of @ref RCC_HSI14_Config */ + + uint32_t HSI14CalibrationValue; /*!< The HSI14 calibration trimming value (default is RCC_HSI14CALIBRATION_DEFAULT). + This parameter must be a number between Min_Data = 0x00 and Max_Data = 0x1F */ + + uint32_t HSI48State; /*!< The new state of the HSI48 (only applicable to STM32F07x and STM32F0x2 devices). + This parameter can be a value of @ref RCCEx_HSI48_Config */ + + uint32_t LSIState; /*!< The new state of the LSI. + This parameter can be a value of @ref RCC_LSI_Config */ + + RCC_PLLInitTypeDef PLL; /*!< PLL structure parameters */ + +}RCC_OscInitTypeDef; + +/** + * @brief RCC System, AHB and APB busses clock configuration structure definition + */ +typedef struct +{ + uint32_t ClockType; /*!< The clock to be configured. + This parameter can be a value of @ref RCC_System_Clock_Type */ + + uint32_t SYSCLKSource; /*!< The clock source (SYSCLKS) used as system clock. + This parameter can be a value of @ref RCC_System_Clock_Source */ + + uint32_t AHBCLKDivider; /*!< The AHB clock (HCLK) divider. This clock is derived from the system clock (SYSCLK). + This parameter can be a value of @ref RCC_AHB_Clock_Source */ + + uint32_t APB1CLKDivider; /*!< The APB1 clock (PCLK1) divider. This clock is derived from the AHB clock (HCLK). + This parameter can be a value of @ref RCC_APB1_Clock_Source */ + +}RCC_ClkInitTypeDef; + +/* Exported constants --------------------------------------------------------*/ +/** @defgroup RCC_Exported_Constants + * @{ + */ + +#define RCC_OFFSET (RCC_BASE - PERIPH_BASE) +/* --- CR Register ---*/ +#define RCC_CR_OFFSET (RCC_OFFSET + 0x00) +/* --- CFGR Register ---*/ +#define RCC_CFGR_OFFSET (RCC_OFFSET + 0x04) +/* --- CIR Register ---*/ +#define RCC_CIR_OFFSET (RCC_OFFSET + 0x08) +/* --- BDCR Register ---*/ +#define RCC_BDCR_OFFSET (RCC_OFFSET + 0x20) +/* --- CSR Register ---*/ +#define RCC_CSR_OFFSET (RCC_OFFSET + 0x24) +/* --- CR2 Register ---*/ +#define RCC_CR2_OFFSET (RCC_OFFSET + 0x34) + +/* CR register byte 2 (Bits[23:16]) base address */ +#define RCC_CR_BYTE2_ADDRESS (PERIPH_BASE + RCC_CR_OFFSET + 0x02) + +/* CIR register byte 1 (Bits[15:8]) base address */ +#define RCC_CIR_BYTE1_ADDRESS (PERIPH_BASE + RCC_CIR_OFFSET + 0x01) + +/* CIR register byte 2 (Bits[23:16]) base address */ +#define RCC_CIR_BYTE2_ADDRESS (PERIPH_BASE + RCC_CIR_OFFSET + 0x02) + +/* CSR register byte 1 (Bits[15:8]) base address */ +#define RCC_CSR_BYTE1_ADDRESS (PERIPH_BASE + RCC_CSR_OFFSET + 0x01) + +/* BDCR register byte 0 (Bits[7:0] base address */ +#define RCC_BDCR_BYTE0_ADDRESS (PERIPH_BASE + RCC_BDCR_OFFSET) + +/* LSE state change timeout */ +#define LSE_TIMEOUT_VALUE ((uint32_t)5000) /* 5 s */ + +/* Disable Backup domain write protection state change timeout */ +#define DBP_TIMEOUT_VALUE ((uint32_t)100) /* 100 ms */ + +#define RCC_CFGR_PLLMUL_BITNUMBER 18 +#define RCC_CFGR2_PREDIV_BITNUMBER 0 + +/** @defgroup RCC_Oscillator_Type + * @{ + */ +#define RCC_OSCILLATORTYPE_NONE ((uint32_t)0x00000000) +#define RCC_OSCILLATORTYPE_HSE ((uint32_t)0x00000001) +#define RCC_OSCILLATORTYPE_HSI ((uint32_t)0x00000002) +#define RCC_OSCILLATORTYPE_LSE ((uint32_t)0x00000004) +#define RCC_OSCILLATORTYPE_LSI ((uint32_t)0x00000008) +#define RCC_OSCILLATORTYPE_HSI14 ((uint32_t)0x00000010) +#define RCC_OSCILLATORTYPE_HSI48 ((uint32_t)0x00000020) + +#define IS_RCC_OSCILLATORTYPE(OSCILLATOR) (((OSCILLATOR) == RCC_OSCILLATORTYPE_NONE) || \ + (((OSCILLATOR) & RCC_OSCILLATORTYPE_HSE) == RCC_OSCILLATORTYPE_HSE) || \ + (((OSCILLATOR) & RCC_OSCILLATORTYPE_HSI) == RCC_OSCILLATORTYPE_HSI) || \ + (((OSCILLATOR) & RCC_OSCILLATORTYPE_LSI) == RCC_OSCILLATORTYPE_LSI) || \ + (((OSCILLATOR) & RCC_OSCILLATORTYPE_LSE) == RCC_OSCILLATORTYPE_LSE) || \ + (((OSCILLATOR) & RCC_OSCILLATORTYPE_HSI14) == RCC_OSCILLATORTYPE_HSI14) || \ + (((OSCILLATOR) & RCC_OSCILLATORTYPE_HSI48) == RCC_OSCILLATORTYPE_HSI48)) +/** + * @} + */ + +/** @defgroup RCC_HSE_Config + * @{ + */ +#define RCC_HSE_OFF ((uint8_t)0x00) +#define RCC_HSE_ON ((uint8_t)0x01) +#define RCC_HSE_BYPASS ((uint8_t)0x05) + +#define IS_RCC_HSE(HSE) (((HSE) == RCC_HSE_OFF) || ((HSE) == RCC_HSE_ON) || \ + ((HSE) == RCC_HSE_BYPASS)) +/** + * @} + */ + +/** @defgroup RCC_LSE_Config + * @{ + */ +#define RCC_LSE_OFF ((uint8_t)0x00) +#define RCC_LSE_ON ((uint8_t)0x01) +#define RCC_LSE_BYPASS ((uint8_t)0x05) + +#define IS_RCC_LSE(LSE) (((LSE) == RCC_LSE_OFF) || ((LSE) == RCC_LSE_ON) || \ + ((LSE) == RCC_LSE_BYPASS)) +/** + * @} + */ + +/** @defgroup RCC_HSI_Config + * @{ + */ +#define RCC_HSI_OFF ((uint8_t)0x00) +#define RCC_HSI_ON ((uint8_t)0x01) + +#define IS_RCC_HSI(HSI) (((HSI) == RCC_HSI_OFF) || ((HSI) == RCC_HSI_ON)) + +#define RCC_HSICALIBRATION_DEFAULT ((uint32_t)0x10) /* Default HSI calibration trimming value */ +/** + * @} + */ + +/** @defgroup RCC_HSI14_Config + * @{ + */ +#define RCC_HSI14_OFF ((uint32_t)0x00) +#define RCC_HSI14_ON RCC_CR2_HSI14ON +#define RCC_HSI14_ADC_CONTROL (~RCC_CR2_HSI14DIS) + +#define IS_RCC_HSI14(HSI14) (((HSI14) == RCC_HSI14_OFF) || ((HSI14) == RCC_HSI14_ON) || ((HSI14) == RCC_HSI14_ADC_CONTROL)) + +#define RCC_HSI14CALIBRATION_DEFAULT ((uint32_t)0x10) /* Default HSI14 calibration trimming value */ +/** + * @} + */ + +/** @defgroup RCC_LSI_Config + * @{ + */ +#define RCC_LSI_OFF ((uint8_t)0x00) +#define RCC_LSI_ON ((uint8_t)0x01) + +#define IS_RCC_LSI(LSI) (((LSI) == RCC_LSI_OFF) || ((LSI) == RCC_LSI_ON)) +/** + * @} + */ + +/** @defgroup RCC_PLL_Config + * @{ + */ +#define RCC_PLL_NONE ((uint8_t)0x00) +#define RCC_PLL_OFF ((uint8_t)0x01) +#define RCC_PLL_ON ((uint8_t)0x02) + +#define IS_RCC_PLL(PLL) (((PLL) == RCC_PLL_NONE) ||((PLL) == RCC_PLL_OFF) || ((PLL) == RCC_PLL_ON)) +/** + * @} + */ + +/** @defgroup RCC_PLL_Prediv_Factor + * @{ + */ +#define RCC_PREDIV_DIV1 RCC_CFGR2_PREDIV_DIV1 +#define RCC_PREDIV_DIV2 RCC_CFGR2_PREDIV_DIV2 +#define RCC_PREDIV_DIV3 RCC_CFGR2_PREDIV_DIV3 +#define RCC_PREDIV_DIV4 RCC_CFGR2_PREDIV_DIV4 +#define RCC_PREDIV_DIV5 RCC_CFGR2_PREDIV_DIV5 +#define RCC_PREDIV_DIV6 RCC_CFGR2_PREDIV_DIV6 +#define RCC_PREDIV_DIV7 RCC_CFGR2_PREDIV_DIV7 +#define RCC_PREDIV_DIV8 RCC_CFGR2_PREDIV_DIV8 +#define RCC_PREDIV_DIV9 RCC_CFGR2_PREDIV_DIV9 +#define RCC_PREDIV_DIV10 RCC_CFGR2_PREDIV_DIV10 +#define RCC_PREDIV_DIV11 RCC_CFGR2_PREDIV_DIV11 +#define RCC_PREDIV_DIV12 RCC_CFGR2_PREDIV_DIV12 +#define RCC_PREDIV_DIV13 RCC_CFGR2_PREDIV_DIV13 +#define RCC_PREDIV_DIV14 RCC_CFGR2_PREDIV_DIV14 +#define RCC_PREDIV_DIV15 RCC_CFGR2_PREDIV_DIV15 +#define RCC_PREDIV_DIV16 RCC_CFGR2_PREDIV_DIV16 + +#define IS_RCC_PREDIV(PREDIV) (((PREDIV) == RCC_PREDIV_DIV1) || ((PREDIV) == RCC_PREDIV_DIV2) || \ + ((PREDIV) == RCC_PREDIV_DIV3) || ((PREDIV) == RCC_PREDIV_DIV4) || \ + ((PREDIV) == RCC_PREDIV_DIV5) || ((PREDIV) == RCC_PREDIV_DIV6) || \ + ((PREDIV) == RCC_PREDIV_DIV7) || ((PREDIV) == RCC_PREDIV_DIV8) || \ + ((PREDIV) == RCC_PREDIV_DIV9) || ((PREDIV) == RCC_PREDIV_DIV10) || \ + ((PREDIV) == RCC_PREDIV_DIV11) || ((PREDIV) == RCC_PREDIV_DIV12) || \ + ((PREDIV) == RCC_PREDIV_DIV13) || ((PREDIV) == RCC_PREDIV_DIV14) || \ + ((PREDIV) == RCC_PREDIV_DIV15) || ((PREDIV) == RCC_PREDIV_DIV16)) +/** + * @} + */ + +/** @defgroup RCC_PLL_Multiplication_Factor + * @{ + */ +#define RCC_PLL_MUL2 RCC_CFGR_PLLMUL2 +#define RCC_PLL_MUL3 RCC_CFGR_PLLMUL3 +#define RCC_PLL_MUL4 RCC_CFGR_PLLMUL4 +#define RCC_PLL_MUL5 RCC_CFGR_PLLMUL5 +#define RCC_PLL_MUL6 RCC_CFGR_PLLMUL6 +#define RCC_PLL_MUL7 RCC_CFGR_PLLMUL7 +#define RCC_PLL_MUL8 RCC_CFGR_PLLMUL8 +#define RCC_PLL_MUL9 RCC_CFGR_PLLMUL9 +#define RCC_PLL_MUL10 RCC_CFGR_PLLMUL10 +#define RCC_PLL_MUL11 RCC_CFGR_PLLMUL11 +#define RCC_PLL_MUL12 RCC_CFGR_PLLMUL12 +#define RCC_PLL_MUL13 RCC_CFGR_PLLMUL13 +#define RCC_PLL_MUL14 RCC_CFGR_PLLMUL14 +#define RCC_PLL_MUL15 RCC_CFGR_PLLMUL15 +#define RCC_PLL_MUL16 RCC_CFGR_PLLMUL16 + +#define IS_RCC_PLL_MUL(MUL) (((MUL) == RCC_PLL_MUL2) || ((MUL) == RCC_PLL_MUL3) || \ + ((MUL) == RCC_PLL_MUL4) || ((MUL) == RCC_PLL_MUL5) || \ + ((MUL) == RCC_PLL_MUL6) || ((MUL) == RCC_PLL_MUL7) || \ + ((MUL) == RCC_PLL_MUL8) || ((MUL) == RCC_PLL_MUL9) || \ + ((MUL) == RCC_PLL_MUL10) || ((MUL) == RCC_PLL_MUL11) || \ + ((MUL) == RCC_PLL_MUL12) || ((MUL) == RCC_PLL_MUL13) || \ + ((MUL) == RCC_PLL_MUL14) || ((MUL) == RCC_PLL_MUL15) || \ + ((MUL) == RCC_PLL_MUL16)) +/** + * @} + */ + +/** @defgroup RCC_PLL_Clock_Source + * @{ + */ +#define RCC_PLLSOURCE_HSE RCC_CFGR_PLLSRC_HSE_PREDIV +/** + * @} + */ + +/** @defgroup RCC_System_Clock_Type + * @{ + */ +#define RCC_CLOCKTYPE_SYSCLK ((uint32_t)0x00000001) +#define RCC_CLOCKTYPE_HCLK ((uint32_t)0x00000002) +#define RCC_CLOCKTYPE_PCLK1 ((uint32_t)0x00000004) + +#define IS_RCC_CLOCKTYPE(CLK) ((((CLK) & RCC_CLOCKTYPE_SYSCLK) == RCC_CLOCKTYPE_SYSCLK) || \ + (((CLK) & RCC_CLOCKTYPE_HCLK) == RCC_CLOCKTYPE_HCLK) || \ + (((CLK) & RCC_CLOCKTYPE_PCLK1) == RCC_CLOCKTYPE_PCLK1)) +/** + * @} + */ + +/** @defgroup RCC_System_Clock_Source + * @{ + */ +#define RCC_SYSCLKSOURCE_HSI RCC_CFGR_SW_HSI +#define RCC_SYSCLKSOURCE_HSE RCC_CFGR_SW_HSE +#define RCC_SYSCLKSOURCE_PLLCLK RCC_CFGR_SW_PLL +/** + * @} + */ + +/** @defgroup RCC_System_Clock_Source_Status + * @{ + */ +#define RCC_SYSCLKSOURCE_STATUS_HSI RCC_CFGR_SWS_HSI +#define RCC_SYSCLKSOURCE_STATUS_HSE RCC_CFGR_SWS_HSE +#define RCC_SYSCLKSOURCE_STATUS_PLLCLK RCC_CFGR_SWS_PLL +/** + * @} + */ + +/** @defgroup RCC_AHB_Clock_Source + * @{ + */ +#define RCC_SYSCLK_DIV1 RCC_CFGR_HPRE_DIV1 +#define RCC_SYSCLK_DIV2 RCC_CFGR_HPRE_DIV2 +#define RCC_SYSCLK_DIV4 RCC_CFGR_HPRE_DIV4 +#define RCC_SYSCLK_DIV8 RCC_CFGR_HPRE_DIV8 +#define RCC_SYSCLK_DIV16 RCC_CFGR_HPRE_DIV16 +#define RCC_SYSCLK_DIV64 RCC_CFGR_HPRE_DIV64 +#define RCC_SYSCLK_DIV128 RCC_CFGR_HPRE_DIV128 +#define RCC_SYSCLK_DIV256 RCC_CFGR_HPRE_DIV256 +#define RCC_SYSCLK_DIV512 RCC_CFGR_HPRE_DIV512 + +#define IS_RCC_SYSCLK_DIV(DIV) (((DIV) == RCC_SYSCLK_DIV1) || ((DIV) == RCC_SYSCLK_DIV2) || \ + ((DIV) == RCC_SYSCLK_DIV4) || ((DIV) == RCC_SYSCLK_DIV8) || \ + ((DIV) == RCC_SYSCLK_DIV16) || ((DIV) == RCC_SYSCLK_DIV64) || \ + ((DIV) == RCC_SYSCLK_DIV128) || ((DIV) == RCC_SYSCLK_DIV256) || \ + ((DIV) == RCC_SYSCLK_DIV512)) +/** + * @} + */ + +/** @defgroup RCC_APB1_Clock_Source + * @{ + */ +#define RCC_HCLK_DIV1 RCC_CFGR_PPRE_DIV1 +#define RCC_HCLK_DIV2 RCC_CFGR_PPRE_DIV2 +#define RCC_HCLK_DIV4 RCC_CFGR_PPRE_DIV4 +#define RCC_HCLK_DIV8 RCC_CFGR_PPRE_DIV8 +#define RCC_HCLK_DIV16 RCC_CFGR_PPRE_DIV16 + +#define IS_RCC_HCLK_DIV(DIV) (((DIV) == RCC_HCLK_DIV1) || ((DIV) == RCC_HCLK_DIV2) || \ + ((DIV) == RCC_HCLK_DIV4) || ((DIV) == RCC_HCLK_DIV8) || \ + ((DIV) == RCC_HCLK_DIV16)) +/** + * @} + */ + +/** @defgroup RCC_RTC_Clock_Source + * @{ + */ +#define RCC_RTCCLKSOURCE_NONE RCC_BDCR_RTCSEL_NOCLOCK +#define RCC_RTCCLKSOURCE_LSE RCC_BDCR_RTCSEL_LSE +#define RCC_RTCCLKSOURCE_LSI RCC_BDCR_RTCSEL_LSI +#define RCC_RTCCLKSOURCE_HSE_DIV32 RCC_BDCR_RTCSEL_HSE + +#define IS_RCC_RTCCLKSOURCE(SOURCE) (((SOURCE) == RCC_RTCCLKSOURCE_NONE) || \ + ((SOURCE) == RCC_RTCCLKSOURCE_LSE) || \ + ((SOURCE) == RCC_RTCCLKSOURCE_LSI) || \ + ((SOURCE) == RCC_RTCCLKSOURCE_HSE_DIV32)) +/** + * @} + */ + + +/** @defgroup RCC_USART1_Clock_Source + * @{ + */ +#define RCC_USART1CLKSOURCE_PCLK1 RCC_CFGR3_USART1SW_PCLK +#define RCC_USART1CLKSOURCE_SYSCLK RCC_CFGR3_USART1SW_SYSCLK +#define RCC_USART1CLKSOURCE_LSE RCC_CFGR3_USART1SW_LSE +#define RCC_USART1CLKSOURCE_HSI RCC_CFGR3_USART1SW_HSI + +#define IS_RCC_USART1CLKSOURCE(SOURCE) (((SOURCE) == RCC_USART1CLKSOURCE_PCLK1) || \ + ((SOURCE) == RCC_USART1CLKSOURCE_SYSCLK) || \ + ((SOURCE) == RCC_USART1CLKSOURCE_LSE) || \ + ((SOURCE) == RCC_USART1CLKSOURCE_HSI)) +/** + * @} + */ + +/** @defgroup RCC_I2C1_Clock_Source + * @{ + */ +#define RCC_I2C1CLKSOURCE_HSI RCC_CFGR3_I2C1SW_HSI +#define RCC_I2C1CLKSOURCE_SYSCLK RCC_CFGR3_I2C1SW_SYSCLK + +#define IS_RCC_I2C1CLKSOURCE(SOURCE) (((SOURCE) == RCC_I2C1CLKSOURCE_HSI) || \ + ((SOURCE) == RCC_I2C1CLKSOURCE_SYSCLK)) +/** + * @} + */ + +/** @defgroup RCC_MCOx_Index + * @{ + */ +#define RCC_MCO ((uint32_t)0x00000000) + +#define IS_RCC_MCO(MCOx) ((MCOx) == RCC_MCO) +/** + * @} + */ + +/** @defgroup RCC_MCO_Clock_Source + * @{ + */ +#define RCC_MCOSOURCE_NONE RCC_CFGR_MCO_NOCLOCK +#define RCC_MCOSOURCE_LSI RCC_CFGR_MCO_LSI +#define RCC_MCOSOURCE_LSE RCC_CFGR_MCO_LSE +#define RCC_MCOSOURCE_SYSCLK RCC_CFGR_MCO_SYSCLK +#define RCC_MCOSOURCE_HSI RCC_CFGR_MCO_HSI +#define RCC_MCOSOURCE_HSE RCC_CFGR_MCO_HSE +#define RCC_MCOSOURCE_PLLCLK_DIV2 RCC_CFGR_MCO_PLL +#define RCC_MCOSOURCE_HSI14 RCC_CFGR_MCO_HSI14 +/** + * @} + */ + +/** @defgroup RCC_Interrupt + * @{ + */ +#define RCC_IT_LSIRDY ((uint8_t)0x01) +#define RCC_IT_LSERDY ((uint8_t)0x02) +#define RCC_IT_HSIRDY ((uint8_t)0x04) +#define RCC_IT_HSERDY ((uint8_t)0x08) +#define RCC_IT_PLLRDY ((uint8_t)0x10) +#define RCC_IT_HSI14 ((uint8_t)0x20) +#define RCC_IT_CSS ((uint8_t)0x80) +/** + * @} + */ + +/** @defgroup RCC_Flag + * Elements values convention: 0XXYYYYYb + * - YYYYY : Flag position in the register + * - XX : Register index + * - 00: CR register + * - 01: CR2 register + * - 10: BDCR register + * - 11: CSR register + * @{ + */ +#define CR_REG_INDEX 0 +#define CR2_REG_INDEX 1 +#define BDCR_REG_INDEX 2 +#define CSR_REG_INDEX 3 + +/* Flags in the CR register */ +#define RCC_CR_HSIRDY_BitNumber 1 +#define RCC_CR_HSERDY_BitNumber 17 +#define RCC_CR_PLLRDY_BitNumber 25 + +#define RCC_FLAG_HSIRDY ((uint8_t)((CR_REG_INDEX << 5) | RCC_CR_HSIRDY_BitNumber)) +#define RCC_FLAG_HSERDY ((uint8_t)((CR_REG_INDEX << 5) | RCC_CR_HSERDY_BitNumber)) +#define RCC_FLAG_PLLRDY ((uint8_t)((CR_REG_INDEX << 5) | RCC_CR_PLLRDY_BitNumber)) + +/* Flags in the CR2 register */ +#define RCC_CR2_HSI14RDY_BitNumber 1 + +#define RCC_FLAG_HSI14RDY ((uint8_t)((CR2_REG_INDEX << 5) | RCC_CR2_HSI14RDY_BitNumber)) + +/* Flags in the BDCR register */ +#define RCC_BDCR_LSERDY_BitNumber 1 + +#define RCC_FLAG_LSERDY ((uint8_t)((BDCR_REG_INDEX << 5) | RCC_BDCR_LSERDY_BitNumber)) + +/* Flags in the CSR register */ +#define RCC_CSR_LSIRDY_BitNumber 1 +#define RCC_CSR_V18PWRRSTF_BitNumber 23 +#define RCC_CSR_RMVF_BitNumber 24 +#define RCC_CSR_OBLRSTF_BitNumber 25 +#define RCC_CSR_PINRSTF_BitNumber 26 +#define RCC_CSR_PORRSTF_BitNumber 27 +#define RCC_CSR_SFTRSTF_BitNumber 28 +#define RCC_CSR_IWDGRSTF_BitNumber 29 +#define RCC_CSR_WWDGRSTF_BitNumber 30 +#define RCC_CSR_LPWRRSTF_BitNumber 31 + +#define RCC_FLAG_LSIRDY ((uint8_t)((CSR_REG_INDEX << 5) | RCC_CSR_LSIRDY_BitNumber)) +#define RCC_FLAG_V18PWRRST ((uint8_t)((CSR_REG_INDEX << 5) | RCC_CSR_LSIRDY_BitNumber)) +#define RCC_FLAG_RMV ((uint8_t)((CSR_REG_INDEX << 5) | RCC_CSR_RMVF_BitNumber)) +#define RCC_FLAG_OBLRST ((uint8_t)((CSR_REG_INDEX << 5) | RCC_CSR_OBLRSTF_BitNumber)) +#define RCC_FLAG_PINRST ((uint8_t)((CSR_REG_INDEX << 5) | RCC_CSR_PINRSTF_BitNumber)) +#define RCC_FLAG_PORRST ((uint8_t)((CSR_REG_INDEX << 5) | RCC_CSR_PORRSTF_BitNumber)) +#define RCC_FLAG_SFTRST ((uint8_t)((CSR_REG_INDEX << 5) | RCC_CSR_SFTRSTF_BitNumber)) +#define RCC_FLAG_IWDGRST ((uint8_t)((CSR_REG_INDEX << 5) | RCC_CSR_IWDGRSTF_BitNumber)) +#define RCC_FLAG_WWDGRST ((uint8_t)((CSR_REG_INDEX << 5) | RCC_CSR_WWDGRSTF_BitNumber)) +#define RCC_FLAG_LPWRRST ((uint8_t)((CSR_REG_INDEX << 5) | RCC_CSR_LPWRRSTF_BitNumber)) +/** + * @} + */ + +#define IS_RCC_CALIBRATION_VALUE(VALUE) ((VALUE) <= 0x1F) + +#define HSE_TIMEOUT_VALUE HSE_STARTUP_TIMEOUT +#define HSI_TIMEOUT_VALUE ((uint32_t)100) /* 100 ms */ +#define LSI_TIMEOUT_VALUE ((uint32_t)100) /* 100 ms */ +#define LSE_TIMEOUT_VALUE ((uint32_t)5000) /* 5 s */ +#define HSI14_TIMEOUT_VALUE ((uint32_t)100) /* 100 ms */ +#define HSI48_TIMEOUT_VALUE ((uint32_t)100) /* 100 ms */ +#define PLL_TIMEOUT_VALUE ((uint32_t)100) /* 100 ms */ +#define CLOCKSWITCH_TIMEOUT_VALUE ((uint32_t)5000) /* 5 s */ + +/** + * @} + */ +/* Exported macro ------------------------------------------------------------*/ +/** @defgroup RCC_Exported_Macros + * @{ + */ + +/** @brief Enable or disable the AHB peripheral clock. + * @note After reset, the peripheral clock (used for registers read/write access) + * is disabled and the application software has to enable this clock before + * using it. + */ +#define __GPIOA_CLK_ENABLE() (RCC->AHBENR |= (RCC_AHBENR_GPIOAEN)) +#define __GPIOB_CLK_ENABLE() (RCC->AHBENR |= (RCC_AHBENR_GPIOBEN)) +#define __GPIOC_CLK_ENABLE() (RCC->AHBENR |= (RCC_AHBENR_GPIOCEN)) +#define __GPIOF_CLK_ENABLE() (RCC->AHBENR |= (RCC_AHBENR_GPIOFEN)) +#define __CRC_CLK_ENABLE() (RCC->AHBENR |= (RCC_AHBENR_CRCEN)) +#define __DMA1_CLK_ENABLE() (RCC->AHBENR |= (RCC_AHBENR_DMA1EN)) +#define __SRAM_CLK_ENABLE() (RCC->AHBENR |= (RCC_AHBENR_SRAMEN)) +#define __FLITF_CLK_ENABLE() (RCC->AHBENR |= (RCC_AHBENR_FLITFEN)) + +#define __GPIOA_CLK_DISABLE() (RCC->AHBENR &= ~(RCC_AHBENR_GPIOAEN)) +#define __GPIOB_CLK_DISABLE() (RCC->AHBENR &= ~(RCC_AHBENR_GPIOBEN)) +#define __GPIOC_CLK_DISABLE() (RCC->AHBENR &= ~(RCC_AHBENR_GPIOCEN)) +#define __GPIOF_CLK_DISABLE() (RCC->AHBENR &= ~(RCC_AHBENR_GPIOFEN)) +#define __CRC_CLK_DISABLE() (RCC->AHBENR &= ~(RCC_AHBENR_CRCEN)) +#define __DMA1_CLK_DISABLE() (RCC->AHBENR &= ~(RCC_AHBENR_DMA1EN)) +#define __SRAM_CLK_DISABLE() (RCC->AHBENR &= ~(RCC_AHBENR_SRAMEN)) +#define __FLITF_CLK_DISABLE() (RCC->AHBENR &= ~(RCC_AHBENR_FLITFEN)) + +/** @brief Enable or disable the Low Speed APB (APB1) peripheral clock. + * @note After reset, the peripheral clock (used for registers read/write access) + * is disabled and the application software has to enable this clock before + * using it. + */ +#define __TIM3_CLK_ENABLE() (RCC->APB1ENR |= (RCC_APB1ENR_TIM3EN)) +#define __TIM14_CLK_ENABLE() (RCC->APB1ENR |= (RCC_APB1ENR_TIM14EN)) +#define __WWDG_CLK_ENABLE() (RCC->APB1ENR |= (RCC_APB1ENR_WWDGEN)) +#define __I2C1_CLK_ENABLE() (RCC->APB1ENR |= (RCC_APB1ENR_I2C1EN)) +#define __PWR_CLK_ENABLE() (RCC->APB1ENR |= (RCC_APB1ENR_PWREN)) + +#define __TIM3_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM3EN)) +#define __TIM14_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM14EN)) +#define __WWDG_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_WWDGEN)) +#define __I2C1_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_I2C1EN)) +#define __PWR_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_PWREN)) + +/** @brief Enable or disable the High Speed APB (APB2) peripheral clock. + * @note After reset, the peripheral clock (used for registers read/write access) + * is disabled and the application software has to enable this clock before + * using it. + */ +#define __SYSCFG_CLK_ENABLE() (RCC->APB2ENR |= (RCC_APB2ENR_SYSCFGEN)) +#define __ADC1_CLK_ENABLE() (RCC->APB2ENR |= (RCC_APB2ENR_ADC1EN)) +#define __TIM1_CLK_ENABLE() (RCC->APB2ENR |= (RCC_APB2ENR_TIM1EN)) +#define __SPI1_CLK_ENABLE() (RCC->APB2ENR |= (RCC_APB2ENR_SPI1EN)) +#define __TIM16_CLK_ENABLE() (RCC->APB2ENR |= (RCC_APB2ENR_TIM16EN)) +#define __TIM17_CLK_ENABLE() (RCC->APB2ENR |= (RCC_APB2ENR_TIM17EN)) +#define __USART1_CLK_ENABLE() (RCC->APB2ENR |= (RCC_APB2ENR_USART1EN)) +#define __DBGMCU_CLK_ENABLE() (RCC->APB2ENR |= (RCC_APB2ENR_DBGMCUEN)) + +#define __SYSCFG_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_SYSCFGEN)) +#define __ADC1_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_ADC1EN)) +#define __TIM1_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_TIM1EN)) +#define __SPI1_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_SPI1EN)) +#define __TIM16_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_TIM16EN)) +#define __TIM17_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_TIM17EN)) +#define __USART1_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_USART1EN)) +#define __DBGMCU_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_DBGMCUEN)) + +/** @brief Force or release AHB peripheral reset. + */ +#define __AHB_FORCE_RESET() (RCC->AHBRSTR = 0xFFFFFFFF) +#define __GPIOA_FORCE_RESET() (RCC->AHBRSTR |= (RCC_AHBRSTR_GPIOARST)) +#define __GPIOB_FORCE_RESET() (RCC->AHBRSTR |= (RCC_AHBRSTR_GPIOBRST)) +#define __GPIOC_FORCE_RESET() (RCC->AHBRSTR |= (RCC_AHBRSTR_GPIOCRST)) +#define __GPIOF_FORCE_RESET() (RCC->AHBRSTR |= (RCC_AHBRSTR_GPIOFRST)) + +#define __AHB_RELEASE_RESET() (RCC->AHBRSTR = 0x00) +#define __GPIOA_RELEASE_RESET() (RCC->AHBRSTR &= ~(RCC_AHBRSTR_GPIOARST)) +#define __GPIOB_RELEASE_RESET() (RCC->AHBRSTR &= ~(RCC_AHBRSTR_GPIOBRST)) +#define __GPIOC_RELEASE_RESET() (RCC->AHBRSTR &= ~(RCC_AHBRSTR_GPIOCRST)) +#define __GPIOF_RELEASE_RESET() (RCC->AHBRSTR &= ~(RCC_AHBRSTR_GPIOFRST)) + +/** @brief Force or release APB1 peripheral reset. + */ +#define __APB1_FORCE_RESET() (RCC->APB1RSTR = 0xFFFFFFFF) +#define __TIM3_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM3RST)) +#define __TIM14_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM14RST)) +#define __WWDG_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_WWDGRST)) +#define __I2C1_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_I2C1RST)) +#define __PWR_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_PWRRST)) + +#define __APB1_RELEASE_RESET() (RCC->APB1RSTR = 0x00) +#define __TIM3_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM3RST)) +#define __TIM14_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM14RST)) +#define __WWDG_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_WWDGRST)) +#define __I2C1_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_I2C1RST)) +#define __PWR_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_PWRRST)) + +/** @brief Force or release APB2 peripheral reset. + */ +#define __APB2_FORCE_RESET() (RCC->APB2RSTR = 0xFFFFFFFF) +#define __SYSCFG_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_SYSCFGRST)) +#define __ADC1_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_ADC1RST)) +#define __TIM1_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_TIM1RST)) +#define __SPI1_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_SPI1RST)) +#define __USART1_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_USART1RST)) +#define __TIM16_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_TIM16RST)) +#define __TIM17_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_TIM17RST)) +#define __DBGMCU_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_DBGMCURST)) + +#define __APB2_RELEASE_RESET() (RCC->APB2RSTR = 0x00) +#define __SYSCFG_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_SYSCFGRST)) +#define __ADC1_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_ADC1RST)) +#define __TIM1_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_TIM1RST)) +#define __SPI1_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_SPI1RST)) +#define __USART1_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_USART1RST)) +#define __TIM16_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_TIM16RST)) +#define __TIM17_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_TIM17RST)) +#define __DBGMCU_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_DBGMCURST)) + +/** @brief Macros to enable or disable the Internal High Speed oscillator (HSI). + * @note The HSI is stopped by hardware when entering STOP and STANDBY modes. + * It is used (enabled by hardware) as system clock source after startup + * from Reset, wakeup from STOP and STANDBY mode, or in case of failure + * of the HSE used directly or indirectly as system clock (if the Clock + * Security System CSS is enabled). + * @note HSI can not be stopped if it is used as system clock source. In this case, + * you have to select another source of the system clock then stop the HSI. + * @note After enabling the HSI, the application software should wait on HSIRDY + * flag to be set indicating that HSI clock is stable and can be used as + * system clock source. + * @note When the HSI is stopped, HSIRDY flag goes low after 6 HSI oscillator + * clock cycles. + */ +#define __HAL_RCC_HSI_ENABLE() SET_BIT(RCC->CR, RCC_CR_HSION) +#define __HAL_RCC_HSI_DISABLE() CLEAR_BIT(RCC->CR, RCC_CR_HSION) + + +/** @brief Macro to adjust the Internal High Speed oscillator (HSI) calibration value. + * @note The calibration is used to compensate for the variations in voltage + * and temperature that influence the frequency of the internal HSI RC. + * @param __HSICalibrationValue__: specifies the calibration trimming value + * (default is RCC_HSICALIBRATION_DEFAULT). + * This parameter must be a number between 0 and 0x1F. + */ +#define RCC_CR_HSITRIM_BitNumber 3 +#define __HAL_RCC_HSI_CALIBRATIONVALUE_ADJUST(__HSICalibrationValue__) \ + MODIFY_REG(RCC->CR, RCC_CR_HSITRIM, (uint32_t)(__HSICalibrationValue__) << RCC_CR_HSITRIM_BitNumber) + +/** @brief Macro to enable or disable the Internal Low Speed oscillator (LSI). + * @note After enabling the LSI, the application software should wait on + * LSIRDY flag to be set indicating that LSI clock is stable and can + * be used to clock the IWDG and/or the RTC. + * @note LSI can not be disabled if the IWDG is running. + * @note When the LSI is stopped, LSIRDY flag goes low after 6 LSI oscillator + * clock cycles. + */ +#define __HAL_RCC_LSI_ENABLE() SET_BIT(RCC->CSR, RCC_CSR_LSION) +#define __HAL_RCC_LSI_DISABLE() CLEAR_BIT(RCC->CSR, RCC_CSR_LSION) + +/** + * @brief Macro to configure the External High Speed oscillator (HSE). + * @note After enabling the HSE (RCC_HSE_ON or RCC_HSE_Bypass), the application + * software should wait on HSERDY flag to be set indicating that HSE clock + * is stable and can be used to clock the PLL and/or system clock. + * @note HSE state can not be changed if it is used directly or through the + * PLL as system clock. In this case, you have to select another source + * of the system clock then change the HSE state (ex. disable it). + * @note The HSE is stopped by hardware when entering STOP and STANDBY modes. + * @note This function reset the CSSON bit, so if the Clock security system(CSS) + * was previously enabled you have to enable it again after calling this + * function. + * @param __STATE__: specifies the new state of the HSE. + * This parameter can be one of the following values: + * @arg RCC_HSE_OFF: turn OFF the HSE oscillator, HSERDY flag goes low after + * 6 HSE oscillator clock cycles. + * @arg RCC_HSE_ON: turn ON the HSE oscillator + * @arg RCC_HSE_BYPASS: HSE oscillator bypassed with external clock + */ +#define __HAL_RCC_HSE_CONFIG(__STATE__) (*(__IO uint8_t *)RCC_CR_BYTE2_ADDRESS = (__STATE__)) + +/** + * @brief Macro to configure the External High Speed oscillator (HSE) Predivision factor for PLL. + * @note Predivision factor can not be changed if PLL is used as system clock + * In this case, you have to select another source of the system clock, disable the PLL and + * then change the HSE predivision factor. + * @param __HSEPredivValue__: specifies the division value applied to HSE. + * This parameter must be a number between RCC_HSE_PREDIV_DIV1 and RCC_HSE_PREDIV_DIV16. + */ +#define __HAL_RCC_HSE_PREDIV_CONFIG(__HSEPredivValue__) \ + MODIFY_REG(RCC->CFGR2, RCC_CFGR2_PREDIV, (uint32_t)(__HSEPredivValue__)) + +/** + * @brief Macro to configure the External Low Speed oscillator (LSE). + * @note As the LSE is in the Backup domain and write access is denied to + * this domain after reset, you have to enable write access using + * HAL_PWR_EnableBkUpAccess() function before to configure the LSE + * (to be done once after reset). + * @note After enabling the LSE (RCC_LSE_ON or RCC_LSE_BYPASS), the application + * software should wait on LSERDY flag to be set indicating that LSE clock + * is stable and can be used to clock the RTC. + * @param __STATE__: specifies the new state of the LSE. + * This parameter can be one of the following values: + * @arg RCC_LSE_OFF: turn OFF the LSE oscillator, LSERDY flag goes low after + * 6 LSE oscillator clock cycles. + * @arg RCC_LSE_ON: turn ON the LSE oscillator + * @arg RCC_LSE_BYPASS: LSE oscillator bypassed with external clock + */ +#define __HAL_RCC_LSE_CONFIG(__STATE__) \ + MODIFY_REG(RCC->BDCR, RCC_BDCR_LSEON|RCC_BDCR_LSEBYP, (uint32_t)(__STATE__)) + +/** @brief Macros to enable or disable the Internal 14Mhz High Speed oscillator (HSI14). + * @note The HSI14 is stopped by hardware when entering STOP and STANDBY modes. + * @note HSI14 can not be stopped if it is used as system clock source. In this case, + * you have to select another source of the system clock then stop the HSI14. + * @note After enabling the HSI14 with __HAL_RCC_HSI14_ENABLE(), the application software + * should wait on HSI14RDY flag to be set indicating that HSI clock is stable and can be + * used as system clock source. This is not necessary if HAL_RCC_OscConfig() is used. + * @note When the HSI14 is stopped, HSI14RDY flag goes low after 6 HSI14 oscillator + * clock cycles. + */ +#define __HAL_RCC_HSI14_ENABLE() SET_BIT(RCC->CR2, RCC_CR2_HSI14ON) +#define __HAL_RCC_HSI14_DISABLE() CLEAR_BIT(RCC->CR2, RCC_CR2_HSI14ON) + +/** @brief macros to Enable or Disable the Internal 14Mhz High Speed oscillator (HSI14) usage by ADC. + */ +#define __HAL_RCC_HSI14ADC_ENABLE() CLEAR_BIT(RCC->CR2, RCC_CR2_HSI14DIS) +#define __HAL_RCC_HSI14ADC_DISABLE() SET_BIT(RCC->CR2, RCC_CR2_HSI14DIS) + + +/** @brief Macro to adjust the Internal 14Mhz High Speed oscillator (HSI) calibration value. + * @note The calibration is used to compensate for the variations in voltage + * and temperature that influence the frequency of the internal HSI14 RC. + * @param __HSI14CalibrationValue__: specifies the calibration trimming value + * (default is RCC_HSI14CALIBRATION_DEFAULT). + * This parameter must be a number between 0 and 0x1F. + */ +#define RCC_CR2_HSI14TRIM_BitNumber 3 +#define __HAL_RCC_HSI14_CALIBRATIONVALUE_ADJUST(__HSI14CalibrationValue__) \ + MODIFY_REG(RCC->CR2, RCC_CR2_HSI14TRIM, (uint32_t)(__HSI14CalibrationValue__) << RCC_CR2_HSI14TRIM_BitNumber) + +/** @brief Macro to configure the USART1 clock (USART1CLK). + * @param __USART1CLKSource__: specifies the USART1 clock source. + * This parameter can be one of the following values: + * @arg RCC_USART1CLKSOURCE_PCLK1: PCLK1 selected as USART1 clock + * @arg RCC_USART1CLKSOURCE_HSI: HSI selected as USART1 clock + * @arg RCC_USART1CLKSOURCE_SYSCLK: System Clock selected as USART1 clock + * @arg RCC_USART1CLKSOURCE_LSE: LSE selected as USART1 clock + */ +#define __HAL_RCC_USART1_CONFIG(__USART1CLKSource__) \ + MODIFY_REG(RCC->CFGR3, RCC_CFGR3_USART1SW, (uint32_t)(__USART1CLKSource__)) + +/** @brief Macro to get the USART1 clock source. + * @retval The clock source can be one of the following values: + * @arg RCC_USART1CLKSOURCE_PCLK1: PCLK1 selected as USART1 clock + * @arg RCC_USART1CLKSOURCE_HSI: HSI selected as USART1 clock + * @arg RCC_USART1CLKSOURCE_SYSCLK: System Clock selected as USART1 clock + * @arg RCC_USART1CLKSOURCE_LSE: LSE selected as USART1 clock + */ +#define __HAL_RCC_GET_USART1_SOURCE() ((uint32_t)(READ_BIT(RCC->CFGR3, RCC_CFGR3_USART1SW))) + +/** @brief Macro to configure the I2C1 clock (I2C1CLK). + * @param __I2C1CLKSource__: specifies the I2C1 clock source. + * This parameter can be one of the following values: + * @arg RCC_I2C1CLKSOURCE_HSI: HSI selected as I2C1 clock + * @arg RCC_I2C1CLKSOURCE_SYSCLK: System Clock selected as I2C1 clock + */ +#define __HAL_RCC_I2C1_CONFIG(__I2C1CLKSource__) \ + MODIFY_REG(RCC->CFGR3, RCC_CFGR3_I2C1SW, (uint32_t)(__I2C1CLKSource__)) + +/** @brief Macro to get the I2C1 clock source. + * @retval The clock source can be one of the following values: + * @arg RCC_I2C1CLKSOURCE_HSI: HSI selected as I2C1 clock + * @arg RCC_I2C1CLKSOURCE_SYSCLK: System Clock selected as I2C1 clock + */ +#define __HAL_RCC_GET_I2C1_SOURCE() ((uint32_t)(READ_BIT(RCC->CFGR3, RCC_CFGR3_I2C1SW))) + +/** @brief Macro to configure the USART2 clock (USART2CLK). + * @param __USART2CLKSource__: specifies the USART2 clock source. + * This parameter can be one of the following values: + * @arg RCC_USART2CLKSOURCE_PCLK1: PCLK1 selected as USART2 clock + * @arg RCC_USART2CLKSOURCE_HSI: HSI selected as USART2 clock + * @arg RCC_USART2CLKSOURCE_SYSCLK: System Clock selected as USART2 clock + * @arg RCC_USART2CLKSOURCE_LSE: LSE selected as USART2 clock + */ +#define __HAL_RCC_USART2_CONFIG(__USART2CLKSource__) \ + MODIFY_REG(RCC->CFGR3, RCC_CFGR3_USART2SW, (uint32_t)(__USART2CLKSource__)) + +/** @brief Macro to get the USART2 clock source. + * @retval The clock source can be one of the following values: + * @arg RCC_USART2CLKSOURCE_PCLK1: PCLK1 selected as USART2 clock + * @arg RCC_USART2CLKSOURCE_HSI: HSI selected as USART2 clock + * @arg RCC_USART2CLKSOURCE_SYSCLK: System Clock selected as USART2 clock + * @arg RCC_USART2CLKSOURCE_LSE: LSE selected as USART2 clock + */ +#define __HAL_RCC_GET_USART2_SOURCE() ((uint32_t)(READ_BIT(RCC->CFGR3, RCC_CFGR3_USART2SW))) + +/** @brief Macros to enable or disable the the RTC clock. + * @note These macros must be used only after the RTC clock source was selected. + */ +#define __HAL_RCC_RTC_ENABLE() SET_BIT(RCC->BDCR, RCC_BDCR_RTCEN) +#define __HAL_RCC_RTC_DISABLE() CLEAR_BIT(RCC->BDCR, RCC_BDCR_RTCEN) + +/** @brief Macro to configure the RTC clock (RTCCLK). + * @note As the RTC clock configuration bits are in the Backup domain and write + * access is denied to this domain after reset, you have to enable write + * access using the Power Backup Access macro before to configure + * the RTC clock source (to be done once after reset). + * @note Once the RTC clock is configured it can't be changed unless the + * Backup domain is reset using __HAL_RCC_BackupReset_RELEASE() macro, or by + * a Power On Reset (POR). + * @param __RTCCLKSource__: specifies the RTC clock source. + * This parameter can be one of the following values: + * @arg RCC_RTCCLKSOURCE_NONE: No clock selected as RTC clock + * @arg RCC_RTCCLKSOURCE_LSE: LSE selected as RTC clock + * @arg RCC_RTCCLKSOURCE_LSI: LSI selected as RTC clock + * @arg RCC_RTCCLKSOURCE_HSE_DIV32: HSE clock divided by 32 + * + * @note If the LSE is used as RTC clock source, the RTC continues to + * work in STOP and STANDBY modes, and can be used as wakeup source. + * However, when the LSI clock and HSE clock divided by 32 is used as RTC clock source, + * the RTC cannot be used in STOP and STANDBY modes. + * @note The system must always be configured so as to get a PCLK frequency greater than or + * equal to the RTCCLK frequency for a proper operation of the RTC. + */ +#define __HAL_RCC_RTC_CONFIG(__RTCCLKSource__) \ + MODIFY_REG(RCC->BDCR, RCC_BDCR_RTCSEL, (uint32_t)(__RTCCLKSource__)) + +/** @brief Macro to get the RTC clock source. + * @retval The clock source can be one of the following values: + * @arg RCC_RTCCLKSOURCE_NONE: No clock selected as RTC clock + * @arg RCC_RTCCLKSOURCE_LSE: LSE selected as RTC clock + * @arg RCC_RTCCLKSOURCE_LSI: LSI selected as RTC clock + * @arg RCC_RTCCLKSOURCE_HSE_DIV32: HSE clock divided by 32 selected as RTC clock + */ +#define __HAL_RCC_GET_RTC_SOURCE() ((uint32_t)(READ_BIT(RCC->BDCR, RCC_BDCR_RTCSEL))) + +/** @brief Macro to force or release the Backup domain reset. + * @note These macros reset the RTC peripheral (including the backup registers) + * and the RTC clock source selection in RCC_CSR register. + * @note The BKPSRAM is not affected by this reset. + */ +#define __HAL_RCC_BACKUPRESET_FORCE() SET_BIT(RCC->BDCR, RCC_BDCR_BDRST) +#define __HAL_RCC_BACKUPRESET_RELEASE() CLEAR_BIT(RCC->BDCR, RCC_BDCR_BDRST) + +/** @brief Macro to enable or disable the PLL. + * @note After enabling the PLL, the application software should wait on + * PLLRDY flag to be set indicating that PLL clock is stable and can + * be used as system clock source. + * @note The PLL can not be disabled if it is used as system clock source + * @note The PLL is disabled by hardware when entering STOP and STANDBY modes. + */ +#define __HAL_RCC_PLL_ENABLE() SET_BIT(RCC->CR, RCC_CR_PLLON) +#define __HAL_RCC_PLL_DISABLE() CLEAR_BIT(RCC->CR, RCC_CR_PLLON) + +/** @brief Macro to configure the PLL clock source, multiplication and division factors. + * @note This macro must be used only when the PLL is disabled. + * + * @param __RCC_PLLSource__: specifies the PLL entry clock source. + * This parameter can be one of the following values: + * @arg RCC_PLLSOURCE_HSI: HSI oscillator clock selected as PLL clock entry + * @arg RCC_PLLSOURCE_HSE: HSE oscillator clock selected as PLL clock entry + * @param __PREDIV__: specifies the predivider factor for PLL VCO input clock + * This parameter must be a number between RCC_PREDIV_DIV1 and RCC_PREDIV_DIV16. + * @param __PLLMUL__: specifies the multiplication factor for PLL VCO input clock + * This parameter must be a number between RCC_PLL_MUL2 and RCC_PLL_MUL16. + * + */ +#define __HAL_RCC_PLL_CONFIG(__RCC_PLLSource__ , __PREDIV__, __PLLMUL__) \ + do { \ + MODIFY_REG(RCC->CFGR2, RCC_CFGR2_PREDIV, (__PREDIV__)); \ + MODIFY_REG(RCC->CFGR, RCC_CFGR_PLLMUL | RCC_CFGR_PLLSRC, (uint32_t)((__PLLMUL__)|(__RCC_PLLSource__))); \ + } while(0) + + +/** @brief Macro to get the clock source used as system clock. + * @retval The clock source used as system clock. + * The returned value can be one of the following value: + * @arg RCC_SYSCLKSOURCE_STATUS_HSI: HSI used as system clock + * @arg RCC_SYSCLKSOURCE_STATUS_HSE: HSE used as system clock + * @arg RCC_SYSCLKSOURCE_STATUS_PLLCLK: PLL used as system clock + */ +#define __HAL_RCC_GET_SYSCLK_SOURCE() ((uint32_t)(READ_BIT(RCC->CFGR, RCC_CFGR_SWS))) + +/** @brief Macro to get the oscillator used as PLL clock source. + * @retval The oscillator used as PLL clock source. The returned value can be one + * of the following: + * - RCC_PLLSOURCE_HSI: HSI oscillator is used as PLL clock source. + * - RCC_PLLSOURCE_HSE: HSE oscillator is used as PLL clock source. + */ +#define __HAL_RCC_GET_PLL_OSCSOURCE() ((uint32_t)(READ_BIT(RCC->CFGR, RCC_CFGR_PLLSRC))) + +/** + * @} + */ + +/** @defgroup RCC_Flags_Interrupts_Management + * @brief macros to manage the specified RCC Flags and interrupts. + * @{ + */ + +/** @brief Enable RCC interrupt (Perform Byte access to RCC_CIR[12:8] bits to enable + * the selected interrupts.). + * @param __INTERRUPT__: specifies the RCC interrupt sources to be enabled. + * This parameter can be any combination of the following values: + * @arg RCC_IT_LSIRDY: LSI ready interrupt enable + * @arg RCC_IT_LSERDY: LSE ready interrupt enable + * @arg RCC_IT_HSIRDY: HSI ready interrupt enable + * @arg RCC_IT_HSERDY: HSE ready interrupt enable + * @arg RCC_IT_PLLRDY: PLL ready interrupt enable + * @arg RCC_IT_HSI14RDY: HSI14 ready interrupt enable + * @arg RCC_IT_HSI48RDY: HSI48 ready interrupt enable (only applicable to STM32F0X2 USB devices) + */ +#define __HAL_RCC_ENABLE_IT(__INTERRUPT__) (*(__IO uint8_t *)RCC_CIR_BYTE1_ADDRESS |= (__INTERRUPT__)) + +/** @brief Disable RCC interrupt (Perform Byte access to RCC_CIR[12:8] bits to disable + * the selected interrupts.). + * @param __INTERRUPT__: specifies the RCC interrupt sources to be disabled. + * This parameter can be any combination of the following values: + * @arg RCC_IT_LSIRDY: LSI ready interrupt enable + * @arg RCC_IT_LSERDY: LSE ready interrupt enable + * @arg RCC_IT_HSIRDY: HSI ready interrupt enable + * @arg RCC_IT_HSERDY: HSE ready interrupt enable + * @arg RCC_IT_PLLRDY: PLL ready interrupt enable + * @arg RCC_IT_HSI14RDY: HSI14 ready interrupt enable + * @arg RCC_IT_HSI48RDY: HSI48 ready interrupt enable (only applicable to STM32F0X2 USB devices) + */ +#define __HAL_RCC_DISABLE_IT(__INTERRUPT__) (*(__IO uint8_t *)RCC_CIR_BYTE1_ADDRESS &= ~(__INTERRUPT__)) + +/** @brief Clear the RCC's interrupt pending bits ( Perform Byte access to RCC_CIR[23:16] + * bits to clear the selected interrupt pending bits. + * @param __IT__: specifies the interrupt pending bit to clear. + * This parameter can be any combination of the following values: + * @arg RCC_IT_LSIRDY: LSI ready interrupt clear + * @arg RCC_IT_LSERDY: LSE ready interrupt clear + * @arg RCC_IT_HSIRDY: HSI ready interrupt clear + * @arg RCC_IT_HSERDY: HSE ready interrupt clear + * @arg RCC_IT_PLLRDY: PLL ready interrupt clear + * @arg RCC_IT_HSI14RDY: HSI14 ready interrupt clear + * @arg RCC_IT_HSI48RDY: HSI48 ready interrupt clear (only applicable to STM32F0X2 USB devices) + * @arg RCC_IT_CSS: Clock Security System interrupt clear + */ +#define __HAL_RCC_CLEAR_IT(__IT__) (*(__IO uint8_t *)RCC_CIR_BYTE2_ADDRESS = (__IT__)) + +/** @brief Check the RCC's interrupt has occurred or not. + * @param __IT__: specifies the RCC interrupt source to check. + * This parameter can be one of the following values: + * @arg RCC_IT_LSIRDY: LSI ready interrupt flag + * @arg RCC_IT_LSERDY: LSE ready interrupt flag + * @arg RCC_IT_HSIRDY: HSI ready interrupt flag + * @arg RCC_IT_HSERDY: HSE ready interrupt flag + * @arg RCC_IT_PLLRDY: PLL ready interrupt flag + * @arg RCC_IT_HSI14RDY: HSI14 ready interrupt flag + * @arg RCC_IT_HSI48RDY: HSI48 ready interrupt flag (only applicable to STM32F0X2 USB devices) + * @arg RCC_IT_CSS: Clock Security System interrupt flag + * @retval The new state of __IT__ (TRUE or FALSE). + */ +#define __HAL_RCC_GET_IT(__IT__) ((RCC->CIR & (__IT__)) == (__IT__)) + +/** @brief Set RMVF bit to clear the reset flags: RCC_FLAG_OBLRST, RCC_FLAG_PINRST, RCC_FLAG_PORRST, RCC_FLAG_SFTRST, + * RCC_FLAG_IWDGRST, RCC_FLAG_WWDGRST, RCC_FLAG_LPWRRST + */ +#define __HAL_RCC_CLEAR_RESET_FLAGS() SET_BIT(RCC->CSR, RCC_CSR_RMVF) + +/** @brief Check RCC flag is set or not. + * @param __FLAG__: specifies the flag to check. + * This parameter can be one of the following values: + * @arg RCC_FLAG_HSIRDY: HSI oscillator clock ready + * @arg RCC_FLAG_HSERDY: HSE oscillator clock ready + * @arg RCC_FLAG_PLLRDY: PLL clock ready + * @arg RCC_FLAG_HSI14RDY: HSI14 oscillator clock ready + * @arg RCC_FLAG_HSI48RDY: HSI48 oscillator clock ready (only applicable to STM32F0X2 USB devices) + * @arg RCC_FLAG_LSERDY: LSE oscillator clock ready + * @arg RCC_FLAG_LSIRDY: LSI oscillator clock ready + * @arg RCC_FLAG_OBLRST: Option Byte Load reset + * @arg RCC_FLAG_PINRST: Pin reset + * @arg RCC_FLAG_PORRST: POR/PDR reset + * @arg RCC_FLAG_SFTRST: Software reset + * @arg RCC_FLAG_IWDGRST: Independent Watchdog reset + * @arg RCC_FLAG_WWDGRST: Window Watchdog reset + * @arg RCC_FLAG_LPWRRST: Low Power reset + * @retval The new state of __FLAG__ (TRUE or FALSE). + */ +#define RCC_FLAG_MASK ((uint8_t)0x1F) +#define __HAL_RCC_GET_FLAG(__FLAG__) (((((__FLAG__) >> 5) == CR_REG_INDEX)? RCC->CR : \ + (((__FLAG__) >> 5) == CR2_REG_INDEX)? RCC->CR2 : \ + (((__FLAG__) >> 5) == BDCR_REG_INDEX) ? RCC->BDCR : \ + RCC->CSR) & ((uint32_t)1 << ((__FLAG__) & RCC_FLAG_MASK))) + + + +/** + * @} + */ + +/* Include RCC HAL Extension module */ +#include "stm32f0xx_hal_rcc_ex.h" + +/* Exported functions --------------------------------------------------------*/ + +/* Initialization and de-initialization functions ***************************/ +void HAL_RCC_DeInit(void); +HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct); +HAL_StatusTypeDef HAL_RCC_ClockConfig(RCC_ClkInitTypeDef *RCC_ClkInitStruct, uint32_t FLatency); + +/* Peripheral Control functions *********************************************/ +void HAL_RCC_MCOConfig(uint32_t RCC_MCOx, uint32_t RCC_MCOSource, uint32_t RCC_MCODiv); +void HAL_RCC_EnableCSS(void); +void HAL_RCC_DisableCSS(void); +uint32_t HAL_RCC_GetSysClockFreq(void); +uint32_t HAL_RCC_GetHCLKFreq(void); +uint32_t HAL_RCC_GetPCLK1Freq(void); +void HAL_RCC_GetOscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct); +void HAL_RCC_GetClockConfig(RCC_ClkInitTypeDef *RCC_ClkInitStruct, uint32_t *pFLatency); + +/* CSS NMI IRQ handler */ +void HAL_RCC_NMI_IRQHandler(void); + +/* User Callbacks in non blocking mode (IT mode) */ +void HAL_RCC_CCSCallback(void); + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __STM32F0xx_HAL_RCC_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_rcc_ex.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_rcc_ex.c new file mode 100644 index 0000000000..03ea3344da --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_rcc_ex.c @@ -0,0 +1,1346 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_rcc_ex.c + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief Extended RCC HAL module driver + * This file provides firmware functions to manage the following + * functionalities RCC extension peripheral: + * + Extended Clock Source configuration functions + * + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + + For CRS, RCC Extention HAL driver can be used as follows: + + (#) In System clock config, HSI48 need to be enabled + + (#] Enable CRS clock in IP MSP init which will use CRS functions + + (#) Call CRS functions like this + (##) Prepare synchronization configuration necessary for HSI48 calibration + (+++) Default values can be set for frequency Error Measurement (reload and error limit) + and also HSI48 oscillator smooth trimming. + (+++) Macro __HAL_RCC_CRS_CALCULATE_RELOADVALUE can be also used to calculate + directly reload value with target and sychronization frequencies values + (##) Call function HAL_RCCEx_CRSConfig which + (+++) Reset CRS registers to their default values. + (+++) Configure CRS registers with synchronization configuration + (+++) Enable automatic calibration and frequency error counter feature + + (##) A polling function is provided to wait for complete Synchronization + (+++) Call function 'HAL_RCCEx_CRSWaitSynchronization()' + (+++) According to CRS status, user can decide to adjust again the calibration or continue + application if synchronization is OK + + (#) User can retrieve information related to synchronization in calling function + HAL_RCCEx_CRSGetSynchronizationInfo() + + (#) Regarding synchronization status and synchronization information, user can try a new calibration + in changing synchronization configuration and call again HAL_RCCEx_CRSConfig. + Note: When the SYNC event is detected during the downcounting phase (before reaching the zero value), + it means that the actual frequency is lower than the target (and so, that the TRIM value should be + incremented), while when it is detected during the upcounting phase it means that the actual frequency + is higher (and that the TRIM value should be decremented). + + (#) To use IT mode, user needs to handle it in calling different macros available to do it + (__HAL_RCC_CRS_XXX_IT). Interuptions will go through RCC Handler (RCC_IRQn/RCC_CRS_IRQHandler) + (+++) Call function HAL_RCCEx_CRSConfig() + (+++) Enable RCC_IRQn (thnaks to NVIC functions) + (+++) Enable CRS IT (__HAL_RCC_CRS_ENABLE_IT) + [+++) Implement CRS status management in RCC_CRS_IRQHandler + + (#) To force a SYNC EVENT, user can use function 'HAL_RCCEx_CRSSoftwareSynchronizationGenerate()'. Function can be + called before calling HAL_RCCEx_CRSConfig (for instance in Systick handler) + + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @defgroup RCCEx + * @brief RCC Extension HAL module driver. + * @{ + */ + +#ifdef HAL_RCC_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +#define HSI48_TIMEOUT_VALUE ((uint32_t)100) /* 100 ms */ + +/* Bit position in register */ +#define CRS_CFGR_FELIM_BITNUMBER 16 +#define CRS_CR_TRIM_BITNUMBER 8 +#define CRS_ISR_FECAP_BITNUMBER 16 + +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +const uint8_t PLLMULFactorTable[16] = { 2, 3, 4, 5, 6, 7, 8, 9, + 10, 11, 12, 13, 14, 15, 16, 16}; +const uint8_t PredivFactorTable[16] = { 1, 2, 3, 4, 5, 6, 7, 8, + 9,10, 11, 12, 13, 14, 15, 16}; + +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup RCCEx_Private_Functions + * @{ + */ + +/** @defgroup RCCEx_Group1 Extended Peripheral Control functions + * @brief Extended RCC clocks control functions + * +@verbatim + =============================================================================== + ##### Extended Peripheral Control functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to control the RCC Clocks + frequencies. + [..] + (@) Important note: Care must be taken when HAL_RCCEx_PeriphCLKConfig() is used to + select the RTC clock source; in this case the Backup domain will be reset in + order to modify the RTC Clock source, as consequence RTC registers (including + the backup registers) and RCC_BDCR register are set to their reset values. + +@endverbatim + * @{ + */ + +/** + * @brief Initializes the RCC Oscillators according to the specified parameters in the + * RCC_OscInitTypeDef. + * @param RCC_OscInitStruct: pointer to an RCC_OscInitTypeDef structure that + * contains the configuration information for the RCC Oscillators. + * @note The PLL is not disabled when used as system clock. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct) +{ + uint32_t tickstart = 0; + + /* Check the parameters */ + assert_param(IS_RCC_OSCILLATORTYPE(RCC_OscInitStruct->OscillatorType)); + /*------------------------------- HSE Configuration ------------------------*/ + if(((RCC_OscInitStruct->OscillatorType) & RCC_OSCILLATORTYPE_HSE) == RCC_OSCILLATORTYPE_HSE) + { + /* Check the parameters */ + assert_param(IS_RCC_HSE(RCC_OscInitStruct->HSEState)); + /* When the HSE is used as system clock or clock source for PLL in these cases it is not allowed to be disabled */ + if((__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_HSE) || + ((__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_PLLCLK) && (__HAL_RCC_GET_PLL_OSCSOURCE() == RCC_PLLSOURCE_HSE))) + { + if((__HAL_RCC_GET_FLAG(RCC_FLAG_HSERDY) != RESET) && (RCC_OscInitStruct->HSEState != RCC_HSE_ON)) + { + return HAL_ERROR; + } + } + else + { + /* Reset HSEON and HSEBYP bits before configuring the HSE --------------*/ + __HAL_RCC_HSE_CONFIG(RCC_HSE_OFF); + + /* Get timeout */ + tickstart = HAL_GetTick(); + + /* Wait till HSE is disabled */ + while(__HAL_RCC_GET_FLAG(RCC_FLAG_HSERDY) != RESET) + { + if((HAL_GetTick() - tickstart) >= HSE_TIMEOUT_VALUE) + { + return HAL_TIMEOUT; + } + } + + /* Set the new HSE configuration ---------------------------------------*/ + __HAL_RCC_HSE_CONFIG((uint8_t)RCC_OscInitStruct->HSEState); + + /* Check the HSE State */ + if((RCC_OscInitStruct->HSEState) == RCC_HSE_ON) + { + /* Get timeout */ + tickstart = HAL_GetTick(); + + /* Wait till HSE is ready */ + while(__HAL_RCC_GET_FLAG(RCC_FLAG_HSERDY) == RESET) + { + if((HAL_GetTick() - tickstart) >= HSE_TIMEOUT_VALUE) + { + return HAL_TIMEOUT; + } + } + } + else + { + /* Get timeout */ + tickstart = HAL_GetTick(); + + /* Wait till HSE is bypassed or disabled */ + while(__HAL_RCC_GET_FLAG(RCC_FLAG_HSERDY) != RESET) + { + if((HAL_GetTick() - tickstart) >= HSE_TIMEOUT_VALUE) + { + return HAL_TIMEOUT; + } + } + } + } + } + /*----------------------------- HSI Configuration --------------------------*/ + if(((RCC_OscInitStruct->OscillatorType) & RCC_OSCILLATORTYPE_HSI) == RCC_OSCILLATORTYPE_HSI) + { + /* Check the parameters */ + assert_param(IS_RCC_HSI(RCC_OscInitStruct->HSIState)); + assert_param(IS_RCC_CALIBRATION_VALUE(RCC_OscInitStruct->HSICalibrationValue)); + + /* When the HSI is used as system clock it is not allowed to be disabled */ + if((__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_HSI) || + ((__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_PLLCLK) && (__HAL_RCC_GET_PLL_OSCSOURCE() == RCC_PLLSOURCE_HSI))) + { + if((__HAL_RCC_GET_FLAG(RCC_FLAG_HSIRDY) != RESET) && (RCC_OscInitStruct->HSIState != RCC_HSI_ON)) + { + return HAL_ERROR; + } + } + else + { + /* Check the HSI State */ + if((RCC_OscInitStruct->HSIState)!= RCC_HSI_OFF) + { + /* Enable the Internal High Speed oscillator (HSI). */ + __HAL_RCC_HSI_ENABLE(); + + tickstart = HAL_GetTick(); + + /* Wait till HSI is ready */ + while(__HAL_RCC_GET_FLAG(RCC_FLAG_HSIRDY) == RESET) + { + if((HAL_GetTick() - tickstart) >= HSI_TIMEOUT_VALUE) + { + return HAL_TIMEOUT; + } + } + + /* Adjusts the Internal High Speed oscillator (HSI) calibration value. */ + __HAL_RCC_HSI_CALIBRATIONVALUE_ADJUST(RCC_OscInitStruct->HSICalibrationValue); + } + else + { + /* Disable the Internal High Speed oscillator (HSI). */ + __HAL_RCC_HSI_DISABLE(); + + /* Get timeout */ + tickstart = HAL_GetTick(); + + /* Wait till HSI is ready */ + while(__HAL_RCC_GET_FLAG(RCC_FLAG_HSIRDY) != RESET) + { + if((HAL_GetTick() - tickstart) >= HSI_TIMEOUT_VALUE) + { + return HAL_TIMEOUT; + } + } + } + } + } + /*------------------------------ LSI Configuration -------------------------*/ + if(((RCC_OscInitStruct->OscillatorType) & RCC_OSCILLATORTYPE_LSI) == RCC_OSCILLATORTYPE_LSI) + { + /* Check the parameters */ + assert_param(IS_RCC_LSI(RCC_OscInitStruct->LSIState)); + + /* Check the LSI State */ + if((RCC_OscInitStruct->LSIState)!= RCC_LSI_OFF) + { + /* Enable the Internal Low Speed oscillator (LSI). */ + __HAL_RCC_LSI_ENABLE(); + + /* Get timeout */ + tickstart = HAL_GetTick() ; + + /* Wait till LSI is ready */ + while(__HAL_RCC_GET_FLAG(RCC_FLAG_LSIRDY) == RESET) + { + if((HAL_GetTick() - tickstart) >= LSI_TIMEOUT_VALUE) + { + return HAL_TIMEOUT; + } + } + } + else + { + /* Disable the Internal Low Speed oscillator (LSI). */ + __HAL_RCC_LSI_DISABLE(); + + /* Get timeout */ + tickstart = HAL_GetTick() ; + + /* Wait till LSI is ready */ + while(__HAL_RCC_GET_FLAG(RCC_FLAG_LSIRDY) != RESET) + { + if((HAL_GetTick() - tickstart) >= LSI_TIMEOUT_VALUE) + { + return HAL_TIMEOUT; + } + } + } + } + /*------------------------------ LSE Configuration -------------------------*/ + if(((RCC_OscInitStruct->OscillatorType) & RCC_OSCILLATORTYPE_LSE) == RCC_OSCILLATORTYPE_LSE) + { + /* Check the parameters */ + assert_param(IS_RCC_LSE(RCC_OscInitStruct->LSEState)); + + /* Enable Power Clock */ + __PWR_CLK_ENABLE(); + + /* Enable write access to Backup domain */ + SET_BIT(PWR->CR, PWR_CR_DBP); + + /* Wait for Backup domain Write protection disable */ + tickstart = HAL_GetTick() ; + + while((PWR->CR & PWR_CR_DBP) == RESET) + { + if((HAL_GetTick() - tickstart) >= DBP_TIMEOUT_VALUE) + { + return HAL_TIMEOUT; + } + } + + /* Reset LSEON and LSEBYP bits before configuring the LSE ----------------*/ + __HAL_RCC_LSE_CONFIG(RCC_LSE_OFF); + + /* Get timeout */ + tickstart = HAL_GetTick() ; + + /* Wait till LSE is ready */ + while(__HAL_RCC_GET_FLAG(RCC_FLAG_LSERDY) != RESET) + { + if((HAL_GetTick() - tickstart) >= LSE_TIMEOUT_VALUE) + { + return HAL_TIMEOUT; + } + } + + /* Set the new LSE configuration -----------------------------------------*/ + __HAL_RCC_LSE_CONFIG(RCC_OscInitStruct->LSEState); + /* Check the LSE State */ + if((RCC_OscInitStruct->LSEState) == RCC_LSE_ON) + { + /* Get timeout */ + tickstart = HAL_GetTick() ; + + /* Wait till LSE is ready */ + while(__HAL_RCC_GET_FLAG(RCC_FLAG_LSERDY) == RESET) + { + if((HAL_GetTick() - tickstart) >= LSE_TIMEOUT_VALUE) + { + return HAL_TIMEOUT; + } + } + } + else + { + /* Get timeout */ + tickstart = HAL_GetTick() ; + + /* Wait till LSE is ready */ + while(__HAL_RCC_GET_FLAG(RCC_FLAG_LSERDY) != RESET) + { + if((HAL_GetTick() - tickstart) >= LSE_TIMEOUT_VALUE) + { + return HAL_TIMEOUT; + } + } + } + } + + /*----------------------------- HSI14 Configuration --------------------------*/ + if(((RCC_OscInitStruct->OscillatorType) & RCC_OSCILLATORTYPE_HSI14) == RCC_OSCILLATORTYPE_HSI14) + { + /* Check the parameters */ + assert_param(IS_RCC_HSI14(RCC_OscInitStruct->HSI14State)); + assert_param(IS_RCC_CALIBRATION_VALUE(RCC_OscInitStruct->HSI14CalibrationValue)); + + /* Check the HSI14 State */ + if((RCC_OscInitStruct->HSI14State) == RCC_HSI14_ON) + { + /* Disable ADC control of the Internal High Speed oscillator HSI14 */ + __HAL_RCC_HSI14ADC_DISABLE(); + + /* Enable the Internal High Speed oscillator (HSI). */ + __HAL_RCC_HSI14_ENABLE(); + + /* Get timeout */ + tickstart = HAL_GetTick(); + + /* Wait till HSI is ready */ + while(__HAL_RCC_GET_FLAG(RCC_FLAG_HSI14RDY) == RESET) + { + if((HAL_GetTick() - tickstart) >= HSI14_TIMEOUT_VALUE) + { + return HAL_TIMEOUT; + } + } + + /* Adjusts the Internal High Speed oscillator 14Mhz (HSI14) calibration value. */ + __HAL_RCC_HSI14_CALIBRATIONVALUE_ADJUST(RCC_OscInitStruct->HSI14CalibrationValue); + } + else if((RCC_OscInitStruct->HSI14State) == RCC_HSI14_ADC_CONTROL) + { + /* Enable ADC control of the Internal High Speed oscillator HSI14 */ + __HAL_RCC_HSI14ADC_ENABLE(); + + /* Adjusts the Internal High Speed oscillator 14Mhz (HSI14) calibration value. */ + __HAL_RCC_HSI14_CALIBRATIONVALUE_ADJUST(RCC_OscInitStruct->HSI14CalibrationValue); + } + else + { + /* Disable ADC control of the Internal High Speed oscillator HSI14 */ + __HAL_RCC_HSI14ADC_DISABLE(); + + /* Disable the Internal High Speed oscillator (HSI). */ + __HAL_RCC_HSI14_DISABLE(); + + /* Get timeout */ + tickstart = HAL_GetTick(); + + /* Wait till HSI is ready */ + while(__HAL_RCC_GET_FLAG(RCC_FLAG_HSI14RDY) != RESET) + { + if((HAL_GetTick() - tickstart) >= HSI14_TIMEOUT_VALUE) + { + return HAL_TIMEOUT; + } + } + } + } + +#if defined(STM32F042x6) || defined(STM32F048xx) || defined(STM32F072xB) || defined(STM32F078xx) + /*----------------------------- HSI48 Configuration --------------------------*/ + if(((RCC_OscInitStruct->OscillatorType) & RCC_OSCILLATORTYPE_HSI48) == RCC_OSCILLATORTYPE_HSI48) + { + /* Check the parameters */ + assert_param(IS_RCC_HSI48(RCC_OscInitStruct->HSI48State)); + + /* When the HSI48 is used as system clock it is not allowed to be disabled */ + if((__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_HSI48) || + ((__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_SYSCLKSOURCE_STATUS_PLLCLK) && (__HAL_RCC_GET_PLL_OSCSOURCE() == RCC_PLLSOURCE_HSI48))) + { + if((__HAL_RCC_GET_FLAG(RCC_FLAG_HSI48RDY) != RESET) && (RCC_OscInitStruct->HSI48State != RCC_HSI48_ON)) + { + return HAL_ERROR; + } + } + else + { + /* Check the HSI State */ + if((RCC_OscInitStruct->HSI48State)!= RCC_HSI48_OFF) + { + /* Enable the Internal High Speed oscillator (HSI48). */ + __HAL_RCC_HSI48_ENABLE(); + + /* Get timeout */ + tickstart = HAL_GetTick(); + + /* Wait till HSI is ready */ + while(__HAL_RCC_GET_FLAG(RCC_FLAG_HSI48RDY) == RESET) + { + if((HAL_GetTick() - tickstart) >= HSI48_TIMEOUT_VALUE) + { + return HAL_TIMEOUT; + } + } + } + else + { + /* Disable the Internal High Speed oscillator (HSI48). */ + __HAL_RCC_HSI48_DISABLE(); + + /* Get timeout */ + tickstart = HAL_GetTick(); + + /* Wait till HSI is ready */ + while(__HAL_RCC_GET_FLAG(RCC_FLAG_HSI48RDY) != RESET) + { + if((HAL_GetTick() - tickstart) >= HSI48_TIMEOUT_VALUE) + { + return HAL_TIMEOUT; + } + } + } + } + } +#endif /* STM32F042x6 || STM32F072xB || STM32F078xx */ + + /*-------------------------------- PLL Configuration -----------------------*/ + /* Check the parameters */ + assert_param(IS_RCC_PLL(RCC_OscInitStruct->PLL.PLLState)); + if ((RCC_OscInitStruct->PLL.PLLState) != RCC_PLL_NONE) + { + /* Check if the PLL is used as system clock or not */ + if(__HAL_RCC_GET_SYSCLK_SOURCE() != RCC_SYSCLKSOURCE_STATUS_PLLCLK) + { + if((RCC_OscInitStruct->PLL.PLLState) == RCC_PLL_ON) + { + /* Check the parameters */ + assert_param(IS_RCC_PLLSOURCE(RCC_OscInitStruct->PLL.PLLSource)); + assert_param(IS_RCC_PREDIV(RCC_OscInitStruct->PLL.PREDIV)); + assert_param(IS_RCC_PLL_MUL(RCC_OscInitStruct->PLL.PLLMUL)); + + /* Disable the main PLL. */ + __HAL_RCC_PLL_DISABLE(); + + /* Get timeout */ + tickstart = HAL_GetTick(); + + /* Wait till PLL is ready */ + while(__HAL_RCC_GET_FLAG(RCC_FLAG_PLLRDY) != RESET) + { + if((HAL_GetTick() - tickstart) >= PLL_TIMEOUT_VALUE) + { + return HAL_TIMEOUT; + } + } + + /* Configure the main PLL clock source, predivider and multiplication factor. */ + __HAL_RCC_PLL_CONFIG(RCC_OscInitStruct->PLL.PLLSource, + RCC_OscInitStruct->PLL.PREDIV, + RCC_OscInitStruct->PLL.PLLMUL); + + /* Enable the main PLL. */ + __HAL_RCC_PLL_ENABLE(); + + /* Get timeout */ + tickstart = HAL_GetTick(); + + /* Wait till PLL is ready */ + while(__HAL_RCC_GET_FLAG(RCC_FLAG_PLLRDY) == RESET) + { + if((HAL_GetTick() - tickstart) >= PLL_TIMEOUT_VALUE) + { + return HAL_TIMEOUT; + } + } + } + else + { + /* Disable the main PLL. */ + __HAL_RCC_PLL_DISABLE(); + /* Get timeout */ + tickstart = HAL_GetTick(); + + /* Wait till PLL is ready */ + while(__HAL_RCC_GET_FLAG(RCC_FLAG_PLLRDY) != RESET) + { + if((HAL_GetTick() - tickstart) >= PLL_TIMEOUT_VALUE) + { + return HAL_TIMEOUT; + } + } + } + } + else + { + return HAL_ERROR; + } + } + return HAL_OK; +} + +/** + * @brief Initializes the CPU, AHB and APB busses clocks according to the specified + * parameters in the RCC_ClkInitStruct. + * @param RCC_ClkInitStruct: pointer to an RCC_OscInitTypeDef structure that + * contains the configuration information for the RCC peripheral. + * @param FLatency: FLASH Latency + * This parameter can be one of the following values: + * @arg FLASH_LATENCY_0: FLASH 0 Latency cycle + * @arg FLASH_LATENCY_1: FLASH 1 Latency cycle + * + * @note The SystemCoreClock CMSIS variable is used to store System Clock Frequency + * and updated by HAL_RCC_GetHCLKFreq() function called within this function + * + * @note The HSI is used (enabled by hardware) as system clock source after + * startup from Reset, wake-up from STOP and STANDBY mode, or in case + * of failure of the HSE used directly or indirectly as system clock + * (if the Clock Security System CSS is enabled). + * + * @note A switch from one clock source to another occurs only if the target + * clock source is ready (clock stable after startup delay or PLL locked). + * If a clock source which is not yet ready is selected, the switch will + * occur when the clock source will be ready. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RCC_ClockConfig(RCC_ClkInitTypeDef *RCC_ClkInitStruct, uint32_t FLatency) +{ + uint32_t tickstart = 0; + + /* Check the parameters */ + assert_param(IS_RCC_CLOCKTYPE(RCC_ClkInitStruct->ClockType)); + assert_param(IS_FLASH_LATENCY(FLatency)); + + /* To correctly read data from FLASH memory, the number of wait states (LATENCY) + must be correctly programmed according to the frequency of the CPU clock + (HCLK) of the device. */ + + /* Increasing the CPU frequency */ + if(FLatency > (FLASH->ACR & FLASH_ACR_LATENCY)) + { + /* Program the new number of wait states to the LATENCY bits in the FLASH_ACR register */ + __HAL_FLASH_SET_LATENCY(FLatency); + + /* Check that the new number of wait states is taken into account to access the Flash + memory by reading the FLASH_ACR register */ + if((FLASH->ACR & FLASH_ACR_LATENCY) != FLatency) + { + return HAL_ERROR; + } + + /*-------------------------- HCLK Configuration --------------------------*/ + if(((RCC_ClkInitStruct->ClockType) & RCC_CLOCKTYPE_HCLK) == RCC_CLOCKTYPE_HCLK) + { + assert_param(IS_RCC_SYSCLK_DIV(RCC_ClkInitStruct->AHBCLKDivider)); + MODIFY_REG(RCC->CFGR, RCC_CFGR_HPRE, RCC_ClkInitStruct->AHBCLKDivider); + } + + /*------------------------- SYSCLK Configuration ---------------------------*/ + if(((RCC_ClkInitStruct->ClockType) & RCC_CLOCKTYPE_SYSCLK) == RCC_CLOCKTYPE_SYSCLK) + { + assert_param(IS_RCC_SYSCLKSOURCE(RCC_ClkInitStruct->SYSCLKSource)); + + /* HSE is selected as System Clock Source */ + if(RCC_ClkInitStruct->SYSCLKSource == RCC_SYSCLKSOURCE_HSE) + { + /* Check the HSE ready flag */ + if(__HAL_RCC_GET_FLAG(RCC_FLAG_HSERDY) == RESET) + { + return HAL_ERROR; + } + } + /* PLL is selected as System Clock Source */ + else if(RCC_ClkInitStruct->SYSCLKSource == RCC_SYSCLKSOURCE_PLLCLK) + { + /* Check the PLL ready flag */ + if(__HAL_RCC_GET_FLAG(RCC_FLAG_PLLRDY) == RESET) + { + return HAL_ERROR; + } + } +#if defined(STM32F042x6) || defined(STM32F048xx) || defined(STM32F072xB) || defined(STM32F078xx) + /* HSI48 is selected as System Clock Source */ + else if(RCC_ClkInitStruct->SYSCLKSource == RCC_SYSCLKSOURCE_HSI48) + { + /* Check the HSI48 ready flag */ + if(__HAL_RCC_GET_FLAG(RCC_FLAG_HSI48RDY) == RESET) + { + return HAL_ERROR; + } + } +#endif /* STM32F042x6 || STM32F072xB || STM32F078xx */ + /* HSI is selected as System Clock Source */ + else + { + /* Check the HSI ready flag */ + if(__HAL_RCC_GET_FLAG(RCC_FLAG_HSIRDY) == RESET) + { + return HAL_ERROR; + } + } + MODIFY_REG(RCC->CFGR, RCC_CFGR_SW, RCC_ClkInitStruct->SYSCLKSource); + + /* Get timeout */ + tickstart = HAL_GetTick(); + + if(RCC_ClkInitStruct->SYSCLKSource == RCC_SYSCLKSOURCE_HSE) + { + while (__HAL_RCC_GET_SYSCLK_SOURCE() != RCC_SYSCLKSOURCE_STATUS_HSE) + { + if((HAL_GetTick() - tickstart) >= CLOCKSWITCH_TIMEOUT_VALUE) + { + return HAL_TIMEOUT; + } + } + } + else if(RCC_ClkInitStruct->SYSCLKSource == RCC_SYSCLKSOURCE_PLLCLK) + { + while (__HAL_RCC_GET_SYSCLK_SOURCE() != RCC_SYSCLKSOURCE_STATUS_PLLCLK) + { + if((HAL_GetTick() - tickstart) >= CLOCKSWITCH_TIMEOUT_VALUE) + { + return HAL_TIMEOUT; + } + } + } +#if defined(STM32F042x6) || defined(STM32F048xx) || defined(STM32F072xB) || defined(STM32F078xx) + else if(RCC_ClkInitStruct->SYSCLKSource == RCC_SYSCLKSOURCE_HSI48) + { + while (__HAL_RCC_GET_SYSCLK_SOURCE() != RCC_SYSCLKSOURCE_STATUS_HSI48) + { + if((HAL_GetTick() - tickstart) >= CLOCKSWITCH_TIMEOUT_VALUE) + { + return HAL_TIMEOUT; + } + } + } +#endif /* STM32F042x6 || STM32F072xB || STM32F078xx */ + else + { + while(__HAL_RCC_GET_SYSCLK_SOURCE() != RCC_SYSCLKSOURCE_STATUS_HSI) + { + if((HAL_GetTick() - tickstart) >= CLOCKSWITCH_TIMEOUT_VALUE) + { + return HAL_TIMEOUT; + } + } + } + } + } + /* Decreasing the CPU frequency */ + else + { + /*-------------------------- HCLK Configuration --------------------------*/ + if(((RCC_ClkInitStruct->ClockType) & RCC_CLOCKTYPE_HCLK) == RCC_CLOCKTYPE_HCLK) + { + assert_param(IS_RCC_SYSCLK_DIV(RCC_ClkInitStruct->AHBCLKDivider)); + MODIFY_REG(RCC->CFGR, RCC_CFGR_HPRE, RCC_ClkInitStruct->AHBCLKDivider); + } + + /*------------------------- SYSCLK Configuration ---------------------------*/ + if(((RCC_ClkInitStruct->ClockType) & RCC_CLOCKTYPE_SYSCLK) == RCC_CLOCKTYPE_SYSCLK) + { + assert_param(IS_RCC_SYSCLKSOURCE(RCC_ClkInitStruct->SYSCLKSource)); + + /* HSE is selected as System Clock Source */ + if(RCC_ClkInitStruct->SYSCLKSource == RCC_SYSCLKSOURCE_HSE) + { + /* Check the HSE ready flag */ + if(__HAL_RCC_GET_FLAG(RCC_FLAG_HSERDY) == RESET) + { + return HAL_ERROR; + } + } + /* PLL is selected as System Clock Source */ + else if(RCC_ClkInitStruct->SYSCLKSource == RCC_SYSCLKSOURCE_PLLCLK) + { + /* Check the PLL ready flag */ + if(__HAL_RCC_GET_FLAG(RCC_FLAG_PLLRDY) == RESET) + { + return HAL_ERROR; + } + } +#if defined(STM32F042x6) || defined(STM32F048xx) || defined(STM32F072xB) || defined(STM32F078xx) + /* HSI48 is selected as System Clock Source */ + else if(RCC_ClkInitStruct->SYSCLKSource == RCC_SYSCLKSOURCE_HSI48) + { + /* Check the HSI48 ready flag */ + if(__HAL_RCC_GET_FLAG(RCC_FLAG_HSI48RDY) == RESET) + { + return HAL_ERROR; + } + } +#endif /* STM32F042x6 || STM32F072xB || STM32F078xx */ + /* HSI is selected as System Clock Source */ + else + { + /* Check the HSI ready flag */ + if(__HAL_RCC_GET_FLAG(RCC_FLAG_HSIRDY) == RESET) + { + return HAL_ERROR; + } + } + MODIFY_REG(RCC->CFGR, RCC_CFGR_SW, RCC_ClkInitStruct->SYSCLKSource); + + /* Get timeout */ + tickstart = HAL_GetTick(); + + if(RCC_ClkInitStruct->SYSCLKSource == RCC_SYSCLKSOURCE_HSE) + { + while (__HAL_RCC_GET_SYSCLK_SOURCE() != RCC_SYSCLKSOURCE_STATUS_HSE) + { + if((HAL_GetTick() - tickstart) >= CLOCKSWITCH_TIMEOUT_VALUE) + { + return HAL_TIMEOUT; + } + } + } + else if(RCC_ClkInitStruct->SYSCLKSource == RCC_SYSCLKSOURCE_PLLCLK) + { + while (__HAL_RCC_GET_SYSCLK_SOURCE() != RCC_SYSCLKSOURCE_STATUS_PLLCLK) + { + if((HAL_GetTick() - tickstart) >= CLOCKSWITCH_TIMEOUT_VALUE) + { + return HAL_TIMEOUT; + } + } + } +#if defined(STM32F042x6) || defined(STM32F048xx) || defined(STM32F072xB) || defined(STM32F078xx) + else if(RCC_ClkInitStruct->SYSCLKSource == RCC_SYSCLKSOURCE_HSI48) + { + while (__HAL_RCC_GET_SYSCLK_SOURCE() != RCC_SYSCLKSOURCE_STATUS_HSI48) + { + if((HAL_GetTick() - tickstart) >= CLOCKSWITCH_TIMEOUT_VALUE) + { + return HAL_TIMEOUT; + } + } + } +#endif /* STM32F042x6 || STM32F072xB || STM32F078xx */ + else + { + while(__HAL_RCC_GET_SYSCLK_SOURCE() != RCC_SYSCLKSOURCE_STATUS_HSI) + { + if((HAL_GetTick() - tickstart) >= CLOCKSWITCH_TIMEOUT_VALUE) + { + return HAL_TIMEOUT; + } + } + } + } + + /* Program the new number of wait states to the LATENCY bits in the FLASH_ACR register */ + __HAL_FLASH_SET_LATENCY(FLatency); + + /* Check that the new number of wait states is taken into account to access the Flash + memory by reading the FLASH_ACR register */ + if((FLASH->ACR & FLASH_ACR_LATENCY) != FLatency) + { + return HAL_ERROR; + } + } + + /*-------------------------- PCLK1 Configuration ---------------------------*/ + if(((RCC_ClkInitStruct->ClockType) & RCC_CLOCKTYPE_PCLK1) == RCC_CLOCKTYPE_PCLK1) + { + assert_param(IS_RCC_HCLK_DIV(RCC_ClkInitStruct->APB1CLKDivider)); + MODIFY_REG(RCC->CFGR, RCC_CFGR_PPRE, RCC_ClkInitStruct->APB1CLKDivider); + } + + /* Configure the source of time base considering new system clocks settings*/ + HAL_InitTick (TICK_INT_PRIORITY); + + return HAL_OK; +} + +/** + * @brief Returns the SYSCLK frequency + * @note The system frequency computed by this function is not the real + * frequency in the chip. It is calculated based on the predefined + * constant and the selected clock source: + * @note If SYSCLK source is HSI, function returns a value based on HSI_VALUE(*) + * @note If SYSCLK source is HSI48, function returns a value based on HSI48_VALUE(*) + * @note If SYSCLK source is HSE, function returns a value based on HSE_VALUE + * divided by PREDIV factor(**) + * @note If SYSCLK source is PLL, function returns a value based on HSE_VALUE + * divided by PREDIV factor(**) or depending on STM32F0xx devices either a value based + * on HSI_VALUE divided by 2 or HSI_VALUE divided by PREDIV factor(*) multiplied by the + * PLL factor . + * @note (*) HSI_VALUE & HSI48_VALUE are constants defined in stm32f0xx_hal_conf.h file + * (default values 8 MHz and 48MHz). + * @note (**) HSE_VALUE is a constant defined in stm32f0xx_hal_conf.h file (default value + * 8 MHz), user has to ensure that HSE_VALUE is same as the real + * frequency of the crystal used. Otherwise, this function may + * have wrong result. + * + * @note The result of this function could be not correct when using fractional + * value for HSE crystal. + * + * @note This function can be used by the user application to compute the + * baudrate for the communication peripherals or configure other parameters. + * + * @note Each time SYSCLK changes, this function must be called to update the + * right SYSCLK value. Otherwise, any configuration based on this function will be incorrect. + * + * @param None + * @retval SYSCLK frequency + */ +uint32_t HAL_RCC_GetSysClockFreq(void) +{ + uint32_t tmpreg = 0, prediv = 0, pllmul = 0, pllclk = 0; + uint32_t sysclockfreq = 0; + + tmpreg = RCC->CFGR; + + /* Get SYSCLK source -------------------------------------------------------*/ + switch (tmpreg & RCC_CFGR_SWS) + { + case RCC_SYSCLKSOURCE_STATUS_HSE: /* HSE used as system clock source */ + sysclockfreq = HSE_VALUE; + break; + + case RCC_SYSCLKSOURCE_STATUS_PLLCLK: /* PLL used as system clock source */ + pllmul = PLLMULFactorTable[(uint32_t)(tmpreg & RCC_CFGR_PLLMUL) >> RCC_CFGR_PLLMUL_BITNUMBER]; + prediv = PredivFactorTable[(uint32_t)(RCC->CFGR2 & RCC_CFGR2_PREDIV) >> RCC_CFGR2_PREDIV_BITNUMBER]; + if ((tmpreg & RCC_CFGR_PLLSRC) == RCC_PLLSOURCE_HSE) + { + /* HSE used as PLL clock source : PLLCLK = HSE/PREDIV * PLLMUL */ + pllclk = (HSE_VALUE/prediv) * pllmul; + } +#if defined(STM32F042x6) || defined(STM32F048xx) || defined(STM32F072xB) || defined(STM32F078xx) + else if ((tmpreg & RCC_CFGR_PLLSRC) == RCC_PLLSOURCE_HSI48) + { + /* HSI48 used as PLL clock source : PLLCLK = HSI48/PREDIV * PLLMUL */ + pllclk = (HSI48_VALUE/prediv) * pllmul; + } +#endif /* STM32F042x6 || STM32F048xx || STM32F072xB || STM32F078xx */ + else + { +#if defined(STM32F042x6) || defined(STM32F048xx) || \ + defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) + /* HSI used as PLL clock source : PLLCLK = HSI/PREDIV * PLLMUL */ + pllclk = (HSI_VALUE/prediv) * pllmul; +#else + /* HSI used as PLL clock source : PLLCLK = HSI/2 * PLLMUL */ + pllclk = (HSI_VALUE >> 1) * pllmul; +#endif /* STM32F042x6 || STM32F048xx || STM32F071xB || STM32F072xB || STM32F078xx */ + } + sysclockfreq = pllclk; + break; + +#if defined(STM32F042x6) || defined(STM32F048xx) || defined(STM32F072xB) || defined(STM32F078xx) + case RCC_SYSCLKSOURCE_STATUS_HSI48: /* HSI48 used as system clock source */ + sysclockfreq = HSI48_VALUE; + break; +#endif /* STM32F042x6 || STM32F072xB || STM32F078xx */ + + case RCC_SYSCLKSOURCE_STATUS_HSI: /* HSI used as system clock source */ + default: + sysclockfreq = HSI_VALUE; + break; + } + return sysclockfreq; +} + +/** + * @brief Initializes the RCC extended peripherals clocks according to the specified + * parameters in the RCC_PeriphCLKInitTypeDef. + * @param PeriphClkInit: pointer to an RCC_PeriphCLKInitTypeDef structure that + * contains the configuration information for the Extended Peripherals clocks + * (USART, RTC, I2C, CEC and USB). + * + * @note Care must be taken when HAL_RCCEx_PeriphCLKConfig() is used to select + * the RTC clock source; in this case the Backup domain will be reset in + * order to modify the RTC Clock source, as consequence RTC registers (including + * the backup registers) and RCC_BDCR register are set to their reset values. + * + * @retval None + */ +HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClkInit) +{ + uint32_t tickstart = 0; + uint32_t tmpreg = 0; + + /* Check the parameters */ + assert_param(IS_RCC_PERIPHCLK(PeriphClkInit->PeriphClockSelection)); + + /*---------------------------- RTC configuration -------------------------------*/ + if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_RTC) == (RCC_PERIPHCLK_RTC)) + { + /* Enable Power Clock*/ + __PWR_CLK_ENABLE(); + + /* Enable write access to Backup domain */ + SET_BIT(PWR->CR, PWR_CR_DBP); + + /* Wait for Backup domain Write protection disable */ + tickstart = HAL_GetTick(); + + while((PWR->CR & PWR_CR_DBP) == RESET) + { + if((HAL_GetTick() - tickstart) >= DBP_TIMEOUT_VALUE) + { + return HAL_TIMEOUT; + } + } + + /* Reset the Backup domain only if the RTC Clock source selction is modified */ + if((RCC->BDCR & RCC_BDCR_RTCSEL) != (PeriphClkInit->RTCClockSelection & RCC_BDCR_RTCSEL)) + { + /* Store the content of BDCR register before the reset of Backup Domain */ + tmpreg = (RCC->BDCR & ~(RCC_BDCR_RTCSEL)); + /* RTC Clock selection can be changed only if the Backup Domain is reset */ + __HAL_RCC_BACKUPRESET_FORCE(); + __HAL_RCC_BACKUPRESET_RELEASE(); + /* Restore the Content of BDCR register */ + RCC->BDCR = tmpreg; + } + + /* If LSE is selected as RTC clock source, wait for LSE reactivation */ + if(PeriphClkInit->RTCClockSelection == RCC_RTCCLKSOURCE_LSE) + { + /* Get timeout */ + tickstart = HAL_GetTick() ; + + /* Wait till LSE is ready */ + while(__HAL_RCC_GET_FLAG(RCC_FLAG_LSERDY) == RESET) + { + if((HAL_GetTick() - tickstart) >= LSE_TIMEOUT_VALUE) + { + return HAL_TIMEOUT; + } + } + } + __HAL_RCC_RTC_CONFIG(PeriphClkInit->RTCClockSelection); + } + + /*------------------------------- USART1 Configuration ------------------------*/ + if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_USART1) == RCC_PERIPHCLK_USART1) + { + /* Check the parameters */ + assert_param(IS_RCC_USART1CLKSOURCE(PeriphClkInit->Usart1ClockSelection)); + + /* Configure the USART1 clock source */ + __HAL_RCC_USART1_CONFIG(PeriphClkInit->Usart1ClockSelection); + } + +#if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) + /*----------------------------- USART2 Configuration --------------------------*/ + if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_USART2) == RCC_PERIPHCLK_USART2) + { + /* Check the parameters */ + assert_param(IS_RCC_USART2CLKSOURCE(PeriphClkInit->Usart2ClockSelection)); + + /* Configure the USART2 clock source */ + __HAL_RCC_USART2_CONFIG(PeriphClkInit->Usart2ClockSelection); + } +#endif /* STM32F071xB || STM32F072xB || STM32F078xx */ + + /*------------------------------ I2C1 Configuration ------------------------*/ + if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_I2C1) == RCC_PERIPHCLK_I2C1) + { + /* Check the parameters */ + assert_param(IS_RCC_I2C1CLKSOURCE(PeriphClkInit->I2c1ClockSelection)); + + /* Configure the I2C1 clock source */ + __HAL_RCC_I2C1_CONFIG(PeriphClkInit->I2c1ClockSelection); + } + +#if defined(STM32F042x6) || defined(STM32F048xx) || defined(STM32F072xB) + /*------------------------------ USB Configuration ------------------------*/ + if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_USB) == RCC_PERIPHCLK_USB) + { + /* Check the parameters */ + assert_param(IS_RCC_USBCLKSOURCE(PeriphClkInit->UsbClockSelection)); + + /* Configure the USB clock source */ + __HAL_RCC_USB_CONFIG(PeriphClkInit->UsbClockSelection); + } +#endif /* STM32F042x6 || STM32F072xB */ + +#if defined(STM32F042x6) || defined(STM32F048xx) || \ + defined(STM32F051x8) || defined(STM32F058xx) || \ + defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) + /*------------------------------ CEC clock Configuration -------------------*/ + if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_CEC) == RCC_PERIPHCLK_CEC) + { + /* Check the parameters */ + assert_param(IS_RCC_CECCLKSOURCE(PeriphClkInit->CecClockSelection)); + + /* Configure the CEC clock source */ + __HAL_RCC_CEC_CONFIG(PeriphClkInit->CecClockSelection); + } +#endif /* STM32F042x6 || */ + /* STM32F051x8 || STM32F058xx || */ + /* STM32F071xB || STM32F072xB || STM32F078xx */ + + return HAL_OK; +} + +/** + * @brief Get the RCC_ClkInitStruct according to the internal + * RCC configuration registers. + * @param PeriphClkInit: pointer to an RCC_PeriphCLKInitTypeDef structure that + * returns the configuration information for the Extended Peripherals clocks + * (USART, RTC, I2C, CEC and USB). + * @retval None + */ +void HAL_RCCEx_GetPeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClkInit) +{ + /* Set all possible values for the extended clock type parameter------------*/ + /* Common part first */ + PeriphClkInit->PeriphClockSelection = RCC_PERIPHCLK_USART1 | RCC_PERIPHCLK_I2C1 | RCC_PERIPHCLK_RTC; + /* Get the RTC configuration --------------------------------------------*/ + PeriphClkInit->RTCClockSelection = __HAL_RCC_GET_RTC_SOURCE(); + /* Get the USART1 configuration --------------------------------------------*/ + PeriphClkInit->Usart1ClockSelection = __HAL_RCC_GET_USART1_SOURCE(); + /* Get the I2C1 clock source -----------------------------------------------*/ + PeriphClkInit->I2c1ClockSelection = __HAL_RCC_GET_I2C1_SOURCE(); + +#if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) + PeriphClkInit->PeriphClockSelection |= RCC_PERIPHCLK_USART2; + /* Get the USART2 clock source ---------------------------------------------*/ + PeriphClkInit->Usart2ClockSelection = __HAL_RCC_GET_USART2_SOURCE(); +#endif /* STM32F071xB || STM32F072xB || STM32F078xx */ + +#if defined(STM32F042x6) || defined(STM32F048xx) || defined(STM32F072xB) + PeriphClkInit->PeriphClockSelection |= RCC_PERIPHCLK_USB; + /* Get the USB clock source ---------------------------------------------*/ + PeriphClkInit->UsbClockSelection = __HAL_RCC_GET_USB_SOURCE(); +#endif /* STM32F042x6 || STM32F072xB */ + +#if defined(STM32F042x6) || defined(STM32F048xx) || \ + defined(STM32F051x8) || defined(STM32F058xx) || \ + defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) + PeriphClkInit->PeriphClockSelection |= RCC_PERIPHCLK_CEC; + /* Get the CEC clock source ------------------------------------------------*/ + PeriphClkInit->CecClockSelection = __HAL_RCC_GET_CEC_SOURCE(); +#endif /* STM32F042x6 || */ + /* STM32F051x8 || STM32F058xx || */ + /* STM32F071xB || STM32F072xB || STM32F078xx */ + +} + +#if defined(STM32F042x6) || defined(STM32F048xx) || \ + defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) +/** + * @brief Start automatic synchronization using polling mode + * @param pInit Pointer on RCC_CRSInitTypeDef structure + * @retval None + */ +void HAL_RCCEx_CRSConfig(RCC_CRSInitTypeDef *pInit) +{ + /* Check the parameters */ + assert_param(IS_RCC_CRS_SYNC_DIV(pInit->Prescaler)); + assert_param(IS_RCC_CRS_SYNC_SOURCE(pInit->Source)); + assert_param(IS_RCC_CRS_SYNC_POLARITY(pInit->Polarity)); + assert_param(IS_RCC_CRS_RELOADVALUE(pInit->ReloadValue)); + assert_param(IS_RCC_CRS_ERRORLIMIT(pInit->ErrorLimitValue)); + assert_param(IS_RCC_CRS_HSI48CALIBRATION(pInit->HSI48CalibrationValue)); + + + /* CONFIGURATION */ + + /* Before configuration, reset CRS registers to their default values*/ + __CRS_FORCE_RESET(); + __CRS_RELEASE_RESET(); + + /* Configure Synchronization input */ + /* Clear SYNCDIV[2:0], SYNCSRC[1:0] & SYNCSPOL bits */ + CRS->CFGR &= ~(CRS_CFGR_SYNCDIV | CRS_CFGR_SYNCSRC | CRS_CFGR_SYNCPOL); + + /* Set the CRS_CFGR_SYNCDIV[2:0] bits according to Prescaler value */ + CRS->CFGR |= pInit->Prescaler; + + /* Set the SYNCSRC[1:0] bits according to Source value */ + CRS->CFGR |= pInit->Source; + + /* Set the SYNCSPOL bits according to Polarity value */ + CRS->CFGR |= pInit->Polarity; + + /* Configure Frequency Error Measurement */ + /* Clear RELOAD[15:0] & FELIM[7:0] bits*/ + CRS->CFGR &= ~(CRS_CFGR_RELOAD | CRS_CFGR_FELIM); + + /* Set the RELOAD[15:0] bits according to ReloadValue value */ + CRS->CFGR |= pInit->ReloadValue; + + /* Set the FELIM[7:0] bits according to ErrorLimitValue value */ + CRS->CFGR |= (pInit->ErrorLimitValue << CRS_CFGR_FELIM_BITNUMBER); + + /* Adjust HSI48 oscillator smooth trimming */ + /* Clear TRIM[5:0] bits */ + CRS->CR &= ~CRS_CR_TRIM; + + /* Set the TRIM[5:0] bits according to RCC_CRS_HSI48CalibrationValue value */ + CRS->CR |= (pInit->HSI48CalibrationValue << CRS_CR_TRIM_BITNUMBER); + + + /* START AUTOMATIC SYNCHRONIZATION*/ + + /* Enable Automatic trimming */ + __HAL_RCC_CRS_ENABLE_AUTOMATIC_CALIB(); + + /* Enable Frequency error counter */ + __HAL_RCC_CRS_ENABLE_FREQ_ERROR_COUNTER(); + +} + +/** + * @brief Generate the software synchronization event + * @param None + * @retval None + */ +void HAL_RCCEx_CRSSoftwareSynchronizationGenerate(void) +{ + CRS->CR |= CRS_CR_SWSYNC; +} + + +/** + * @brief Function to return synchronization info + * @param pSynchroInfo Pointer on RCC_CRSSynchroInfoTypeDef structure + * @retval None + */ +void HAL_RCCEx_CRSGetSynchronizationInfo(RCC_CRSSynchroInfoTypeDef *pSynchroInfo) +{ + /* Check the parameter */ + assert_param(pSynchroInfo != NULL); + + /* Get the reload value */ + pSynchroInfo->ReloadValue = (uint32_t)(CRS->CFGR & CRS_CFGR_RELOAD); + + /* Get HSI48 oscillator smooth trimming */ + pSynchroInfo->HSI48CalibrationValue = (uint32_t)((CRS->CR & CRS_CR_TRIM) >> CRS_CR_TRIM_BITNUMBER); + + /* Get Frequency error capture */ + pSynchroInfo->FreqErrorCapture = (uint32_t)((CRS->ISR & CRS_ISR_FECAP) >> CRS_ISR_FECAP_BITNUMBER); + + /* Get FFrequency error direction */ + pSynchroInfo->FreqErrorDirection = (uint32_t)(CRS->ISR & CRS_ISR_FEDIR); + + +} + +/** +* @brief This function handles CRS Synchronization Timeout. +* @param Timeout: Duration of the timeout +* @note Timeout is based on the maximum time to receive a SYNC event based on synchronization +* frequency. +* @note If Timeout set to HAL_MAX_DELAY, HAL_TIMEOUT will be never returned. +* @retval Combination of Synchronization status +* This parameter can be a combination of the following values: +* @arg RCC_CRS_TIMEOUT +* @arg RCC_CRS_SYNCOK +* @arg RCC_CRS_SYNCWARM +* @arg RCC_CRS_SYNCERR +* @arg RCC_CRS_SYNCMISS +* @arg RCC_CRS_TRIMOV +*/ +RCC_CRSStatusTypeDef HAL_RCCEx_CRSWaitSynchronization(uint32_t Timeout) +{ + RCC_CRSStatusTypeDef crsstatus = RCC_CRS_NONE; + uint32_t tickstart = 0; + + /* Get timeout */ + tickstart = HAL_GetTick(); + + /* Check that if one of CRS flags have been set */ + while(RCC_CRS_NONE == crsstatus) + { + if(Timeout != HAL_MAX_DELAY) + { + if((HAL_GetTick() - tickstart ) >= Timeout) + { + crsstatus = RCC_CRS_TIMEOUT; + } + } + /* Check CRS SYNCOK flag */ + if(__HAL_RCC_CRS_GET_FLAG(RCC_CRS_FLAG_SYNCOK)) + { + /* CRS SYNC event OK */ + crsstatus |= RCC_CRS_SYNCOK; + + /* Clear CRS SYNC event OK bit */ + __HAL_RCC_CRS_CLEAR_FLAG(RCC_CRS_FLAG_SYNCOK); + } + + /* Check CRS SYNCWARN flag */ + if(__HAL_RCC_CRS_GET_FLAG(RCC_CRS_FLAG_SYNCWARN)) + { + /* CRS SYNC warning */ + crsstatus |= RCC_CRS_SYNCWARM; + + /* Clear CRS SYNCWARN bit */ + __HAL_RCC_CRS_CLEAR_FLAG(RCC_CRS_FLAG_SYNCWARN); + } + + /* Check CRS TRIM overflow flag */ + if(__HAL_RCC_CRS_GET_FLAG(RCC_CRS_FLAG_TRIMOVF)) + { + /* CRS SYNC Error */ + crsstatus |= RCC_CRS_TRIMOV; + + /* Clear CRS Error bit */ + __HAL_RCC_CRS_CLEAR_FLAG(RCC_CRS_FLAG_TRIMOVF); + } + + /* Check CRS Error flag */ + if(__HAL_RCC_CRS_GET_FLAG(RCC_CRS_FLAG_SYNCERR)) + { + /* CRS SYNC Error */ + crsstatus |= RCC_CRS_SYNCERR; + + /* Clear CRS Error bit */ + __HAL_RCC_CRS_CLEAR_FLAG(RCC_CRS_FLAG_SYNCERR); + } + + /* Check CRS SYNC Missed flag */ + if(__HAL_RCC_CRS_GET_FLAG(RCC_CRS_FLAG_SYNCMISS)) + { + /* CRS SYNC Missed */ + crsstatus |= RCC_CRS_SYNCMISS; + + /* Clear CRS SYNC Missed bit */ + __HAL_RCC_CRS_CLEAR_FLAG(RCC_CRS_FLAG_SYNCMISS); + } + + /* Check CRS Expected SYNC flag */ + if(__HAL_RCC_CRS_GET_FLAG(RCC_CRS_FLAG_ESYNC)) + { + /* frequency error counter reached a zero value */ + __HAL_RCC_CRS_CLEAR_FLAG(RCC_CRS_FLAG_ESYNC); + } + } + + return crsstatus; +} + +#endif /* STM32F042x6 || */ + /* STM32F071xB || STM32F072xB || STM32F078xx */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* HAL_RCC_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_rcc_ex.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_rcc_ex.h new file mode 100644 index 0000000000..6ae1920de9 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_rcc_ex.h @@ -0,0 +1,1375 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_rcc_ex.h + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief Header file of RCC HAL Extension module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32F0xx_HAL_RCC_EX_H +#define __STM32F0xx_HAL_RCC_EX_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal_def.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @addtogroup RCCEx + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ + +/** + * @brief RCC extended clocks structure definition + */ +#if defined(STM32F030x6) || defined(STM32F030x8) || defined(STM32F031x6) || defined(STM32F038xx) +typedef struct +{ + uint32_t PeriphClockSelection; /*!< The Extended Clock to be configured. + This parameter can be a value of @ref RCCEx_Periph_Clock_Selection */ + + uint32_t RTCClockSelection; /*!< Specifies RTC Clock Prescalers Selection + This parameter can be a value of @ref RCC_RTC_Clock_Source */ + + uint32_t Usart1ClockSelection; /*!< USART1 clock source + This parameter can be a value of @ref RCC_USART1_Clock_Source */ + + uint32_t I2c1ClockSelection; /*!< I2C1 clock source + This parameter can be a value of @ref RCC_I2C1_Clock_Source */ + +}RCC_PeriphCLKInitTypeDef; +#endif /* STM32F030x6 || STM32F030x8 || STM32F031x6 || STM32F038xx */ + +#if defined(STM32F042x6) || defined(STM32F048xx) +typedef struct +{ + uint32_t PeriphClockSelection; /*!< The Extended Clock to be configured. + This parameter can be a value of @ref RCCEx_Periph_Clock_Selection */ + + uint32_t RTCClockSelection; /*!< Specifies RTC Clock Prescalers Selection + This parameter can be a value of @ref RCC_RTC_Clock_Source */ + + uint32_t Usart1ClockSelection; /*!< USART1 clock source + This parameter can be a value of @ref RCC_USART1_Clock_Source */ + + uint32_t I2c1ClockSelection; /*!< I2C1 clock source + This parameter can be a value of @ref RCC_I2C1_Clock_Source */ + + uint32_t CecClockSelection; /*!< HDMI CEC clock source + This parameter can be a value of @ref RCCEx_CEC_Clock_Source */ + + uint32_t UsbClockSelection; /*!< USB clock source + This parameter can be a value of @ref RCCEx_USB_Clock_Source */ + +}RCC_PeriphCLKInitTypeDef; +#endif /* STM32F042x6 || STM32F048xx */ + +#if defined(STM32F051x8) || defined(STM32F058xx) +typedef struct +{ + uint32_t PeriphClockSelection; /*!< The Extended Clock to be configured. + This parameter can be a value of @ref RCCEx_Periph_Clock_Selection */ + + uint32_t RTCClockSelection; /*!< Specifies RTC Clock Prescalers Selection + This parameter can be a value of @ref RCC_RTC_Clock_Source */ + + uint32_t Usart1ClockSelection; /*!< USART1 clock source + This parameter can be a value of @ref RCC_USART1_Clock_Source */ + + uint32_t I2c1ClockSelection; /*!< I2C1 clock source + This parameter can be a value of @ref RCC_I2C1_Clock_Source */ + + uint32_t CecClockSelection; /*!< HDMI CEC clock source + This parameter can be a value of @ref RCCEx_CEC_Clock_Source */ + +}RCC_PeriphCLKInitTypeDef; +#endif /* STM32F051x8 || STM32F058xx */ + +#if defined(STM32F071xB) +typedef struct +{ + uint32_t PeriphClockSelection; /*!< The Extended Clock to be configured. + This parameter can be a value of @ref RCCEx_Periph_Clock_Selection */ + + uint32_t RTCClockSelection; /*!< Specifies RTC Clock Prescalers Selection + This parameter can be a value of @ref RCC_RTC_Clock_Source */ + + uint32_t Usart1ClockSelection; /*!< USART1 clock source + This parameter can be a value of @ref RCC_USART1_Clock_Source */ + + uint32_t Usart2ClockSelection; /*!< USART2 clock source + This parameter can be a value of @ref RCCEx_USART2_Clock_Source */ + + uint32_t I2c1ClockSelection; /*!< I2C1 clock source + This parameter can be a value of @ref RCC_I2C1_Clock_Source */ + + uint32_t CecClockSelection; /*!< HDMI CEC clock source + This parameter can be a value of @ref RCCEx_CEC_Clock_Source */ + +}RCC_PeriphCLKInitTypeDef; +#endif /* STM32F071xB */ + +#if defined(STM32F072xB) +typedef struct +{ + uint32_t PeriphClockSelection; /*!< The Extended Clock to be configured. + This parameter can be a value of @ref RCCEx_Periph_Clock_Selection */ + + uint32_t RTCClockSelection; /*!< Specifies RTC Clock Prescalers Selection + This parameter can be a value of @ref RCC_RTC_Clock_Source */ + + uint32_t Usart1ClockSelection; /*!< USART1 clock source + This parameter can be a value of @ref RCC_USART1_Clock_Source */ + + uint32_t Usart2ClockSelection; /*!< USART2 clock source + This parameter can be a value of @ref RCCEx_USART2_Clock_Source */ + + uint32_t I2c1ClockSelection; /*!< I2C1 clock source + This parameter can be a value of @ref RCC_I2C1_Clock_Source */ + + uint32_t CecClockSelection; /*!< HDMI CEC clock source + This parameter can be a value of @ref RCCEx_CEC_Clock_Source */ + + uint32_t UsbClockSelection; /*!< USB clock source + This parameter can be a value of @ref RCCEx_USB_Clock_Source */ + +}RCC_PeriphCLKInitTypeDef; +#endif /* STM32F072xB */ + +#if defined(STM32F078xx) +typedef struct +{ + uint32_t PeriphClockSelection; /*!< The Extended Clock to be configured. + This parameter can be a value of @ref RCCEx_Periph_Clock_Selection */ + + uint32_t RTCClockSelection; /*!< Specifies RTC Clock Prescalers Selection + This parameter can be a value of @ref RCC_RTC_Clock_Source */ + + uint32_t Usart1ClockSelection; /*!< USART1 clock source + This parameter can be a value of @ref RCC_USART1_Clock_Source */ + + uint32_t Usart2ClockSelection; /*!< USART2 clock source + This parameter can be a value of @ref RCCEx_USART2_Clock_Source */ + + uint32_t I2c1ClockSelection; /*!< I2C1 clock source + This parameter can be a value of @ref RCC_I2C1_Clock_Source */ + + uint32_t CecClockSelection; /*!< HDMI CEC clock source + This parameter can be a value of @ref RCCEx_CEC_Clock_Source */ + +}RCC_PeriphCLKInitTypeDef; +#endif /* STM32F078xx */ + + +#if defined(STM32F042x6) || defined(STM32F048xx) || \ + defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) +/** + * @brief RCC CRS Status structures definition + */ +typedef enum +{ + RCC_CRS_NONE = 0x00, + RCC_CRS_TIMEOUT = 0x01, + RCC_CRS_SYNCOK = 0x02, + RCC_CRS_SYNCWARM = 0x04, + RCC_CRS_SYNCERR = 0x08, + RCC_CRS_SYNCMISS = 0x10, + RCC_CRS_TRIMOV = 0x20 +} RCC_CRSStatusTypeDef; + +/** + * @brief RCC_CRS Init structure definition + */ +typedef struct +{ + uint32_t Prescaler; /*!< Specifies the division factor of the SYNC signal. + This parameter can be a value of @ref RCCEx_CRS_SynchroDivider */ + + uint32_t Source; /*!< Specifies the SYNC signal source. + This parameter can be a value of @ref RCCEx_CRS_SynchroSource */ + + uint32_t Polarity; /*!< Specifies the input polarity for the SYNC signal source. + This parameter can be a value of @ref RCCEx_CRS_SynchroPolarity */ + + uint32_t ReloadValue; /*!< Specifies the value to be loaded in the frequency error counter with each SYNC event. + It can be calculated in using macro __HAL_RCC_CRS_CALCULATE_RELOADVALUE(_FTARGET_, _FSYNC_) + This parameter must be a number between 0 and 0xFFFF or a value of @ref RCCEx_CRS_ReloadValueDefault .*/ + + uint32_t ErrorLimitValue; /*!< Specifies the value to be used to evaluate the captured frequency error value. + This parameter must be a number between 0 and 0xFF or a value of @ref RCCEx_CRS_ErrorLimitDefault */ + + uint32_t HSI48CalibrationValue; /*!< Specifies a user-programmable trimming value to the HSI48 oscillator. + This parameter must be a number between 0 and 0x3F or a value of @ref RCCEx_CRS_HSI48CalibrationDefault */ + +}RCC_CRSInitTypeDef; + +/** + * @brief RCC_CRS Synchronization structure definition + */ +typedef struct +{ + uint32_t ReloadValue; /*!< Specifies the value loaded in the Counter reload value. + This parameter must be a number between 0 and 0xFFFF*/ + + uint32_t HSI48CalibrationValue; /*!< Specifies value loaded in HSI48 oscillator smooth trimming. + This parameter must be a number between 0 and 0x3F */ + + uint32_t FreqErrorCapture; /*!< Specifies the value loaded in the .FECAP, the frequency error counter + value latched in the time of the last SYNC event. + This parameter must be a number between 0 and 0xFFFF */ + + uint32_t FreqErrorDirection; /*!< Specifies the value loaded in the .FEDIR, the counting direction of the + frequency error counter latched in the time of the last SYNC event. + It shows whether the actual frequency is below or above the target. + This parameter must be a value of @ref RCCEx_CRS_FreqErrorDirection*/ + +}RCC_CRSSynchroInfoTypeDef; + +#endif /* STM32F042x6 || */ + /* STM32F071xB || STM32F072xB || STM32F078xx */ + +/* Exported constants --------------------------------------------------------*/ +/** @defgroup RCCEx_Exported_Constants + * @{ + */ + +/** @defgroup RCCEx_Periph_Clock_Selection + * @{ + */ +#if defined(STM32F030x6) || defined(STM32F030x8) || defined(STM32F031x6) || defined(STM32F038xx) +#define RCC_PERIPHCLK_USART1 ((uint32_t)0x00000001) +#define RCC_PERIPHCLK_I2C1 ((uint32_t)0x00000020) +#define RCC_PERIPHCLK_RTC ((uint32_t)0x00010000) + +#define IS_RCC_PERIPHCLK(SELECTION) ((SELECTION) <= (RCC_PERIPHCLK_USART1 | RCC_PERIPHCLK_I2C1 | \ + RCC_PERIPHCLK_RTC)) +#endif /* STM32F030x6 || STM32F030x8 || STM32F031x6 */ + +#if defined(STM32F051x8) || defined(STM32F058xx) +#define RCC_PERIPHCLK_USART1 ((uint32_t)0x00000001) +#define RCC_PERIPHCLK_I2C1 ((uint32_t)0x00000020) +#define RCC_PERIPHCLK_CEC ((uint32_t)0x00000400) +#define RCC_PERIPHCLK_RTC ((uint32_t)0x00010000) + +#define IS_RCC_PERIPHCLK(SELECTION) ((SELECTION) <= (RCC_PERIPHCLK_USART1 | RCC_PERIPHCLK_I2C1 | \ + RCC_PERIPHCLK_CEC | RCC_PERIPHCLK_RTC)) +#endif /* STM32F051x8 || STM32F058xx */ + +#if defined(STM32F071xB) +#define RCC_PERIPHCLK_USART1 ((uint32_t)0x00000001) +#define RCC_PERIPHCLK_USART2 ((uint32_t)0x00000002) +#define RCC_PERIPHCLK_I2C1 ((uint32_t)0x00000020) +#define RCC_PERIPHCLK_CEC ((uint32_t)0x00000400) +#define RCC_PERIPHCLK_RTC ((uint32_t)0x00010000) + +#define IS_RCC_PERIPHCLK(SELECTION) ((SELECTION) <= (RCC_PERIPHCLK_USART1 | RCC_PERIPHCLK_USART2 | \ + RCC_PERIPHCLK_I2C1 | RCC_PERIPHCLK_CEC | \ + RCC_PERIPHCLK_RTC)) +#endif /* STM32F071xB */ + +#if defined(STM32F042x6) || defined(STM32F048xx) +#define RCC_PERIPHCLK_USART1 ((uint32_t)0x00000001) +#define RCC_PERIPHCLK_I2C1 ((uint32_t)0x00000020) +#define RCC_PERIPHCLK_CEC ((uint32_t)0x00000400) +#define RCC_PERIPHCLK_RTC ((uint32_t)0x00010000) +#define RCC_PERIPHCLK_USB ((uint32_t)0x00020000) + +#define IS_RCC_PERIPHCLK(SELECTION) ((SELECTION) <= (RCC_PERIPHCLK_USART1 | RCC_PERIPHCLK_I2C1 | \ + RCC_PERIPHCLK_CEC | RCC_PERIPHCLK_RTC | \ + RCC_PERIPHCLK_USB)) +#endif /* STM32F042x6 || STM32F048xx */ + +#if defined(STM32F072xB) +#define RCC_PERIPHCLK_USART1 ((uint32_t)0x00000001) +#define RCC_PERIPHCLK_USART2 ((uint32_t)0x00000002) +#define RCC_PERIPHCLK_I2C1 ((uint32_t)0x00000020) +#define RCC_PERIPHCLK_CEC ((uint32_t)0x00000400) +#define RCC_PERIPHCLK_RTC ((uint32_t)0x00010000) +#define RCC_PERIPHCLK_USB ((uint32_t)0x00020000) + +#define IS_RCC_PERIPHCLK(SELECTION) ((SELECTION) <= (RCC_PERIPHCLK_USART1 | RCC_PERIPHCLK_USART2 | \ + RCC_PERIPHCLK_I2C1 | RCC_PERIPHCLK_CEC | \ + RCC_PERIPHCLK_RTC | RCC_PERIPHCLK_USB)) +#endif /* STM32F072xB */ + +#if defined(STM32F078xx) +#define RCC_PERIPHCLK_USART1 ((uint32_t)0x00000001) +#define RCC_PERIPHCLK_USART2 ((uint32_t)0x00000002) +#define RCC_PERIPHCLK_I2C1 ((uint32_t)0x00000020) +#define RCC_PERIPHCLK_CEC ((uint32_t)0x00000400) +#define RCC_PERIPHCLK_RTC ((uint32_t)0x00010000) + +#define IS_RCC_PERIPHCLK(SELECTION) ((SELECTION) <= (RCC_PERIPHCLK_USART1 | RCC_PERIPHCLK_USART2 | \ + RCC_PERIPHCLK_I2C1 | RCC_PERIPHCLK_CEC | \ + RCC_PERIPHCLK_RTC)) +#endif /* STM32F078xx */ + +/** + * @} + */ + +#if defined(STM32F030x6) || defined(STM32F031x6) || defined(STM32F038xx) + +/** @defgroup RCCEx_MCO_Clock_Source + * @{ + */ +#define RCC_MCOSOURCE_PLLCLK_NODIV (RCC_CFGR_MCO_PLL | RCC_CFGR_PLLNODIV) + +#define IS_RCC_MCOSOURCE(SOURCE) (((SOURCE) == RCC_MCOSOURCE_NONE) || \ + ((SOURCE) == RCC_MCOSOURCE_LSI) || \ + ((SOURCE) == RCC_MCOSOURCE_LSE) || \ + ((SOURCE) == RCC_MCOSOURCE_SYSCLK) || \ + ((SOURCE) == RCC_MCOSOURCE_HSI) || \ + ((SOURCE) == RCC_MCOSOURCE_HSE) || \ + ((SOURCE) == RCC_MCOSOURCE_PLLCLK_NODIV) || \ + ((SOURCE) == RCC_MCOSOURCE_PLLCLK_DIV2) || \ + ((SOURCE) == RCC_MCOSOURCE_HSI14)) +/** + * @} + */ + +#endif /* STM32F030x6 || STM32F031x6 || STM32F038xx */ + +#if defined(STM32F030x8) || defined(STM32F051x8) || defined(STM32F058xx) + +/** @defgroup RCCEx_MCO_Clock_Source + * @{ + */ +#define IS_RCC_MCOSOURCE(SOURCE) (((SOURCE) == RCC_MCOSOURCE_NONE) || \ + ((SOURCE) == RCC_MCOSOURCE_LSI) || \ + ((SOURCE) == RCC_MCOSOURCE_LSE) || \ + ((SOURCE) == RCC_MCOSOURCE_SYSCLK) || \ + ((SOURCE) == RCC_MCOSOURCE_HSI) || \ + ((SOURCE) == RCC_MCOSOURCE_HSE) || \ + ((SOURCE) == RCC_MCOSOURCE_PLLCLK_DIV2) || \ + ((SOURCE) == RCC_MCOSOURCE_HSI14)) +/** + * @} + */ + +#endif /* STM32F030x8 || STM32F051x8 || STM32F058xx */ + +#if defined(STM32F042x6) || defined(STM32F048xx) || \ + defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) +/** @defgroup RCCEx_MCO_Clock_Source + * @{ + */ +#define RCC_MCOSOURCE_HSI48 RCC_CFGR_MCO_HSI48 +#define RCC_MCOSOURCE_PLLCLK_NODIV (RCC_CFGR_MCO_PLL | RCC_CFGR_PLLNODIV) + +#define IS_RCC_MCOSOURCE(SOURCE) (((SOURCE) == RCC_MCOSOURCE_NONE) || \ + ((SOURCE) == RCC_MCOSOURCE_LSI) || \ + ((SOURCE) == RCC_MCOSOURCE_LSE) || \ + ((SOURCE) == RCC_MCOSOURCE_SYSCLK) || \ + ((SOURCE) == RCC_MCOSOURCE_HSI) || \ + ((SOURCE) == RCC_MCOSOURCE_HSE) || \ + ((SOURCE) == RCC_MCOSOURCE_PLLCLK_NODIV) || \ + ((SOURCE) == RCC_MCOSOURCE_PLLCLK_DIV2) || \ + ((SOURCE) == RCC_MCOSOURCE_HSI14) || \ + ((SOURCE) == RCC_MCOSOURCE_HSI48)) +/** + * @} + */ + +/** @defgroup RCCEx_Interrupt + * @{ + */ +#define RCC_IT_HSI48 ((uint8_t)0x40) +/** + * @} + */ + +/* Flags in the CR2 register */ +#define RCC_CR2_HSI48RDY_BitNumber 16 + +#define RCC_FLAG_HSI48RDY ((uint8_t)((CR2_REG_INDEX << 5) | RCC_CR2_HSI48RDY_BitNumber)) + +#endif /* STM32F042x6 || */ + /* STM32F071xB || STM32F072xB || STM32F078xx */ + +#if defined(STM32F042x6) || defined(STM32F048xx) || defined(STM32F072xB) + +/** @defgroup RCCEx_USB_Clock_Source + * @{ + */ +#define RCC_USBCLKSOURCE_HSI48 RCC_CFGR3_USBSW_HSI48 +#define RCC_USBCLKSOURCE_PLLCLK RCC_CFGR3_USBSW_PLLCLK + +#define IS_RCC_USBCLKSOURCE(SOURCE) (((SOURCE) == RCC_USBCLKSOURCE_HSI48) || \ + ((SOURCE) == RCC_USBCLKSOURCE_PLLCLK)) +/** + * @} + */ + +#endif /* STM32F042x6 || STM32F072xB */ + +#if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) + +/** @defgroup RCCEx_USART2_Clock_Source + * @{ + */ +#define RCC_USART2CLKSOURCE_PCLK1 RCC_CFGR3_USART2SW_PCLK +#define RCC_USART2CLKSOURCE_SYSCLK RCC_CFGR3_USART2SW_SYSCLK +#define RCC_USART2CLKSOURCE_LSE RCC_CFGR3_USART2SW_LSE +#define RCC_USART2CLKSOURCE_HSI RCC_CFGR3_USART2SW_HSI + +#define IS_RCC_USART2CLKSOURCE(SOURCE) (((SOURCE) == RCC_USART2CLKSOURCE_PCLK1) || \ + ((SOURCE) == RCC_USART2CLKSOURCE_SYSCLK) || \ + ((SOURCE) == RCC_USART2CLKSOURCE_LSE) || \ + ((SOURCE) == RCC_USART2CLKSOURCE_HSI)) +/** + * @} + */ + +#endif /* STM32F071xB || STM32F072xB || STM32F078xx */ + +#if defined(STM32F042x6) || defined(STM32F048xx) || \ + defined(STM32F051x8) || defined(STM32F058xx) || \ + defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) + +/** @defgroup RCCEx_CEC_Clock_Source + * @{ + */ +#define RCC_CECCLKSOURCE_HSI RCC_CFGR3_CECSW_HSI_DIV244 +#define RCC_CECCLKSOURCE_LSE RCC_CFGR3_CECSW_LSE + +#define IS_RCC_CECCLKSOURCE(SOURCE) (((SOURCE) == RCC_CECCLKSOURCE_HSI) || \ + ((SOURCE) == RCC_CECCLKSOURCE_LSE)) +/** + * @} + */ + +#endif /* STM32F042x6 || */ + /* STM32F051x8 || STM32F058xx || */ + /* STM32F071xB || STM32F072xB || STM32F078xx */ + +#if defined(STM32F042x6) || defined(STM32F048xx) || \ + defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) +/** @addtogroup RCC_PLL_Clock_Source + * @{ + */ +#define RCC_PLLSOURCE_HSI RCC_CFGR_PLLSRC_HSI_PREDIV +#define RCC_PLLSOURCE_HSI48 RCC_CFGR_PLLSRC_HSI48_PREDIV + +#define IS_RCC_PLLSOURCE(SOURCE) (((SOURCE) == RCC_PLLSOURCE_HSI) || \ + ((SOURCE) == RCC_PLLSOURCE_HSI48) || \ + ((SOURCE) == RCC_PLLSOURCE_HSE)) +/** + * @} + */ + +/** @addtogroup RCC_System_Clock_Source + * @{ + */ +#define RCC_SYSCLKSOURCE_HSI48 RCC_CFGR_SW_HSI48 + +#define IS_RCC_SYSCLKSOURCE(SOURCE) (((SOURCE) == RCC_SYSCLKSOURCE_HSI) || \ + ((SOURCE) == RCC_SYSCLKSOURCE_HSE) || \ + ((SOURCE) == RCC_SYSCLKSOURCE_PLLCLK) || \ + ((SOURCE) == RCC_SYSCLKSOURCE_HSI48)) +/** + * @} + */ + +/** @addtogroup RCC_System_Clock_Source_Status + * @{ + */ +#define RCC_SYSCLKSOURCE_STATUS_HSI48 RCC_CFGR_SWS_HSI48 + +#define IS_RCC_SYSCLKSOURCE_STATUS(SOURCE) (((SOURCE) == RCC_SYSCLKSOURCE_STATUS_HSI) || \ + ((SOURCE) == RCC_SYSCLKSOURCE_STATUS_HSE) || \ + ((SOURCE) == RCC_SYSCLKSOURCE_STATUS_PLLCLK) || \ + ((SOURCE) == RCC_SYSCLKSOURCE_STATUS_HSI48)) +/** + * @} + */ + +/** @defgroup RCCEx_HSI48_Config + * @{ + */ +#define RCC_HSI48_OFF ((uint8_t)0x00) +#define RCC_HSI48_ON ((uint8_t)0x01) + +#define IS_RCC_HSI48(HSI48) (((HSI48) == RCC_HSI48_OFF) || ((HSI48) == RCC_HSI48_ON)) +/** + * @} + */ + +#else +/** @addtogroup RCC_PLL_Clock_Source + * @{ + */ +#define RCC_PLLSOURCE_HSI RCC_CFGR_PLLSRC_HSI_DIV2 + /** + * @} + */ + +/** @addtogroup RCC_PLL_Clock_Source + * @{ + */ +#define IS_RCC_PLLSOURCE(SOURCE) (((SOURCE) == RCC_PLLSOURCE_HSI) || \ + ((SOURCE) == RCC_PLLSOURCE_HSE)) +/** + * @} + */ +/** @addtogroup RCC_System_Clock_Source + * @{ + */ +#define IS_RCC_SYSCLKSOURCE(SOURCE) (((SOURCE) == RCC_SYSCLKSOURCE_HSI) || \ + ((SOURCE) == RCC_SYSCLKSOURCE_HSE) || \ + ((SOURCE) == RCC_SYSCLKSOURCE_PLLCLK)) +/** + * @} + */ + +/** @addtogroup RCC_System_Clock_Source_Status + * @{ + */ +#define IS_RCC_SYSCLKSOURCE_STATUS(SOURCE) (((SOURCE) == RCC_SYSCLKSOURCE_STATUS_HSI) || \ + ((SOURCE) == RCC_SYSCLKSOURCE_STATUS_HSE) || \ + ((SOURCE) == RCC_SYSCLKSOURCE_STATUS_PLLCLK)) +/** + * @} + */ + +/** @defgroup RCCEx_HSI48_Config + * @{ + */ +#define RCC_HSI48_OFF ((uint8_t)0x00) + +#define IS_RCC_HSI48(HSI48) (((HSI48) == RCC_HSI48_OFF)) +/** + * @} + */ + +#endif /* STM32F042x6 || */ + /* STM32F071xB || STM32F072xB || STM32F078xx */ + + +#if defined(STM32F030x8) || defined(STM32F051x8) || defined(STM32F058xx) + +/** @defgroup RCCEx_MCOx_Clock_Prescaler + * @{ + */ +#define RCC_MCO_NODIV ((uint32_t)0x00000000) + +#define IS_RCC_MCODIV(DIV) (((DIV) == RCC_MCO_NODIV)) +/** + * @} + */ + +#endif /* STM32F030x8 || STM32F051x8 || STM32F058xx */ + +#if defined(STM32F030x6) || defined(STM32F031x6) || defined(STM32F038xx) || \ + defined(STM32F042x6) || defined(STM32F048xx) || defined(STM32F071xB) || \ + defined(STM32F072xB) || defined(STM32F078xx) + +/** @defgroup RCCEx_MCOx_Clock_Prescaler + * @{ + */ +#define RCC_MCO_DIV1 ((uint32_t)0x00000000) +#define RCC_MCO_DIV2 ((uint32_t)0x10000000) +#define RCC_MCO_DIV4 ((uint32_t)0x20000000) +#define RCC_MCO_DIV8 ((uint32_t)0x30000000) +#define RCC_MCO_DIV16 ((uint32_t)0x40000000) +#define RCC_MCO_DIV32 ((uint32_t)0x50000000) +#define RCC_MCO_DIV64 ((uint32_t)0x60000000) +#define RCC_MCO_DIV128 ((uint32_t)0x70000000) + +#define IS_RCC_MCODIV(DIV) (((DIV) == RCC_MCO_DIV1) || ((DIV) == RCC_MCO_DIV2) || \ + ((DIV) == RCC_MCO_DIV4) || ((DIV) == RCC_MCO_DIV8) || \ + ((DIV) == RCC_MCO_DIV16) || ((DIV) == RCC_MCO_DIV32) || \ + ((DIV) == RCC_MCO_DIV64) || ((DIV) == RCC_MCO_DIV128)) +/** + * @} + */ + +#endif /* STM32F030x6 || STM32F031x6 || STM32F038xx || STM32F042x6 || STM32F048xx || */ + /* STM32F071xB || STM32F072xB || STM32F078xx */ + +#if defined(STM32F042x6) || defined(STM32F048xx) || \ + defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) +/** @defgroup RCCEx_CRS_SynchroSource + * @{ + */ +#define RCC_CRS_SYNC_SOURCE_GPIO ((uint32_t)0x00) /*!< Synchro Signal soucre GPIO */ +#define RCC_CRS_SYNC_SOURCE_LSE CRS_CFGR_SYNCSRC_0 /*!< Synchro Signal source LSE */ +#define RCC_CRS_SYNC_SOURCE_USB CRS_CFGR_SYNCSRC_1 /*!< Synchro Signal source USB SOF (default)*/ + +#define IS_RCC_CRS_SYNC_SOURCE(_SOURCE_) (((_SOURCE_) == RCC_CRS_SYNC_SOURCE_GPIO) || \ + ((_SOURCE_) == RCC_CRS_SYNC_SOURCE_LSE) ||\ + ((_SOURCE_) == RCC_CRS_SYNC_SOURCE_USB)) +/** + * @} + */ + +/** @defgroup RCCEx_CRS_SynchroDivider + * @{ + */ +#define RCC_CRS_SYNC_DIV1 ((uint32_t)0x00) /*!< Synchro Signal not divided (default) */ +#define RCC_CRS_SYNC_DIV2 CRS_CFGR_SYNCDIV_0 /*!< Synchro Signal divided by 2 */ +#define RCC_CRS_SYNC_DIV4 CRS_CFGR_SYNCDIV_1 /*!< Synchro Signal divided by 4 */ +#define RCC_CRS_SYNC_DIV8 (CRS_CFGR_SYNCDIV_1 | CRS_CFGR_SYNCDIV_0) /*!< Synchro Signal divided by 8 */ +#define RCC_CRS_SYNC_DIV16 CRS_CFGR_SYNCDIV_2 /*!< Synchro Signal divided by 16 */ +#define RCC_CRS_SYNC_DIV32 (CRS_CFGR_SYNCDIV_2 | CRS_CFGR_SYNCDIV_0) /*!< Synchro Signal divided by 32 */ +#define RCC_CRS_SYNC_DIV64 (CRS_CFGR_SYNCDIV_2 | CRS_CFGR_SYNCDIV_1) /*!< Synchro Signal divided by 64 */ +#define RCC_CRS_SYNC_DIV128 CRS_CFGR_SYNCDIV /*!< Synchro Signal divided by 128 */ + +#define IS_RCC_CRS_SYNC_DIV(_DIV_) (((_DIV_) == RCC_CRS_SYNC_DIV1) || ((_DIV_) == RCC_CRS_SYNC_DIV2) ||\ + ((_DIV_) == RCC_CRS_SYNC_DIV4) || ((_DIV_) == RCC_CRS_SYNC_DIV8) || \ + ((_DIV_) == RCC_CRS_SYNC_DIV16) || ((_DIV_) == RCC_CRS_SYNC_DIV32) || \ + ((_DIV_) == RCC_CRS_SYNC_DIV64) || ((_DIV_) == RCC_CRS_SYNC_DIV128)) +/** + * @} + */ + +/** @defgroup RCCEx_CRS_SynchroPolarity + * @{ + */ +#define RCC_CRS_SYNC_POLARITY_RISING ((uint32_t)0x00) /*!< Synchro Active on rising edge (default) */ +#define RCC_CRS_SYNC_POLARITY_FALLING CRS_CFGR_SYNCPOL /*!< Synchro Active on falling edge */ + +#define IS_RCC_CRS_SYNC_POLARITY(_POLARITY_) (((_POLARITY_) == RCC_CRS_SYNC_POLARITY_RISING) || \ + ((_POLARITY_) == RCC_CRS_SYNC_POLARITY_FALLING)) +/** + * @} + */ + +/** @defgroup RCCEx_CRS_ReloadValueDefault + * @{ + */ +#define RCC_CRS_RELOADVALUE_DEFAULT ((uint32_t)0xBB7F) /*!< The reset value of the RELOAD field corresponds + to a target frequency of 48 MHz and a synchronization signal frequency of 1 kHz (SOF signal from USB). */ + +#define IS_RCC_CRS_RELOADVALUE(_VALUE_) (((_VALUE_) <= 0xFFFF)) +/** + * @} + */ + +/** @defgroup RCCEx_CRS_ErrorLimitDefault + * @{ + */ +#define RCC_CRS_ERRORLIMIT_DEFAULT ((uint32_t)0x22) /*!< Default Frequency error limit */ + +#define IS_RCC_CRS_ERRORLIMIT(_VALUE_) (((_VALUE_) <= 0xFF)) +/** + * @} + */ + +/** @defgroup RCCEx_CRS_HSI48CalibrationDefault + * @{ + */ +#define RCC_CRS_HSI48CALIBRATION_DEFAULT ((uint32_t)0x20) /*!< The default value is 32, which corresponds to the middle of the trimming interval. + The trimming step is around 67 kHz between two consecutive TRIM steps. A higher TRIM value + corresponds to a higher output frequency */ + +#define IS_RCC_CRS_HSI48CALIBRATION(_VALUE_) (((_VALUE_) <= 0x3F)) +/** + * @} + */ + +/** @defgroup RCCEx_CRS_FreqErrorDirection + * @{ + */ +#define RCC_CRS_FREQERRORDIR_UP ((uint32_t)0x00) /*!< Upcounting direction, the actual frequency is above the target */ +#define RCC_CRS_FREQERRORDIR_DOWN ((uint32_t)CRS_ISR_FEDIR) /*!< Downcounting direction, the actual frequency is below the target */ + +#define IS_RCC_CRS_FREQERRORDIR(_DIR_) (((_DIR_) == RCC_CRS_FREQERRORDIR_UP) || \ + ((_DIR_) == RCC_CRS_FREQERRORDIR_DOWN)) +/** + * @} + */ + +/** @defgroup RCCEx_CRS_Interrupt_Sources + * @{ + */ +#define RCC_CRS_IT_SYNCOK CRS_ISR_SYNCOKF /*!< SYNC event OK */ +#define RCC_CRS_IT_SYNCWARN CRS_ISR_SYNCWARNF /*!< SYNC warning */ +#define RCC_CRS_IT_ERR CRS_ISR_ERRF /*!< error */ +#define RCC_CRS_IT_ESYNC CRS_ISR_ESYNCF /*!< Expected SYNC */ +#define RCC_CRS_IT_TRIMOVF CRS_ISR_TRIMOVF /*!< Trimming overflow or underflow */ +#define RCC_CRS_IT_SYNCERR CRS_ISR_SYNCERR /*!< SYNC error */ +#define RCC_CRS_IT_SYNCMISS CRS_ISR_SYNCMISS /*!< SYNC missed*/ + +/** + * @} + */ + +/** @defgroup RCCEx_CRS_Flags + * @{ + */ +#define RCC_CRS_FLAG_SYNCOK CRS_ISR_SYNCOKF /* SYNC event OK flag */ +#define RCC_CRS_FLAG_SYNCWARN CRS_ISR_SYNCWARNF /* SYNC warning flag */ +#define RCC_CRS_FLAG_ERR CRS_ISR_ERRF /* Error flag */ +#define RCC_CRS_FLAG_ESYNC CRS_ISR_ESYNCF /* Expected SYNC flag */ +#define RCC_CRS_FLAG_TRIMOVF CRS_ISR_TRIMOVF /*!< Trimming overflow or underflow */ +#define RCC_CRS_FLAG_SYNCERR CRS_ISR_SYNCERR /*!< SYNC error */ +#define RCC_CRS_FLAG_SYNCMISS CRS_ISR_SYNCMISS /*!< SYNC missed*/ + +/** + * @} + */ + +#endif /* STM32F042x6 || */ + /* STM32F071xB || STM32F072xB || STM32F078xx */ + +/** + * @} + */ + +/* Exported macros -----------------------------------------------------------*/ +/** @defgroup RCCEx_Exported_Macros + * @{ + */ + +/** @brief Enable or disable the AHB peripheral clock. + * @note After reset, the peripheral clock (used for registers read/write access) + * is disabled and the application software has to enable this clock before + * using it. + */ +#if defined(STM32F030x6) || defined(STM32F030x8) || \ + defined(STM32F051x8) || defined(STM32F058xx) || \ + defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) + +#define __GPIOD_CLK_ENABLE() (RCC->AHBENR |= (RCC_AHBENR_GPIODEN)) + +#define __GPIOD_CLK_DISABLE() (RCC->AHBENR &= ~(RCC_AHBENR_GPIODEN)) + +#endif /* STM32F030x6 || STM32F030x8 || */ + /* STM32F051x8 || STM32F058xx || */ + /* STM32F071xB || STM32F072xB || STM32F078xx */ + +#if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) + +#define __GPIOE_CLK_ENABLE() (RCC->AHBENR |= (RCC_AHBENR_GPIOEEN)) + +#define __GPIOE_CLK_DISABLE() (RCC->AHBENR &= ~(RCC_AHBENR_GPIOEEN)) + +#endif /* STM32F071xB || STM32F072xB || STM32F078xx */ + +#if defined(STM32F042x6) || defined(STM32F048xx) || \ + defined(STM32F051x8) || defined(STM32F058xx) || \ + defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) + +#define __TSC_CLK_ENABLE() (RCC->AHBENR |= (RCC_AHBENR_TSCEN)) + +#define __TSC_CLK_DISABLE() (RCC->AHBENR &= ~(RCC_AHBENR_TSCEN)) + +#endif /* STM32F042x6 || */ + /* STM32F051x8 || STM32F058xx || */ + /* STM32F071xB || STM32F072xB || STM32F078xx */ + +/** @brief Enable or disable the Low Speed APB (APB1) peripheral clock. + * @note After reset, the peripheral clock (used for registers read/write access) + * is disabled and the application software has to enable this clock before + * using it. + */ +#if defined(STM32F030x8) || \ + defined(STM32F042x6) || defined(STM32F048xx) || \ + defined(STM32F051x8) || defined(STM32F058xx) || \ + defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) + +#define __USART2_CLK_ENABLE() (RCC->APB1ENR |= (RCC_APB1ENR_USART2EN)) +#define __SPI2_CLK_ENABLE() (RCC->APB1ENR |= (RCC_APB1ENR_SPI2EN)) + +#define __USART2_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_USART2EN)) +#define __SPI2_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_SPI2EN)) + +#endif /* STM32F030x8 || STM32F042x6 || STM32F048xx || */ + /* STM32F051x8 || STM32F058xx || */ + /* STM32F071xB || STM32F072xB || STM32F078xx */ + +#if defined(STM32F031x6) || defined(STM32F038xx) || \ + defined(STM32F042x6) || defined(STM32F048xx) || \ + defined(STM32F051x8) || defined(STM32F058xx) || \ + defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) + +#define __TIM2_CLK_ENABLE() (RCC->APB1ENR |= (RCC_APB1ENR_TIM2EN)) + +#define __TIM2_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM2EN)) + +#endif /* STM32F031x6 || STM32F038xx || STM32F042x6 || STM32F048xx || STM32F051x8 || STM32F058xx || */ + /* STM32F071xB || STM32F072xB || STM32F078xx */ + +#if defined(STM32F030x8) || \ + defined(STM32F051x8) || defined(STM32F058xx) || \ + defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) + +#define __TIM6_CLK_ENABLE() (RCC->APB1ENR |= (RCC_APB1ENR_TIM6EN)) +#define __I2C2_CLK_ENABLE() (RCC->APB1ENR |= (RCC_APB1ENR_I2C2EN)) + +#define __TIM6_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM6EN)) +#define __I2C2_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_I2C2EN)) + +#endif /* STM32F030x8 || */ + /* STM32F051x8 || STM32F058xx || */ + /* STM32F071xB || STM32F072xB || STM32F078xx */ + +#if defined(STM32F051x8) || defined(STM32F058xx) || \ + defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) + +#define __DAC1_CLK_ENABLE() (RCC->APB1ENR |= (RCC_APB1ENR_DACEN)) + +#define __DAC1_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_DACEN)) + +#endif /* STM32F051x8 || STM32F058xx || */ + /* STM32F071xB || STM32F072xB || STM32F078xx */ + +#if defined(STM32F042x6) || defined(STM32F048xx) || \ + defined(STM32F051x8) || defined(STM32F058xx) || \ + defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) + +#define __CEC_CLK_ENABLE() (RCC->APB1ENR |= (RCC_APB1ENR_CECEN)) + +#define __CEC_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_CECEN)) + +#endif /* STM32F042x6 || */ + /* STM32F051x8 || STM32F058xx || */ + /* STM32F071xB || STM32F072xB || STM32F078xx */ + +#if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) + +#define __TIM7_CLK_ENABLE() (RCC->APB1ENR |= (RCC_APB1ENR_TIM7EN)) +#define __USART3_CLK_ENABLE() (RCC->APB1ENR |= (RCC_APB1ENR_USART3EN)) +#define __USART4_CLK_ENABLE() (RCC->APB1ENR |= (RCC_APB1ENR_USART4EN)) + +#define __TIM7_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_TIM7EN)) +#define __USART3_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_USART3EN)) +#define __USART4_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_USART4EN)) + +#endif /* STM32F071xB || STM32F072xB || STM32F078xx */ + +#if defined(STM32F042x6) || defined(STM32F048xx) || defined(STM32F072xB) + +#define __USB_CLK_ENABLE() (RCC->APB1ENR |= (RCC_APB1ENR_USBEN)) + +#define __USB_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_USBEN)) + +#endif /* STM32F042x6 || STM32F072xB */ + +#if defined(STM32F042x6) || defined(STM32F048xx) || defined(STM32F072xB) + +#define __CAN_CLK_ENABLE() (RCC->APB1ENR |= (RCC_APB1ENR_CANEN)) +#define __CAN_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_CANEN)) + +#endif /* STM32F042x6 || STM32F072xB */ + +#if defined(STM32F042x6) || defined(STM32F048xx) || \ + defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) + +#define __CRS_CLK_ENABLE() (RCC->APB1ENR |= (RCC_APB1ENR_CRSEN)) + +#define __CRS_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_CRSEN)) + +#endif /* STM32F042x6 || */ + /* STM32F071xB || STM32F072xB || STM32F078xx */ + +/** @brief Enable or disable the High Speed APB (APB2) peripheral clock. + * @note After reset, the peripheral clock (used for registers read/write access) + * is disabled and the application software has to enable this clock before + * using it. + */ +#if defined(STM32F030x8) || defined(STM32F042x6) || defined(STM32F048xx) || \ + defined(STM32F051x8) || defined(STM32F058xx) || \ + defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) + +#define __TIM15_CLK_ENABLE() (RCC->APB2ENR |= (RCC_APB2ENR_TIM15EN)) + +#define __TIM15_CLK_DISABLE() (RCC->APB2ENR &= ~(RCC_APB2ENR_TIM15EN)) + +#endif /* STM32F030x8 || STM32F042x6 || STM32F048xx || */ + /* STM32F051x8 || STM32F058xx || */ + /* STM32F071xB || STM32F072xB || STM32F078xx */ + +/** @brief Force or release AHB peripheral reset. + */ +#if defined(STM32F030x6) || defined(STM32F030x8) || \ + defined(STM32F051x8) || defined(STM32F058xx) || \ + defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) + +#define __GPIOD_FORCE_RESET() (RCC->AHBRSTR |= (RCC_AHBRSTR_GPIODRST)) + +#define __GPIOD_RELEASE_RESET() (RCC->AHBRSTR &= ~(RCC_AHBRSTR_GPIODRST)) + +#endif /* STM32F030x6 || STM32F030x8 || */ + /* STM32F051x8 || STM32F058xx || */ + /* STM32F071xB || STM32F072xB || STM32F078xx */ + +#if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) + +#define __GPIOE_FORCE_RESET() (RCC->AHBRSTR |= (RCC_AHBRSTR_GPIOERST)) + +#define __GPIOE_RELEASE_RESET() (RCC->AHBRSTR &= ~(RCC_AHBRSTR_GPIOERST)) + +#endif /* STM32F071xB || STM32F072xB || STM32F078xx */ + +#if defined(STM32F042x6) || defined(STM32F048xx) || \ + defined(STM32F051x8) || defined(STM32F058xx) || \ + defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) + +#define __TSC_FORCE_RESET() (RCC->AHBRSTR |= (RCC_AHBRSTR_TSCRST)) + +#define __TSC_RELEASE_RESET() (RCC->AHBRSTR &= ~(RCC_AHBRSTR_TSCRST)) + +#endif /* STM32F042x6 || */ + /* STM32F051x8 || STM32F058xx || */ + /* STM32F071xB || STM32F072xB || STM32F078xx */ + +/** @brief Force or release APB1 peripheral reset. + */ +#if defined(STM32F030x8) || \ + defined(STM32F042x6) || defined(STM32F048xx) || \ + defined(STM32F051x8) || defined(STM32F058xx) || \ + defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) + +#define __USART2_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_USART2RST)) +#define __SPI2_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_SPI2RST)) + +#define __USART2_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_USART2RST)) +#define __SPI2_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_SPI2RST)) + +#endif /* STM32F030x8 || STM32F042x6 || STM32F048xx || */ + /* STM32F051x8 || STM32F058xx || */ + /* STM32F071xB || STM32F072xB || STM32F078xx */ + +#if defined(STM32F031x6) || defined(STM32F038xx) || \ + defined(STM32F042x6) || defined(STM32F048xx) || \ + defined(STM32F051x8) || defined(STM32F058xx) || \ + defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) + +#define __TIM2_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM2RST)) + +#define __TIM2_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM2RST)) + +#endif /* STM32F031x6 || STM32F038xx || STM32F042x6 || STM32F048xx || STM32F051x8 || STM32F058xx || */ + /* STM32F071xB || STM32F072xB || STM32F078xx */ + +#if defined(STM32F030x8) || \ + defined(STM32F051x8) || defined(STM32F058xx) || \ + defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) + +#define __TIM6_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM6RST)) +#define __I2C2_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_I2C2RST)) + +#define __TIM6_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM6RST)) +#define __I2C2_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_I2C2RST)) + +#endif /* STM32F030x8 || */ + /* STM32F051x8 || STM32F058xx || */ + /* STM32F071xB || STM32F072xB || STM32F078xx */ + +#if defined(STM32F051x8) || defined(STM32F058xx) || \ + defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) + +#define __DAC1_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_DACRST)) + +#define __DAC1_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_DACRST)) + +#endif /* STM32F051x8 || STM32F058xx || */ + /* STM32F071xB || STM32F072xB || STM32F078xx */ + +#if defined(STM32F042x6) || defined(STM32F048xx) || \ + defined(STM32F051x8) || defined(STM32F058xx) || \ + defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) + +#define __CEC_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_CECRST)) + +#define __CEC_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_CECRST)) + +#endif /* STM32F042x6 || */ + /* STM32F051x8 || STM32F058xx || */ + /* STM32F071xB || STM32F072xB || STM32F078xx */ + +#if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) + +#define __TIM7_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM7RST)) +#define __USART3_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_USART3RST)) +#define __USART4_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_USART4RST)) + +#define __TIM7_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_TIM7RST)) +#define __USART3_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_USART3RST)) +#define __USART4_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_USART4RST)) + +#endif /* STM32F071xB || STM32F072xB || STM32F078xx */ + +#if defined(STM32F042x6) || defined(STM32F048xx) || defined(STM32F072xB) + +#define __USB_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_USBRST)) + +#define __USB_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_USBRST)) + +#endif /* STM32F042x6 || STM32F072xB */ + +#if defined(STM32F042x6) || defined(STM32F048xx) || defined(STM32F072xB) + +#define __CAN_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_CANRST)) + +#define __CAN_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_CANRST)) + +#endif /* STM32F042x6 || STM32F072xB */ + +#if defined(STM32F042x6) || defined(STM32F048xx) || \ + defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) + +#define __CRS_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_CRSRST)) + +#define __CRS_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_CRSRST)) + +#endif /* STM32F042x6 || */ + /* STM32F071xB || STM32F072xB || STM32F078xx */ + + +/** @brief Force or release APB2 peripheral reset. + */ +#if defined(STM32F030x8) || defined(STM32F042x6) || defined(STM32F048xx) || \ + defined(STM32F051x8) || defined(STM32F058xx) || \ + defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) + +#define __TIM15_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_TIM15RST)) + +#define __TIM15_RELEASE_RESET() (RCC->APB2RSTR &= ~(RCC_APB2RSTR_TIM15RST)) + +#endif /* STM32F030x8 || STM32F042x6 || STM32F048xx || */ + /* STM32F051x8 || STM32F058xx || */ + /* STM32F071xB || STM32F072xB || STM32F078xx */ + +#if defined(STM32F042x6) || defined(STM32F048xx) || \ + defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) + +/** @brief Macros to enable or disable the Internal 48Mhz High Speed oscillator (HSI48). + * @note The HSI48 is stopped by hardware when entering STOP and STANDBY modes. + * @note HSI48 can not be stopped if it is used as system clock source. In this case, + * you have to select another source of the system clock then stop the HSI14. + * @note After enabling the HSI48 with __HAL_RCC_HSI48_ENABLE(), the application software + * should wait on HSI48RDY flag to be set indicating that HSI48 clock is stable and can be + * used as system clock source. This is not necessary if HAL_RCC_OscConfig() is used. + * @note When the HSI48 is stopped, HSI48RDY flag goes low after 6 HSI48 oscillator + * clock cycles. + */ +#define __HAL_RCC_HSI48_ENABLE() SET_BIT(RCC->CR2, RCC_CR2_HSI48ON) +#define __HAL_RCC_HSI48_DISABLE() CLEAR_BIT(RCC->CR2, RCC_CR2_HSI48ON) + +/** @brief Macro to get the Internal 48Mhz High Speed oscillator (HSI48) state. + * @retval The clock source can be one of the following values: + * @arg RCC_HSI48_ON: HSI48 enabled + * @arg RCC_HSI48_OFF: HSI48 disabled + */ +#define __HAL_RCC_GET_HSI48_STATE() \ + (((uint32_t)(READ_BIT(RCC->CFGR3, RCC_CR2_HSI48ON)) != RESET) ? RCC_HSI48_ON : RCC_HSI48_OFF) + +#else + +/** @brief Macro to get the Internal 48Mhz High Speed oscillator (HSI48) state. + * @retval The clock source can be one of the following values: + * @arg RCC_HSI_OFF: HSI48 disabled + */ +#define __HAL_RCC_GET_HSI48_STATE() RCC_HSI_OFF + +#endif /* STM32F042x6 || */ + /* STM32F071xB || STM32F072xB || STM32F078xx */ + +#if defined(STM32F042x6) || defined(STM32F048xx) || defined(STM32F072xB) + +/** @brief Macro to configure the USB clock (USBCLK). + * @param __USBCLKSource__: specifies the USB clock source. + * This parameter can be one of the following values: + * @arg RCC_USBCLKSOURCE_HSI48: HSI48 selected as USB clock + * @arg RCC_USBCLKSOURCE_PLLCLK: PLL Clock selected as USB clock + */ +#define __HAL_RCC_USB_CONFIG(__USBCLKSource__) \ + MODIFY_REG(RCC->CFGR3, RCC_CFGR3_USBSW, (uint32_t)(__USBCLKSource__)) + +/** @brief Macro to get the USB clock source. + * @retval The clock source can be one of the following values: + * @arg RCC_USBCLKSOURCE_HSI48: HSI48 selected as USB clock + * @arg RCC_USBCLKSOURCE_PLLCLK: PLL Clock selected as USB clock + */ +#define __HAL_RCC_GET_USB_SOURCE() ((uint32_t)(READ_BIT(RCC->CFGR3, RCC_CFGR3_USBSW))) + +#endif /* STM32F042x6 || STM32F072xB */ + +#if defined(STM32F042x6) || defined(STM32F048xx) || \ + defined(STM32F051x8) || defined(STM32F058xx) || \ + defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) + +/** @brief Macro to configure the CEC clock. + * @param __CECCLKSource__: specifies the CEC clock source. + * This parameter can be one of the following values: + * @arg RCC_CECCLKSOURCE_HSI: HSI selected as CEC clock + * @arg RCC_CECCLKSOURCE_LSE: LSE selected as CEC clock + */ +#define __HAL_RCC_CEC_CONFIG(__CECCLKSource__) \ + MODIFY_REG(RCC->CFGR3, RCC_CFGR3_CECSW, (uint32_t)(__CECCLKSource__)) + +/** @brief Macro to get the HDMI CEC clock source. + * @retval The clock source can be one of the following values: + * @arg RCC_CECCLKSOURCE_HSI: HSI selected as CEC clock + * @arg RCC_CECCLKSOURCE_LSE: LSE selected as CEC clock + */ +#define __HAL_RCC_GET_CEC_SOURCE() ((uint32_t)(READ_BIT(RCC->CFGR3, RCC_CFGR3_CECSW))) + +#endif /* STM32F042x6 || */ + /* STM32F051x8 || STM32F058xx || */ + /* STM32F071xB || STM32F072xB || STM32F078xx */ + +#if defined(STM32F030x6) || defined(STM32F031x6) || defined(STM32F038xx) || \ + defined(STM32F042x6) || defined(STM32F048xx) || defined(STM32F071xB) || \ + defined(STM32F072xB) || defined(STM32F078xx) + +/** @brief Macro to configure the MCO clock. + * @param __MCOCLKSource__: specifies the MCO clock source. + * This parameter can be one of the following values: + * @arg RCC_MCOSOURCE_HSI: HSI selected as MCO clock + * @arg RCC_MCOSOURCE_HSE: HSE selected as MCO clock + * @arg RCC_MCOSOURCE_LSI: LSI selected as MCO clock + * @arg RCC_MCOSOURCE_LSE: LSE selected as MCO clock + * @arg RCC_MCOSOURCE_PLLCLK_NODIV: PLLCLK selected as MCO clock + * @arg RCC_MCOSOURCE_PLLCLK_DIV2: PLLCLK Divided by 2 selected as MCO clock + * @arg RCC_MCOSOURCE_SYSCLK: System Clock selected as MCO clock + * @arg RCC_MCOSOURCE_HSI14: HSI14 selected as MCO clock + * @arg RCC_MCOSOURCE_HSI48: HSI48 selected as MCO clock + * @param __MCODiv__: specifies the MCO clock prescaler. + * This parameter can be one of the following values: + * @arg RCC_MCO_DIV1: MCO clock source is divided by 1 + * @arg RCC_MCO_DIV2: MCO clock source is divided by 2 + * @arg RCC_MCO_DIV4: MCO clock source is divided by 4 + * @arg RCC_MCO_DIV8: MCO clock source is divided by 8 + * @arg RCC_MCO_DIV16: MCO clock source is divided by 16 + * @arg RCC_MCO_DIV32: MCO clock source is divided by 32 + * @arg RCC_MCO_DIV64: MCO clock source is divided by 64 + * @arg RCC_MCO_DIV128: MCO clock source is divided by 128 + */ +#define __HAL_RCC_MCO_CONFIG(__MCOCLKSource__, __MCODiv__) \ + MODIFY_REG(RCC->CFGR, (RCC_CFGR_MCO | RCC_CFGR_MCOPRE), ((__MCOCLKSource__) | (__MCODiv__))) +#else + +/** @brief Macro to configure the MCO clock. + * @param __MCOCLKSource__: specifies the MCO clock source. + * This parameter can be one of the following values: + * @arg RCC_MCOSOURCE_HSI: HSI selected as MCO clock + * @arg RCC_MCOSOURCE_HSE: HSE selected as MCO clock + * @arg RCC_MCOSOURCE_LSI: LSI selected as MCO clock + * @arg RCC_MCOSOURCE_LSE: LSE selected as MCO clock + * @arg RCC_MCOSOURCE_PLLCLK_DIV2: PLLCLK Divided by 2 selected as MCO clock + * @arg RCC_MCOSOURCE_SYSCLK: System Clock selected as MCO clock + * @arg RCC_MCOSOURCE_HSI14: HSI14 selected as MCO clock + * @arg RCC_MCOSOURCE_HSI48: HSI48 selected as MCO clock + * @param __MCODiv__: specifies the MCO clock prescaler. + * This parameter can be one of the following values: + * @arg RCC_MCO_NODIV: No division applied on MCO clock source + */ +#define __HAL_RCC_MCO_CONFIG(__MCOCLKSource__, __MCODiv__) \ + MODIFY_REG(RCC->CFGR, RCC_CFGR_MCO, __MCOCLKSource__) + +#endif /* STM32F030x6 || STM32F031x6 || STM32F038xx || */ + /* STM32F042x6 || STM32F071xB || */ + /* STM32F072xB || STM32F078xx */ + +#if defined(STM32F042x6) || defined(STM32F048xx) || \ + defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) +/* Interrupt & Flag management */ + +/** + * @brief Enables the specified CRS interrupts. + * @param __INTERRUPT__: specifies the CRS interrupt sources to be enabled. + * This parameter can be any combination of the following values: + * @arg RCC_CRS_IT_SYNCOK + * @arg RCC_CRS_IT_SYNCWARN + * @arg RCC_CRS_IT_ERR + * @arg RCC_CRS_IT_ESYNC + * @retval None + */ +#define __HAL_RCC_CRS_ENABLE_IT(__INTERRUPT__) (CRS->CR |= (__INTERRUPT__)) + +/** + * @brief Disables the specified CRS interrupts. + * @param __INTERRUPT__: specifies the CRS interrupt sources to be disabled. + * This parameter can be any combination of the following values: + * @arg RCC_CRS_IT_SYNCOK + * @arg RCC_CRS_IT_SYNCWARN + * @arg RCC_CRS_IT_ERR + * @arg RCC_CRS_IT_ESYNC + * @retval None + */ +#define __HAL_RCC_CRS_DISABLE_IT(__INTERRUPT__) (CRS->CR &= ~(__INTERRUPT__)) + +/** @brief Check the CRS's interrupt has occurred or not. + * @param __INTERRUPT__: specifies the CRS interrupt source to check. + * This parameter can be one of the following values: + * @arg RCC_CRS_IT_SYNCOK + * @arg RCC_CRS_IT_SYNCWARN + * @arg RCC_CRS_IT_ERR + * @arg RCC_CRS_IT_ESYNC + * @retval The new state of __INTERRUPT__ (SET or RESET). + */ +#define __HAL_RCC_CRS_GET_IT_SOURCE(__INTERRUPT__) ((CRS->CR & (__INTERRUPT__))? SET : RESET) + +/** @brief Clear the CRS's interrupt pending bits + * bits to clear the selected interrupt pending bits. + * @param __INTERRUPT__: specifies the interrupt pending bit to clear. + * This parameter can be any combination of the following values: + * @arg RCC_CRS_IT_SYNCOK + * @arg RCC_CRS_IT_SYNCWARN + * @arg RCC_CRS_IT_ERR + * @arg RCC_CRS_IT_ESYNC + * @arg RCC_CRS_IT_TRIMOVF + * @arg RCC_CRS_IT_SYNCERR + * @arg RCC_CRS_IT_SYNCMISS + */ +/* CRS IT Error Mask */ +#define RCC_CRS_IT_ERROR_MASK ((uint32_t)(RCC_CRS_IT_TRIMOVF | RCC_CRS_IT_SYNCERR | RCC_CRS_IT_SYNCMISS)) + +#define __HAL_RCC_CRS_CLEAR_IT(__INTERRUPT__) ((((__INTERRUPT__) & RCC_CRS_IT_ERROR_MASK)!= 0) ? (CRS->ICR |= CRS_ICR_ERRC) : \ + (CRS->ICR |= (__INTERRUPT__))) + +/** + * @brief Checks whether the specified CRS flag is set or not. + * @param _FLAG_: specifies the flag to check. + * This parameter can be one of the following values: + * @arg RCC_CRS_FLAG_SYNCOK + * @arg RCC_CRS_FLAG_SYNCWARN + * @arg RCC_CRS_FLAG_ERR + * @arg RCC_CRS_FLAG_ESYNC + * @arg RCC_CRS_FLAG_TRIMOVF + * @arg RCC_CRS_FLAG_SYNCERR + * @arg RCC_CRS_FLAG_SYNCMISS + * @retval The new state of _FLAG_ (TRUE or FALSE). + */ +#define __HAL_RCC_CRS_GET_FLAG(_FLAG_) ((CRS->ISR & (_FLAG_)) == (_FLAG_)) + +/** + * @brief Clears the CRS specified FLAG. + * @param _FLAG_: specifies the flag to clear. + * This parameter can be one of the following values: + * @arg RCC_CRS_FLAG_SYNCOK + * @arg RCC_CRS_FLAG_SYNCWARN + * @arg RCC_CRS_FLAG_ERR + * @arg RCC_CRS_FLAG_ESYNC + * @arg RCC_CRS_FLAG_TRIMOVF + * @arg RCC_CRS_FLAG_SYNCERR + * @arg RCC_CRS_FLAG_SYNCMISS + * @retval None + */ + +/* CRS Flag Error Mask */ +#define RCC_CRS_FLAG_ERROR_MASK ((uint32_t)(RCC_CRS_FLAG_TRIMOVF | RCC_CRS_FLAG_SYNCERR | RCC_CRS_FLAG_SYNCMISS)) + +#define __HAL_RCC_CRS_CLEAR_FLAG(__FLAG__) ((((__FLAG__) & RCC_CRS_FLAG_ERROR_MASK)!= 0) ? (CRS->ICR |= CRS_ICR_ERRC) : \ + (CRS->ICR |= (__FLAG__))) + + +/** + * @brief Enables the oscillator clock for frequency error counter. + * @note when the CEN bit is set the CRS_CFGR register becomes write-protected. + * @param None + * @retval None + */ +#define __HAL_RCC_CRS_ENABLE_FREQ_ERROR_COUNTER() (CRS->CR |= CRS_CR_CEN) + +/** + * @brief Disables the oscillator clock for frequency error counter. + * @param None + * @retval None + */ +#define __HAL_RCC_CRS_DISABLE_FREQ_ERROR_COUNTER() (CRS->CR &= ~CRS_CR_CEN) + +/** + * @brief Enables the automatic hardware adjustement of TRIM bits. + * @note When the AUTOTRIMEN bit is set the CRS_CFGR register becomes write-protected. + * @param None + * @retval None + */ +#define __HAL_RCC_CRS_ENABLE_AUTOMATIC_CALIB() (CRS->CR |= CRS_CR_AUTOTRIMEN) + +/** + * @brief Enables or disables the automatic hardware adjustement of TRIM bits. + * @param None + * @retval None + */ +#define __HAL_RCC_CRS_DISABLE_AUTOMATIC_CALIB() (CRS->CR &= ~CRS_CR_AUTOTRIMEN) + +/** + * @brief Macro to calculate reload value to be set in CRS register according to target and sync frequencies + * @note The RELOAD value should be selected according to the ratio between the target frequency and the frequency + * of the synchronization source after prescaling. It is then decreased by one in order to + * reach the expected synchronization on the zero value. The formula is the following: + * RELOAD = (fTARGET / fSYNC) -1 + * @param _FTARGET_ Target frequency (value in Hz) + * @param _FSYNC_ Synchronization signal frequency (value in Hz) + * @retval None + */ +#define __HAL_RCC_CRS_CALCULATE_RELOADVALUE(_FTARGET_, _FSYNC_) (((_FTARGET_) / (_FSYNC_)) - 1) + +#endif /* STM32F042x6 || */ + /* STM32F071xB || STM32F072xB || STM32F078xx */ + +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClkInit); +void HAL_RCCEx_GetPeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClkInit); + +#if defined(STM32F042x6) || defined(STM32F048xx) || \ + defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) +void HAL_RCCEx_CRSConfig(RCC_CRSInitTypeDef *pInit); +void HAL_RCCEx_CRSSoftwareSynchronizationGenerate(void); +void HAL_RCCEx_CRSGetSynchronizationInfo(RCC_CRSSynchroInfoTypeDef *pSynchroInfo); +RCC_CRSStatusTypeDef HAL_RCCEx_CRSWaitSynchronization(uint32_t Timeout); +#endif /* STM32F042x6 || */ + /* STM32F071xB || STM32F072xB || STM32F078xx */ + + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __STM32F0xx_HAL_RCC_EX_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_rtc.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_rtc.c new file mode 100644 index 0000000000..5c9ba33864 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_rtc.c @@ -0,0 +1,1355 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_rtc.c + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief RTC HAL module driver. + * + * This file provides firmware functions to manage the following + * functionalities of the Real-Time Clock (RTC) peripheral: + * - Initialization + * - Calendar (Time and Date) configuration + * - Alarm A configuration + * - Backup Data Registers configuration + * - Interrupts and flags management + * + @verbatim + + =============================================================================== + ##### RTC Operating Condition ##### + =============================================================================== + [..] The real-time clock (RTC) and the RTC backup registers can be powered + from the VBAT voltage when the main VDD supply is powered off. + To retain the content of the RTC backup registers and supply the RTC + when VDD is turned off, VBAT pin can be connected to an optional + standby voltage supplied by a battery or by another source. + + [..] To allow the RTC to operate even when the main digital supply (VDD) + is turned off, the VBAT pin powers the following blocks: + (#) The RTC + (#) The LSE oscillator + (#) PC13 to PC15 I/Os (when available) + + [..] When the backup domain is supplied by VDD (analog switch connected + to VDD), the following functions are available: + (#) PC14 and PC15 can be used as either GPIO or LSE pins + (#) PC13 can be used as a GPIO or as the RTC_OUT pin + + [..] When the backup domain is supplied by VBAT (analog switch connected + to VBAT because VDD is not present), the following functions are available: + (#) PC14 and PC15 can be used as LSE pins only + (#) PC13 can be used as the RTC_OUT pin + + ##### Backup Domain Reset ##### + =============================================================================== + [..] The backup domain reset sets all RTC registers and the RCC_BDCR + register to their reset values. + A backup domain reset is generated when one of the following events + occurs: + (#) Software reset, triggered by setting the BDRST bit in the + RCC Backup domain control register (RCC_BDCR). + (#) VDD or VBAT power on, if both supplies have previously been + powered off. + + ##### Backup Domain Access ##### + =================================================================== + [..] After reset, the backup domain (RTC registers, RTC backup data + registers and backup SRAM) is protected against possible unwanted write + accesses. + + [..] To enable access to the RTC Domain and RTC registers, proceed as follows: + (#) Enable the Power Controller (PWR) APB1 interface clock using the + __PWR_CLK_ENABLE() function. + (#) Enable access to RTC domain using the HAL_PWR_EnableBkUpAccess() function. + (#) Select the RTC clock source using the __HAL_RCC_RTC_CONFIG() function. + (#) Enable RTC Clock using the __HAL_RCC_RTC_ENABLE() function. + + + ##### How to use RTC Driver ##### + =================================================================== + [..] + (+) Enable the RTC domain access (see description in the section above). + (+) Configure the RTC Prescaler (Asynchronous and Synchronous) and RTC hour + format using the HAL_RTC_Init() function. + + *** Time and Date configuration *** + =================================== + [..] + (+) To configure the RTC Calendar (Time and Date) use the HAL_RTC_SetTime() + and HAL_RTC_SetDate() functions. + (+) To read the RTC Calendar, use the HAL_RTC_GetTime() and HAL_RTC_GetDate() functions. + + *** Alarm configuration *** + =========================== + [..] + (+) To configure the RTC Alarm use the HAL_RTC_SetAlarm() function. + You can also configure the RTC Alarm with interrupt mode using the + HAL_RTC_SetAlarm_IT() function. + (+) To read the RTC Alarm, use the HAL_RTC_GetAlarm() function. + + + ##### RTC and low power modes ##### + =================================================================== + [..] The MCU can be woken up from a low power mode by an RTC alternate + function. + [..] The RTC alternate functions are the RTC alarm (Alarm A), + RTC wakeup, RTC tamper event detection and RTC time stamp event detection. + These RTC alternate functions can wake up the system from the Stop and + Standby low power modes. + [..] The system can also wake up from low power modes without depending + on an external interrupt (Auto-wakeup mode), by using the RTC alarm + or the RTC wakeup events. + [..] The RTC provides a programmable time base for waking up from the + Stop or Standby mode at regular intervals. + Wakeup from STOP and Standby modes is possible only when the RTC clock source + is LSE or LSI. + + @endverbatim + + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @defgroup RTC + * @brief RTC HAL module driver + * @{ + */ + +#ifdef HAL_RTC_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup RTC_Private_Functions + * @{ + */ + +/** @defgroup RTC_Group1 Initialization and de-initialization functions + * @brief Initialization and Configuration functions + * +@verbatim + =============================================================================== + ##### Initialization and de-initialization functions ##### + =============================================================================== + [..] This section provide functions allowing to initialize and configure the + RTC Prescaler (Synchronous and Asynchronous), RTC Hour format, disable + RTC registers Write protection, enter and exit the RTC initialization mode, + RTC registers synchronization check and reference clock detection enable. + (#) The RTC Prescaler is programmed to generate the RTC 1Hz time base. + It is split into 2 programmable prescalers to minimize power consumption. + (++) A 7-bit asynchronous prescaler and A 15-bit synchronous prescaler. + (++) When both prescalers are used, it is recommended to configure the + asynchronous prescaler to a high value to minimize consumption. + (#) All RTC registers are Write protected. Writing to the RTC registers + is enabled by writing a key into the Write Protection register, RTC_WPR. + (#) To Configure the RTC Calendar, user application should enter + initialization mode. In this mode, the calendar counter is stopped + and its value can be updated. When the initialization sequence is + complete, the calendar restarts counting after 4 RTCCLK cycles. + (#) To read the calendar through the shadow registers after Calendar + initialization, calendar update or after wakeup from low power modes + the software must first clear the RSF flag. The software must then + wait until it is set again before reading the calendar, which means + that the calendar registers have been correctly copied into the + RTC_TR and RTC_DR shadow registers.The HAL_RTC_WaitForSynchro() function + implements the above software sequence (RSF clear and RSF check). + +@endverbatim + * @{ + */ + +/** + * @brief Initializes the RTC peripheral + * @param hrtc: RTC handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTC_Init(RTC_HandleTypeDef *hrtc) +{ + /* Check the RTC peripheral state */ + if(hrtc == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_RTC_ALL_INSTANCE(hrtc->Instance)); + assert_param(IS_RTC_HOUR_FORMAT(hrtc->Init.HourFormat)); + assert_param(IS_RTC_ASYNCH_PREDIV(hrtc->Init.AsynchPrediv)); + assert_param(IS_RTC_SYNCH_PREDIV(hrtc->Init.SynchPrediv)); + assert_param(IS_RTC_OUTPUT(hrtc->Init.OutPut)); + assert_param(IS_RTC_OUTPUT_POL(hrtc->Init.OutPutPolarity)); + assert_param(IS_RTC_OUTPUT_TYPE(hrtc->Init.OutPutType)); + + if(hrtc->State == HAL_RTC_STATE_RESET) + { + /* Initialize RTC MSP */ + HAL_RTC_MspInit(hrtc); + } + + /* Set RTC state */ + hrtc->State = HAL_RTC_STATE_BUSY; + + /* Disable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + /* Set Initialization mode */ + if(RTC_EnterInitMode(hrtc) != HAL_OK) + { + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + /* Set RTC state */ + hrtc->State = HAL_RTC_STATE_ERROR; + + return HAL_ERROR; + } + else + { + /* Clear RTC_CR FMT, OSEL and POL Bits */ + hrtc->Instance->CR &= ((uint32_t)~(RTC_CR_FMT | RTC_CR_OSEL | RTC_CR_POL)); + /* Set RTC_CR register */ + hrtc->Instance->CR |= (uint32_t)(hrtc->Init.HourFormat | hrtc->Init.OutPut | hrtc->Init.OutPutPolarity); + + /* Configure the RTC PRER */ + hrtc->Instance->PRER = (uint32_t)(hrtc->Init.SynchPrediv); + hrtc->Instance->PRER |= (uint32_t)(hrtc->Init.AsynchPrediv << 16); + + /* Exit Initialization mode */ + hrtc->Instance->ISR &= (uint32_t)~RTC_ISR_INIT; + + hrtc->Instance->TAFCR &= (uint32_t)~RTC_TAFCR_ALARMOUTTYPE; + hrtc->Instance->TAFCR |= (uint32_t)(hrtc->Init.OutPutType); + + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + /* Set RTC state */ + hrtc->State = HAL_RTC_STATE_READY; + + return HAL_OK; + } +} + +/** + * @brief DeInitializes the RTC peripheral + * @param hrtc: RTC handle + * @note This function doesn't reset the RTC Backup Data registers. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTC_DeInit(RTC_HandleTypeDef *hrtc) +{ + /* Check the parameters */ + assert_param(IS_RTC_ALL_INSTANCE(hrtc->Instance)); + + /* Set RTC state */ + hrtc->State = HAL_RTC_STATE_BUSY; + + /* Disable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + /* Set Initialization mode */ + if(RTC_EnterInitMode(hrtc) != HAL_OK) + { + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + /* Set RTC state */ + hrtc->State = HAL_RTC_STATE_ERROR; + + return HAL_ERROR; + } + else + { + /* Reset TR, DR and CR registers */ + hrtc->Instance->TR = (uint32_t)0x00000000; + hrtc->Instance->DR = (uint32_t)0x00002101; + /* Reset all RTC CR register bits */ + hrtc->Instance->CR &= (uint32_t)0x00000000; + hrtc->Instance->PRER = (uint32_t)0x007F00FF; + hrtc->Instance->ALRMAR = (uint32_t)0x00000000; + hrtc->Instance->SHIFTR = (uint32_t)0x00000000; + hrtc->Instance->CALR = (uint32_t)0x00000000; + hrtc->Instance->ALRMASSR = (uint32_t)0x00000000; + + /* Reset ISR register and exit initialization mode */ + hrtc->Instance->ISR = (uint32_t)0x00000000; + + /* Reset Tamper and alternate functions configuration register */ + hrtc->Instance->TAFCR = 0x00000000; + + /* If RTC_CR_BYPSHAD bit = 0, wait for synchro else this check is not needed */ + if((hrtc->Instance->CR & RTC_CR_BYPSHAD) == RESET) + { + if(HAL_RTC_WaitForSynchro(hrtc) != HAL_OK) + { + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + hrtc->State = HAL_RTC_STATE_ERROR; + + return HAL_ERROR; + } + } + } + + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + /* De-Initialize RTC MSP */ + HAL_RTC_MspDeInit(hrtc); + + hrtc->State = HAL_RTC_STATE_RESET; + + /* Release Lock */ + __HAL_UNLOCK(hrtc); + + return HAL_OK; +} + +/** + * @brief Initializes the RTC MSP. + * @param hrtc: RTC handle + * @retval None + */ +__weak void HAL_RTC_MspInit(RTC_HandleTypeDef* hrtc) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_RTC_MspInit could be implenetd in the user file + */ +} + +/** + * @brief DeInitializes the RTC MSP. + * @param hrtc: RTC handle + * @retval None + */ +__weak void HAL_RTC_MspDeInit(RTC_HandleTypeDef* hrtc) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_RTC_MspDeInit could be implenetd in the user file + */ +} + +/** + * @} + */ + +/** @defgroup RTC_Group2 RTC Time and Date functions + * @brief RTC Time and Date functions + * +@verbatim + =============================================================================== + ##### RTC Time and Date functions ##### + =============================================================================== + + [..] This section provide functions allowing to configure Time and Date features + +@endverbatim + * @{ + */ + +/** + * @brief Sets RTC current time. + * @param hrtc: RTC handle + * @param sTime: Pointer to Time structure + * @param Format: Specifies the format of the entered parameters. + * This parameter can be one of the following values: + * @arg Format_BIN: Binary data format + * @arg Format_BCD: BCD data format + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTC_SetTime(RTC_HandleTypeDef *hrtc, RTC_TimeTypeDef *sTime, uint32_t Format) +{ + uint32_t tmpreg = 0; + + /* Check the parameters */ + assert_param(IS_RTC_FORMAT(Format)); + assert_param(IS_RTC_DAYLIGHT_SAVING(sTime->DayLightSaving)); + assert_param(IS_RTC_STORE_OPERATION(sTime->StoreOperation)); + + /* Process Locked */ + __HAL_LOCK(hrtc); + + hrtc->State = HAL_RTC_STATE_BUSY; + + if(Format == FORMAT_BIN) + { + if((hrtc->Instance->CR & RTC_CR_FMT) != (uint32_t)RESET) + { + assert_param(IS_RTC_HOUR12(sTime->Hours)); + assert_param(IS_RTC_HOURFORMAT12(sTime->TimeFormat)); + } + else + { + sTime->TimeFormat = 0x00; + assert_param(IS_RTC_HOUR24(sTime->Hours)); + } + assert_param(IS_RTC_MINUTES(sTime->Minutes)); + assert_param(IS_RTC_SECONDS(sTime->Seconds)); + + tmpreg = (uint32_t)(((uint32_t)RTC_ByteToBcd2(sTime->Hours) << 16) | \ + ((uint32_t)RTC_ByteToBcd2(sTime->Minutes) << 8) | \ + ((uint32_t)RTC_ByteToBcd2(sTime->Seconds)) | \ + (((uint32_t)sTime->TimeFormat) << 16)); + } + else + { + if((hrtc->Instance->CR & RTC_CR_FMT) != (uint32_t)RESET) + { + tmpreg = RTC_Bcd2ToByte(sTime->Hours); + assert_param(IS_RTC_HOUR12(tmpreg)); + assert_param(IS_RTC_HOURFORMAT12(sTime->TimeFormat)); + } + else + { + sTime->TimeFormat = 0x00; + assert_param(IS_RTC_HOUR24(RTC_Bcd2ToByte(sTime->Hours))); + } + assert_param(IS_RTC_MINUTES(RTC_Bcd2ToByte(sTime->Minutes))); + assert_param(IS_RTC_SECONDS(RTC_Bcd2ToByte(sTime->Seconds))); + tmpreg = (((uint32_t)(sTime->Hours) << 16) | \ + ((uint32_t)(sTime->Minutes) << 8) | \ + ((uint32_t)sTime->Seconds) | \ + ((uint32_t)(sTime->TimeFormat) << 16)); + } + + /* Disable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + /* Set Initialization mode */ + if(RTC_EnterInitMode(hrtc) != HAL_OK) + { + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + /* Set RTC state */ + hrtc->State = HAL_RTC_STATE_ERROR; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_ERROR; + } + else + { + /* Set the RTC_TR register */ + hrtc->Instance->TR = (uint32_t)(tmpreg & RTC_TR_RESERVED_MASK); + + /* Clear the bits to be configured */ + hrtc->Instance->CR &= (uint32_t)~RTC_CR_BCK; + + /* Configure the RTC_CR register */ + hrtc->Instance->CR |= (uint32_t)(sTime->DayLightSaving | sTime->StoreOperation); + + /* Exit Initialization mode */ + hrtc->Instance->ISR &= (uint32_t)~RTC_ISR_INIT; + + /* If CR_BYPSHAD bit = 0, wait for synchro else this check is not needed */ + if((hrtc->Instance->CR & RTC_CR_BYPSHAD) == RESET) + { + if(HAL_RTC_WaitForSynchro(hrtc) != HAL_OK) + { + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + hrtc->State = HAL_RTC_STATE_ERROR; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_ERROR; + } + } + + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + hrtc->State = HAL_RTC_STATE_READY; + + __HAL_UNLOCK(hrtc); + + return HAL_OK; + } +} + +/** + * @brief Gets RTC current time. + * @param hrtc: RTC handle + * @param sTime: Pointer to Time structure + * @param Format: Specifies the format of the entered parameters. + * This parameter can be one of the following values: + * @arg Format_BIN: Binary data format + * @arg Format_BCD: BCD data format + * @note Call HAL_RTC_GetDate() after HAL_RTC_GetTime() to unlock the values + * in the higher-order calendar shadow registers. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTC_GetTime(RTC_HandleTypeDef *hrtc, RTC_TimeTypeDef *sTime, uint32_t Format) +{ + uint32_t tmpreg = 0; + + /* Check the parameters */ + assert_param(IS_RTC_FORMAT(Format)); + + /* Get subseconds values from the correspondent registers*/ + sTime->SubSeconds = (uint32_t)(hrtc->Instance->SSR); + + /* Get the TR register */ + tmpreg = (uint32_t)(hrtc->Instance->TR & RTC_TR_RESERVED_MASK); + + /* Fill the structure fields with the read parameters */ + sTime->Hours = (uint8_t)((tmpreg & (RTC_TR_HT | RTC_TR_HU)) >> 16); + sTime->Minutes = (uint8_t)((tmpreg & (RTC_TR_MNT | RTC_TR_MNU)) >>8); + sTime->Seconds = (uint8_t)(tmpreg & (RTC_TR_ST | RTC_TR_SU)); + sTime->TimeFormat = (uint8_t)((tmpreg & (RTC_TR_PM)) >> 16); + + /* Check the input parameters format */ + if(Format == FORMAT_BIN) + { + /* Convert the time structure parameters to Binary format */ + sTime->Hours = (uint8_t)RTC_Bcd2ToByte(sTime->Hours); + sTime->Minutes = (uint8_t)RTC_Bcd2ToByte(sTime->Minutes); + sTime->Seconds = (uint8_t)RTC_Bcd2ToByte(sTime->Seconds); + } + + return HAL_OK; +} + +/** + * @brief Sets RTC current date. + * @param hrtc: RTC handle + * @param sDate: Pointer to date structure + * @param Format: specifies the format of the entered parameters. + * This parameter can be one of the following values: + * @arg Format_BIN: Binary data format + * @arg Format_BCD: BCD data format + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTC_SetDate(RTC_HandleTypeDef *hrtc, RTC_DateTypeDef *sDate, uint32_t Format) +{ + uint32_t datetmpreg = 0; + + /* Check the parameters */ + assert_param(IS_RTC_FORMAT(Format)); + + /* Process Locked */ + __HAL_LOCK(hrtc); + + hrtc->State = HAL_RTC_STATE_BUSY; + + if((Format == FORMAT_BIN) && ((sDate->Month & 0x10) == 0x10)) + { + sDate->Month = (uint8_t)((sDate->Month & (uint8_t)~(0x10)) + (uint8_t)0x0A); + } + + assert_param(IS_RTC_WEEKDAY(sDate->WeekDay)); + + if(Format == FORMAT_BIN) + { + assert_param(IS_RTC_YEAR(sDate->Year)); + assert_param(IS_RTC_MONTH(sDate->Month)); + assert_param(IS_RTC_DATE(sDate->Date)); + + datetmpreg = (((uint32_t)RTC_ByteToBcd2(sDate->Year) << 16) | \ + ((uint32_t)RTC_ByteToBcd2(sDate->Month) << 8) | \ + ((uint32_t)RTC_ByteToBcd2(sDate->Date)) | \ + ((uint32_t)sDate->WeekDay << 13)); + } + else + { + assert_param(IS_RTC_YEAR(RTC_Bcd2ToByte(sDate->Year))); + datetmpreg = RTC_Bcd2ToByte(sDate->Month); + assert_param(IS_RTC_MONTH(datetmpreg)); + datetmpreg = RTC_Bcd2ToByte(sDate->Date); + assert_param(IS_RTC_DATE(datetmpreg)); + + datetmpreg = ((((uint32_t)sDate->Year) << 16) | \ + (((uint32_t)sDate->Month) << 8) | \ + ((uint32_t)sDate->Date) | \ + (((uint32_t)sDate->WeekDay) << 13)); + } + + /* Disable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + /* Set Initialization mode */ + if(RTC_EnterInitMode(hrtc) != HAL_OK) + { + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + /* Set RTC state*/ + hrtc->State = HAL_RTC_STATE_ERROR; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_ERROR; + } + else + { + /* Set the RTC_DR register */ + hrtc->Instance->DR = (uint32_t)(datetmpreg & RTC_DR_RESERVED_MASK); + + /* Exit Initialization mode */ + hrtc->Instance->ISR &= (uint32_t)~RTC_ISR_INIT; + + /* If CR_BYPSHAD bit = 0, wait for synchro else this check is not needed */ + if((hrtc->Instance->CR & RTC_CR_BYPSHAD) == RESET) + { + if(HAL_RTC_WaitForSynchro(hrtc) != HAL_OK) + { + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + hrtc->State = HAL_RTC_STATE_ERROR; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_ERROR; + } + } + + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + hrtc->State = HAL_RTC_STATE_READY ; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_OK; + } +} + +/** + * @brief Gets RTC current date. + * @param hrtc: RTC handle + * @param sDate: Pointer to Date structure + * @param Format: Specifies the format of the entered parameters. + * This parameter can be one of the following values: + * @arg Format_BIN : Binary data format + * @arg Format_BCD : BCD data format + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTC_GetDate(RTC_HandleTypeDef *hrtc, RTC_DateTypeDef *sDate, uint32_t Format) +{ + uint32_t datetmpreg = 0; + + /* Check the parameters */ + assert_param(IS_RTC_FORMAT(Format)); + + /* Get the DR register */ + datetmpreg = (uint32_t)(hrtc->Instance->DR & RTC_DR_RESERVED_MASK); + + /* Fill the structure fields with the read parameters */ + sDate->Year = (uint8_t)((datetmpreg & (RTC_DR_YT | RTC_DR_YU)) >> 16); + sDate->Month = (uint8_t)((datetmpreg & (RTC_DR_MT | RTC_DR_MU)) >> 8); + sDate->Date = (uint8_t)(datetmpreg & (RTC_DR_DT | RTC_DR_DU)); + sDate->WeekDay = (uint8_t)((datetmpreg & (RTC_DR_WDU)) >> 13); + + /* Check the input parameters format */ + if(Format == FORMAT_BIN) + { + /* Convert the date structure parameters to Binary format */ + sDate->Year = (uint8_t)RTC_Bcd2ToByte(sDate->Year); + sDate->Month = (uint8_t)RTC_Bcd2ToByte(sDate->Month); + sDate->Date = (uint8_t)RTC_Bcd2ToByte(sDate->Date); + } + return HAL_OK; +} + +/** + * @} + */ + +/** @defgroup RTC_Group3 RTC Alarm functions + * @brief RTC Alarm functions + * +@verbatim + =============================================================================== + ##### RTC Alarm functions ##### + =============================================================================== + + [..] This section provide functions allowing to configure Alarm feature + +@endverbatim + * @{ + */ +/** + * @brief Sets the specified RTC Alarm. + * @param hrtc: RTC handle + * @param sAlarm: Pointer to Alarm structure + * @param Format: Specifies the format of the entered parameters. + * This parameter can be one of the following values: + * @arg Format_BIN: Binary data format + * @arg Format_BCD: BCD data format + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTC_SetAlarm(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef *sAlarm, uint32_t Format) +{ + uint32_t timeout = 0; + uint32_t tmpreg = 0, subsecondtmpreg = 0; + + /* Check the parameters */ + assert_param(IS_RTC_FORMAT(Format)); + assert_param(IS_ALARM(sAlarm->Alarm)); + assert_param(IS_ALARM_MASK(sAlarm->AlarmMask)); + assert_param(IS_RTC_ALARM_DATE_WEEKDAY_SEL(sAlarm->AlarmDateWeekDaySel)); + assert_param(IS_RTC_ALARM_SUB_SECOND_VALUE(sAlarm->AlarmTime.SubSeconds)); + assert_param(IS_RTC_ALARM_SUB_SECOND_MASK(sAlarm->AlarmSubSecondMask)); + + /* Process Locked */ + __HAL_LOCK(hrtc); + + hrtc->State = HAL_RTC_STATE_BUSY; + + if(Format == FORMAT_BIN) + { + if((hrtc->Instance->CR & RTC_CR_FMT) != (uint32_t)RESET) + { + assert_param(IS_RTC_HOUR12(sAlarm->AlarmTime.Hours)); + assert_param(IS_RTC_HOURFORMAT12(sAlarm->AlarmTime.TimeFormat)); + } + else + { + sAlarm->AlarmTime.TimeFormat = 0x00; + assert_param(IS_RTC_HOUR24(sAlarm->AlarmTime.Hours)); + } + assert_param(IS_RTC_MINUTES(sAlarm->AlarmTime.Minutes)); + assert_param(IS_RTC_SECONDS(sAlarm->AlarmTime.Seconds)); + + if(sAlarm->AlarmDateWeekDaySel == RTC_ALARMDATEWEEKDAYSEL_DATE) + { + assert_param(IS_RTC_ALARM_DATE_WEEKDAY_DATE(sAlarm->AlarmDateWeekDay)); + } + else + { + assert_param(IS_RTC_ALARM_DATE_WEEKDAY_WEEKDAY(sAlarm->AlarmDateWeekDay)); + } + + tmpreg = (((uint32_t)RTC_ByteToBcd2(sAlarm->AlarmTime.Hours) << 16) | \ + ((uint32_t)RTC_ByteToBcd2(sAlarm->AlarmTime.Minutes) << 8) | \ + ((uint32_t)RTC_ByteToBcd2(sAlarm->AlarmTime.Seconds)) | \ + ((uint32_t)(sAlarm->AlarmTime.TimeFormat) << 16) | \ + ((uint32_t)RTC_ByteToBcd2(sAlarm->AlarmDateWeekDay) << 24) | \ + ((uint32_t)sAlarm->AlarmDateWeekDaySel) | \ + ((uint32_t)sAlarm->AlarmMask)); + } + else + { + if((hrtc->Instance->CR & RTC_CR_FMT) != (uint32_t)RESET) + { + tmpreg = RTC_Bcd2ToByte(sAlarm->AlarmTime.Hours); + assert_param(IS_RTC_HOUR12(tmpreg)); + assert_param(IS_RTC_HOURFORMAT12(sAlarm->AlarmTime.TimeFormat)); + } + else + { + sAlarm->AlarmTime.TimeFormat = 0x00; + assert_param(IS_RTC_HOUR24(RTC_Bcd2ToByte(sAlarm->AlarmTime.Hours))); + } + + assert_param(IS_RTC_MINUTES(RTC_Bcd2ToByte(sAlarm->AlarmTime.Minutes))); + assert_param(IS_RTC_SECONDS(RTC_Bcd2ToByte(sAlarm->AlarmTime.Seconds))); + + if(sAlarm->AlarmDateWeekDaySel == RTC_ALARMDATEWEEKDAYSEL_DATE) + { + tmpreg = RTC_Bcd2ToByte(sAlarm->AlarmDateWeekDay); + assert_param(IS_RTC_ALARM_DATE_WEEKDAY_DATE(tmpreg)); + } + else + { + tmpreg = RTC_Bcd2ToByte(sAlarm->AlarmDateWeekDay); + assert_param(IS_RTC_ALARM_DATE_WEEKDAY_WEEKDAY(tmpreg)); + } + + tmpreg = (((uint32_t)(sAlarm->AlarmTime.Hours) << 16) | \ + ((uint32_t)(sAlarm->AlarmTime.Minutes) << 8) | \ + ((uint32_t) sAlarm->AlarmTime.Seconds) | \ + ((uint32_t)(sAlarm->AlarmTime.TimeFormat) << 16) | \ + ((uint32_t)(sAlarm->AlarmDateWeekDay) << 24) | \ + ((uint32_t)sAlarm->AlarmDateWeekDaySel) | \ + ((uint32_t)sAlarm->AlarmMask)); + } + + /* Configure the Alarm A Sub Second registers */ + subsecondtmpreg = (uint32_t)((uint32_t)(sAlarm->AlarmTime.SubSeconds) | (uint32_t)(sAlarm->AlarmSubSecondMask)); + + /* Disable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + /* Disable the Alarm A interrupt */ + __HAL_RTC_ALARMA_DISABLE(hrtc); + + /* In case of interrupt mode is used, the interrupt source must disabled */ + __HAL_RTC_ALARM_DISABLE_IT(hrtc, RTC_IT_ALRA); + + timeout = HAL_GetTick() + RTC_TIMEOUT_VALUE; + /* Wait till RTC ALRAWF flag is set and if Time out is reached exit */ + while(__HAL_RTC_ALARM_GET_FLAG(hrtc, RTC_FLAG_ALRAWF) == RESET) + { + if(HAL_GetTick() >= timeout) + { + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + hrtc->State = HAL_RTC_STATE_TIMEOUT; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_TIMEOUT; + } + } + + hrtc->Instance->ALRMAR = (uint32_t)tmpreg; + /* Configure the Alarm A Sub Second register */ + hrtc->Instance->ALRMASSR = subsecondtmpreg; + /* Configure the Alarm state: Enable Alarm */ + __HAL_RTC_ALARMA_ENABLE(hrtc); + + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_OK; +} + +/** + * @brief Sets the specified RTC Alarm with Interrupt + * @param hrtc: RTC handle + * @param sAlarm: Pointer to Alarm structure + * @param Format: Specifies the format of the entered parameters. + * This parameter can be one of the following values: + * @arg Format_BIN: Binary data format + * @arg Format_BCD: BCD data format + * @note The Alarm register can only be written when the corresponding Alarm + * is disabled (Use the HAL_RTC_DeactivateAlarm()). + * @note The HAL_RTC_SetTime() must be called before enabling the Alarm feature. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTC_SetAlarm_IT(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef *sAlarm, uint32_t Format) +{ + uint32_t timeout = 0; + uint32_t tmpreg = 0, subsecondtmpreg = 0; + + /* Check the parameters */ + assert_param(IS_RTC_FORMAT(Format)); + assert_param(IS_ALARM(sAlarm->Alarm)); + assert_param(IS_ALARM_MASK(sAlarm->AlarmMask)); + assert_param(IS_RTC_ALARM_DATE_WEEKDAY_SEL(sAlarm->AlarmDateWeekDaySel)); + assert_param(IS_RTC_ALARM_SUB_SECOND_VALUE(sAlarm->AlarmTime.SubSeconds)); + assert_param(IS_RTC_ALARM_SUB_SECOND_MASK(sAlarm->AlarmSubSecondMask)); + + /* Process Locked */ + __HAL_LOCK(hrtc); + + hrtc->State = HAL_RTC_STATE_BUSY; + + if(Format == FORMAT_BIN) + { + if((hrtc->Instance->CR & RTC_CR_FMT) != (uint32_t)RESET) + { + assert_param(IS_RTC_HOUR12(sAlarm->AlarmTime.Hours)); + assert_param(IS_RTC_HOURFORMAT12(sAlarm->AlarmTime.TimeFormat)); + } + else + { + sAlarm->AlarmTime.TimeFormat = 0x00; + assert_param(IS_RTC_HOUR24(sAlarm->AlarmTime.Hours)); + } + assert_param(IS_RTC_MINUTES(sAlarm->AlarmTime.Minutes)); + assert_param(IS_RTC_SECONDS(sAlarm->AlarmTime.Seconds)); + + if(sAlarm->AlarmDateWeekDaySel == RTC_ALARMDATEWEEKDAYSEL_DATE) + { + assert_param(IS_RTC_ALARM_DATE_WEEKDAY_DATE(sAlarm->AlarmDateWeekDay)); + } + else + { + assert_param(IS_RTC_ALARM_DATE_WEEKDAY_WEEKDAY(sAlarm->AlarmDateWeekDay)); + } + tmpreg = (((uint32_t)RTC_ByteToBcd2(sAlarm->AlarmTime.Hours) << 16) | \ + ((uint32_t)RTC_ByteToBcd2(sAlarm->AlarmTime.Minutes) << 8) | \ + ((uint32_t)RTC_ByteToBcd2(sAlarm->AlarmTime.Seconds)) | \ + ((uint32_t)(sAlarm->AlarmTime.TimeFormat) << 16) | \ + ((uint32_t)RTC_ByteToBcd2(sAlarm->AlarmDateWeekDay) << 24) | \ + ((uint32_t)sAlarm->AlarmDateWeekDaySel) | \ + ((uint32_t)sAlarm->AlarmMask)); + } + else + { + if((hrtc->Instance->CR & RTC_CR_FMT) != (uint32_t)RESET) + { + tmpreg = RTC_Bcd2ToByte(sAlarm->AlarmTime.Hours); + assert_param(IS_RTC_HOUR12(tmpreg)); + assert_param(IS_RTC_HOURFORMAT12(sAlarm->AlarmTime.TimeFormat)); + } + else + { + sAlarm->AlarmTime.TimeFormat = 0x00; + assert_param(IS_RTC_HOUR24(RTC_Bcd2ToByte(sAlarm->AlarmTime.Hours))); + } + + assert_param(IS_RTC_MINUTES(RTC_Bcd2ToByte(sAlarm->AlarmTime.Minutes))); + assert_param(IS_RTC_SECONDS(RTC_Bcd2ToByte(sAlarm->AlarmTime.Seconds))); + + if(sAlarm->AlarmDateWeekDaySel == RTC_ALARMDATEWEEKDAYSEL_DATE) + { + tmpreg = RTC_Bcd2ToByte(sAlarm->AlarmDateWeekDay); + assert_param(IS_RTC_ALARM_DATE_WEEKDAY_DATE(tmpreg)); + } + else + { + tmpreg = RTC_Bcd2ToByte(sAlarm->AlarmDateWeekDay); + assert_param(IS_RTC_ALARM_DATE_WEEKDAY_WEEKDAY(tmpreg)); + } + tmpreg = (((uint32_t)(sAlarm->AlarmTime.Hours) << 16) | \ + ((uint32_t)(sAlarm->AlarmTime.Minutes) << 8) | \ + ((uint32_t) sAlarm->AlarmTime.Seconds) | \ + ((uint32_t)(sAlarm->AlarmTime.TimeFormat) << 16) | \ + ((uint32_t)(sAlarm->AlarmDateWeekDay) << 24) | \ + ((uint32_t)sAlarm->AlarmDateWeekDaySel) | \ + ((uint32_t)sAlarm->AlarmMask)); + } + /* Configure the Alarm A Sub Second registers */ + subsecondtmpreg = (uint32_t)((uint32_t)(sAlarm->AlarmTime.SubSeconds) | (uint32_t)(sAlarm->AlarmSubSecondMask)); + + /* Disable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + /* Disable the Alarm A interrupt */ + __HAL_RTC_ALARMA_DISABLE(hrtc); + + /* Clear flag alarm A */ + __HAL_RTC_ALARM_CLEAR_FLAG(hrtc, RTC_FLAG_ALRAF); + + timeout = HAL_GetTick() + RTC_TIMEOUT_VALUE; + /* Wait till RTC ALRAWF flag is set and if Time out is reached exit */ + while(__HAL_RTC_ALARM_GET_FLAG(hrtc, RTC_FLAG_ALRAWF) == RESET) + { + if(HAL_GetTick() >= timeout) + { + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + hrtc->State = HAL_RTC_STATE_TIMEOUT; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_TIMEOUT; + } + } + + hrtc->Instance->ALRMAR = (uint32_t)tmpreg; + /* Configure the Alarm A Sub Second register */ + hrtc->Instance->ALRMASSR = subsecondtmpreg; + /* Configure the Alarm state: Enable Alarm */ + __HAL_RTC_ALARMA_ENABLE(hrtc); + /* Configure the Alarm interrupt */ + __HAL_RTC_ALARM_ENABLE_IT(hrtc,RTC_IT_ALRA); + + /* RTC Alarm Interrupt Configuration: EXTI configuration */ + __HAL_RTC_EXTI_ENABLE_IT(RTC_EXTI_LINE_ALARM_EVENT); + + EXTI->RTSR |= RTC_EXTI_LINE_ALARM_EVENT; + + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + hrtc->State = HAL_RTC_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_OK; +} + +/** + * @brief Deactive the specified RTC Alarm + * @param hrtc: RTC handle + * @param Alarm: Specifies the Alarm. + * This parameter can be one of the following values: + * @arg ALARM_A : AlarmA + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTC_DeactivateAlarm(RTC_HandleTypeDef *hrtc, uint32_t Alarm) +{ + uint32_t timeout = 0; + + /* Check the parameters */ + assert_param(IS_ALARM(Alarm)); + + /* Process Locked */ + __HAL_LOCK(hrtc); + + hrtc->State = HAL_RTC_STATE_BUSY; + + /* Disable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + __HAL_RTC_ALARMA_DISABLE(hrtc); + + /* In case of interrupt mode is used, the interrupt source must disabled */ + __HAL_RTC_ALARM_DISABLE_IT(hrtc, RTC_IT_ALRA); + + timeout = HAL_GetTick() + RTC_TIMEOUT_VALUE; + + /* Wait till RTC ALRxWF flag is set and if Time out is reached exit */ + while(__HAL_RTC_ALARM_GET_FLAG(hrtc, RTC_FLAG_ALRAWF) == RESET) + { + if(HAL_GetTick() >= timeout) + { + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + hrtc->State = HAL_RTC_STATE_TIMEOUT; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_TIMEOUT; + } + } + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + hrtc->State = HAL_RTC_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_OK; +} + +/** + * @brief Gets the RTC Alarm value and masks. + * @param hrtc: RTC handle + * @param sAlarm: Pointer to Date structure + * @param Alarm: Specifies the Alarm + * This parameter can be one of the following values: + * @arg ALARM_A: AlarmA + * @param Format: Specifies the format of the entered parameters. + * This parameter can be one of the following values: + * @arg Format_BIN: Binary data format + * @arg Format_BCD: BCD data format + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTC_GetAlarm(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef *sAlarm, uint32_t Alarm, uint32_t Format) +{ + uint32_t tmpreg = 0, subsecondtmpreg = 0; + + /* Check the parameters */ + assert_param(IS_RTC_FORMAT(Format)); + assert_param(IS_ALARM(Alarm)); + + sAlarm->Alarm = RTC_ALARM_A; + + tmpreg = (uint32_t)(hrtc->Instance->ALRMAR); + subsecondtmpreg = (uint32_t)((hrtc->Instance->ALRMASSR ) & RTC_ALRMASSR_SS); + + /* Fill the structure with the read parameters */ + sAlarm->AlarmTime.Hours = (uint32_t)((tmpreg & (RTC_ALRMAR_HT | RTC_ALRMAR_HU)) >> 16); + sAlarm->AlarmTime.Minutes = (uint32_t)((tmpreg & (RTC_ALRMAR_MNT | RTC_ALRMAR_MNU)) >> 8); + sAlarm->AlarmTime.Seconds = (uint32_t)(tmpreg & (RTC_ALRMAR_ST | RTC_ALRMAR_SU)); + sAlarm->AlarmTime.TimeFormat = (uint32_t)((tmpreg & RTC_ALRMAR_PM) >> 16); + sAlarm->AlarmTime.SubSeconds = (uint32_t) subsecondtmpreg; + sAlarm->AlarmDateWeekDay = (uint32_t)((tmpreg & (RTC_ALRMAR_DT | RTC_ALRMAR_DU)) >> 24); + sAlarm->AlarmDateWeekDaySel = (uint32_t)(tmpreg & RTC_ALRMAR_WDSEL); + sAlarm->AlarmMask = (uint32_t)(tmpreg & RTC_ALARMMASK_ALL); + + if(Format == FORMAT_BIN) + { + sAlarm->AlarmTime.Hours = RTC_Bcd2ToByte(sAlarm->AlarmTime.Hours); + sAlarm->AlarmTime.Minutes = RTC_Bcd2ToByte(sAlarm->AlarmTime.Minutes); + sAlarm->AlarmTime.Seconds = RTC_Bcd2ToByte(sAlarm->AlarmTime.Seconds); + sAlarm->AlarmDateWeekDay = RTC_Bcd2ToByte(sAlarm->AlarmDateWeekDay); + } + + return HAL_OK; +} + +/** + * @brief This function handles Alarm interrupt request. + * @param hrtc: RTC handle + * @retval None + */ +void HAL_RTC_AlarmIRQHandler(RTC_HandleTypeDef* hrtc) +{ + if(__HAL_RTC_ALARM_GET_IT(hrtc, RTC_IT_ALRA)) + { + /* Get the status of the Interrupt */ + if((uint32_t)(hrtc->Instance->CR & RTC_IT_ALRA) != (uint32_t)RESET) + { + /* AlarmA callback */ + HAL_RTC_AlarmAEventCallback(hrtc); + + /* Clear the Alarm interrupt pending bit */ + __HAL_RTC_ALARM_CLEAR_FLAG(hrtc,RTC_FLAG_ALRAF); + } + } + + /* Clear the EXTI's line Flag for RTC Alarm */ + __HAL_RTC_EXTI_CLEAR_FLAG(RTC_EXTI_LINE_ALARM_EVENT); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_READY; +} + +/** + * @brief Alarm A callback. + * @param hrtc: RTC handle + * @retval None + */ +__weak void HAL_RTC_AlarmAEventCallback(RTC_HandleTypeDef *hrtc) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_RTC_AlarmAEventCallback could be implemented in the user file + */ +} + +/** + * @brief This function handles AlarmA Polling request. + * @param hrtc: RTC handle + * @param Timeout: Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTC_PollForAlarmAEvent(RTC_HandleTypeDef *hrtc, uint32_t Timeout) +{ + + uint32_t timeout = 0; + + /* Get Timeout value */ + timeout = HAL_GetTick() + Timeout; + + while(__HAL_RTC_ALARM_GET_FLAG(hrtc, RTC_FLAG_ALRAF) == RESET) + { + if(Timeout != HAL_MAX_DELAY) + { + if(HAL_GetTick() >= timeout) + { + hrtc->State = HAL_RTC_STATE_TIMEOUT; + return HAL_TIMEOUT; + } + } + } + + /* Clear the Alarm interrupt pending bit */ + __HAL_RTC_ALARM_CLEAR_FLAG(hrtc, RTC_FLAG_ALRAF); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_READY; + + return HAL_OK; +} + +/** + * @} + */ + +/** @defgroup RTC_Group4 Peripheral Control functions + * @brief Peripheral Control functions + * +@verbatim + =============================================================================== + ##### Peripheral Control functions ##### + =============================================================================== + [..] + This subsection provides functions allowing to + (+) Wait for RTC Time and Date Synchronization + +@endverbatim + * @{ + */ + +/** + * @brief Waits until the RTC Time and Date registers (RTC_TR and RTC_DR) are + * synchronized with RTC APB clock. + * @note The RTC Resynchronization mode is write protected, use the + * __HAL_RTC_WRITEPROTECTION_DISABLE() before calling this function. + * @note To read the calendar through the shadow registers after Calendar + * initialization, calendar update or after wakeup from low power modes + * the software must first clear the RSF flag. + * The software must then wait until it is set again before reading + * the calendar, which means that the calendar registers have been + * correctly copied into the RTC_TR and RTC_DR shadow registers. + * @param hrtc: RTC handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTC_WaitForSynchro(RTC_HandleTypeDef* hrtc) +{ + uint32_t timeout = 0; + + /* Clear RSF flag */ + hrtc->Instance->ISR &= (uint32_t)RTC_RSF_MASK; + + timeout = HAL_GetTick() + RTC_TIMEOUT_VALUE; + + /* Wait the registers to be synchronised */ + while((hrtc->Instance->ISR & RTC_ISR_RSF) == (uint32_t)RESET) + { + if(HAL_GetTick() >= timeout) + { + return HAL_TIMEOUT; + } + } + + return HAL_OK; +} + +/** + * @} + */ + +/** @defgroup RTC_Group5 Peripheral State functions + * @brief Peripheral State functions + * +@verbatim + =============================================================================== + ##### Peripheral State functions ##### + =============================================================================== + [..] + This subsection provides functions allowing to + (+) Get RTC state + +@endverbatim + * @{ + */ +/** + * @brief Returns the Alarm state. + * @param hrtc: RTC handle + * @retval HAL state + */ +HAL_RTCStateTypeDef HAL_RTC_GetState(RTC_HandleTypeDef* hrtc) +{ + return hrtc->State; +} + +/** + * @} + */ + +/** + * @brief Enters the RTC Initialization mode. + * @note The RTC Initialization mode is write protected, use the + * __HAL_RTC_WRITEPROTECTION_DISABLE() before calling this function. + * @param hrtc: RTC handle + * @retval An ErrorStatus enumeration value: + * - HAL_OK : RTC is in Init mode + * - HAL_TIMEOUT : RTC is not in Init mode and in Timeout + */ +HAL_StatusTypeDef RTC_EnterInitMode(RTC_HandleTypeDef* hrtc) +{ + uint32_t timeout = 0; + + /* Check if the Initialization mode is set */ + if((hrtc->Instance->ISR & RTC_ISR_INITF) == (uint32_t)RESET) + { + /* Set the Initialization mode */ + hrtc->Instance->ISR = (uint32_t)RTC_INIT_MASK; + + timeout = HAL_GetTick() + RTC_TIMEOUT_VALUE; + /* Wait till RTC is in INIT state and if Time out is reached exit */ + while((hrtc->Instance->ISR & RTC_ISR_INITF) == (uint32_t)RESET) + { + if(HAL_GetTick() >= timeout) + { + return HAL_TIMEOUT; + } + } + } + + return HAL_OK; +} + + +/** + * @brief Converts a 2 digit decimal to BCD format. + * @param Value: Byte to be converted + * @retval Converted byte + */ +uint8_t RTC_ByteToBcd2(uint8_t Value) +{ + uint32_t bcdhigh = 0; + + while(Value >= 10) + { + bcdhigh++; + Value -= 10; + } + + return ((uint8_t)(bcdhigh << 4) | Value); +} + +/** + * @brief Converts from 2 digit BCD to Binary. + * @param Value: BCD value to be converted + * @retval Converted word + */ +uint8_t RTC_Bcd2ToByte(uint8_t Value) +{ + uint32_t tmp = 0; + tmp = ((uint8_t)(Value & (uint8_t)0xF0) >> (uint8_t)0x4) * 10; + return (tmp + (Value & (uint8_t)0x0F)); +} + +/** + * @} + */ + +#endif /* HAL_RTC_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_rtc.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_rtc.h new file mode 100644 index 0000000000..1721236f60 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_rtc.h @@ -0,0 +1,722 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_rtc.h + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief Header file of RTC HAL module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32F0xx_HAL_RTC_H +#define __STM32F0xx_HAL_RTC_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal_def.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @addtogroup RTC + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/** + * @brief HAL State structures definition + */ +typedef enum +{ + HAL_RTC_STATE_RESET = 0x00, /*!< RTC not yet initialized or disabled */ + HAL_RTC_STATE_READY = 0x01, /*!< RTC initialized and ready for use */ + HAL_RTC_STATE_BUSY = 0x02, /*!< RTC process is ongoing */ + HAL_RTC_STATE_TIMEOUT = 0x03, /*!< RTC timeout state */ + HAL_RTC_STATE_ERROR = 0x04 /*!< RTC error state */ + +}HAL_RTCStateTypeDef; + +/** + * @brief RTC Configuration Structure definition + */ +typedef struct +{ + uint32_t HourFormat; /*!< Specifies the RTC Hour Format. + This parameter can be a value of @ref RTC_Hour_Formats */ + + uint32_t AsynchPrediv; /*!< Specifies the RTC Asynchronous Predivider value. + This parameter must be a number between Min_Data = 0x00 and Max_Data = 0x7F */ + + uint32_t SynchPrediv; /*!< Specifies the RTC Synchronous Predivider value. + This parameter must be a number between Min_Data = 0x00 and Max_Data = 0x7FFF */ + + uint32_t OutPut; /*!< Specifies which signal will be routed to the RTC output. + This parameter can be a value of @ref RTCEx_Output_selection_Definitions */ + + uint32_t OutPutPolarity; /*!< Specifies the polarity of the output signal. + This parameter can be a value of @ref RTC_Output_Polarity_Definitions */ + + uint32_t OutPutType; /*!< Specifies the RTC Output Pin mode. + This parameter can be a value of @ref RTC_Output_Type_ALARM_OUT */ +}RTC_InitTypeDef; + +/** + * @brief RTC Time structure definition + */ +typedef struct +{ + uint8_t Hours; /*!< Specifies the RTC Time Hour. + This parameter must be a number between Min_Data = 0 and Max_Data = 12 if the RTC_HourFormat_12 is selected. + This parameter must be a number between Min_Data = 0 and Max_Data = 23 if the RTC_HourFormat_24 is selected */ + + uint8_t Minutes; /*!< Specifies the RTC Time Minutes. + This parameter must be a number between Min_Data = 0 and Max_Data = 59 */ + + uint8_t Seconds; /*!< Specifies the RTC Time Seconds. + This parameter must be a number between Min_Data = 0 and Max_Data = 59 */ + + uint32_t SubSeconds; /*!< Specifies the RTC Time SubSeconds. + This parameter must be a number between Min_Data = 0 and Max_Data = 59 */ + + uint8_t TimeFormat; /*!< Specifies the RTC AM/PM Time. + This parameter can be a value of @ref RTC_AM_PM_Definitions */ + + uint32_t DayLightSaving; /*!< Specifies RTC_DayLightSaveOperation: the value of hour adjustment. + This parameter can be a value of @ref RTC_DayLightSaving_Definitions */ + + uint32_t StoreOperation; /*!< Specifies RTC_StoreOperation value to be written in the BCK bit + in CR register to store the operation. + This parameter can be a value of @ref RTC_StoreOperation_Definitions */ +}RTC_TimeTypeDef; + +/** + * @brief RTC Date structure definition + */ +typedef struct +{ + uint8_t WeekDay; /*!< Specifies the RTC Date WeekDay. + This parameter can be a value of @ref RTC_WeekDay_Definitions */ + + uint8_t Month; /*!< Specifies the RTC Date Month (in BCD format). + This parameter can be a value of @ref RTC_Month_Date_Definitions */ + + uint8_t Date; /*!< Specifies the RTC Date. + This parameter must be a number between Min_Data = 1 and Max_Data = 31 */ + + uint8_t Year; /*!< Specifies the RTC Date Year. + This parameter must be a number between Min_Data = 0 and Max_Data = 99 */ + +}RTC_DateTypeDef; + +/** + * @brief RTC Alarm structure definition + */ +typedef struct +{ + RTC_TimeTypeDef AlarmTime; /*!< Specifies the RTC Alarm Time members */ + + uint32_t AlarmMask; /*!< Specifies the RTC Alarm Masks. + This parameter can be a value of @ref RTC_AlarmMask_Definitions */ + + uint32_t AlarmSubSecondMask; /*!< Specifies the RTC Alarm SubSeconds Masks. + This parameter can be a value of @ref RTC_Alarm_Sub_Seconds_Masks_Definitions */ + + uint32_t AlarmDateWeekDaySel; /*!< Specifies the RTC Alarm is on Date or WeekDay. + This parameter can be a value of @ref RTC_AlarmDateWeekDay_Definitions */ + + uint8_t AlarmDateWeekDay; /*!< Specifies the RTC Alarm Date/WeekDay. + If the Alarm Date is selected, this parameter must be set to a value in the 1-31 range. + If the Alarm WeekDay is selected, this parameter can be a value of @ref RTC_WeekDay_Definitions */ + + uint32_t Alarm; /*!< Specifies the alarm . + This parameter can be a value of @ref RTC_Alarms_Definitions */ +}RTC_AlarmTypeDef; + +/** + * @brief Time Handle Structure definition + */ +typedef struct +{ + RTC_TypeDef *Instance; /*!< Register base address */ + + RTC_InitTypeDef Init; /*!< RTC required parameters */ + + HAL_LockTypeDef Lock; /*!< RTC locking object */ + + __IO HAL_RTCStateTypeDef State; /*!< Time communication state */ + +}RTC_HandleTypeDef; + +/* Exported constants --------------------------------------------------------*/ +/** @defgroup RTC_Exported_Constants + * @{ + */ + +/* Masks Definition */ +#define RTC_TR_RESERVED_MASK ((uint32_t)0x007F7F7F) +#define RTC_DR_RESERVED_MASK ((uint32_t)0x00FFFF3F) +#define RTC_INIT_MASK ((uint32_t)0xFFFFFFFF) +#define RTC_RSF_MASK ((uint32_t)0xFFFFFF5F) + +#define RTC_TIMEOUT_VALUE 1000 + +/** @defgroup RTC_Hour_Formats + * @{ + */ +#define RTC_HOURFORMAT_24 ((uint32_t)0x00000000) +#define RTC_HOURFORMAT_12 ((uint32_t)0x00000040) + +#define IS_RTC_HOUR_FORMAT(FORMAT) (((FORMAT) == RTC_HOURFORMAT_12) || \ + ((FORMAT) == RTC_HOURFORMAT_24)) +/** + * @} + */ + +/** @defgroup RTC_Output_Polarity_Definitions + * @{ + */ +#define RTC_OUTPUT_POLARITY_HIGH ((uint32_t)0x00000000) +#define RTC_OUTPUT_POLARITY_LOW ((uint32_t)0x00100000) + +#define IS_RTC_OUTPUT_POL(POL) (((POL) == RTC_OUTPUT_POLARITY_HIGH) || \ + ((POL) == RTC_OUTPUT_POLARITY_LOW)) +/** + * @} + */ + +/** @defgroup RTC_Output_Type_ALARM_OUT + * @{ + */ +#define RTC_OUTPUT_TYPE_OPENDRAIN ((uint32_t)0x00000000) +#define RTC_OUTPUT_TYPE_PUSHPULL ((uint32_t)0x00040000) + +#define IS_RTC_OUTPUT_TYPE(TYPE) (((TYPE) == RTC_OUTPUT_TYPE_OPENDRAIN) || \ + ((TYPE) == RTC_OUTPUT_TYPE_PUSHPULL)) + +/** + * @} + */ + +/** @defgroup RTC_Asynchronous_Predivider + * @{ + */ +#define IS_RTC_ASYNCH_PREDIV(PREDIV) ((PREDIV) <= (uint32_t)0x7F) +/** + * @} + */ + + +/** @defgroup RTC_Synchronous_Predivider + * @{ + */ +#define IS_RTC_SYNCH_PREDIV(PREDIV) ((PREDIV) <= (uint32_t)0x7FFF) +/** + * @} + */ + +/** @defgroup RTC_Time_Definitions + * @{ + */ +#define IS_RTC_HOUR12(HOUR) (((HOUR) > (uint32_t)0) && ((HOUR) <= (uint32_t)12)) +#define IS_RTC_HOUR24(HOUR) ((HOUR) <= (uint32_t)23) +#define IS_RTC_MINUTES(MINUTES) ((MINUTES) <= (uint32_t)59) +#define IS_RTC_SECONDS(SECONDS) ((SECONDS) <= (uint32_t)59) +/** + * @} + */ + +/** @defgroup RTC_AM_PM_Definitions + * @{ + */ +#define RTC_HOURFORMAT12_AM ((uint8_t)0x00) +#define RTC_HOURFORMAT12_PM ((uint8_t)0x40) + +#define IS_RTC_HOURFORMAT12(PM) (((PM) == RTC_HOURFORMAT12_AM) || ((PM) == RTC_HOURFORMAT12_PM)) +/** + * @} + */ + +/** @defgroup RTC_DayLightSaving_Definitions + * @{ + */ +#define RTC_DAYLIGHTSAVING_SUB1H ((uint32_t)0x00020000) +#define RTC_DAYLIGHTSAVING_ADD1H ((uint32_t)0x00010000) +#define RTC_DAYLIGHTSAVING_NONE ((uint32_t)0x00000000) + +#define IS_RTC_DAYLIGHT_SAVING(SAVE) (((SAVE) == RTC_DAYLIGHTSAVING_SUB1H) || \ + ((SAVE) == RTC_DAYLIGHTSAVING_ADD1H) || \ + ((SAVE) == RTC_DAYLIGHTSAVING_NONE)) +/** + * @} + */ + +/** @defgroup RTC_StoreOperation_Definitions + * @{ + */ +#define RTC_STOREOPERATION_RESET ((uint32_t)0x00000000) +#define RTC_STOREOPERATION_SET ((uint32_t)0x00040000) + +#define IS_RTC_STORE_OPERATION(OPERATION) (((OPERATION) == RTC_STOREOPERATION_RESET) || \ + ((OPERATION) == RTC_STOREOPERATION_SET)) +/** + * @} + */ + +/** @defgroup RTC_Input_parameter_format_definitions + * @{ + */ +#define FORMAT_BIN ((uint32_t)0x000000000) +#define FORMAT_BCD ((uint32_t)0x000000001) + +#define IS_RTC_FORMAT(FORMAT) (((FORMAT) == FORMAT_BIN) || ((FORMAT) == FORMAT_BCD)) +/** + * @} + */ + +/** @defgroup RTC_Year_Date_Definitions + * @{ + */ +#define IS_RTC_YEAR(YEAR) ((YEAR) <= (uint32_t)99) +/** + * @} + */ + +/** @defgroup RTC_Month_Date_Definitions + * @{ + */ + +/* Coded in BCD format */ +#define RTC_MONTH_JANUARY ((uint8_t)0x01) +#define RTC_MONTH_FEBRUARY ((uint8_t)0x02) +#define RTC_MONTH_MARCH ((uint8_t)0x03) +#define RTC_MONTH_APRIL ((uint8_t)0x04) +#define RTC_MONTH_MAY ((uint8_t)0x05) +#define RTC_MONTH_JUNE ((uint8_t)0x06) +#define RTC_MONTH_JULY ((uint8_t)0x07) +#define RTC_MONTH_AUGUST ((uint8_t)0x08) +#define RTC_MONTH_SEPTEMBER ((uint8_t)0x09) +#define RTC_MONTH_OCTOBER ((uint8_t)0x10) +#define RTC_MONTH_NOVEMBER ((uint8_t)0x11) +#define RTC_MONTH_DECEMBER ((uint8_t)0x12) + +#define IS_RTC_MONTH(MONTH) (((MONTH) >= (uint32_t)1) && ((MONTH) <= (uint32_t)12)) +#define IS_RTC_DATE(DATE) (((DATE) >= (uint32_t)1) && ((DATE) <= (uint32_t)31)) +/** + * @} + */ + +/** @defgroup RTC_WeekDay_Definitions + * @{ + */ +#define RTC_WEEKDAY_MONDAY ((uint8_t)0x01) +#define RTC_WEEKDAY_TUESDAY ((uint8_t)0x02) +#define RTC_WEEKDAY_WEDNESDAY ((uint8_t)0x03) +#define RTC_WEEKDAY_THURSDAY ((uint8_t)0x04) +#define RTC_WEEKDAY_FRIDAY ((uint8_t)0x05) +#define RTC_WEEKDAY_SATURDAY ((uint8_t)0x06) +#define RTC_WEEKDAY_SUNDAY ((uint8_t)0x07) + +#define IS_RTC_WEEKDAY(WEEKDAY) (((WEEKDAY) == RTC_WEEKDAY_MONDAY) || \ + ((WEEKDAY) == RTC_WEEKDAY_TUESDAY) || \ + ((WEEKDAY) == RTC_WEEKDAY_WEDNESDAY) || \ + ((WEEKDAY) == RTC_WEEKDAY_THURSDAY) || \ + ((WEEKDAY) == RTC_WEEKDAY_FRIDAY) || \ + ((WEEKDAY) == RTC_WEEKDAY_SATURDAY) || \ + ((WEEKDAY) == RTC_WEEKDAY_SUNDAY)) +/** + * @} + */ + +/** @defgroup RTC_Alarm_Definitions + * @{ + */ +#define IS_RTC_ALARM_DATE_WEEKDAY_DATE(DATE) (((DATE) >(uint32_t) 0) && ((DATE) <= (uint32_t)31)) +#define IS_RTC_ALARM_DATE_WEEKDAY_WEEKDAY(WEEKDAY) (((WEEKDAY) == RTC_WEEKDAY_MONDAY) || \ + ((WEEKDAY) == RTC_WEEKDAY_TUESDAY) || \ + ((WEEKDAY) == RTC_WEEKDAY_WEDNESDAY) || \ + ((WEEKDAY) == RTC_WEEKDAY_THURSDAY) || \ + ((WEEKDAY) == RTC_WEEKDAY_FRIDAY) || \ + ((WEEKDAY) == RTC_WEEKDAY_SATURDAY) || \ + ((WEEKDAY) == RTC_WEEKDAY_SUNDAY)) +/** + * @} + */ + + +/** @defgroup RTC_AlarmDateWeekDay_Definitions + * @{ + */ +#define RTC_ALARMDATEWEEKDAYSEL_DATE ((uint32_t)0x00000000) +#define RTC_ALARMDATEWEEKDAYSEL_WEEKDAY ((uint32_t)0x40000000) + +#define IS_RTC_ALARM_DATE_WEEKDAY_SEL(SEL) (((SEL) == RTC_ALARMDATEWEEKDAYSEL_DATE) || \ + ((SEL) == RTC_ALARMDATEWEEKDAYSEL_WEEKDAY)) +/** + * @} + */ + + +/** @defgroup RTC_AlarmMask_Definitions + * @{ + */ +#define RTC_ALARMMASK_NONE ((uint32_t)0x00000000) +#define RTC_ALARMMASK_DATEWEEKDAY RTC_ALRMAR_MSK4 +#define RTC_ALARMMASK_HOURS RTC_ALRMAR_MSK3 +#define RTC_ALARMMASK_MINUTES RTC_ALRMAR_MSK2 +#define RTC_ALARMMASK_SECONDS RTC_ALRMAR_MSK1 +#define RTC_ALARMMASK_ALL ((uint32_t)0x80808080) + +#define IS_ALARM_MASK(MASK) (((MASK) & 0x7F7F7F7F) == (uint32_t)RESET) +/** + * @} + */ + +/** @defgroup RTC_Alarms_Definitions + * @{ + */ +#define RTC_ALARM_A RTC_CR_ALRAE + +#define IS_ALARM(ALARM) ((ALARM) == RTC_ALARM_A) +/** + * @} + */ + +/** @defgroup RTC_Alarm_Sub_Seconds_Value + * @{ + */ +#define IS_RTC_ALARM_SUB_SECOND_VALUE(VALUE) ((VALUE) <= (uint32_t)0x00007FFF) +/** + * @} + */ + + /** @defgroup RTC_Alarm_Sub_Seconds_Masks_Definitions + * @{ + */ +#define RTC_ALARMSUBSECONDMASK_ALL ((uint32_t)0x00000000) /*!< All Alarm SS fields are masked. + There is no comparison on sub seconds + for Alarm */ +#define RTC_ALARMSUBSECONDMASK_SS14_1 ((uint32_t)0x01000000) /*!< SS[14:1] are don't care in Alarm + comparison. Only SS[0] is compared. */ +#define RTC_ALARMSUBSECONDMASK_SS14_2 ((uint32_t)0x02000000) /*!< SS[14:2] are don't care in Alarm + comparison. Only SS[1:0] are compared */ +#define RTC_ALARMSUBSECONDMASK_SS14_3 ((uint32_t)0x03000000) /*!< SS[14:3] are don't care in Alarm + comparison. Only SS[2:0] are compared */ +#define RTC_ALARMSUBSECONDMASK_SS14_4 ((uint32_t)0x04000000) /*!< SS[14:4] are don't care in Alarm + comparison. Only SS[3:0] are compared */ +#define RTC_ALARMSUBSECONDMASK_SS14_5 ((uint32_t)0x05000000) /*!< SS[14:5] are don't care in Alarm + comparison. Only SS[4:0] are compared */ +#define RTC_ALARMSUBSECONDMASK_SS14_6 ((uint32_t)0x06000000) /*!< SS[14:6] are don't care in Alarm + comparison. Only SS[5:0] are compared */ +#define RTC_ALARMSUBSECONDMASK_SS14_7 ((uint32_t)0x07000000) /*!< SS[14:7] are don't care in Alarm + comparison. Only SS[6:0] are compared */ +#define RTC_ALARMSUBSECONDMASK_SS14_8 ((uint32_t)0x08000000) /*!< SS[14:8] are don't care in Alarm + comparison. Only SS[7:0] are compared */ +#define RTC_ALARMSUBSECONDMASK_SS14_9 ((uint32_t)0x09000000) /*!< SS[14:9] are don't care in Alarm + comparison. Only SS[8:0] are compared */ +#define RTC_ALARMSUBSECONDMASK_SS14_10 ((uint32_t)0x0A000000) /*!< SS[14:10] are don't care in Alarm + comparison. Only SS[9:0] are compared */ +#define RTC_ALARMSUBSECONDMASK_SS14_11 ((uint32_t)0x0B000000) /*!< SS[14:11] are don't care in Alarm + comparison. Only SS[10:0] are compared */ +#define RTC_ALARMSUBSECONDMASK_SS14_12 ((uint32_t)0x0C000000) /*!< SS[14:12] are don't care in Alarm + comparison.Only SS[11:0] are compared */ +#define RTC_ALARMSUBSECONDMASK_SS14_13 ((uint32_t)0x0D000000) /*!< SS[14:13] are don't care in Alarm + comparison. Only SS[12:0] are compared */ +#define RTC_ALARMSUBSECONDMASK_SS14 ((uint32_t)0x0E000000) /*!< SS[14] is don't care in Alarm + comparison.Only SS[13:0] are compared */ +#define RTC_ALARMSUBSECONDMASK_None ((uint32_t)0x0F000000) /*!< SS[14:0] are compared and must match + to activate alarm. */ + +#define IS_RTC_ALARM_SUB_SECOND_MASK(MASK) (((MASK) == RTC_ALARMSUBSECONDMASK_ALL) || \ + ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_1) || \ + ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_2) || \ + ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_3) || \ + ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_4) || \ + ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_5) || \ + ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_6) || \ + ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_7) || \ + ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_8) || \ + ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_9) || \ + ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_10) || \ + ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_11) || \ + ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_12) || \ + ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_13) || \ + ((MASK) == RTC_ALARMSUBSECONDMASK_SS14) || \ + ((MASK) == RTC_ALARMSUBSECONDMASK_None)) +/** + * @} + */ + +/** @defgroup RTC_Interrupts_Definitions + * @{ + */ +#define RTC_IT_TS ((uint32_t)0x00008000) +#define RTC_IT_WUT ((uint32_t)0x00004000) +#define RTC_IT_ALRA ((uint32_t)0x00001000) +#define RTC_IT_TAMP ((uint32_t)0x00000004) /* Used only to Enable the Tamper Interrupt */ +#define RTC_IT_TAMP1 ((uint32_t)0x00020000) +#define RTC_IT_TAMP2 ((uint32_t)0x00040000) +#define RTC_IT_TAMP3 ((uint32_t)0x00080000) +/** + * @} + */ + +/** @defgroup RTC_Flags_Definitions + * @{ + */ +#define RTC_FLAG_RECALPF ((uint32_t)0x00010000) +#define RTC_FLAG_TAMP3F ((uint32_t)0x00008000) +#define RTC_FLAG_TAMP2F ((uint32_t)0x00004000) +#define RTC_FLAG_TAMP1F ((uint32_t)0x00002000) +#define RTC_FLAG_TSOVF ((uint32_t)0x00001000) +#define RTC_FLAG_TSF ((uint32_t)0x00000800) +#define RTC_FLAG_WUTF ((uint32_t)0x00000400) +#define RTC_FLAG_ALRAF ((uint32_t)0x00000100) +#define RTC_FLAG_INITF ((uint32_t)0x00000040) +#define RTC_FLAG_RSF ((uint32_t)0x00000020) +#define RTC_FLAG_INITS ((uint32_t)0x00000010) +#define RTC_FLAG_SHPF ((uint32_t)0x00000008) +#define RTC_FLAG_WUTWF ((uint32_t)0x00000004) +#define RTC_FLAG_ALRAWF ((uint32_t)0x00000001) +/** + * @} + */ + +/** + * @} + */ + +/* Exported macros -----------------------------------------------------------*/ + +/** @brief Reset RTC handle state + * @param __HANDLE__: RTC handle. + * @retval None + */ +#define __HAL_RTC_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_RTC_STATE_RESET) + +/** + * @brief Disable the write protection for RTC registers. + * @param __HANDLE__: specifies the RTC handle. + * @retval None + */ +#define __HAL_RTC_WRITEPROTECTION_DISABLE(__HANDLE__) \ + do{ \ + (__HANDLE__)->Instance->WPR = 0xCA; \ + (__HANDLE__)->Instance->WPR = 0x53; \ + } while(0) + +/** + * @brief Enable the write protection for RTC registers. + * @param __HANDLE__: specifies the RTC handle. + * @retval None + */ +#define __HAL_RTC_WRITEPROTECTION_ENABLE(__HANDLE__) \ + do{ \ + (__HANDLE__)->Instance->WPR = 0xFF; \ + } while(0) + +/** + * @brief Enable the RTC ALARMA peripheral. + * @param __HANDLE__: specifies the RTC handle. + * @retval None + */ +#define __HAL_RTC_ALARMA_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= (RTC_CR_ALRAE)) + +/** + * @brief Disable the RTC ALARMA peripheral. + * @param __HANDLE__: specifies the RTC handle. + * @retval None + */ +#define __HAL_RTC_ALARMA_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~(RTC_CR_ALRAE)) + +/** + * @brief Enable the RTC Alarm interrupt. + * @param __HANDLE__: specifies the RTC handle. + * @param __INTERRUPT__: specifies the RTC Alarm interrupt sources to be enabled or disabled. + * This parameter can be any combination of the following values: + * @arg RTC_IT_ALRA: Alarm A interrupt + * @retval None + */ +#define __HAL_RTC_ALARM_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR |= (__INTERRUPT__)) + +/** + * @brief Disable the RTC Alarm interrupt. + * @param __HANDLE__: specifies the RTC handle. + * @param __INTERRUPT__: specifies the RTC Alarm interrupt sources to be enabled or disabled. + * This parameter can be any combination of the following values: + * @arg RTC_IT_ALRA: Alarm A interrupt + * @retval None + */ +#define __HAL_RTC_ALARM_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR &= ~(__INTERRUPT__)) + +/** + * @brief Check whether the specified RTC Alarm interrupt has occurred or not. + * @param __HANDLE__: specifies the RTC handle. + * @param __FLAG__: specifies the RTC Alarm interrupt sources to be enabled or disabled. + * This parameter can be: + * @arg RTC_IT_ALRA: Alarm A interrupt + * @retval None + */ +#define __HAL_RTC_ALARM_GET_IT(__HANDLE__, __FLAG__) ((((((__HANDLE__)->Instance->ISR)& ((__FLAG__)>> 4)) & 0x0000FFFF) != RESET)? SET : RESET) + +/** + * @brief Get the selected RTC Alarm's flag status. + * @param __HANDLE__: specifies the RTC handle. + * @param __FLAG__: specifies the RTC Alarm Flag sources to be enabled or disabled. + * This parameter can be: + * @arg RTC_FLAG_ALRAF + * @arg RTC_FLAG_ALRAWF + * @retval None + */ +#define __HAL_RTC_ALARM_GET_FLAG(__HANDLE__, __FLAG__) (((((__HANDLE__)->Instance->ISR) & (__FLAG__)) != RESET)? SET : RESET) + +/** + * @brief Clear the RTC Alarm's pending flags. + * @param __HANDLE__: specifies the RTC handle. + * @param __FLAG__: specifies the RTC Alarm Flag sources to be enabled or disabled. + * This parameter can be: + * @arg RTC_FLAG_ALRAF + * @retval None + */ +#define __HAL_RTC_ALARM_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->ISR) = (~(((__FLAG__) | RTC_ISR_INIT)& 0x0000FFFF)|((__HANDLE__)->Instance->ISR & RTC_ISR_INIT)) + + +#define RTC_EXTI_LINE_ALARM_EVENT ((uint32_t)0x00020000) /*!< External interrupt line 17 Connected to the RTC Alarm event */ +#define RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT ((uint32_t)0x00080000) /*!< External interrupt line 19 Connected to the RTC Tamper and Time Stamp events */ +#define RTC_EXTI_LINE_WAKEUPTIMER_EVENT ((uint32_t)0x00100000) /*!< External interrupt line 20 Connected to the RTC Wakeup event */ + +/** + * @brief Enable the RTC Exti line. + * @param __EXTILINE__: specifies the RTC Exti sources to be enabled or disabled. + * This parameter can be: + * @arg RTC_EXTI_LINE_ALARM_EVENT + * @arg RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT + * @arg RTC_EXTI_LINE_WAKEUPTIMER_EVENT + * @retval None + */ +#define __HAL_RTC_EXTI_ENABLE_IT(__EXTILINE__) (EXTI->IMR |= (__EXTILINE__)) + +/* alias define maintained for legacy */ +#define __HAL_RTC_ENABLE_IT __HAL_RTC_EXTI_ENABLE_IT + +/** + * @brief Disable the RTC Exti line. + * @param __EXTILINE__: specifies the RTC Exti sources to be enabled or disabled. + * This parameter can be: + * @arg RTC_EXTI_LINE_ALARM_EVENT + * @arg RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT + * @arg RTC_EXTI_LINE_WAKEUPTIMER_EVENT + * @retval None + */ +#define __HAL_RTC_EXTI_DISABLE_IT(__EXTILINE__) (EXTI->IMR &= ~(__EXTILINE__)) + +/* alias define maintained for legacy */ +#define __HAL_RTC_DISABLE_IT __HAL_RTC_EXTI_DISABLE_IT + +/** + * @brief Generates a Software interrupt on selected EXTI line. + * @param __EXTILINE__: specifies the RTC Exti sources to be enabled or disabled. + * This parameter can be: + * @arg RTC_EXTI_LINE_ALARM_EVENT + * @arg RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT + * @arg RTC_EXTI_LINE_WAKEUPTIMER_EVENT + * @retval None + */ +#define __HAL_RTC_EXTI_GENERATE_SWIT(__EXTILINE__) (EXTI->SWIER |= (__EXTILINE__)) + +/** + * @brief Clear the RTC Exti flags. + * @param __FLAG__: specifies the RTC Exti sources to be enabled or disabled. + * This parameter can be: + * @arg RTC_EXTI_LINE_ALARM_EVENT + * @arg RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT + * @arg RTC_EXTI_LINE_WAKEUPTIMER_EVENT + * @retval None + */ +#define __HAL_RTC_EXTI_CLEAR_FLAG(__FLAG__) (EXTI->PR = (__FLAG__)) + +/* alias define maintained for legacy */ +#define __HAL_RTC_CLEAR_FLAG __HAL_RTC_EXTI_CLEAR_FLAG + +/* Include RTC HAL Extension module */ +#include "stm32f0xx_hal_rtc_ex.h" + +/* Exported functions --------------------------------------------------------*/ + +/* Initialization and de-initialization functions ****************************/ +HAL_StatusTypeDef HAL_RTC_Init(RTC_HandleTypeDef *hrtc); +HAL_StatusTypeDef HAL_RTC_DeInit(RTC_HandleTypeDef *hrtc); +void HAL_RTC_MspInit(RTC_HandleTypeDef *hrtc); +void HAL_RTC_MspDeInit(RTC_HandleTypeDef *hrtc); + +/* RTC Time and Date functions ************************************************/ +HAL_StatusTypeDef HAL_RTC_SetTime(RTC_HandleTypeDef *hrtc, RTC_TimeTypeDef *sTime, uint32_t Format); +HAL_StatusTypeDef HAL_RTC_GetTime(RTC_HandleTypeDef *hrtc, RTC_TimeTypeDef *sTime, uint32_t Format); +HAL_StatusTypeDef HAL_RTC_SetDate(RTC_HandleTypeDef *hrtc, RTC_DateTypeDef *sDate, uint32_t Format); +HAL_StatusTypeDef HAL_RTC_GetDate(RTC_HandleTypeDef *hrtc, RTC_DateTypeDef *sDate, uint32_t Format); + +/* RTC Alarm functions ********************************************************/ +HAL_StatusTypeDef HAL_RTC_SetAlarm(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef *sAlarm, uint32_t Format); +HAL_StatusTypeDef HAL_RTC_SetAlarm_IT(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef *sAlarm, uint32_t Format); +HAL_StatusTypeDef HAL_RTC_DeactivateAlarm(RTC_HandleTypeDef *hrtc, uint32_t Alarm); +HAL_StatusTypeDef HAL_RTC_GetAlarm(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef *sAlarm, uint32_t Alarm, uint32_t Format); +void HAL_RTC_AlarmIRQHandler(RTC_HandleTypeDef *hrtc); +HAL_StatusTypeDef HAL_RTC_PollForAlarmAEvent(RTC_HandleTypeDef *hrtc, uint32_t Timeout); +void HAL_RTC_AlarmAEventCallback(RTC_HandleTypeDef *hrtc); + +/* Peripheral Control functions ***********************************************/ +HAL_StatusTypeDef HAL_RTC_WaitForSynchro(RTC_HandleTypeDef* hrtc); + +/* Peripheral State functions *************************************************/ +HAL_RTCStateTypeDef HAL_RTC_GetState(RTC_HandleTypeDef *hrtc); + +HAL_StatusTypeDef RTC_EnterInitMode(RTC_HandleTypeDef* hrtc); +uint8_t RTC_ByteToBcd2(uint8_t Value); +uint8_t RTC_Bcd2ToByte(uint8_t Value); + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __STM32F0xx_HAL_RTC_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_rtc_ex.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_rtc_ex.c new file mode 100644 index 0000000000..85661b7d12 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_rtc_ex.c @@ -0,0 +1,1539 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_rtc_ex.c + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief Extended RTC HAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the Real Time Clock (RTC) Extension peripheral: + * - TimeStamp configuration + * - Tampers configuration + * - WakeUp Timer configuration + * - RTC Tamper and TimeStamp Pins Selection + * - Extension Control functions + * - Extension RTC features functions + * + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + (+) Enable the RTC domain access (see description in the section above). + (+) Configure the RTC Prescaler (Asynchronous and Synchronous) and RTC hour + format using the HAL_RTC_Init() function. + + *** RTC Wakeup configuration *** + ================================ + [..] + (+) To configure the RTC Wakeup Clock source and Counter use the HAL_RTCEx_SetWakeUpTimer() + function. You can also configure the RTC Wakeup timer with interrupt mode + using the HAL_RTCEx_SetWakeUpTimer_IT() function. + (+) To read the RTC WakeUp Counter register, use the HAL_RTCEx_GetWakeUpTimer() + function. + + *** TimeStamp configuration *** + =============================== + [..] + (+) Configure the RTC_AF trigger and enables the RTC TimeStamp using the + HAL_RTCEx_SetTimeStamp() function. You can also configure the RTC TimeStamp with + interrupt mode using the HAL_RTCEx_SetTimeStamp_IT() function. + (+) To read the RTC TimeStamp Time and Date register, use the HAL_RTCEx_GetTimeStamp() + function. + + *** Tamper configuration *** + ============================ + [..] + (+) Enable the RTC Tamper and Configure the Tamper filter count, trigger Edge + or Level according to the Tamper filter (if equal to 0 Edge else Level) + value, sampling frequency, precharge or discharge and Pull-UP using the + HAL_RTCEx_SetTamper() function. You can configure RTC Tamper with interrupt + mode using HAL_RTCEx_SetTamper_IT() function. + + *** Backup Data Registers configuration *** + =========================================== + [..] + (+) To write to the RTC Backup Data registers, use the HAL_RTCEx_BKUPWrite() + function. + (+) To read the RTC Backup Data registers, use the HAL_RTCEx_BKUPRead() + function. + + + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @defgroup RTCEx + * @brief RTC HAL module driver + * @{ + */ + +#ifdef HAL_RTC_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup RTCEx_Private_Functions + * @{ + */ + + +/** @defgroup RTCEx_Group1 RTC TimeStamp and Tamper functions + * @brief RTC TimeStamp and Tamper functions + * +@verbatim + =============================================================================== + ##### RTC TimeStamp and Tamper functions ##### + =============================================================================== + + [..] This section provide functions allowing to configure TimeStamp feature + +@endverbatim + * @{ + */ + +/** + * @brief Sets TimeStamp. + * @note This API must be called before enabling the TimeStamp feature. + * @param hrtc: RTC handle + * @param TimeStampEdge: Specifies the pin edge on which the TimeStamp is + * activated. + * This parameter can be one of the following: + * @arg TimeStampEdge_Rising: the Time stamp event occurs on the + * rising edge of the related pin. + * @arg TimeStampEdge_Falling: the Time stamp event occurs on the + * falling edge of the related pin. + * @param RTC_TimeStampPin: specifies the RTC TimeStamp Pin. + * This parameter can be one of the following values: + * @arg RTC_TIMESTAMPPIN_PC13: PC13 is selected as RTC TimeStamp Pin. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_SetTimeStamp(RTC_HandleTypeDef *hrtc, uint32_t TimeStampEdge, uint32_t RTC_TimeStampPin) +{ + uint32_t tmpreg = 0; + + /* Check the parameters */ + assert_param(IS_TIMESTAMP_EDGE(TimeStampEdge)); + assert_param(IS_RTC_TIMESTAMP_PIN(RTC_TimeStampPin)); + + /* Process Locked */ + __HAL_LOCK(hrtc); + + hrtc->State = HAL_RTC_STATE_BUSY; + + /* Get the RTC_CR register and clear the bits to be configured */ + tmpreg = (uint32_t)(hrtc->Instance->CR & (uint32_t)~(RTC_CR_TSEDGE | RTC_CR_TSE)); + + tmpreg|= TimeStampEdge; + + /* Disable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + /* Configure the Time Stamp TSEDGE and Enable bits */ + hrtc->Instance->CR = (uint32_t)tmpreg; + + __HAL_RTC_TIMESTAMP_ENABLE(hrtc); + + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_OK; +} + +/** + * @brief Sets TimeStamp with Interrupt. + * @param hrtc: RTC handle + * @note This API must be called before enabling the TimeStamp feature. + * @param TimeStampEdge: Specifies the pin edge on which the TimeStamp is + * activated. + * This parameter can be one of the following: + * @arg TimeStampEdge_Rising: the Time stamp event occurs on the + * rising edge of the related pin. + * @arg TimeStampEdge_Falling: the Time stamp event occurs on the + * falling edge of the related pin. + * @param RTC_TimeStampPin: Specifies the RTC TimeStamp Pin. + * This parameter can be one of the following values: + * @arg RTC_TIMESTAMPPIN_PC13: PC13 is selected as RTC TimeStamp Pin. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_SetTimeStamp_IT(RTC_HandleTypeDef *hrtc, uint32_t TimeStampEdge, uint32_t RTC_TimeStampPin) +{ + uint32_t tmpreg = 0; + + /* Check the parameters */ + assert_param(IS_TIMESTAMP_EDGE(TimeStampEdge)); + assert_param(IS_RTC_TIMESTAMP_PIN(RTC_TimeStampPin)); + + /* Process Locked */ + __HAL_LOCK(hrtc); + + hrtc->State = HAL_RTC_STATE_BUSY; + + /* Get the RTC_CR register and clear the bits to be configured */ + tmpreg = (uint32_t)(hrtc->Instance->CR & (uint32_t)~(RTC_CR_TSEDGE | RTC_CR_TSE)); + + tmpreg |= TimeStampEdge; + + /* Disable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + /* Configure the Time Stamp TSEDGE and Enable bits */ + hrtc->Instance->CR = (uint32_t)tmpreg; + + __HAL_RTC_TIMESTAMP_ENABLE(hrtc); + + /* Enable IT timestamp */ + __HAL_RTC_TIMESTAMP_ENABLE_IT(hrtc,RTC_IT_TS); + + /* RTC timestamp Interrupt Configuration: EXTI configuration */ + __HAL_RTC_EXTI_ENABLE_IT(RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT); + + EXTI->RTSR |= RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT; + + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + hrtc->State = HAL_RTC_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_OK; +} + +/** + * @brief Deactivates TimeStamp. + * @param hrtc: RTC handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_DeactivateTimeStamp(RTC_HandleTypeDef *hrtc) +{ + uint32_t tmpreg = 0; + + /* Process Locked */ + __HAL_LOCK(hrtc); + + hrtc->State = HAL_RTC_STATE_BUSY; + + /* Disable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + /* In case of interrupt mode is used, the interrupt source must disabled */ + __HAL_RTC_TIMESTAMP_DISABLE_IT(hrtc, RTC_IT_TS); + + /* Get the RTC_CR register and clear the bits to be configured */ + tmpreg = (uint32_t)(hrtc->Instance->CR & (uint32_t)~(RTC_CR_TSEDGE | RTC_CR_TSE)); + + /* Configure the Time Stamp TSEDGE and Enable bits */ + hrtc->Instance->CR = (uint32_t)tmpreg; + + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + hrtc->State = HAL_RTC_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_OK; +} + +/** + * @brief Gets the RTC TimeStamp value. + * @param hrtc: RTC handle + * @param sTimeStamp: Pointer to Time structure + * @param sTimeStampDate: Pointer to Date structure + * @param Format: specifies the format of the entered parameters. + * This parameter can be one of the following values: + * @arg Format_BIN: Binary data format + * @arg Format_BCD: BCD data format + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_GetTimeStamp(RTC_HandleTypeDef *hrtc, RTC_TimeTypeDef* sTimeStamp, RTC_DateTypeDef* sTimeStampDate, uint32_t Format) +{ + uint32_t tmptime = 0, tmpdate = 0; + + /* Check the parameters */ + assert_param(IS_RTC_FORMAT(Format)); + + /* Get the TimeStamp time and date registers values */ + tmptime = (uint32_t)(hrtc->Instance->TSTR & RTC_TR_RESERVED_MASK); + tmpdate = (uint32_t)(hrtc->Instance->TSDR & RTC_DR_RESERVED_MASK); + + /* Fill the Time structure fields with the read parameters */ + sTimeStamp->Hours = (uint8_t)((tmptime & (RTC_TR_HT | RTC_TR_HU)) >> 16); + sTimeStamp->Minutes = (uint8_t)((tmptime & (RTC_TR_MNT | RTC_TR_MNU)) >> 8); + sTimeStamp->Seconds = (uint8_t)(tmptime & (RTC_TR_ST | RTC_TR_SU)); + sTimeStamp->TimeFormat = (uint8_t)((tmptime & (RTC_TR_PM)) >> 16); + sTimeStamp->SubSeconds = (uint32_t) hrtc->Instance->TSSSR; + + /* Fill the Date structure fields with the read parameters */ + sTimeStampDate->Year = 0; + sTimeStampDate->Month = (uint8_t)((tmpdate & (RTC_DR_MT | RTC_DR_MU)) >> 8); + sTimeStampDate->Date = (uint8_t)(tmpdate & (RTC_DR_DT | RTC_DR_DU)); + sTimeStampDate->WeekDay = (uint8_t)((tmpdate & (RTC_DR_WDU)) >> 13); + + /* Check the input parameters format */ + if(Format == FORMAT_BIN) + { + /* Convert the TimeStamp structure parameters to Binary format */ + sTimeStamp->Hours = (uint8_t)RTC_Bcd2ToByte(sTimeStamp->Hours); + sTimeStamp->Minutes = (uint8_t)RTC_Bcd2ToByte(sTimeStamp->Minutes); + sTimeStamp->Seconds = (uint8_t)RTC_Bcd2ToByte(sTimeStamp->Seconds); + + /* Convert the DateTimeStamp structure parameters to Binary format */ + sTimeStampDate->Month = (uint8_t)RTC_Bcd2ToByte(sTimeStampDate->Month); + sTimeStampDate->Date = (uint8_t)RTC_Bcd2ToByte(sTimeStampDate->Date); + sTimeStampDate->WeekDay = (uint8_t)RTC_Bcd2ToByte(sTimeStampDate->WeekDay); + } + + /* Clear the TIMESTAMP Flag */ + __HAL_RTC_TIMESTAMP_CLEAR_FLAG(hrtc, RTC_FLAG_TSF); + + return HAL_OK; +} + +/** + * @brief Sets Tamper + * @note By calling this API we disable the tamper interrupt for all tampers. + * @param hrtc: RTC handle + * @param sTamper: Pointer to Tamper Structure. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_SetTamper(RTC_HandleTypeDef *hrtc, RTC_TamperTypeDef* sTamper) +{ + uint32_t tmpreg = 0; + + /* Check the parameters */ + assert_param(IS_TAMPER(sTamper->Tamper)); + assert_param(IS_TAMPER_TRIGGER(sTamper->Trigger)); + assert_param(IS_TAMPER_FILTER(sTamper->Filter)); + assert_param(IS_TAMPER_SAMPLING_FREQ(sTamper->SamplingFrequency)); + assert_param(IS_TAMPER_PRECHARGE_DURATION(sTamper->PrechargeDuration)); + assert_param(IS_TAMPER_PULLUP_STATE(sTamper->TamperPullUp)); + assert_param(IS_TAMPER_TIMESTAMPONTAMPER_DETECTION(sTamper->TimeStampOnTamperDetection)); + + /* Process Locked */ + __HAL_LOCK(hrtc); + + hrtc->State = HAL_RTC_STATE_BUSY; + + if(sTamper->Trigger != RTC_TAMPERTRIGGER_RISINGEDGE) + { + sTamper->Trigger = (uint32_t)(sTamper->Tamper << 1); + } + + tmpreg = ((uint32_t)sTamper->Tamper | (uint32_t)sTamper->Trigger | (uint32_t)sTamper->Filter |\ + (uint32_t)sTamper->SamplingFrequency | (uint32_t)sTamper->PrechargeDuration |\ + (uint32_t)sTamper->TamperPullUp | sTamper->TimeStampOnTamperDetection); + + hrtc->Instance->TAFCR &= (uint32_t)~((uint32_t)sTamper->Tamper | (uint32_t)(sTamper->Tamper << 1) | (uint32_t)RTC_TAFCR_TAMPTS |\ + (uint32_t)RTC_TAFCR_TAMPFREQ | (uint32_t)RTC_TAFCR_TAMPFLT | (uint32_t)RTC_TAFCR_TAMPPRCH |\ + (uint32_t)RTC_TAFCR_TAMPPUDIS | (uint32_t)RTC_TAFCR_TAMPIE); + + hrtc->Instance->TAFCR |= tmpreg; + + hrtc->State = HAL_RTC_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_OK; +} + +/** + * @brief Sets Tamper with interrupt. + * @note By calling this API we force the tamper interrupt for all tampers. + * @param hrtc: RTC handle + * @param sTamper: Pointer to RTC Tamper. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_SetTamper_IT(RTC_HandleTypeDef *hrtc, RTC_TamperTypeDef* sTamper) +{ + uint32_t tmpreg = 0; + + /* Check the parameters */ + assert_param(IS_TAMPER(sTamper->Tamper)); + assert_param(IS_TAMPER_TRIGGER(sTamper->Trigger)); + assert_param(IS_TAMPER_FILTER(sTamper->Filter)); + assert_param(IS_TAMPER_SAMPLING_FREQ(sTamper->SamplingFrequency)); + assert_param(IS_TAMPER_PRECHARGE_DURATION(sTamper->PrechargeDuration)); + assert_param(IS_TAMPER_PULLUP_STATE(sTamper->TamperPullUp)); + assert_param(IS_TAMPER_TIMESTAMPONTAMPER_DETECTION(sTamper->TimeStampOnTamperDetection)); + + /* Process Locked */ + __HAL_LOCK(hrtc); + + hrtc->State = HAL_RTC_STATE_BUSY; + + /* Configure the tamper trigger */ + if(sTamper->Trigger != RTC_TAMPERTRIGGER_RISINGEDGE) + { + sTamper->Trigger = (uint32_t)(sTamper->Tamper << 1); + } + + tmpreg = ((uint32_t)sTamper->Tamper | (uint32_t)sTamper->Trigger | (uint32_t)sTamper->Filter |\ + (uint32_t)sTamper->SamplingFrequency | (uint32_t)sTamper->PrechargeDuration |\ + (uint32_t)sTamper->TamperPullUp | sTamper->TimeStampOnTamperDetection); + + hrtc->Instance->TAFCR &= (uint32_t)~((uint32_t)sTamper->Tamper | (uint32_t)(sTamper->Tamper << 1) | (uint32_t)RTC_TAFCR_TAMPTS |\ + (uint32_t)RTC_TAFCR_TAMPFREQ | (uint32_t)RTC_TAFCR_TAMPFLT | (uint32_t)RTC_TAFCR_TAMPPRCH |\ + (uint32_t)RTC_TAFCR_TAMPPUDIS); + + hrtc->Instance->TAFCR |= tmpreg; + + /* Configure the Tamper Interrupt in the RTC_TAFCR */ + hrtc->Instance->TAFCR |= (uint32_t)RTC_TAFCR_TAMPIE; + + /* RTC Tamper Interrupt Configuration: EXTI configuration */ + __HAL_RTC_EXTI_ENABLE_IT(RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT); + + EXTI->RTSR |= RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT; + + hrtc->State = HAL_RTC_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_OK; +} + +/** + * @brief Deactivates Tamper. + * @param hrtc: RTC handle + * @param Tamper: Selected tamper pin. + * This parameter can be any combination of RTC_TAMPER_1, RTC_TAMPER_2 and RTC_TAMPER_3. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_DeactivateTamper(RTC_HandleTypeDef *hrtc, uint32_t Tamper) +{ + assert_param(IS_TAMPER(Tamper)); + + /* Process Locked */ + __HAL_LOCK(hrtc); + + hrtc->State = HAL_RTC_STATE_BUSY; + + /* Disable the selected Tamper pin */ + hrtc->Instance->TAFCR &= (uint32_t)~Tamper; + + hrtc->State = HAL_RTC_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_OK; +} + +/** + * @brief This function handles TimeStamp interrupt request. + * @param hrtc: RTC handle + * @retval None + */ +void HAL_RTCEx_TamperTimeStampIRQHandler(RTC_HandleTypeDef *hrtc) +{ + if(__HAL_RTC_TIMESTAMP_GET_IT(hrtc, RTC_IT_TS)) + { + /* Get the status of the Interrupt */ + if((uint32_t)(hrtc->Instance->CR & RTC_IT_TS) != (uint32_t)RESET) + { + /* TIMESTAMP callback */ + HAL_RTCEx_TimeStampEventCallback(hrtc); + + /* Clear the TIMESTAMP interrupt pending bit */ + __HAL_RTC_TIMESTAMP_CLEAR_FLAG(hrtc,RTC_FLAG_TSF); + } + } + + /* Get the status of the Interrupt */ + if(__HAL_RTC_TAMPER_GET_IT(hrtc,RTC_IT_TAMP1)) + { + /* Get the TAMPER Interrupt enable bit and pending bit */ + if(((hrtc->Instance->TAFCR & (RTC_TAFCR_TAMPIE))) != (uint32_t)RESET) + { + /* Tamper callback */ + HAL_RTCEx_Tamper1EventCallback(hrtc); + + /* Clear the Tamper interrupt pending bit */ + __HAL_RTC_TAMPER_CLEAR_FLAG(hrtc,RTC_FLAG_TAMP1F); + } + } + + /* Get the status of the Interrupt */ + if(__HAL_RTC_TAMPER_GET_IT(hrtc, RTC_IT_TAMP2)) + { + /* Get the TAMPER Interrupt enable bit and pending bit */ + if(((hrtc->Instance->TAFCR & RTC_TAFCR_TAMPIE)) != (uint32_t)RESET) + { + /* Tamper callback */ + HAL_RTCEx_Tamper2EventCallback(hrtc); + + /* Clear the Tamper interrupt pending bit */ + __HAL_RTC_TAMPER_CLEAR_FLAG(hrtc, RTC_FLAG_TAMP2F); + } + } + +#if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) + /* Get the status of the Interrupt */ + if(__HAL_RTC_TAMPER_GET_IT(hrtc, RTC_IT_TAMP3)) + { + /* Get the TAMPER Interrupt enable bit and pending bit */ + if(((hrtc->Instance->TAFCR & RTC_TAFCR_TAMPIE)) != (uint32_t)RESET) + { + /* Tamper callback */ + HAL_RTCEx_Tamper3EventCallback(hrtc); + + /* Clear the Tamper interrupt pending bit */ + __HAL_RTC_TAMPER_CLEAR_FLAG(hrtc, RTC_FLAG_TAMP3F); + } + } +#endif + + /* Clear the EXTI's Flag for RTC TimeStamp and Tamper */ + __HAL_RTC_EXTI_CLEAR_FLAG(RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_READY; +} + +/** + * @brief TimeStamp callback. + * @param hrtc: RTC handle + * @retval None + */ +__weak void HAL_RTCEx_TimeStampEventCallback(RTC_HandleTypeDef *hrtc) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_RTCEx_TimeStampEventCallback could be implemented in the user file + */ +} + +/** + * @brief Tamper 1 callback. + * @param hrtc: RTC handle + * @retval None + */ +__weak void HAL_RTCEx_Tamper1EventCallback(RTC_HandleTypeDef *hrtc) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_RTCEx_Tamper1EventCallback could be implemented in the user file + */ +} + +/** + * @brief Tamper 2 callback. + * @param hrtc: RTC handle + * @retval None + */ +__weak void HAL_RTCEx_Tamper2EventCallback(RTC_HandleTypeDef *hrtc) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_RTCEx_Tamper2EventCallback could be implemented in the user file + */ +} + +#if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) +/** + * @brief Tamper 3 callback. + * @param hrtc: RTC handle + * @retval None + */ +__weak void HAL_RTCEx_Tamper3EventCallback(RTC_HandleTypeDef *hrtc) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_RTCEx_Tamper3EventCallback could be implemented in the user file + */ +} +#endif + +/** + * @brief This function handles TimeStamp polling request. + * @param hrtc: RTC handle + * @param Timeout: Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_PollForTimeStampEvent(RTC_HandleTypeDef *hrtc, uint32_t Timeout) +{ + uint32_t timeout = 0; + + /* Get Timeout value */ + timeout = HAL_GetTick() + Timeout; + + while(__HAL_RTC_TIMESTAMP_GET_FLAG(hrtc, RTC_FLAG_TSF) == RESET) + { + if(__HAL_RTC_TIMESTAMP_GET_FLAG(hrtc, RTC_FLAG_TSOVF) != RESET) + { + /* Clear the TIMESTAMP OverRun Flag */ + __HAL_RTC_TIMESTAMP_CLEAR_FLAG(hrtc, RTC_FLAG_TSOVF); + + /* Change TIMESTAMP state */ + hrtc->State = HAL_RTC_STATE_ERROR; + + return HAL_ERROR; + } + + if(Timeout != HAL_MAX_DELAY) + { + if(HAL_GetTick() >= timeout) + { + hrtc->State = HAL_RTC_STATE_TIMEOUT; + return HAL_TIMEOUT; + } + } + } + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_READY; + + return HAL_OK; +} + +/** + * @brief This function handles Tamper1 Polling. + * @param hrtc: RTC handle + * @param Timeout: Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_PollForTamper1Event(RTC_HandleTypeDef *hrtc, uint32_t Timeout) +{ + uint32_t timeout = 0; + + /* Get Timeout value */ + timeout = HAL_GetTick() + Timeout; + + /* Get the status of the Interrupt */ + while(__HAL_RTC_TAMPER_GET_FLAG(hrtc,RTC_FLAG_TAMP1F)== RESET) + { + if(Timeout != HAL_MAX_DELAY) + { + if(HAL_GetTick() >= timeout) + { + hrtc->State = HAL_RTC_STATE_TIMEOUT; + return HAL_TIMEOUT; + } + } + } + + /* Clear the Tamper Flag */ + __HAL_RTC_TAMPER_CLEAR_FLAG(hrtc,RTC_FLAG_TAMP1F); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_READY; + + return HAL_OK; +} + +/** + * @brief This function handles Tamper2 Polling. + * @param hrtc: RTC handle + * @param Timeout: Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_PollForTamper2Event(RTC_HandleTypeDef *hrtc, uint32_t Timeout) +{ + uint32_t timeout = 0; + + /* Get Timeout value */ + timeout = HAL_GetTick() + Timeout; + + /* Get the status of the Interrupt */ + while(__HAL_RTC_TAMPER_GET_FLAG(hrtc,RTC_FLAG_TAMP2F) == RESET) + { + if(Timeout != HAL_MAX_DELAY) + { + if(HAL_GetTick() >= timeout) + { + hrtc->State = HAL_RTC_STATE_TIMEOUT; + return HAL_TIMEOUT; + } + } + } + + /* Clear the Tamper Flag */ + __HAL_RTC_TAMPER_CLEAR_FLAG(hrtc,RTC_FLAG_TAMP2F); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_READY; + + return HAL_OK; +} + +#if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) +/** + * @brief This function handles Tamper3 Polling. + * @param hrtc: RTC handle + * @param Timeout: Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_PollForTamper3Event(RTC_HandleTypeDef *hrtc, uint32_t Timeout) +{ + uint32_t timeout = 0; + + /* Get Timeout value */ + timeout = HAL_GetTick() + Timeout; + + /* Get the status of the Interrupt */ + while(__HAL_RTC_TAMPER_GET_FLAG(hrtc,RTC_FLAG_TAMP3F) == RESET) + { + if(Timeout != HAL_MAX_DELAY) + { + if(HAL_GetTick() >= timeout) + { + hrtc->State = HAL_RTC_STATE_TIMEOUT; + return HAL_TIMEOUT; + } + } + } + + /* Clear the Tamper Flag */ + __HAL_RTC_TAMPER_CLEAR_FLAG(hrtc,RTC_FLAG_TAMP3F); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_READY; + + return HAL_OK; +} +#endif + +/** + * @} + */ + +#if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) +/** @defgroup RTCEx_Group2 RTC Wake-up functions + * @brief RTC Wake-up functions + * +@verbatim + =============================================================================== + ##### RTC Wake-up functions ##### + =============================================================================== + + [..] This section provide functions allowing to configure Wake-up feature + +@endverbatim + * @{ + */ + +/** + * @brief Sets wake up timer. + * @param hrtc: RTC handle + * @param WakeUpCounter: Wake up counter + * @param WakeUpClock: Wake up clock + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_SetWakeUpTimer(RTC_HandleTypeDef *hrtc, uint32_t WakeUpCounter, uint32_t WakeUpClock) +{ + uint32_t timeout = 0; + + /* Check the parameters */ + assert_param(IS_WAKEUP_CLOCK(WakeUpClock)); + assert_param(IS_WAKEUP_COUNTER(WakeUpCounter)); + + /* Process Locked */ + __HAL_LOCK(hrtc); + + hrtc->State = HAL_RTC_STATE_BUSY; + + /* Disable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + __HAL_RTC_WAKEUPTIMER_DISABLE(hrtc); + + timeout = HAL_GetTick() + RTC_TIMEOUT_VALUE; + + /* Wait till RTC WUTWF flag is set and if Time out is reached exit */ + while(__HAL_RTC_WAKEUPTIMER_GET_FLAG(hrtc, RTC_FLAG_WUTWF) == RESET) + { + if(HAL_GetTick() >= timeout) + { + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + hrtc->State = HAL_RTC_STATE_TIMEOUT; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_TIMEOUT; + } + } + + /* Clear the Wakeup Timer clock source bits in CR register */ + hrtc->Instance->CR &= (uint32_t)~RTC_CR_WUCKSEL; + + /* Configure the clock source */ + hrtc->Instance->CR |= (uint32_t)WakeUpClock; + + /* Configure the Wakeup Timer counter */ + hrtc->Instance->WUTR = (uint32_t)WakeUpCounter; + + /* Enable the Wakeup Timer */ + __HAL_RTC_WAKEUPTIMER_ENABLE(hrtc); + + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + hrtc->State = HAL_RTC_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_OK; +} + +/** + * @brief Sets wake up timer with interrupt + * @param hrtc: RTC handle + * @param WakeUpCounter: wake up counter + * @param WakeUpClock: wake up clock + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_SetWakeUpTimer_IT(RTC_HandleTypeDef *hrtc, uint32_t WakeUpCounter, uint32_t WakeUpClock) +{ + uint32_t timeout = 0; + + /* Check the parameters */ + assert_param(IS_WAKEUP_CLOCK(WakeUpClock)); + assert_param(IS_WAKEUP_COUNTER(WakeUpCounter)); + + /* Process Locked */ + __HAL_LOCK(hrtc); + + hrtc->State = HAL_RTC_STATE_BUSY; + + /* Disable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + __HAL_RTC_WAKEUPTIMER_DISABLE(hrtc); + + timeout = HAL_GetTick() + RTC_TIMEOUT_VALUE; + + /* Wait till RTC WUTWF flag is set and if Time out is reached exit */ + while(__HAL_RTC_WAKEUPTIMER_GET_FLAG(hrtc, RTC_FLAG_WUTWF) == RESET) + { + if(HAL_GetTick() >= timeout) + { + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + hrtc->State = HAL_RTC_STATE_TIMEOUT; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_TIMEOUT; + } + } + + /* Configure the Wakeup Timer counter */ + hrtc->Instance->WUTR = (uint32_t)WakeUpCounter; + + /* Clear the Wakeup Timer clock source bits in CR register */ + hrtc->Instance->CR &= (uint32_t)~RTC_CR_WUCKSEL; + + /* Configure the clock source */ + hrtc->Instance->CR |= (uint32_t)WakeUpClock; + + /* RTC WakeUpTimer Interrupt Configuration: EXTI configuration */ + __HAL_RTC_EXTI_ENABLE_IT(RTC_EXTI_LINE_WAKEUPTIMER_EVENT); + + EXTI->RTSR |= RTC_EXTI_LINE_WAKEUPTIMER_EVENT; + + /* Configure the Interrupt in the RTC_CR register */ + __HAL_RTC_WAKEUPTIMER_ENABLE_IT(hrtc,RTC_IT_WUT); + + /* Enable the Wakeup Timer */ + __HAL_RTC_WAKEUPTIMER_ENABLE(hrtc); + + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + hrtc->State = HAL_RTC_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_OK; +} + +/** + * @brief Deactivates wake up timer counter. + * @param hrtc: RTC handle + * @retval HAL status + */ +uint32_t HAL_RTCEx_DeactivateWakeUpTimer(RTC_HandleTypeDef *hrtc) +{ + uint32_t timeout = 0; + + /* Process Locked */ + __HAL_LOCK(hrtc); + + hrtc->State = HAL_RTC_STATE_BUSY; + + /* Disable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + /* Disable the Wakeup Timer */ + __HAL_RTC_WAKEUPTIMER_DISABLE(hrtc); + + /* In case of interrupt mode is used, the interrupt source must disabled */ + __HAL_RTC_WAKEUPTIMER_DISABLE_IT(hrtc,RTC_IT_WUT); + + timeout = HAL_GetTick() + RTC_TIMEOUT_VALUE; + /* Wait till RTC WUTWF flag is set and if Time out is reached exit */ + while(__HAL_RTC_WAKEUPTIMER_GET_FLAG(hrtc, RTC_FLAG_WUTWF) == RESET) + { + if(HAL_GetTick() >= timeout) + { + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + hrtc->State = HAL_RTC_STATE_TIMEOUT; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_TIMEOUT; + } + } + + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + hrtc->State = HAL_RTC_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_OK; +} + +/** + * @brief Gets wake up timer counter. + * @param hrtc: RTC handle + * @retval Counter value + */ +uint32_t HAL_RTCEx_GetWakeUpTimer(RTC_HandleTypeDef *hrtc) +{ + /* Get the counter value */ + return ((uint32_t)(hrtc->Instance->WUTR & RTC_WUTR_WUT)); +} + +/** + * @brief This function handles Wake Up Timer interrupt request. + * @param hrtc: RTC handle + * @retval None + */ +void HAL_RTCEx_WakeUpTimerIRQHandler(RTC_HandleTypeDef *hrtc) +{ + if(__HAL_RTC_WAKEUPTIMER_GET_IT(hrtc, RTC_IT_WUT)) + { + /* Get the status of the Interrupt */ + if((uint32_t)(hrtc->Instance->CR & RTC_IT_WUT) != (uint32_t)RESET) + { + /* WAKEUPTIMER callback */ + HAL_RTCEx_WakeUpTimerEventCallback(hrtc); + + /* Clear the WAKEUPTIMER interrupt pending bit */ + __HAL_RTC_WAKEUPTIMER_CLEAR_FLAG(hrtc, RTC_FLAG_WUTF); + } + } + + /* Clear the EXTI's line Flag for RTC WakeUpTimer */ + __HAL_RTC_EXTI_CLEAR_FLAG(RTC_EXTI_LINE_WAKEUPTIMER_EVENT); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_READY; +} + +/** + * @brief Wake Up Timer callback. + * @param hrtc: RTC handle + * @retval None + */ +__weak void HAL_RTCEx_WakeUpTimerEventCallback(RTC_HandleTypeDef *hrtc) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_RTCEx_WakeUpTimerEventCallback could be implemented in the user file + */ +} + +/** + * @brief This function handles Wake Up Timer Polling. + * @param hrtc: RTC handle + * @param Timeout: Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_PollForWakeUpTimerEvent(RTC_HandleTypeDef *hrtc, uint32_t Timeout) +{ + uint32_t timeout = 0; + + /* Get Timeout value */ + timeout = HAL_GetTick() + Timeout; + + while(__HAL_RTC_WAKEUPTIMER_GET_FLAG(hrtc, RTC_FLAG_WUTF) == RESET) + { + if(Timeout != HAL_MAX_DELAY) + { + if(HAL_GetTick() >= timeout) + { + hrtc->State = HAL_RTC_STATE_TIMEOUT; + + return HAL_TIMEOUT; + } + } + } + + /* Clear the WAKEUPTIMER Flag */ + __HAL_RTC_WAKEUPTIMER_CLEAR_FLAG(hrtc, RTC_FLAG_WUTF); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_READY; + + return HAL_OK; +} + +/** + * @} + */ +#endif /* defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) */ + +/** @defgroup RTCEx_Group3 Extension Peripheral Control functions + * @brief Extension Peripheral Control functions + * +@verbatim + =============================================================================== + ##### Extension Peripheral Control functions ##### + =============================================================================== + [..] + This subsection provides functions allowing to + (+) Writes a data in a specified RTC Backup data register + (+) Read a data in a specified RTC Backup data register + (+) Sets the Coarse calibration parameters. + (+) Deactivates the Coarse calibration parameters + (+) Sets the Smooth calibration parameters. + (+) Configures the Synchronization Shift Control Settings. + (+) Configures the Calibration Pinout (RTC_CALIB) Selection (1Hz or 512Hz). + (+) Deactivates the Calibration Pinout (RTC_CALIB) Selection (1Hz or 512Hz). + (+) Enables the RTC reference clock detection. + (+) Disable the RTC reference clock detection. + (+) Enables the Bypass Shadow feature. + (+) Disables the Bypass Shadow feature. + +@endverbatim + * @{ + */ + +#if !defined(STM32F030x6) && !defined(STM32F030x8) +/** + * @brief Writes a data in a specified RTC Backup data register. + * @param hrtc: RTC handle + * @param BackupRegister: RTC Backup data Register number. + * This parameter can be: RTC_BKP_DRx where x can be from 0 to 4 to + * specify the register. + * @param Data: Data to be written in the specified RTC Backup data register. + * @retval None + */ +void HAL_RTCEx_BKUPWrite(RTC_HandleTypeDef *hrtc, uint32_t BackupRegister, uint32_t Data) +{ + uint32_t tmp = 0; + + /* Check the parameters */ + assert_param(IS_RTC_BKP(BackupRegister)); + + tmp = (uint32_t)&(hrtc->Instance->BKP0R); + tmp += (BackupRegister * 4); + + /* Write the specified register */ + *(__IO uint32_t *)tmp = (uint32_t)Data; +} + +/** + * @brief Reads data from the specified RTC Backup data Register. + * @param hrtc: RTC handle + * @param BackupRegister: RTC Backup data Register number. + * This parameter can be: RTC_BKP_DRx where x can be from 0 to 4 to + * specify the register. + * @retval Read value + */ +uint32_t HAL_RTCEx_BKUPRead(RTC_HandleTypeDef *hrtc, uint32_t BackupRegister) +{ + uint32_t tmp = 0; + + /* Check the parameters */ + assert_param(IS_RTC_BKP(BackupRegister)); + + tmp = (uint32_t)&(hrtc->Instance->BKP0R); + tmp += (BackupRegister * 4); + + /* Read the specified register */ + return (*(__IO uint32_t *)tmp); +} +#endif /* !defined(STM32F030x6) && !defined(STM32F030x8) */ + +/** + * @brief Sets the Smooth calibration parameters. + * @param hrtc: RTC handle + * @param SmoothCalibPeriod: Select the Smooth Calibration Period. + * This parameter can be can be one of the following values : + * @arg RTC_SMOOTHCALIB_PERIOD_32SEC: The smooth calibration periode is 32s. + * @arg RTC_SMOOTHCALIB_PERIOD_16SEC: The smooth calibration periode is 16s. + * @arg RTC_SMOOTHCALIB_PERIOD_8SEC: The smooth calibartion periode is 8s. + * @param SmoothCalibPlusPulses: Select to Set or reset the CALP bit. + * This parameter can be one of the following values: + * @arg RTC_SMOOTHCALIB_PLUSPULSES_SET: Add one RTCCLK puls every 2*11 pulses. + * @arg RTC_SMOOTHCALIB_PLUSPULSES_RESET: No RTCCLK pulses are added. + * @param SmouthCalibMinusPulsesValue: Select the value of CALM[8:0] bits. + * This parameter can be one any value from 0 to 0x000001FF. + * @note To deactivate the smooth calibration, the field SmoothCalibPlusPulses + * must be equal to SMOOTHCALIB_PLUSPULSES_RESET and the field + * SmouthCalibMinusPulsesValue mut be equal to 0. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_SetSmoothCalib(RTC_HandleTypeDef* hrtc, uint32_t SmoothCalibPeriod, uint32_t SmoothCalibPlusPulses, uint32_t SmouthCalibMinusPulsesValue) +{ + uint32_t timeout = 0; + + /* Check the parameters */ + assert_param(IS_RTC_SMOOTH_CALIB_PERIOD(SmoothCalibPeriod)); + assert_param(IS_RTC_SMOOTH_CALIB_PLUS(SmoothCalibPlusPulses)); + assert_param(IS_RTC_SMOOTH_CALIB_MINUS(SmouthCalibMinusPulsesValue)); + + /* Process Locked */ + __HAL_LOCK(hrtc); + + hrtc->State = HAL_RTC_STATE_BUSY; + + /* Disable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + /* check if a calibration is pending*/ + if((hrtc->Instance->ISR & RTC_ISR_RECALPF) != RESET) + { + timeout = HAL_GetTick() + RTC_TIMEOUT_VALUE; + + /* check if a calibration is pending*/ + while((hrtc->Instance->ISR & RTC_ISR_RECALPF) != RESET) + { + if(HAL_GetTick() >= timeout) + { + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_TIMEOUT; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_TIMEOUT; + } + } + } + + /* Configure the Smooth calibration settings */ + hrtc->Instance->CALR = (uint32_t)((uint32_t)SmoothCalibPeriod | (uint32_t)SmoothCalibPlusPulses | (uint32_t)SmouthCalibMinusPulsesValue); + + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_OK; +} + +/** + * @brief Configures the Synchronization Shift Control Settings. + * @note When REFCKON is set, firmware must not write to Shift control register. + * @param hrtc: RTC handle + * @param ShiftAdd1S: Select to add or not 1 second to the time calendar. + * This parameter can be one of the following values : + * @arg RTC_SHIFTADD1S_SET: Add one second to the clock calendar. + * @arg RTC_SHIFTADD1S_RESET: No effect. + * @param ShiftSubFS: Select the number of Second Fractions to substitute. + * This parameter can be one any value from 0 to 0x7FFF. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_SetSynchroShift(RTC_HandleTypeDef* hrtc, uint32_t ShiftAdd1S, uint32_t ShiftSubFS) +{ + uint32_t timeout = 0; + + /* Check the parameters */ + assert_param(IS_RTC_SHIFT_ADD1S(ShiftAdd1S)); + assert_param(IS_RTC_SHIFT_SUBFS(ShiftSubFS)); + + /* Process Locked */ + __HAL_LOCK(hrtc); + + hrtc->State = HAL_RTC_STATE_BUSY; + + /* Disable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + timeout = HAL_GetTick() + RTC_TIMEOUT_VALUE; + + /* Wait until the shift is completed*/ + while((hrtc->Instance->ISR & RTC_ISR_SHPF) != RESET) + { + if(HAL_GetTick() >= timeout) + { + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + hrtc->State = HAL_RTC_STATE_TIMEOUT; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_TIMEOUT; + } + } + + /* Check if the reference clock detection is disabled */ + if((hrtc->Instance->CR & RTC_CR_REFCKON) == RESET) + { + /* Configure the Shift settings */ + hrtc->Instance->SHIFTR = (uint32_t)(uint32_t)(ShiftSubFS) | (uint32_t)(ShiftAdd1S); + + /* If RTC_CR_BYPSHAD bit = 0, wait for synchro else this check is not needed */ + if((hrtc->Instance->CR & RTC_CR_BYPSHAD) == RESET) + { + if(HAL_RTC_WaitForSynchro(hrtc) != HAL_OK) + { + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + hrtc->State = HAL_RTC_STATE_ERROR; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_ERROR; + } + } + } + else + { + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_ERROR; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_ERROR; + } + + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_OK; +} + +/** + * @brief Configures the Calibration Pinout (RTC_CALIB) Selection (1Hz or 512Hz). + * @param hrtc: RTC handle + * @param CalibOutput : Select the Calibration output Selection . + * This parameter can be one of the following values: + * @arg RTC_CALIBOUTPUT_512HZ: A signal has a regular waveform at 512Hz. + * @arg RTC_CALIBOUTPUT_1HZ: A signal has a regular waveform at 1Hz. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_SetCalibrationOutPut(RTC_HandleTypeDef* hrtc, uint32_t CalibOutput) +{ + /* Check the parameters */ + assert_param(IS_RTC_CALIB_OUTPUT(CalibOutput)); + + /* Process Locked */ + __HAL_LOCK(hrtc); + + hrtc->State = HAL_RTC_STATE_BUSY; + + /* Disable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + /* Clear flags before config */ + hrtc->Instance->CR &= (uint32_t)~RTC_CR_COSEL; + + /* Configure the RTC_CR register */ + hrtc->Instance->CR |= (uint32_t)CalibOutput; + + __HAL_RTC_CALIBRATION_OUTPUT_ENABLE(hrtc); + + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_OK; +} + +/** + * @brief Deactivates the Calibration Pinout (RTC_CALIB) Selection (1Hz or 512Hz). + * @param hrtc: RTC handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_DeactivateCalibrationOutPut(RTC_HandleTypeDef* hrtc) +{ + /* Process Locked */ + __HAL_LOCK(hrtc); + + hrtc->State = HAL_RTC_STATE_BUSY; + + /* Disable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + __HAL_RTC_CALIBRATION_OUTPUT_DISABLE(hrtc); + + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_OK; +} + +/** + * @brief Enables the RTC reference clock detection. + * @param hrtc: RTC handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_SetRefClock(RTC_HandleTypeDef* hrtc) +{ + /* Process Locked */ + __HAL_LOCK(hrtc); + + hrtc->State = HAL_RTC_STATE_BUSY; + + /* Disable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + /* Set Initialization mode */ + if(RTC_EnterInitMode(hrtc) != HAL_OK) + { + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + /* Set RTC state*/ + hrtc->State = HAL_RTC_STATE_ERROR; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_ERROR; + } + else + { + __HAL_RTC_CLOCKREF_DETECTION_ENABLE(hrtc); + + /* Exit Initialization mode */ + hrtc->Instance->ISR &= (uint32_t)~RTC_ISR_INIT; + } + + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_OK; +} + +/** + * @brief Disable the RTC reference clock detection. + * @param hrtc: RTC handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_DeactivateRefClock(RTC_HandleTypeDef* hrtc) +{ + /* Process Locked */ + __HAL_LOCK(hrtc); + + hrtc->State = HAL_RTC_STATE_BUSY; + + /* Disable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + /* Set Initialization mode */ + if(RTC_EnterInitMode(hrtc) != HAL_OK) + { + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + /* Set RTC state*/ + hrtc->State = HAL_RTC_STATE_ERROR; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_ERROR; + } + else + { + __HAL_RTC_CLOCKREF_DETECTION_DISABLE(hrtc); + + /* Exit Initialization mode */ + hrtc->Instance->ISR &= (uint32_t)~RTC_ISR_INIT; + } + + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_OK; +} + +/** + * @brief Enables the Bypass Shadow feature. + * @param hrtc: RTC handle + * @note When the Bypass Shadow is enabled the calendar value are taken + * directly from the Calendar counter. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_EnableBypassShadow(RTC_HandleTypeDef* hrtc) +{ + /* Process Locked */ + __HAL_LOCK(hrtc); + + hrtc->State = HAL_RTC_STATE_BUSY; + + /* Disable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + /* Set the BYPSHAD bit */ + hrtc->Instance->CR |= (uint8_t)RTC_CR_BYPSHAD; + + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_OK; +} + +/** + * @brief Disables the Bypass Shadow feature. + * @param hrtc: RTC handle + * @note When the Bypass Shadow is enabled the calendar value are taken + * directly from the Calendar counter. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_DisableBypassShadow(RTC_HandleTypeDef* hrtc) +{ + /* Process Locked */ + __HAL_LOCK(hrtc); + + hrtc->State = HAL_RTC_STATE_BUSY; + + /* Disable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + /* Reset the BYPSHAD bit */ + hrtc->Instance->CR &= (uint8_t)~RTC_CR_BYPSHAD; + + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_OK; +} + +/** + * @} + */ + +/** + * @} + */ + +#endif /* HAL_RTC_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_rtc_ex.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_rtc_ex.h new file mode 100644 index 0000000000..e779978c35 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_rtc_ex.h @@ -0,0 +1,667 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_rtc_ex.h + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief Header file of RTC HAL Extension module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32F0xx_HAL_RTC_EX_H +#define __STM32F0xx_HAL_RTC_EX_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal_def.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @addtogroup RTCEx + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ + +/** + * @brief RTC Tamper structure definition + */ +typedef struct +{ + uint32_t Tamper; /*!< Specifies the Tamper Pin. + This parameter can be a value of @ref RTCEx_Tamper_Pins_Definitions */ + + uint32_t Trigger; /*!< Specifies the Tamper Trigger. + This parameter can be a value of @ref RTCEx_Tamper_Trigger_Definitions */ + + uint32_t Filter; /*!< Specifies the RTC Filter Tamper. + This parameter can be a value of @ref RTCEx_Tamper_Filter_Definitions */ + + uint32_t SamplingFrequency; /*!< Specifies the sampling frequency. + This parameter can be a value of @ref RTCEx_Tamper_Sampling_Frequencies_Definitions */ + + uint32_t PrechargeDuration; /*!< Specifies the Precharge Duration . + This parameter can be a value of @ref RTCEx_Tamper_Pin_Precharge_Duration_Definitions */ + + uint32_t TamperPullUp; /*!< Specifies the Tamper PullUp . + This parameter can be a value of @ref RTCEx_Tamper_Pull_UP_Definitions */ + + uint32_t TimeStampOnTamperDetection; /*!< Specifies the TimeStampOnTamperDetection. + This parameter can be a value of @ref RTCEx_Tamper_TimeStampOnTamperDetection_Definitions */ +}RTC_TamperTypeDef; + +/* Exported constants --------------------------------------------------------*/ +/** @defgroup RTCEx_Exported_Constants + * @{ + */ + +/** @defgroup RTCEx_Output_selection_Definitions + * @{ + */ +#define RTC_OUTPUT_DISABLE ((uint32_t)0x00000000) +#define RTC_OUTPUT_ALARMA ((uint32_t)0x00200000) +#if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) +#define RTC_OUTPUT_WAKEUP ((uint32_t)0x00600000) +#endif + +#if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) +#define IS_RTC_OUTPUT(OUTPUT) (((OUTPUT) == RTC_OUTPUT_DISABLE) || \ + ((OUTPUT) == RTC_OUTPUT_ALARMA) || \ + ((OUTPUT) == RTC_OUTPUT_WAKEUP)) +#else +#define IS_RTC_OUTPUT(OUTPUT) (((OUTPUT) == RTC_OUTPUT_DISABLE) || \ + ((OUTPUT) == RTC_OUTPUT_ALARMA)) +#endif +/** + * @} + */ + +#if !defined(STM32F030x6) && !defined(STM32F030x8) +/** @defgroup RTCEx_Backup_Registers_Definitions + * @{ + */ +#define RTC_BKP_DR0 ((uint32_t)0x00000000) +#define RTC_BKP_DR1 ((uint32_t)0x00000001) +#define RTC_BKP_DR2 ((uint32_t)0x00000002) +#define RTC_BKP_DR3 ((uint32_t)0x00000003) +#define RTC_BKP_DR4 ((uint32_t)0x00000004) + +#define IS_RTC_BKP(BKP) ((BKP) < (uint32_t) RTC_BKP_NUMBER) +/** + * @} + */ +#endif /* !defined(STM32F030x6) && !defined(STM32F030x8) */ + +/** @defgroup RTCEx_Time_Stamp_Edges_definitions + * @{ + */ +#define RTC_TIMESTAMPEDGE_RISING ((uint32_t)0x00000000) +#define RTC_TIMESTAMPEDGE_FALLING ((uint32_t)0x00000008) + +#define IS_TIMESTAMP_EDGE(EDGE) (((EDGE) == RTC_TIMESTAMPEDGE_RISING) || \ + ((EDGE) == RTC_TIMESTAMPEDGE_FALLING)) +/** + * @} + */ + +/** @defgroup RTCEx_Tamper_Pins_Definitions + * @{ + */ +#define RTC_TAMPER_1 RTC_TAFCR_TAMP1E +#define RTC_TAMPER_2 RTC_TAFCR_TAMP2E +#if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) +#define RTC_TAMPER_3 RTC_TAFCR_TAMP3E +#endif + +#if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) +#define IS_TAMPER(TAMPER) (((TAMPER) == RTC_TAMPER_1) || \ + ((TAMPER) == RTC_TAMPER_2) || \ + ((TAMPER) == RTC_TAMPER_3)) +#else +#define IS_TAMPER(TAMPER) (((TAMPER) == RTC_TAMPER_1) || \ + ((TAMPER) == RTC_TAMPER_2)) +#endif +/** + * @} + */ + +/** @defgroup RTCEx_TimeStamp_Pin_Selection + * @{ + */ +#define RTC_TIMESTAMPPIN_PC13 ((uint32_t)0x00000000) + +#define IS_RTC_TIMESTAMP_PIN(PIN) (((PIN) == RTC_TIMESTAMPPIN_PC13)) +/** + * @} + */ + +/** @defgroup RTCEx_Tamper_Trigger_Definitions + * @{ + */ +#define RTC_TAMPERTRIGGER_RISINGEDGE ((uint32_t)0x00000000) +#define RTC_TAMPERTRIGGER_FALLINGEDGE ((uint32_t)0x00000002) +#define RTC_TAMPERTRIGGER_LOWLEVEL RTC_TAMPERTRIGGER_RISINGEDGE +#define RTC_TAMPERTRIGGER_HIGHLEVEL RTC_TAMPERTRIGGER_FALLINGEDGE + +#define IS_TAMPER_TRIGGER(TRIGGER) (((TRIGGER) == RTC_TAMPERTRIGGER_RISINGEDGE) || \ + ((TRIGGER) == RTC_TAMPERTRIGGER_FALLINGEDGE) || \ + ((TRIGGER) == RTC_TAMPERTRIGGER_LOWLEVEL) || \ + ((TRIGGER) == RTC_TAMPERTRIGGER_HIGHLEVEL)) + +/** + * @} + */ + +/** @defgroup RTCEx_Tamper_Filter_Definitions + * @{ + */ +#define RTC_TAMPERFILTER_DISABLE ((uint32_t)0x00000000) /*!< Tamper filter is disabled */ + +#define RTC_TAMPERFILTER_2SAMPLE ((uint32_t)0x00000800) /*!< Tamper is activated after 2 + consecutive samples at the active level */ +#define RTC_TAMPERFILTER_4SAMPLE ((uint32_t)0x00001000) /*!< Tamper is activated after 4 + consecutive samples at the active level */ +#define RTC_TAMPERFILTER_8SAMPLE ((uint32_t)0x00001800) /*!< Tamper is activated after 8 + consecutive samples at the active level. */ + +#define IS_TAMPER_FILTER(FILTER) (((FILTER) == RTC_TAMPERFILTER_DISABLE) || \ + ((FILTER) == RTC_TAMPERFILTER_2SAMPLE) || \ + ((FILTER) == RTC_TAMPERFILTER_4SAMPLE) || \ + ((FILTER) == RTC_TAMPERFILTER_8SAMPLE)) +/** + * @} + */ + +/** @defgroup RTCEx_Tamper_Sampling_Frequencies_Definitions + * @{ + */ +#define RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV32768 ((uint32_t)0x00000000) /*!< Each of the tamper inputs are sampled + with a frequency = RTCCLK / 32768 */ +#define RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV16384 ((uint32_t)0x00000100) /*!< Each of the tamper inputs are sampled + with a frequency = RTCCLK / 16384 */ +#define RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV8192 ((uint32_t)0x00000200) /*!< Each of the tamper inputs are sampled + with a frequency = RTCCLK / 8192 */ +#define RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV4096 ((uint32_t)0x00000300) /*!< Each of the tamper inputs are sampled + with a frequency = RTCCLK / 4096 */ +#define RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV2048 ((uint32_t)0x00000400) /*!< Each of the tamper inputs are sampled + with a frequency = RTCCLK / 2048 */ +#define RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV1024 ((uint32_t)0x00000500) /*!< Each of the tamper inputs are sampled + with a frequency = RTCCLK / 1024 */ +#define RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV512 ((uint32_t)0x00000600) /*!< Each of the tamper inputs are sampled + with a frequency = RTCCLK / 512 */ +#define RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV256 ((uint32_t)0x00000700) /*!< Each of the tamper inputs are sampled + with a frequency = RTCCLK / 256 */ + +#define IS_TAMPER_SAMPLING_FREQ(FREQ) (((FREQ) == RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV32768)|| \ + ((FREQ) == RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV16384)|| \ + ((FREQ) == RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV8192) || \ + ((FREQ) == RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV4096) || \ + ((FREQ) == RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV2048) || \ + ((FREQ) == RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV1024) || \ + ((FREQ) == RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV512) || \ + ((FREQ) == RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV256)) +/** + * @} + */ + +/** @defgroup RTCEx_Tamper_Pin_Precharge_Duration_Definitions + * @{ + */ +#define RTC_TAMPERPRECHARGEDURATION_1RTCCLK ((uint32_t)0x00000000) /*!< Tamper pins are pre-charged before + sampling during 1 RTCCLK cycle */ +#define RTC_TAMPERPRECHARGEDURATION_2RTCCLK ((uint32_t)0x00002000) /*!< Tamper pins are pre-charged before + sampling during 2 RTCCLK cycles */ +#define RTC_TAMPERPRECHARGEDURATION_4RTCCLK ((uint32_t)0x00004000) /*!< Tamper pins are pre-charged before + sampling during 4 RTCCLK cycles */ +#define RTC_TAMPERPRECHARGEDURATION_8RTCCLK ((uint32_t)0x00006000) /*!< Tamper pins are pre-charged before + sampling during 8 RTCCLK cycles */ + +#define IS_TAMPER_PRECHARGE_DURATION(DURATION) (((DURATION) == RTC_TAMPERPRECHARGEDURATION_1RTCCLK) || \ + ((DURATION) == RTC_TAMPERPRECHARGEDURATION_2RTCCLK) || \ + ((DURATION) == RTC_TAMPERPRECHARGEDURATION_4RTCCLK) || \ + ((DURATION) == RTC_TAMPERPRECHARGEDURATION_8RTCCLK)) +/** + * @} + */ + +/** @defgroup RTCEx_Tamper_TimeStampOnTamperDetection_Definitions + * @{ + */ +#define RTC_TIMESTAMPONTAMPERDETECTION_ENABLE ((uint32_t)RTC_TAFCR_TAMPTS) /*!< TimeStamp on Tamper Detection event saved */ +#define RTC_TIMESTAMPONTAMPERDETECTION_DISABLE ((uint32_t)0x00000000) /*!< TimeStamp on Tamper Detection event is not saved */ + +#define IS_TAMPER_TIMESTAMPONTAMPER_DETECTION(DETECTION) (((DETECTION) == RTC_TIMESTAMPONTAMPERDETECTION_ENABLE) || \ + ((DETECTION) == RTC_TIMESTAMPONTAMPERDETECTION_DISABLE)) +/** + * @} + */ + +/** @defgroup RTCEx_Tamper_Pull_UP_Definitions + * @{ + */ +#define RTC_TAMPER_PULLUP_ENABLE ((uint32_t)0x00000000) /*!< TimeStamp on Tamper Detection event saved */ +#define RTC_TAMPER_PULLUP_DISABLE ((uint32_t)RTC_TAFCR_TAMPPUDIS) /*!< TimeStamp on Tamper Detection event is not saved */ + +#define IS_TAMPER_PULLUP_STATE(STATE) (((STATE) == RTC_TAMPER_PULLUP_ENABLE) || \ + ((STATE) == RTC_TAMPER_PULLUP_DISABLE)) +/** + * @} + */ + +#if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) +/** @defgroup RTCEx_Wakeup_Timer_Definitions + * @{ + */ +#define RTC_WAKEUPCLOCK_RTCCLK_DIV16 ((uint32_t)0x00000000) +#define RTC_WAKEUPCLOCK_RTCCLK_DIV8 ((uint32_t)0x00000001) +#define RTC_WAKEUPCLOCK_RTCCLK_DIV4 ((uint32_t)0x00000002) +#define RTC_WAKEUPCLOCK_RTCCLK_DIV2 ((uint32_t)0x00000003) +#define RTC_WAKEUPCLOCK_CK_SPRE_16BITS ((uint32_t)0x00000004) +#define RTC_WAKEUPCLOCK_CK_SPRE_17BITS ((uint32_t)0x00000006) + +#define IS_WAKEUP_CLOCK(CLOCK) (((CLOCK) == RTC_WAKEUPCLOCK_RTCCLK_DIV16) || \ + ((CLOCK) == RTC_WAKEUPCLOCK_RTCCLK_DIV8) || \ + ((CLOCK) == RTC_WAKEUPCLOCK_RTCCLK_DIV4) || \ + ((CLOCK) == RTC_WAKEUPCLOCK_RTCCLK_DIV2) || \ + ((CLOCK) == RTC_WAKEUPCLOCK_CK_SPRE_16BITS) || \ + ((CLOCK) == RTC_WAKEUPCLOCK_CK_SPRE_17BITS)) + +#define IS_WAKEUP_COUNTER(COUNTER) ((COUNTER) <= 0xFFFF) +/** + * @} + */ +#endif /* defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) */ + +/** @defgroup RTCEx_Smooth_calib_period_Definitions + * @{ + */ +#define RTC_SMOOTHCALIB_PERIOD_32SEC ((uint32_t)0x00000000) /*!< If RTCCLK = 32768 Hz, Smooth calibation + period is 32s, else 2exp20 RTCCLK seconds */ +#define RTC_SMOOTHCALIB_PERIOD_16SEC ((uint32_t)0x00002000) /*!< If RTCCLK = 32768 Hz, Smooth calibation + period is 16s, else 2exp19 RTCCLK seconds */ +#define RTC_SMOOTHCALIB_PERIOD_8SEC ((uint32_t)0x00004000) /*!< If RTCCLK = 32768 Hz, Smooth calibation + period is 8s, else 2exp18 RTCCLK seconds */ + +#define IS_RTC_SMOOTH_CALIB_PERIOD(PERIOD) (((PERIOD) == RTC_SMOOTHCALIB_PERIOD_32SEC) || \ + ((PERIOD) == RTC_SMOOTHCALIB_PERIOD_16SEC) || \ + ((PERIOD) == RTC_SMOOTHCALIB_PERIOD_8SEC)) +/** + * @} + */ + +/** @defgroup RTCEx_Smooth_calib_Plus_pulses_Definitions + * @{ + */ +#define RTC_SMOOTHCALIB_PLUSPULSES_SET ((uint32_t)0x00008000) /*!< The number of RTCCLK pulses added + during a X -second window = Y - CALM[8:0] + with Y = 512, 256, 128 when X = 32, 16, 8 */ +#define RTC_SMOOTHCALIB_PLUSPULSES_RESET ((uint32_t)0x00000000) /*!< The number of RTCCLK pulses subbstited + during a 32-second window = CALM[8:0] */ + +#define IS_RTC_SMOOTH_CALIB_PLUS(PLUS) (((PLUS) == RTC_SMOOTHCALIB_PLUSPULSES_SET) || \ + ((PLUS) == RTC_SMOOTHCALIB_PLUSPULSES_RESET)) +/** + * @} + */ + +/** @defgroup RTCEx_Smooth_calib_Minus_pulses_Definitions + * @{ + */ +#define IS_RTC_SMOOTH_CALIB_MINUS(VALUE) ((VALUE) <= 0x000001FF) +/** + * @} + */ + +/** @defgroup RTCEx_Add_1_Second_Parameter_Definitions + * @{ + */ +#define RTC_SHIFTADD1S_RESET ((uint32_t)0x00000000) +#define RTC_SHIFTADD1S_SET ((uint32_t)0x80000000) + +#define IS_RTC_SHIFT_ADD1S(SEL) (((SEL) == RTC_SHIFTADD1S_RESET) || \ + ((SEL) == RTC_SHIFTADD1S_SET)) +/** + * @} + */ + +/** @defgroup RTCEx_Substract_Fraction_Of_Second_Value + * @{ + */ +#define IS_RTC_SHIFT_SUBFS(FS) ((FS) <= 0x00007FFF) +/** + * @} + */ + + /** @defgroup RTCEx_Calib_Output_selection_Definitions + * @{ + */ +#define RTC_CALIBOUTPUT_512HZ ((uint32_t)0x00000000) +#define RTC_CALIBOUTPUT_1HZ ((uint32_t)0x00080000) + +#define IS_RTC_CALIB_OUTPUT(OUTPUT) (((OUTPUT) == RTC_CALIBOUTPUT_512HZ) || \ + ((OUTPUT) == RTC_CALIBOUTPUT_1HZ)) +/** + * @} + */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ + +#if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) +/** + * @brief Enable the RTC WakeUp Timer peripheral. + * @param __HANDLE__: specifies the RTC handle. + * @retval None + */ +#define __HAL_RTC_WAKEUPTIMER_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= (RTC_CR_WUTE)) +#endif /* defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) */ + +/** + * @brief Enable the RTC TimeStamp peripheral. + * @param __HANDLE__: specifies the RTC handle. + * @retval None + */ +#define __HAL_RTC_TIMESTAMP_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= (RTC_CR_TSE)) + +#if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) +/** + * @brief Disable the RTC WakeUp Timer peripheral. + * @param __HANDLE__: specifies the RTC handle. + * @retval None + */ +#define __HAL_RTC_WAKEUPTIMER_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~(RTC_CR_WUTE)) +#endif /* defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) */ + +/** + * @brief Disable the RTC TimeStamp peripheral. + * @param __HANDLE__: specifies the RTC handle. + * @retval None + */ +#define __HAL_RTC_TIMESTAMP_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~(RTC_CR_TSE)) + +/** + * @brief Enable the RTC calibration output. + * @param __HANDLE__: specifies the RTC handle. + * @retval None + */ +#define __HAL_RTC_CALIBRATION_OUTPUT_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= (RTC_CR_COE)) + +/** + * @brief Disable the calibration output. + * @param __HANDLE__: specifies the RTC handle. + * @retval None + */ +#define __HAL_RTC_CALIBRATION_OUTPUT_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~(RTC_CR_COE)) + +/** + * @brief Enable the clock reference detection. + * @param __HANDLE__: specifies the RTC handle. + * @retval None + */ +#define __HAL_RTC_CLOCKREF_DETECTION_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= (RTC_CR_REFCKON)) + +/** + * @brief Disable the clock reference detection. + * @param __HANDLE__: specifies the RTC handle. + * @retval None + */ +#define __HAL_RTC_CLOCKREF_DETECTION_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~(RTC_CR_REFCKON)) + +/** + * @brief Enable the RTC TimeStamp interrupt. + * @param __HANDLE__: specifies the RTC handle. + * @param __INTERRUPT__: specifies the RTC TimeStamp interrupt sources to be enabled or disabled. + * This parameter can be: + * @arg RTC_IT_TS: TimeStamp interrupt + * @retval None + */ +#define __HAL_RTC_TIMESTAMP_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR |= (__INTERRUPT__)) + +#if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) +/** + * @brief Enable the RTC WakeUpTimer interrupt. + * @param __HANDLE__: specifies the RTC handle. + * @param __INTERRUPT__: specifies the RTC WakeUpTimer interrupt sources to be enabled or disabled. + * This parameter can be: + * @arg RTC_IT_WUT: WakeUpTimer A interrupt + * @retval None + */ +#define __HAL_RTC_WAKEUPTIMER_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR |= (__INTERRUPT__)) +#endif /* defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) */ + +/** + * @brief Disable the RTC TimeStamp interrupt. + * @param __HANDLE__: specifies the RTC handle. + * @param __INTERRUPT__: specifies the RTC TimeStamp interrupt sources to be enabled or disabled. + * This parameter can be: + * @arg RTC_IT_TS: TimeStamp interrupt + * @retval None + */ +#define __HAL_RTC_TIMESTAMP_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR &= ~(__INTERRUPT__)) + +#if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) +/** + * @brief Disable the RTC WakeUpTimer interrupt. + * @param __HANDLE__: specifies the RTC handle. + * @param __INTERRUPT__: specifies the RTC WakeUpTimer interrupt sources to be enabled or disabled. + * This parameter can be: + * @arg RTC_IT_WUT: WakeUpTimer A interrupt + * @retval None + */ +#define __HAL_RTC_WAKEUPTIMER_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR &= ~(__INTERRUPT__)) +#endif /* defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) */ + +/** + * @brief Check whether the specified RTC Tamper interrupt has occurred or not. + * @param __HANDLE__: specifies the RTC handle. + * @param __FLAG__: specifies the RTC Tamper interrupt sources to be enabled or disabled. + * This parameter can be: + * @arg RTC_IT_TAMP1 + * @retval None + */ +#define __HAL_RTC_TAMPER_GET_IT(__HANDLE__, __FLAG__) (((((__HANDLE__)->Instance->ISR) & ((__FLAG__)>> 4)) != RESET)? SET : RESET) + +#if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) +/** + * @brief Check whether the specified RTC WakeUpTimer interrupt has occurred or not. + * @param __HANDLE__: specifies the RTC handle. + * @param __FLAG__: specifies the RTC WakeUpTimer interrupt sources to be enabled or disabled. + * This parameter can be: + * @arg RTC_IT_WUT: WakeUpTimer A interrupt + * @retval None + */ +#define __HAL_RTC_WAKEUPTIMER_GET_IT(__HANDLE__, __FLAG__) (((((__HANDLE__)->Instance->ISR) & ((__FLAG__)>> 4)) != RESET)? SET : RESET) +#endif /* defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) */ + +/** + * @brief Check whether the specified RTC TimeStamp interrupt has occurred or not. + * @param __HANDLE__: specifies the RTC handle. + * @param __FLAG__: specifies the RTC TimeStamp interrupt sources to be enabled or disabled. + * This parameter can be: + * @arg RTC_IT_TS: TimeStamp interrupt + * @retval None + */ +#define __HAL_RTC_TIMESTAMP_GET_IT(__HANDLE__, __FLAG__) (((((__HANDLE__)->Instance->ISR) & ((__FLAG__)>> 4)) != RESET)? SET : RESET) + +/** + * @brief Get the selected RTC TimeStamp's flag status. + * @param __HANDLE__: specifies the RTC handle. + * @param __FLAG__: specifies the RTC TimeStamp Flag sources to be enabled or disabled. + * This parameter can be: + * @arg RTC_FLAG_TSF + * @arg RTC_FLAG_TSOVF + * @retval None + */ +#define __HAL_RTC_TIMESTAMP_GET_FLAG(__HANDLE__, __FLAG__) (((((__HANDLE__)->Instance->ISR) & (__FLAG__)) != RESET)? SET : RESET) + +#if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) +/** + * @brief Get the selected RTC WakeUpTimer's flag status. + * @param __HANDLE__: specifies the RTC handle. + * @param __FLAG__: specifies the RTC WakeUpTimer Flag sources to be enabled or disabled. + * This parameter can be: + * @arg RTC_FLAG_WUTF + * @arg RTC_FLAG_WUTWF + * @retval None + */ +#define __HAL_RTC_WAKEUPTIMER_GET_FLAG(__HANDLE__, __FLAG__) (((((__HANDLE__)->Instance->ISR) & (__FLAG__)) != RESET)? SET : RESET) +#endif /* defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) */ + +/** + * @brief Get the selected RTC Tamper's flag status. + * @param __HANDLE__: specifies the RTC handle. + * @param __FLAG__: specifies the RTC Tamper Flag sources to be enabled or disabled. + * This parameter can be: + * @arg RTC_FLAG_TAMP1F + * @retval None + */ +#define __HAL_RTC_TAMPER_GET_FLAG(__HANDLE__, __FLAG__) (((((__HANDLE__)->Instance->ISR) & (__FLAG__)) != RESET)? SET : RESET) + +/** + * @brief Get the selected RTC shift operation's flag status. + * @param __HANDLE__: specifies the RTC handle. + * @param __FLAG__: specifies the RTC shift operation Flag is pending or not. + * This parameter can be: + * @arg RTC_FLAG_SHPF + * @retval None + */ +#define __HAL_RTC_SHIFT_GET_FLAG(__HANDLE__, __FLAG__) (((((__HANDLE__)->Instance->ISR) & (__FLAG__)) != RESET)? SET : RESET) + +/** + * @brief Clear the RTC Time Stamp's pending flags. + * @param __HANDLE__: specifies the RTC handle. + * @param __FLAG__: specifies the RTC Alarm Flag sources to be enabled or disabled. + * This parameter can be: + * @arg RTC_FLAG_TSF + * @retval None + */ +#define __HAL_RTC_TIMESTAMP_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->ISR) = (~(((__FLAG__) | RTC_ISR_INIT)& 0x0000FFFF)|((__HANDLE__)->Instance->ISR & RTC_ISR_INIT)) + +/** + * @brief Clear the RTC Tamper's pending flags. + * @param __HANDLE__: specifies the RTC handle. + * @param __FLAG__: specifies the RTC Tamper Flag sources to be enabled or disabled. + * This parameter can be: + * @arg RTC_FLAG_TAMP1F + * @retval None + */ +#define __HAL_RTC_TAMPER_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->ISR) = (~(((__FLAG__) | RTC_ISR_INIT)& 0x0000FFFF)|((__HANDLE__)->Instance->ISR & RTC_ISR_INIT)) + +#if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) +/** + * @brief Clear the RTC Wake Up timer's pending flags. + * @param __HANDLE__: specifies the RTC handle. + * @param __FLAG__: specifies the RTC Tamper Flag sources to be enabled or disabled. + * This parameter can be: + * @arg RTC_FLAG_WUTF + * @retval None + */ +#define __HAL_RTC_WAKEUPTIMER_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->ISR) = (~(((__FLAG__) | RTC_ISR_INIT)& 0x0000FFFF)|((__HANDLE__)->Instance->ISR & RTC_ISR_INIT)) +#endif /* defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) */ + +/* Exported functions --------------------------------------------------------*/ + +/* RTC TimeStamp and Tamper functions *****************************************/ +HAL_StatusTypeDef HAL_RTCEx_SetTimeStamp(RTC_HandleTypeDef *hrtc, uint32_t TimeStampEdge, uint32_t RTC_TimeStampPin); +HAL_StatusTypeDef HAL_RTCEx_SetTimeStamp_IT(RTC_HandleTypeDef *hrtc, uint32_t TimeStampEdge, uint32_t RTC_TimeStampPin); +HAL_StatusTypeDef HAL_RTCEx_DeactivateTimeStamp(RTC_HandleTypeDef *hrtc); +HAL_StatusTypeDef HAL_RTCEx_GetTimeStamp(RTC_HandleTypeDef *hrtc, RTC_TimeTypeDef *sTimeStamp, RTC_DateTypeDef *sTimeStampDate, uint32_t Format); + +HAL_StatusTypeDef HAL_RTCEx_SetTamper(RTC_HandleTypeDef *hrtc, RTC_TamperTypeDef* sTamper); +HAL_StatusTypeDef HAL_RTCEx_SetTamper_IT(RTC_HandleTypeDef *hrtc, RTC_TamperTypeDef* sTamper); +HAL_StatusTypeDef HAL_RTCEx_DeactivateTamper(RTC_HandleTypeDef *hrtc, uint32_t Tamper); +void HAL_RTCEx_TamperTimeStampIRQHandler(RTC_HandleTypeDef *hrtc); + +void HAL_RTCEx_Tamper1EventCallback(RTC_HandleTypeDef *hrtc); +void HAL_RTCEx_Tamper2EventCallback(RTC_HandleTypeDef *hrtc); +#if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) +void HAL_RTCEx_Tamper3EventCallback(RTC_HandleTypeDef *hrtc); +#endif +void HAL_RTCEx_TimeStampEventCallback(RTC_HandleTypeDef *hrtc); +HAL_StatusTypeDef HAL_RTCEx_PollForTimeStampEvent(RTC_HandleTypeDef *hrtc, uint32_t Timeout); +HAL_StatusTypeDef HAL_RTCEx_PollForTamper1Event(RTC_HandleTypeDef *hrtc, uint32_t Timeout); +HAL_StatusTypeDef HAL_RTCEx_PollForTamper2Event(RTC_HandleTypeDef *hrtc, uint32_t Timeout); +#if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) +HAL_StatusTypeDef HAL_RTCEx_PollForTamper3Event(RTC_HandleTypeDef *hrtc, uint32_t Timeout); +#endif + +#if defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) +/* RTC Wake-up functions ******************************************************/ +HAL_StatusTypeDef HAL_RTCEx_SetWakeUpTimer(RTC_HandleTypeDef *hrtc, uint32_t WakeUpCounter, uint32_t WakeUpClock); +HAL_StatusTypeDef HAL_RTCEx_SetWakeUpTimer_IT(RTC_HandleTypeDef *hrtc, uint32_t WakeUpCounter, uint32_t WakeUpClock); +uint32_t HAL_RTCEx_DeactivateWakeUpTimer(RTC_HandleTypeDef *hrtc); +uint32_t HAL_RTCEx_GetWakeUpTimer(RTC_HandleTypeDef *hrtc); +void HAL_RTCEx_WakeUpTimerIRQHandler(RTC_HandleTypeDef *hrtc); +void HAL_RTCEx_WakeUpTimerEventCallback(RTC_HandleTypeDef *hrtc); +HAL_StatusTypeDef HAL_RTCEx_PollForWakeUpTimerEvent(RTC_HandleTypeDef *hrtc, uint32_t Timeout); +#endif + +/* Extension Control functions ************************************************/ +#if !defined(STM32F030x6) && !defined(STM32F030x8) +void HAL_RTCEx_BKUPWrite(RTC_HandleTypeDef *hrtc, uint32_t BackupRegister, uint32_t Data); +uint32_t HAL_RTCEx_BKUPRead(RTC_HandleTypeDef *hrtc, uint32_t BackupRegister); +#endif + +HAL_StatusTypeDef HAL_RTCEx_SetSmoothCalib(RTC_HandleTypeDef *hrtc, uint32_t SmoothCalibPeriod, uint32_t SmoothCalibPlusPulses, uint32_t SmouthCalibMinusPulsesValue); +HAL_StatusTypeDef HAL_RTCEx_SetSynchroShift(RTC_HandleTypeDef *hrtc, uint32_t ShiftAdd1S, uint32_t ShiftSubFS); +HAL_StatusTypeDef HAL_RTCEx_SetCalibrationOutPut(RTC_HandleTypeDef *hrtc, uint32_t CalibOutput); +HAL_StatusTypeDef HAL_RTCEx_DeactivateCalibrationOutPut(RTC_HandleTypeDef *hrtc); +HAL_StatusTypeDef HAL_RTCEx_SetRefClock(RTC_HandleTypeDef *hrtc); +HAL_StatusTypeDef HAL_RTCEx_DeactivateRefClock(RTC_HandleTypeDef *hrtc); +HAL_StatusTypeDef HAL_RTCEx_EnableBypassShadow(RTC_HandleTypeDef *hrtc); +HAL_StatusTypeDef HAL_RTCEx_DisableBypassShadow(RTC_HandleTypeDef *hrtc); + +/* Extension RTC features functions *******************************************/ + + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __STM32F0xx_HAL_RTC_EX_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_smartcard.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_smartcard.c new file mode 100644 index 0000000000..9f2ca105cd --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_smartcard.c @@ -0,0 +1,1361 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_smartcard.c + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief SMARTCARD HAL module driver. + * + * This file provides firmware functions to manage the following + * functionalities of the SmartCard. + * + Initialization and de-initialization function + * + IO operation function + * + Peripheral Control function + * + * + @verbatim + =============================================================================== + ##### How to use this driver ##### + =============================================================================== + [..] + The SMARTCARD HAL driver can be used as follows: + + (#) Declare a SMARTCARD_HandleTypeDef handle structure. + (#) Associate a USART to the SMARTCARD handle hsmartcard. + (#) Initialize the SMARTCARD low level resources by implementing the HAL_SMARTCARD_MspInit ()API: + (##) Enable the USARTx interface clock. + (##) USART pins configuration: + (+) Enable the clock for the USART GPIOs. + (+) Configure these USART pins as alternate function pull-up. + (##) NVIC configuration if you need to use interrupt process (HAL_SMARTCARD_Transmit_IT() + and HAL_SMARTCARD_Receive_IT() APIs): + (+) Configure the USARTx interrupt priority. + (+) Enable the NVIC USART IRQ handle. + (@) The specific USART interrupts (Transmission complete interrupt, + RXNE interrupt and Error Interrupts) will be managed using the macros + __HAL_SMARTCARD_ENABLE_IT() and __HAL_SMARTCARD_DISABLE_IT() inside the transmit and receive process. + (##) DMA Configuration if you need to use DMA process (HAL_SMARTCARD_Transmit_DMA() + and HAL_SMARTCARD_Receive_DMA() APIs): + (+) Declare a DMA handle structure for the Tx/Rx stream. + (+) Enable the DMAx interface clock. + (+) Configure the declared DMA handle structure with the required Tx/Rx parameters. + (+) Configure the DMA Tx/Rx Stream. + (+) Associate the initialized DMA handle to the SMARTCARD DMA Tx/Rx handle. + (+) Configure the priority and enable the NVIC for the transfer complete interrupt on the DMA Tx/Rx Stream. + + (#) Program the Baud Rate, Parity, Mode(Receiver/Transmitter), clock enabling/disabling and accordingly, + the clock parameters (parity, phase, last bit), prescaler value, guard time and NACK on transmission + error enabling or disabling in the hsmartcard Init structure. + + (#) If required, program SMARTCARD advanced features (TX/RX pins swap, TimeOut, auto-retry counter,...) + in the hsmartcard AdvancedInit structure. + + (#) Initialize the SMARTCARD associated USART registers by calling + the HAL_SMARTCARD_Init() API. + + (@) HAL_SMARTCARD_Init() API also configure also the low level Hardware GPIO, CLOCK, CORTEX...etc) by + calling the customized HAL_SMARTCARD_MspInit() API. + + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @defgroup SMARTCARD + * @brief HAL SMARTCARD module driver + * @{ + */ +#ifdef HAL_SMARTCARD_MODULE_ENABLED + +#if !defined(STM32F030x6) && !defined(STM32F030x8) + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +#define TEACK_REACK_TIMEOUT 1000 +#define HAL_SMARTCARD_TXDMA_TIMEOUTVALUE 22000 +#define USART_CR1_FIELDS ((uint32_t)(USART_CR1_M | USART_CR1_PCE | USART_CR1_PS | \ + USART_CR1_TE | USART_CR1_RE | USART_CR1_OVER8)) +#define USART_CR2_CLK_FIELDS ((uint32_t)(USART_CR2_CLKEN|USART_CR2_CPOL|USART_CR2_CPHA|USART_CR2_LBCL)) +#define USART_CR2_FIELDS ((uint32_t)(USART_CR2_RTOEN|USART_CR2_CLK_FIELDS|USART_CR2_STOP)) +#define USART_CR3_FIELDS ((uint32_t)(USART_CR3_ONEBIT|USART_CR3_NACK|USART_CR3_SCARCNT)) +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +static void SMARTCARD_DMATransmitCplt(DMA_HandleTypeDef *hdma); +static void SMARTCARD_DMAReceiveCplt(DMA_HandleTypeDef *hdma); +static void SMARTCARD_DMAError(DMA_HandleTypeDef *hdma); +static HAL_StatusTypeDef SMARTCARD_SetConfig(SMARTCARD_HandleTypeDef *hsmartcard); +static HAL_StatusTypeDef SMARTCARD_WaitOnFlagUntilTimeout(SMARTCARD_HandleTypeDef *hsmartcard, uint32_t Flag, FlagStatus Status, uint32_t Timeout); +static HAL_StatusTypeDef SMARTCARD_CheckIdleState(SMARTCARD_HandleTypeDef *hsmartcard); +static HAL_StatusTypeDef SMARTCARD_Transmit_IT(SMARTCARD_HandleTypeDef *hsmartcard); +static HAL_StatusTypeDef SMARTCARD_Receive_IT(SMARTCARD_HandleTypeDef *hsmartcard); +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup SMARTCARD_Private_Functions + * @{ + */ + +/** @defgroup HAL_SMARTCARD_Group1 Initialization/de-initialization functions + * @brief Initialization and Configuration functions + * +@verbatim +=============================================================================== + ##### Initialization and Configuration functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to initialize the USARTx + associated to the SmartCard. + (+) These parameters can be configured: + (++) Baud Rate + (++) Parity: parity should be enabled, + Frame Length is fixed to 8 bits plus parity: + the USART frame format is given in the following table: + +---------------------------------------------------------------+ + | M bit | PCE bit | USART frame | + |---------------------|-----------------------------------------| + | 1 | 1 | | SB | 8 bit data | PB | STB | | + +---------------------------------------------------------------+ + or + +---------------------------------------------------------------+ + | M1M0 bits | PCE bit | USART frame | + |-----------------------|---------------------------------------| + | 01 | 1 | | SB | 8 bit data | PB | STB | | + +---------------------------------------------------------------+ + + (++) Receiver/transmitter modes + (++) Synchronous mode (and if enabled, phase, polarity and last bit parameters) + (++) Prescaler value + (++) Guard bit time + (++) NACK enabling or disabling on transmission error + + (+) The following advanced features can be configured as well: + (++) TX and/or RX pin level inversion + (++) data logical level inversion + (++) RX and TX pins swap + (++) RX overrun detection disabling + (++) DMA disabling on RX error + (++) MSB first on communication line + (++) Time out enabling (and if activated, timeout value) + (++) Block length + (++) Auto-retry counter + + [..] + The HAL_SMARTCARD_Init() API follow respectively the USART (a)synchronous configuration procedures + (details for the procedures are available in reference manual). + +@endverbatim + * @{ + */ + +/** + * @brief Initializes the SMARTCARD mode according to the specified + * parameters in the SMARTCARD_InitTypeDef and creates the associated handle . + * @param hsmartcard: SMARTCARD handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMARTCARD_Init(SMARTCARD_HandleTypeDef *hsmartcard) +{ + /* Check the SMARTCARD handle allocation */ + if(hsmartcard == NULL) + { + return HAL_ERROR; + } + + /* Check the USART associated to the SmartCard */ + assert_param(IS_SMARTCARD_INSTANCE(hsmartcard->Instance)); + + if(hsmartcard->State == HAL_SMARTCARD_STATE_RESET) + { + /* Init the low level hardware : GPIO, CLOCK */ + HAL_SMARTCARD_MspInit(hsmartcard); + } + + hsmartcard->State = HAL_SMARTCARD_STATE_BUSY; + + /* Disable the Peripheral */ + __HAL_SMARTCARD_DISABLE(hsmartcard); + + /* Set the SMARTCARD Communication parameters */ + if (SMARTCARD_SetConfig(hsmartcard) == HAL_ERROR) + { + return HAL_ERROR; + } + + if (hsmartcard->AdvancedInit.AdvFeatureInit != SMARTCARD_ADVFEATURE_NO_INIT) + { + SMARTCARD_AdvFeatureConfig(hsmartcard); + } + + /* In SmartCard mode, the following bits must be kept cleared: + - LINEN in the USART_CR2 register, + - HDSEL and IREN bits in the USART_CR3 register.*/ + hsmartcard->Instance->CR2 &= ~(USART_CR2_LINEN); + hsmartcard->Instance->CR3 &= ~(USART_CR3_HDSEL | USART_CR3_IREN); + + /* set the USART in SMARTCARD mode */ + hsmartcard->Instance->CR3 |= USART_CR3_SCEN; + + /* Enable the Peripheral */ + __HAL_SMARTCARD_ENABLE(hsmartcard); + + /* TEACK and/or REACK to check before moving hsmartcard->State to Ready */ + return (SMARTCARD_CheckIdleState(hsmartcard)); +} + + +/** + * @brief DeInitializes the SMARTCARD peripheral + * @param hsmartcard: SMARTCARD handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMARTCARD_DeInit(SMARTCARD_HandleTypeDef *hsmartcard) +{ + /* Check the SMARTCARD handle allocation */ + if(hsmartcard == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_SMARTCARD_INSTANCE(hsmartcard->Instance)); + + hsmartcard->State = HAL_SMARTCARD_STATE_BUSY; + + /* Disable the Peripheral */ + __HAL_SMARTCARD_DISABLE(hsmartcard); + + hsmartcard->Instance->CR1 = 0x0; + hsmartcard->Instance->CR2 = 0x0; + hsmartcard->Instance->CR3 = 0x0; + hsmartcard->Instance->RTOR = 0x0; + hsmartcard->Instance->GTPR = 0x0; + + /* DeInit the low level hardware */ + HAL_SMARTCARD_MspDeInit(hsmartcard); + + hsmartcard->ErrorCode = HAL_SMARTCARD_ERROR_NONE; + hsmartcard->State = HAL_SMARTCARD_STATE_RESET; + + /* Process Unlock */ + __HAL_UNLOCK(hsmartcard); + + return HAL_OK; +} + +/** + * @brief SMARTCARD MSP Init + * @param hsmartcard: SMARTCARD handle + * @retval None + */ + __weak void HAL_SMARTCARD_MspInit(SMARTCARD_HandleTypeDef *hsmartcard) +{ + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_SMARTCARD_MspInit can be implemented in the user file + */ +} + +/** + * @brief SMARTCARD MSP DeInit + * @param hsmartcard: SMARTCARD handle + * @retval None + */ + __weak void HAL_SMARTCARD_MspDeInit(SMARTCARD_HandleTypeDef *hsmartcard) +{ + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_SMARTCARD_MspDeInit can be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup HAL_SMARTCARD_Group2 IO operation functions + * @brief SMARTCARD Transmit/Receive functions + * +@verbatim + =============================================================================== + ##### I/O operation functions ##### + =============================================================================== + This subsection provides a set of functions allowing to manage the SMARTCARD data transfers. + + (#) There are two mode of transfer: + (+) Blocking mode: The communication is performed in polling mode. + The HAL status of all data processing is returned by the same function + after finishing transfer. + (+) No-Blocking mode: The communication is performed using Interrupts + or DMA, These API's return the HAL status. + The end of the data processing will be indicated through the + dedicated SMARTCARD IRQ when using Interrupt mode or the DMA IRQ when + using DMA mode. + The HAL_SMARTCARD_TxCpltCallback(), HAL_SMARTCARD_RxCpltCallback() user callbacks + will be executed respectivelly at the end of the transmit or Receive process + The HAL_SMARTCARD_ErrorCallback()user callback will be executed when a communication error is detected + + (#) Blocking mode API's are : + (+) HAL_SMARTCARD_Transmit() + (+) HAL_SMARTCARD_Receive() + + (#) Non-Blocking mode API's with Interrupt are : + (+) HAL_SMARTCARD_Transmit_IT() + (+) HAL_SMARTCARD_Receive_IT() + (+) HAL_SMARTCARD_IRQHandler() + (+) SMARTCARD_Transmit_IT() + (+) SMARTCARD_Receive_IT() + + (#) No-Blocking mode functions with DMA are : + (+) HAL_SMARTCARD_Transmit_DMA() + (+) HAL_SMARTCARD_Receive_DMA() + + (#) A set of Transfer Complete Callbacks are provided in No_Blocking mode: + (+) HAL_SMARTCARD_TxCpltCallback() + (+) HAL_SMARTCARD_RxCpltCallback() + (+) HAL_SMARTCARD_ErrorCallback() + +@endverbatim + * @{ + */ + +/** + * @brief Send an amount of data in blocking mode + * @param hsmartcard: SMARTCARD handle + * @param pData: pointer to data buffer + * @param Size: amount of data to be sent + * @param Timeout : Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMARTCARD_Transmit(SMARTCARD_HandleTypeDef *hsmartcard, uint8_t *pData, uint16_t Size, uint32_t Timeout) +{ + if ((hsmartcard->State == HAL_SMARTCARD_STATE_READY) || (hsmartcard->State == HAL_SMARTCARD_STATE_BUSY_RX)) + { + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(hsmartcard); + hsmartcard->ErrorCode = HAL_SMARTCARD_ERROR_NONE; + /* Check if a non-blocking receive process is ongoing or not */ + if(hsmartcard->State == HAL_SMARTCARD_STATE_BUSY_RX) + { + hsmartcard->State = HAL_SMARTCARD_STATE_BUSY_TX_RX; + } + else + { + hsmartcard->State = HAL_SMARTCARD_STATE_BUSY_TX; + } + + hsmartcard->TxXferSize = Size; + hsmartcard->TxXferCount = Size; + while(hsmartcard->TxXferCount > 0) + { + hsmartcard->TxXferCount--; + if(SMARTCARD_WaitOnFlagUntilTimeout(hsmartcard, SMARTCARD_FLAG_TXE, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + hsmartcard->Instance->TDR = (*pData++ & (uint8_t)0xFF); + } + if(SMARTCARD_WaitOnFlagUntilTimeout(hsmartcard, SMARTCARD_FLAG_TC, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + /* Check if a non-blocking receive Process is ongoing or not */ + if(hsmartcard->State == HAL_SMARTCARD_STATE_BUSY_TX_RX) + { + hsmartcard->State = HAL_SMARTCARD_STATE_BUSY_RX; + } + else + { + hsmartcard->State = HAL_SMARTCARD_STATE_READY; + } + + /* Process Unlocked */ + __HAL_UNLOCK(hsmartcard); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive an amount of data in blocking mode + * @param hsmartcard: SMARTCARD handle + * @param pData: pointer to data buffer + * @param Size: amount of data to be received + * @param Timeout : Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMARTCARD_Receive(SMARTCARD_HandleTypeDef *hsmartcard, uint8_t *pData, uint16_t Size, uint32_t Timeout) +{ + if ((hsmartcard->State == HAL_SMARTCARD_STATE_READY) || (hsmartcard->State == HAL_SMARTCARD_STATE_BUSY_TX)) + { + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(hsmartcard); + + hsmartcard->ErrorCode = HAL_SMARTCARD_ERROR_NONE; + /* Check if a non-blocking transmit process is ongoing or not */ + if(hsmartcard->State == HAL_SMARTCARD_STATE_BUSY_TX) + { + hsmartcard->State = HAL_SMARTCARD_STATE_BUSY_TX_RX; + } + else + { + hsmartcard->State = HAL_SMARTCARD_STATE_BUSY_RX; + } + + hsmartcard->RxXferSize = Size; + hsmartcard->RxXferCount = Size; + /* Check the remain data to be received */ + while(hsmartcard->RxXferCount > 0) + { + hsmartcard->RxXferCount--; + if(SMARTCARD_WaitOnFlagUntilTimeout(hsmartcard, SMARTCARD_FLAG_RXNE, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + *pData++ = (uint8_t)(hsmartcard->Instance->RDR & (uint8_t)0x00FF); + } + + /* Check if a non-blocking transmit Process is ongoing or not */ + if(hsmartcard->State == HAL_SMARTCARD_STATE_BUSY_TX_RX) + { + hsmartcard->State = HAL_SMARTCARD_STATE_BUSY_TX; + } + else + { + hsmartcard->State = HAL_SMARTCARD_STATE_READY; + } + + /* Process Unlocked */ + __HAL_UNLOCK(hsmartcard); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Send an amount of data in interrupt mode + * @param hsmartcard: SMARTCARD handle + * @param pData: pointer to data buffer + * @param Size: amount of data to be sent + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMARTCARD_Transmit_IT(SMARTCARD_HandleTypeDef *hsmartcard, uint8_t *pData, uint16_t Size) +{ + if ((hsmartcard->State == HAL_SMARTCARD_STATE_READY) || (hsmartcard->State == HAL_SMARTCARD_STATE_BUSY_RX)) + { + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(hsmartcard); + + hsmartcard->pTxBuffPtr = pData; + hsmartcard->TxXferSize = Size; + hsmartcard->TxXferCount = Size; + + hsmartcard->ErrorCode = HAL_SMARTCARD_ERROR_NONE; + /* Check if a receive process is ongoing or not */ + if(hsmartcard->State == HAL_SMARTCARD_STATE_BUSY_RX) + { + hsmartcard->State = HAL_SMARTCARD_STATE_BUSY_TX_RX; + } + else + { + hsmartcard->State = HAL_SMARTCARD_STATE_BUSY_TX; + } + + /* Enable the SMARTCARD Error Interrupt: (Frame error, noise error, overrun error) */ + __HAL_SMARTCARD_ENABLE_IT(hsmartcard, SMARTCARD_IT_ERR); + + /* Process Unlocked */ + __HAL_UNLOCK(hsmartcard); + + /* Enable the SMARTCARD Transmit Complete Interrupt */ + __HAL_SMARTCARD_ENABLE_IT(hsmartcard, SMARTCARD_IT_TC); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive an amount of data in interrupt mode + * @param hsmartcard: SMARTCARD handle + * @param pData: pointer to data buffer + * @param Size: amount of data to be received + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMARTCARD_Receive_IT(SMARTCARD_HandleTypeDef *hsmartcard, uint8_t *pData, uint16_t Size) +{ + if ((hsmartcard->State == HAL_SMARTCARD_STATE_READY) || (hsmartcard->State == HAL_SMARTCARD_STATE_BUSY_TX)) + { + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(hsmartcard); + + hsmartcard->pRxBuffPtr = pData; + hsmartcard->RxXferSize = Size; + hsmartcard->RxXferCount = Size; + + hsmartcard->ErrorCode = HAL_SMARTCARD_ERROR_NONE; + /* Check if a transmit process is ongoing or not */ + if(hsmartcard->State == HAL_SMARTCARD_STATE_BUSY_TX) + { + hsmartcard->State = HAL_SMARTCARD_STATE_BUSY_TX_RX; + } + else + { + hsmartcard->State = HAL_SMARTCARD_STATE_BUSY_RX; + } + + /* Enable the SMARTCARD Parity Error Interrupt */ + __HAL_SMARTCARD_ENABLE_IT(hsmartcard, SMARTCARD_IT_PE); + + /* Enable the SMARTCARD Error Interrupt: (Frame error, noise error, overrun error) */ + __HAL_SMARTCARD_ENABLE_IT(hsmartcard, SMARTCARD_IT_ERR); + + /* Process Unlocked */ + __HAL_UNLOCK(hsmartcard); + + /* Enable the SMARTCARD Data Register not empty Interrupt */ + __HAL_SMARTCARD_ENABLE_IT(hsmartcard, SMARTCARD_IT_RXNE); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Send an amount of data in DMA mode + * @param hsmartcard: SMARTCARD handle + * @param pData: pointer to data buffer + * @param Size: amount of data to be sent + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMARTCARD_Transmit_DMA(SMARTCARD_HandleTypeDef *hsmartcard, uint8_t *pData, uint16_t Size) +{ + uint32_t *tmp; + + if ((hsmartcard->State == HAL_SMARTCARD_STATE_READY) || (hsmartcard->State == HAL_SMARTCARD_STATE_BUSY_RX)) + { + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(hsmartcard); + + hsmartcard->pTxBuffPtr = pData; + hsmartcard->TxXferSize = Size; + hsmartcard->TxXferCount = Size; + + hsmartcard->ErrorCode = HAL_SMARTCARD_ERROR_NONE; + /* Check if a receive process is ongoing or not */ + if(hsmartcard->State == HAL_SMARTCARD_STATE_BUSY_RX) + { + hsmartcard->State = HAL_SMARTCARD_STATE_BUSY_TX_RX; + } + else + { + hsmartcard->State = HAL_SMARTCARD_STATE_BUSY_TX; + } + + /* Set the SMARTCARD DMA transfer complete callback */ + hsmartcard->hdmatx->XferCpltCallback = SMARTCARD_DMATransmitCplt; + + /* Set the SMARTCARD error callback */ + hsmartcard->hdmatx->XferErrorCallback = SMARTCARD_DMAError; + + /* Enable the SMARTCARD transmit DMA channel */ + tmp = (uint32_t*)&pData; + HAL_DMA_Start_IT(hsmartcard->hdmatx, *(uint32_t*)tmp, (uint32_t)&hsmartcard->Instance->TDR, Size); + + /* Enable the DMA transfer for transmit request by setting the DMAT bit + in the SMARTCARD associated USART CR3 register */ + hsmartcard->Instance->CR3 |= USART_CR3_DMAT; + + /* Process Unlocked */ + __HAL_UNLOCK(hsmartcard); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive an amount of data in DMA mode + * @param hsmartcard: SMARTCARD handle + * @param pData: pointer to data buffer + * @param Size: amount of data to be received + * @note The SMARTCARD-associated USART parity is enabled (PCE = 1), + * the received data contain the parity bit (MSB position) + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMARTCARD_Receive_DMA(SMARTCARD_HandleTypeDef *hsmartcard, uint8_t *pData, uint16_t Size) +{ + uint32_t *tmp; + + if ((hsmartcard->State == HAL_SMARTCARD_STATE_READY) || (hsmartcard->State == HAL_SMARTCARD_STATE_BUSY_TX)) + { + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(hsmartcard); + + hsmartcard->pRxBuffPtr = pData; + hsmartcard->RxXferSize = Size; + + hsmartcard->ErrorCode = HAL_SMARTCARD_ERROR_NONE; + /* Check if a transmit rocess is ongoing or not */ + if(hsmartcard->State == HAL_SMARTCARD_STATE_BUSY_TX) + { + hsmartcard->State = HAL_SMARTCARD_STATE_BUSY_TX_RX; + } + else + { + hsmartcard->State = HAL_SMARTCARD_STATE_BUSY_RX; + } + + /* Set the SMARTCARD DMA transfer complete callback */ + hsmartcard->hdmarx->XferCpltCallback = SMARTCARD_DMAReceiveCplt; + + /* Set the SMARTCARD DMA error callback */ + hsmartcard->hdmarx->XferErrorCallback = SMARTCARD_DMAError; + + /* Enable the DMA channel */ + tmp = (uint32_t*)&pData; + HAL_DMA_Start_IT(hsmartcard->hdmarx, (uint32_t)&hsmartcard->Instance->RDR, *(uint32_t*)tmp, Size); + + /* Enable the DMA transfer for the receiver request by setting the DMAR bit + in the SMARTCARD associated USART CR3 register */ + hsmartcard->Instance->CR3 |= USART_CR3_DMAR; + + /* Process Unlocked */ + __HAL_UNLOCK(hsmartcard); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief SMARTCARD interrupt requests handling. + * @param hsmartcard: SMARTCARD handle + * @retval None + */ +void HAL_SMARTCARD_IRQHandler(SMARTCARD_HandleTypeDef *hsmartcard) +{ + /* SMARTCARD parity error interrupt occurred -------------------------------------*/ + if((__HAL_SMARTCARD_GET_IT(hsmartcard, SMARTCARD_IT_PE) != RESET) && (__HAL_SMARTCARD_GET_IT_SOURCE(hsmartcard, SMARTCARD_IT_PE) != RESET)) + { + __HAL_SMARTCARD_CLEAR_IT(hsmartcard, SMARTCARD_CLEAR_PEF); + hsmartcard->ErrorCode |= HAL_SMARTCARD_ERROR_PE; + /* Set the SMARTCARD state ready to be able to start again the process */ + hsmartcard->State = HAL_SMARTCARD_STATE_READY; + } + + /* SMARTCARD frame error interrupt occured --------------------------------------*/ + if((__HAL_SMARTCARD_GET_IT(hsmartcard, SMARTCARD_IT_FE) != RESET) && (__HAL_SMARTCARD_GET_IT_SOURCE(hsmartcard, SMARTCARD_IT_ERR) != RESET)) + { + __HAL_SMARTCARD_CLEAR_IT(hsmartcard, SMARTCARD_CLEAR_FEF); + hsmartcard->ErrorCode |= HAL_SMARTCARD_ERROR_FE; + /* Set the SMARTCARD state ready to be able to start again the process */ + hsmartcard->State = HAL_SMARTCARD_STATE_READY; + } + + /* SMARTCARD noise error interrupt occured --------------------------------------*/ + if((__HAL_SMARTCARD_GET_IT(hsmartcard, SMARTCARD_IT_NE) != RESET) && (__HAL_SMARTCARD_GET_IT_SOURCE(hsmartcard, SMARTCARD_IT_ERR) != RESET)) + { + __HAL_SMARTCARD_CLEAR_IT(hsmartcard, SMARTCARD_CLEAR_NEF); + hsmartcard->ErrorCode |= HAL_SMARTCARD_ERROR_NE; + /* Set the SMARTCARD state ready to be able to start again the process */ + hsmartcard->State = HAL_SMARTCARD_STATE_READY; + } + + /* SMARTCARD Over-Run interrupt occured -----------------------------------------*/ + if((__HAL_SMARTCARD_GET_IT(hsmartcard, SMARTCARD_IT_ORE) != RESET) && (__HAL_SMARTCARD_GET_IT_SOURCE(hsmartcard, SMARTCARD_IT_ERR) != RESET)) + { + __HAL_SMARTCARD_CLEAR_IT(hsmartcard, SMARTCARD_CLEAR_OREF); + hsmartcard->ErrorCode |= HAL_SMARTCARD_ERROR_ORE; + /* Set the SMARTCARD state ready to be able to start again the process */ + hsmartcard->State = HAL_SMARTCARD_STATE_READY; + } + + /* SMARTCARD receiver timeout interrupt occured -----------------------------------------*/ + if((__HAL_SMARTCARD_GET_IT(hsmartcard, SMARTCARD_IT_RTO) != RESET) && (__HAL_SMARTCARD_GET_IT_SOURCE(hsmartcard, SMARTCARD_IT_RTO) != RESET)) + { + __HAL_SMARTCARD_CLEAR_IT(hsmartcard, SMARTCARD_CLEAR_RTOF); + hsmartcard->ErrorCode |= HAL_SMARTCARD_ERROR_RTO; + /* Set the SMARTCARD state ready to be able to start again the process */ + hsmartcard->State = HAL_SMARTCARD_STATE_READY; + } + + /* Call SMARTCARD Error Call back function if need be --------------------------*/ + if(hsmartcard->ErrorCode != HAL_SMARTCARD_ERROR_NONE) + { + HAL_SMARTCARD_ErrorCallback(hsmartcard); + } + + /* SMARTCARD in mode Receiver ---------------------------------------------------*/ + if((__HAL_SMARTCARD_GET_IT(hsmartcard, SMARTCARD_IT_RXNE) != RESET) && (__HAL_SMARTCARD_GET_IT_SOURCE(hsmartcard, SMARTCARD_IT_RXNE) != RESET)) + { + SMARTCARD_Receive_IT(hsmartcard); + /* Clear RXNE interrupt flag */ + __HAL_SMARTCARD_SEND_REQ(hsmartcard, SMARTCARD_RXDATA_FLUSH_REQUEST); + } + + /* SMARTCARD in mode Receiver, end of block interruption ------------------------*/ + if((__HAL_SMARTCARD_GET_IT(hsmartcard, SMARTCARD_IT_EOB) != RESET) && (__HAL_SMARTCARD_GET_IT_SOURCE(hsmartcard, SMARTCARD_IT_EOB) != RESET)) + { + hsmartcard->State = HAL_SMARTCARD_STATE_READY; + __HAL_UNLOCK(hsmartcard); + HAL_SMARTCARD_RxCpltCallback(hsmartcard); + /* Clear EOBF interrupt after HAL_SMARTCARD_RxCpltCallback() call for the End of Block information + * to be available during HAL_SMARTCARD_RxCpltCallback() processing */ + __HAL_SMARTCARD_CLEAR_IT(hsmartcard, SMARTCARD_CLEAR_EOBF); + } + + /* SMARTCARD in mode Transmitter ------------------------------------------------*/ + if((__HAL_SMARTCARD_GET_IT(hsmartcard, SMARTCARD_IT_TC) != RESET) &&(__HAL_SMARTCARD_GET_IT_SOURCE(hsmartcard, SMARTCARD_IT_TC) != RESET)) + { + SMARTCARD_Transmit_IT(hsmartcard); + } +} + +/** + * @brief This function handles SMARTCARD Communication Timeout. + * @param hsmartcard: SMARTCARD handle + * @param Flag: specifies the SMARTCARD flag to check. + * @param Status: The new Flag status (SET or RESET). + * @param Timeout: Timeout duration + * @retval HAL status + */ +static HAL_StatusTypeDef SMARTCARD_WaitOnFlagUntilTimeout(SMARTCARD_HandleTypeDef *hsmartcard, uint32_t Flag, FlagStatus Status, uint32_t Timeout) +{ + uint32_t tickstart = HAL_GetTick(); + + /* Wait until flag is set */ + if(Status == RESET) + { + while(__HAL_SMARTCARD_GET_FLAG(hsmartcard, Flag) == RESET) + { + /* Check for the Timeout */ + if(Timeout != HAL_MAX_DELAY) + { + if((HAL_GetTick() - tickstart) >= Timeout) + { + /* Disable TXE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts for the interrupt process */ + __HAL_SMARTCARD_DISABLE_IT(hsmartcard, SMARTCARD_IT_TXE); + __HAL_SMARTCARD_DISABLE_IT(hsmartcard, SMARTCARD_IT_RXNE); + __HAL_SMARTCARD_DISABLE_IT(hsmartcard, SMARTCARD_IT_PE); + __HAL_SMARTCARD_DISABLE_IT(hsmartcard, SMARTCARD_IT_ERR); + + hsmartcard->State= HAL_SMARTCARD_STATE_TIMEOUT; + + /* Process Unlocked */ + __HAL_UNLOCK(hsmartcard); + + return HAL_TIMEOUT; + } + } + } + } + else + { + while(__HAL_SMARTCARD_GET_FLAG(hsmartcard, Flag) != RESET) + { + /* Check for the Timeout */ + if(Timeout != HAL_MAX_DELAY) + { + if((HAL_GetTick() - tickstart) >= Timeout) + { + /* Disable TXE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts for the interrupt process */ + __HAL_SMARTCARD_DISABLE_IT(hsmartcard, SMARTCARD_IT_TXE); + __HAL_SMARTCARD_DISABLE_IT(hsmartcard, SMARTCARD_IT_RXNE); + __HAL_SMARTCARD_DISABLE_IT(hsmartcard, SMARTCARD_IT_PE); + __HAL_SMARTCARD_DISABLE_IT(hsmartcard, SMARTCARD_IT_ERR); + + hsmartcard->State= HAL_SMARTCARD_STATE_TIMEOUT; + + /* Process Unlocked */ + __HAL_UNLOCK(hsmartcard); + + return HAL_TIMEOUT; + } + } + } + } + return HAL_OK; +} + + +/** + * @brief DMA SMARTCARD transmit process complete callback + * @param hdma: DMA handle + * @retval None + */ +static void SMARTCARD_DMATransmitCplt(DMA_HandleTypeDef *hdma) +{ + SMARTCARD_HandleTypeDef* hsmartcard = ( SMARTCARD_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + hsmartcard->TxXferCount = 0; + + /* Disable the DMA transfer for transmit request by setting the DMAT bit + in the SMARTCARD associated USART CR3 register */ + hsmartcard->Instance->CR3 &= (uint16_t)~((uint16_t)USART_CR3_DMAT); + + /* Wait for SMARTCARD TC Flag */ + if(SMARTCARD_WaitOnFlagUntilTimeout(hsmartcard, SMARTCARD_FLAG_TC, RESET, HAL_SMARTCARD_TXDMA_TIMEOUTVALUE) != HAL_OK) + { + /* Timeout Occured */ + HAL_SMARTCARD_ErrorCallback(hsmartcard); + } + else + { + /* No Timeout */ + /* Check if a receive Process is ongoing or not */ + if(hsmartcard->State == HAL_SMARTCARD_STATE_BUSY_TX_RX) + { + hsmartcard->State = HAL_SMARTCARD_STATE_BUSY_RX; + } + else + { + hsmartcard->State = HAL_SMARTCARD_STATE_READY; + } + HAL_SMARTCARD_TxCpltCallback(hsmartcard); + } +} + +/** + * @brief DMA SMARTCARD receive process complete callback + * @param hdma: DMA handle + * @retval None + */ +static void SMARTCARD_DMAReceiveCplt(DMA_HandleTypeDef *hdma) +{ + SMARTCARD_HandleTypeDef* hsmartcard = ( SMARTCARD_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + hsmartcard->RxXferCount = 0; + + /* Disable the DMA transfer for the receiver request by setting the DMAR bit + in the SMARTCARD associated USART CR3 register */ + hsmartcard->Instance->CR3 &= (uint16_t)~((uint16_t)USART_CR3_DMAR); + + /* Check if a transmit Process is ongoing or not */ + if(hsmartcard->State == HAL_SMARTCARD_STATE_BUSY_TX_RX) + { + hsmartcard->State = HAL_SMARTCARD_STATE_BUSY_TX; + } + else + { + hsmartcard->State = HAL_SMARTCARD_STATE_READY; + } + + HAL_SMARTCARD_RxCpltCallback(hsmartcard); +} + +/** + * @brief DMA SMARTCARD communication error callback + * @param hdma: DMA handle + * @retval None + */ +static void SMARTCARD_DMAError(DMA_HandleTypeDef *hdma) +{ + SMARTCARD_HandleTypeDef* hsmartcard = ( SMARTCARD_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + hsmartcard->RxXferCount = 0; + hsmartcard->TxXferCount = 0; + hsmartcard->State= HAL_SMARTCARD_STATE_READY; + hsmartcard->ErrorCode |= HAL_SMARTCARD_ERROR_DMA; + HAL_SMARTCARD_ErrorCallback(hsmartcard); +} + +/** + * @brief Tx Transfer completed callbacks + * @param hsmartcard: SMARTCARD handle + * @retval None + */ + __weak void HAL_SMARTCARD_TxCpltCallback(SMARTCARD_HandleTypeDef *hsmartcard) +{ + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_SMARTCARD_TxCpltCallback can be implemented in the user file + */ +} + +/** + * @brief Rx Transfer completed callbacks + * @param hsmartcard: SMARTCARD handle + * @retval None + */ +__weak void HAL_SMARTCARD_RxCpltCallback(SMARTCARD_HandleTypeDef *hsmartcard) +{ + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_SMARTCARD_TxCpltCallback can be implemented in the user file + */ +} + +/** + * @brief SMARTCARD error callbacks + * @param hsmartcard: SMARTCARD handle + * @retval None + */ + __weak void HAL_SMARTCARD_ErrorCallback(SMARTCARD_HandleTypeDef *hsmartcard) +{ + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_SMARTCARD_ErrorCallback can be implemented in the user file + */ +} + + + +/** + * @brief Send an amount of data in non blocking mode + * @param hsmartcard: SMARTCARD handle. + * Function called under interruption only, once + * interruptions have been enabled by HAL_SMARTCARD_Transmit_IT() + * @retval HAL status + */ +static HAL_StatusTypeDef SMARTCARD_Transmit_IT(SMARTCARD_HandleTypeDef *hsmartcard) +{ + if ((hsmartcard->State == HAL_SMARTCARD_STATE_BUSY_TX) || (hsmartcard->State == HAL_SMARTCARD_STATE_BUSY_TX_RX)) + { + __HAL_LOCK(hsmartcard); + + if(hsmartcard->TxXferCount == 0) + { + /* Disable the SMARTCARD Transmit Complete Interrupt */ + __HAL_SMARTCARD_DISABLE_IT(hsmartcard, SMARTCARD_IT_TC); + + /* Check if a receive Process is ongoing or not */ + if(hsmartcard->State == HAL_SMARTCARD_STATE_BUSY_TX_RX) + { + hsmartcard->State = HAL_SMARTCARD_STATE_BUSY_RX; + } + else + { + /* Disable the SMARTCARD Error Interrupt: (Frame error, noise error, overrun error) */ + __HAL_SMARTCARD_DISABLE_IT(hsmartcard, SMARTCARD_IT_ERR); + + hsmartcard->State = HAL_SMARTCARD_STATE_READY; + } + + /* Call the Process Unlocked before calling the Tx call back API to give the possibiity to + start again the Transmission under the Tx call back API */ + __HAL_UNLOCK(hsmartcard); + + HAL_SMARTCARD_TxCpltCallback(hsmartcard); + + return HAL_OK; + } + else + { + hsmartcard->Instance->TDR = (*hsmartcard->pTxBuffPtr++ & (uint8_t)0xFF); + hsmartcard->TxXferCount--; + + /* Process Unlocked */ + __HAL_UNLOCK(hsmartcard); + + return HAL_OK; + } + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive an amount of data in non blocking mode + * @param hsmartcard: SMARTCARD handle. + * Function called under interruption only, once + * interruptions have been enabled by HAL_SMARTCARD_Receive_IT() + * @retval HAL status + */ +static HAL_StatusTypeDef SMARTCARD_Receive_IT(SMARTCARD_HandleTypeDef *hsmartcard) +{ + if ((hsmartcard->State == HAL_SMARTCARD_STATE_BUSY_RX) || (hsmartcard->State == HAL_SMARTCARD_STATE_BUSY_TX_RX)) + { + /* Process Locked */ + __HAL_LOCK(hsmartcard); + + *hsmartcard->pRxBuffPtr++ = (uint8_t)(hsmartcard->Instance->RDR & (uint8_t)0xFF); + + if(--hsmartcard->RxXferCount == 0) + { + __HAL_SMARTCARD_DISABLE_IT(hsmartcard, SMARTCARD_IT_RXNE); + + /* Check if a transmit Process is ongoing or not */ + if(hsmartcard->State == HAL_SMARTCARD_STATE_BUSY_TX_RX) + { + hsmartcard->State = HAL_SMARTCARD_STATE_BUSY_TX; + } + else + { + /* Disable the SMARTCARD Parity Error Interrupt */ + __HAL_SMARTCARD_DISABLE_IT(hsmartcard, SMARTCARD_IT_PE); + + /* Disable the SMARTCARD Error Interrupt: (Frame error, noise error, overrun error) */ + __HAL_SMARTCARD_DISABLE_IT(hsmartcard, SMARTCARD_IT_ERR); + + hsmartcard->State = HAL_SMARTCARD_STATE_READY; + } + + /* Call the Process Unlocked before calling the Rx call back API to give the possibiity to + start again the receiption under the Rx call back API */ + __HAL_UNLOCK(hsmartcard); + + HAL_SMARTCARD_RxCpltCallback(hsmartcard); + + return HAL_OK; + } + /* Process Unlocked */ + __HAL_UNLOCK(hsmartcard); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @} + */ + +/** @defgroup HAL_SMARTCARD_Group3 Peripheral Control functions + * @brief SMARTCARD control functions + * +@verbatim + =============================================================================== + ##### Peripheral Control functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to initialize the SMARTCARD. + (+) HAL_SMARTCARD_GetState() API is helpful to check in run-time the state of the SMARTCARD peripheral + (+) SMARTCARD_SetConfig() API configures the SMARTCARD peripheral + (+) SMARTCARD_AdvFeatureConfig() API optionally configures the SMARTCARD advanced features + (+) SMARTCARD_CheckIdleState() API ensures that TEACK and/or REACK are set after initialization + + +@endverbatim + * @{ + */ + + +/** + * @brief return the SMARTCARD state + * @param hsmartcard: SMARTCARD handle + * @retval HAL state + */ +HAL_SMARTCARD_StateTypeDef HAL_SMARTCARD_GetState(SMARTCARD_HandleTypeDef *hsmartcard) +{ + return hsmartcard->State; +} + +/** +* @brief Return the SMARTCARD error code +* @param hsmartcard : pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for the specified SMARTCARD. +* @retval SMARTCARD Error Code +*/ +uint32_t HAL_SMARTCARD_GetError(SMARTCARD_HandleTypeDef *hsmartcard) +{ + return hsmartcard->ErrorCode; +} + +/** + * @brief Configure the SMARTCARD associated USART peripheral + * @param hsmartcard: SMARTCARD handle + * @retval None + */ +static HAL_StatusTypeDef SMARTCARD_SetConfig(SMARTCARD_HandleTypeDef *hsmartcard) +{ + uint32_t tmpreg = 0x00000000; + SMARTCARD_ClockSourceTypeDef clocksource = SMARTCARD_CLOCKSOURCE_UNDEFINED; + HAL_StatusTypeDef ret = HAL_OK; + + /* Check the parameters */ + assert_param(IS_SMARTCARD_INSTANCE(hsmartcard->Instance)); + assert_param(IS_SMARTCARD_BAUDRATE(hsmartcard->Init.BaudRate)); + assert_param(IS_SMARTCARD_WORD_LENGTH(hsmartcard->Init.WordLength)); + assert_param(IS_SMARTCARD_STOPBITS(hsmartcard->Init.StopBits)); + assert_param(IS_SMARTCARD_PARITY(hsmartcard->Init.Parity)); + assert_param(IS_SMARTCARD_MODE(hsmartcard->Init.Mode)); + assert_param(IS_SMARTCARD_POLARITY(hsmartcard->Init.CLKPolarity)); + assert_param(IS_SMARTCARD_PHASE(hsmartcard->Init.CLKPhase)); + assert_param(IS_SMARTCARD_LASTBIT(hsmartcard->Init.CLKLastBit)); + assert_param(IS_SMARTCARD_ONEBIT_SAMPLING(hsmartcard->Init.OneBitSampling)); + assert_param(IS_SMARTCARD_NACK(hsmartcard->Init.NACKEnable)); + assert_param(IS_SMARTCARD_TIMEOUT(hsmartcard->Init.TimeOutEnable)); + assert_param(IS_SMARTCARD_AUTORETRY_COUNT(hsmartcard->Init.AutoRetryCount)); + + /*-------------------------- USART CR1 Configuration -----------------------*/ + /* In SmartCard mode, M and PCE are forced to 1 (8 bits + parity). + * Oversampling is forced to 16 (OVER8 = 0). + * Configure the Parity and Mode: + * set PS bit according to hsmartcard->Init.Parity value + * set TE and RE bits according to hsmartcard->Init.Mode value */ + tmpreg = (uint32_t) hsmartcard->Init.Parity | hsmartcard->Init.Mode; + /* in case of TX-only mode, if NACK is enabled, the USART must be able to monitor + the bidirectional line to detect a NACK signal in case of parity error. + Therefore, the receiver block must be enabled as well (RE bit must be set). */ + if ((hsmartcard->Init.Mode == SMARTCARD_MODE_TX) + && (hsmartcard->Init.NACKEnable == SMARTCARD_NACK_ENABLED)) + { + tmpreg |= USART_CR1_RE; + } + tmpreg |= (uint32_t) hsmartcard->Init.WordLength; + MODIFY_REG(hsmartcard->Instance->CR1, USART_CR1_FIELDS, tmpreg); + + /*-------------------------- USART CR2 Configuration -----------------------*/ + /* Stop bits are forced to 1.5 (STOP = 11) */ + tmpreg = hsmartcard->Init.StopBits; + /* Synchronous mode is activated by default */ + tmpreg |= (uint32_t) USART_CR2_CLKEN | hsmartcard->Init.CLKPolarity; + tmpreg |= (uint32_t) hsmartcard->Init.CLKPhase | hsmartcard->Init.CLKLastBit; + tmpreg |= (uint32_t) hsmartcard->Init.TimeOutEnable; + MODIFY_REG(hsmartcard->Instance->CR2, USART_CR2_FIELDS, tmpreg); + + /*-------------------------- USART CR3 Configuration -----------------------*/ + /* Configure + * - one-bit sampling method versus three samples' majority rule + * according to hsmartcard->Init.OneBitSampling + * - NACK transmission in case of parity error according + * to hsmartcard->Init.NACKEnable + * - autoretry counter according to hsmartcard->Init.AutoRetryCount */ + tmpreg = (uint32_t) hsmartcard->Init.OneBitSampling | hsmartcard->Init.NACKEnable; + tmpreg |= ((uint32_t)hsmartcard->Init.AutoRetryCount << SMARTCARD_CR3_SCARCNT_LSB_POS); + MODIFY_REG(hsmartcard->Instance-> CR3,USART_CR3_FIELDS, tmpreg); + + /*-------------------------- USART GTPR Configuration ----------------------*/ + tmpreg = ((uint32_t)hsmartcard->Init.Prescaler | ((uint32_t)hsmartcard->Init.GuardTime << SMARTCARD_GTPR_GT_LSB_POS)); + MODIFY_REG(hsmartcard->Instance->GTPR, (USART_GTPR_GT|USART_GTPR_PSC), tmpreg); + + /*-------------------------- USART RTOR Configuration ----------------------*/ + tmpreg = ((uint32_t)hsmartcard->Init.BlockLength << SMARTCARD_RTOR_BLEN_LSB_POS); + if (hsmartcard->Init.TimeOutEnable == SMARTCARD_TIMEOUT_ENABLED) + { + assert_param(IS_SMARTCARD_TIMEOUT_VALUE(hsmartcard->Init.TimeOutValue)); + tmpreg |= (uint32_t) hsmartcard->Init.TimeOutValue; + } + MODIFY_REG(hsmartcard->Instance->RTOR, (USART_RTOR_RTO|USART_RTOR_BLEN), tmpreg); + + /*-------------------------- USART BRR Configuration -----------------------*/ + __HAL_SMARTCARD_GETCLOCKSOURCE(hsmartcard, clocksource); + switch (clocksource) + { + case SMARTCARD_CLOCKSOURCE_PCLK1: + hsmartcard->Instance->BRR = (uint16_t)(HAL_RCC_GetPCLK1Freq() / hsmartcard->Init.BaudRate); + break; + case SMARTCARD_CLOCKSOURCE_HSI: + hsmartcard->Instance->BRR = (uint16_t)(HSI_VALUE / hsmartcard->Init.BaudRate); + break; + case SMARTCARD_CLOCKSOURCE_SYSCLK: + hsmartcard->Instance->BRR = (uint16_t)(HAL_RCC_GetSysClockFreq() / hsmartcard->Init.BaudRate); + break; + case SMARTCARD_CLOCKSOURCE_LSE: + hsmartcard->Instance->BRR = (uint16_t)(LSE_VALUE / hsmartcard->Init.BaudRate); + break; + case SMARTCARD_CLOCKSOURCE_UNDEFINED: + default: + ret = HAL_ERROR; + break; + } + + return ret; +} + + +/** + * @brief Configure the SMARTCARD associated USART peripheral advanced feautures + * @param hsmartcard: SMARTCARD handle + * @retval None + */ +void SMARTCARD_AdvFeatureConfig(SMARTCARD_HandleTypeDef *hsmartcard) +{ + /* Check whether the set of advanced features to configure is properly set */ + assert_param(IS_SMARTCARD_ADVFEATURE_INIT(hsmartcard->AdvancedInit.AdvFeatureInit)); + + /* if required, configure TX pin active level inversion */ + if (HAL_IS_BIT_SET(hsmartcard->AdvancedInit.AdvFeatureInit, SMARTCARD_ADVFEATURE_TXINVERT_INIT)) + { + assert_param(IS_SMARTCARD_ADVFEATURE_TXINV(hsmartcard->AdvancedInit.TxPinLevelInvert)); + MODIFY_REG(hsmartcard->Instance->CR2, USART_CR2_TXINV, hsmartcard->AdvancedInit.TxPinLevelInvert); + } + + /* if required, configure RX pin active level inversion */ + if (HAL_IS_BIT_SET(hsmartcard->AdvancedInit.AdvFeatureInit, SMARTCARD_ADVFEATURE_RXINVERT_INIT)) + { + assert_param(IS_SMARTCARD_ADVFEATURE_RXINV(hsmartcard->AdvancedInit.RxPinLevelInvert)); + MODIFY_REG(hsmartcard->Instance->CR2, USART_CR2_RXINV, hsmartcard->AdvancedInit.RxPinLevelInvert); + } + + /* if required, configure data inversion */ + if (HAL_IS_BIT_SET(hsmartcard->AdvancedInit.AdvFeatureInit, SMARTCARD_ADVFEATURE_DATAINVERT_INIT)) + { + assert_param(IS_SMARTCARD_ADVFEATURE_DATAINV(hsmartcard->AdvancedInit.DataInvert)); + MODIFY_REG(hsmartcard->Instance->CR2, USART_CR2_DATAINV, hsmartcard->AdvancedInit.DataInvert); + } + + /* if required, configure RX/TX pins swap */ + if (HAL_IS_BIT_SET(hsmartcard->AdvancedInit.AdvFeatureInit, SMARTCARD_ADVFEATURE_SWAP_INIT)) + { + assert_param(IS_SMARTCARD_ADVFEATURE_SWAP(hsmartcard->AdvancedInit.Swap)); + MODIFY_REG(hsmartcard->Instance->CR2, USART_CR2_SWAP, hsmartcard->AdvancedInit.Swap); + } + + /* if required, configure RX overrun detection disabling */ + if (HAL_IS_BIT_SET(hsmartcard->AdvancedInit.AdvFeatureInit, SMARTCARD_ADVFEATURE_RXOVERRUNDISABLE_INIT)) + { + assert_param(IS_SMARTCARD_OVERRUN(hsmartcard->AdvancedInit.OverrunDisable)); + MODIFY_REG(hsmartcard->Instance->CR3, USART_CR3_OVRDIS, hsmartcard->AdvancedInit.OverrunDisable); + } + + /* if required, configure DMA disabling on reception error */ + if (HAL_IS_BIT_SET(hsmartcard->AdvancedInit.AdvFeatureInit, SMARTCARD_ADVFEATURE_DMADISABLEONERROR_INIT)) + { + assert_param(IS_SMARTCARD_ADVFEATURE_DMAONRXERROR(hsmartcard->AdvancedInit.DMADisableonRxError)); + MODIFY_REG(hsmartcard->Instance->CR3, USART_CR3_DDRE, hsmartcard->AdvancedInit.DMADisableonRxError); + } + + /* if required, configure MSB first on communication line */ + if (HAL_IS_BIT_SET(hsmartcard->AdvancedInit.AdvFeatureInit, SMARTCARD_ADVFEATURE_MSBFIRST_INIT)) + { + assert_param(IS_SMARTCARD_ADVFEATURE_MSBFIRST(hsmartcard->AdvancedInit.MSBFirst)); + MODIFY_REG(hsmartcard->Instance->CR2, USART_CR2_MSBFIRST, hsmartcard->AdvancedInit.MSBFirst); + } + +} + + + + +/** + * @brief Check the SMARTCARD Idle State + * @param hsmartcard: SMARTCARD handle + * @retval HAL status + */ +static HAL_StatusTypeDef SMARTCARD_CheckIdleState(SMARTCARD_HandleTypeDef *hsmartcard) +{ + + /* Initialize the SMARTCARD ErrorCode */ + hsmartcard->ErrorCode = HAL_SMARTCARD_ERROR_NONE; + + /* Check if the Transmitter is enabled */ + if((hsmartcard->Instance->CR1 & USART_CR1_TE) == USART_CR1_TE) + { + /* Wait until TEACK flag is set */ + if(SMARTCARD_WaitOnFlagUntilTimeout(hsmartcard, USART_ISR_TEACK, RESET, TEACK_REACK_TIMEOUT) != HAL_OK) + { + return HAL_TIMEOUT; + } + } + /* Check if the Receiver is enabled */ + if((hsmartcard->Instance->CR1 & USART_CR1_RE) == USART_CR1_RE) + { + /* Wait until REACK flag is set */ + if(SMARTCARD_WaitOnFlagUntilTimeout(hsmartcard, USART_ISR_REACK, RESET, TEACK_REACK_TIMEOUT) != HAL_OK) + { + return HAL_TIMEOUT; + } + } + + /* Initialize the SMARTCARD state*/ + hsmartcard->State= HAL_SMARTCARD_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hsmartcard); + + return HAL_OK; +} + + + +/** + * @} + */ + +/** + * @} + */ + +#endif /* !defined(STM32F030x6) && !defined(STM32F030x8) */ + +#endif /* HAL_SMARTCARD_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_smartcard.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_smartcard.h new file mode 100644 index 0000000000..790907638f --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_smartcard.h @@ -0,0 +1,783 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_smartcard.h + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief Header file of SMARTCARD HAL module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32F0xx_HAL_SMARTCARD_H +#define __STM32F0xx_HAL_SMARTCARD_H + +#ifdef __cplusplus + extern "C" { +#endif + +#if !defined(STM32F030x4) && !defined(STM32F030x6) && !defined(STM32F030x8) + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal_def.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @addtogroup SMARTCARD + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/** + * @brief SMARTCARD Init Structure definition + */ +typedef struct +{ + uint32_t BaudRate; /*!< Configures the SmartCard communication baud rate. + The baud rate register is computed using the following formula: + Baud Rate Register = ((PCLKx) / ((hsmartcard->Init.BaudRate))) */ + + uint32_t WordLength; /*!< Specifies the number of data bits transmitted or received in a frame. + This parameter @ref SMARTCARD_Word_Length can only be set to 9 (8 data + 1 parity bits). */ + + uint32_t StopBits; /*!< Specifies the number of stop bits @ref SMARTCARD_Stop_Bits. + Only 1.5 stop bits are authorized in SmartCard mode. */ + + uint16_t Parity; /*!< Specifies the parity mode. + This parameter can be a value of @ref SMARTCARD_Parity + @note The parity is enabled by default (PCE is forced to 1). + Since the WordLength is forced to 8 bits + parity, M is + forced to 1 and the parity bit is the 9th bit. */ + + uint16_t Mode; /*!< Specifies whether the Receive or Transmit mode is enabled or disabled. + This parameter can be a value of @ref SMARTCARD_Mode */ + + uint16_t CLKPolarity; /*!< Specifies the steady state of the serial clock. + This parameter can be a value of @ref SMARTCARD_Clock_Polarity */ + + uint16_t CLKPhase; /*!< Specifies the clock transition on which the bit capture is made. + This parameter can be a value of @ref SMARTCARD_Clock_Phase */ + + uint16_t CLKLastBit; /*!< Specifies whether the clock pulse corresponding to the last transmitted + data bit (MSB) has to be output on the SCLK pin in synchronous mode. + This parameter can be a value of @ref SMARTCARD_Last_Bit */ + + uint16_t OneBitSampling; /*!< Specifies wether a single sample or three samples' majority vote is selected. + Selecting the single sample method increases the receiver tolerance to clock + deviations. This parameter can be a value of @ref SMARTCARD_OneBit_Sampling. */ + + uint8_t Prescaler; /*!< Specifies the SmartCard Prescaler */ + + uint8_t GuardTime; /*!< Specifies the SmartCard Guard Time */ + + uint16_t NACKEnable; /*!< Specifies whether the SmartCard NACK transmission is enabled + in case of parity error. + This parameter can be a value of @ref SMARTCARD_NACK_Enable */ + + uint32_t TimeOutEnable; /*!< Specifies whether the receiver timeout is enabled. + This parameter can be a value of @ref SMARTCARD_Timeout_Enable*/ + + uint32_t TimeOutValue; /*!< Specifies the receiver time out value in number of baud blocks: + it is used to implement the Character Wait Time (CWT) and + Block Wait Time (BWT). It is coded over 24 bits. */ + + uint8_t BlockLength; /*!< Specifies the SmartCard Block Length in T=1 Reception mode. + This parameter can be any value from 0x0 to 0xFF */ + + uint8_t AutoRetryCount; /*!< Specifies the SmartCard auto-retry count (number of retries in + receive and transmit mode). When set to 0, retransmission is + disabled. Otherwise, its maximum value is 7 (before signalling + an error) */ + +}SMARTCARD_InitTypeDef; + +/** + * @brief SMARTCARD advanced features initalization structure definition + */ +typedef struct +{ + uint32_t AdvFeatureInit; /*!< Specifies which advanced SMARTCARD features is initialized. Several + advanced features may be initialized at the same time. This parameter + can be a value of @ref SMARTCARD_Advanced_Features_Initialization_Type */ + + uint32_t TxPinLevelInvert; /*!< Specifies whether the TX pin active level is inverted. + This parameter can be a value of @ref SMARTCARD_Tx_Inv */ + + uint32_t RxPinLevelInvert; /*!< Specifies whether the RX pin active level is inverted. + This parameter can be a value of @ref SMARTCARD_Rx_Inv */ + + uint32_t DataInvert; /*!< Specifies whether data are inverted (positive/direct logic + vs negative/inverted logic). + This parameter can be a value of @ref SMARTCARD_Data_Inv */ + + uint32_t Swap; /*!< Specifies whether TX and RX pins are swapped. + This parameter can be a value of @ref SMARTCARD_Rx_Tx_Swap */ + + uint32_t OverrunDisable; /*!< Specifies whether the reception overrun detection is disabled. + This parameter can be a value of @ref SMARTCARD_Overrun_Disable */ + + uint32_t DMADisableonRxError; /*!< Specifies whether the DMA is disabled in case of reception error. + This parameter can be a value of @ref SMARTCARD_DMA_Disable_on_Rx_Error */ + + uint32_t MSBFirst; /*!< Specifies whether MSB is sent first on UART line. + This parameter can be a value of @ref SMARTCARD_MSB_First */ +}SMARTCARD_AdvFeatureInitTypeDef; + +/** + * @brief HAL State structures definition + */ +typedef enum +{ + HAL_SMARTCARD_STATE_RESET = 0x00, /*!< Peripheral is not initialized */ + HAL_SMARTCARD_STATE_READY = 0x01, /*!< Peripheral Initialized and ready for use */ + HAL_SMARTCARD_STATE_BUSY = 0x02, /*!< an internal process is ongoing */ + HAL_SMARTCARD_STATE_BUSY_TX = 0x12, /*!< Data Transmission process is ongoing */ + HAL_SMARTCARD_STATE_BUSY_RX = 0x22, /*!< Data Reception process is ongoing */ + HAL_SMARTCARD_STATE_BUSY_TX_RX = 0x32, /*!< Data Transmission and Reception process is ongoing */ + HAL_SMARTCARD_STATE_TIMEOUT = 0x03, /*!< Timeout state */ + HAL_SMARTCARD_STATE_ERROR = 0x04 /*!< Error */ +}HAL_SMARTCARD_StateTypeDef; + +/** + * @brief HAL SMARTCARD Error Code structure definition + */ +typedef enum +{ + HAL_SMARTCARD_ERROR_NONE = 0x00, /*!< No error */ + HAL_SMARTCARD_ERROR_PE = 0x01, /*!< Parity error */ + HAL_SMARTCARD_ERROR_NE = 0x02, /*!< Noise error */ + HAL_SMARTCARD_ERROR_FE = 0x04, /*!< frame error */ + HAL_SMARTCARD_ERROR_ORE = 0x08, /*!< Overrun error */ + HAL_SMARTCARD_ERROR_DMA = 0x10, /*!< DMA transfer error */ + HAL_SMARTCARD_ERROR_RTO = 0x20 /*!< Receiver TimeOut error */ +}HAL_SMARTCARD_ErrorTypeDef; + +/** + * @brief SMARTCARD clock sources + */ +typedef enum +{ + SMARTCARD_CLOCKSOURCE_PCLK1 = 0x00, /*!< PCLK1 clock source */ + SMARTCARD_CLOCKSOURCE_HSI = 0x02, /*!< HSI clock source */ + SMARTCARD_CLOCKSOURCE_SYSCLK = 0x04, /*!< SYSCLK clock source */ + SMARTCARD_CLOCKSOURCE_LSE = 0x08, /*!< LSE clock source */ + SMARTCARD_CLOCKSOURCE_UNDEFINED = 0x10 /*!< undefined clock source */ +}SMARTCARD_ClockSourceTypeDef; + +/** + * @brief SMARTCARD handle Structure definition + */ +typedef struct +{ + USART_TypeDef *Instance; /* USART registers base address */ + + SMARTCARD_InitTypeDef Init; /* SmartCard communication parameters */ + + SMARTCARD_AdvFeatureInitTypeDef AdvancedInit; /* SmartCard advanced features initialization parameters */ + + uint8_t *pTxBuffPtr; /* Pointer to SmartCard Tx transfer Buffer */ + + uint16_t TxXferSize; /* SmartCard Tx Transfer size */ + + uint16_t TxXferCount; /* SmartCard Tx Transfer Counter */ + + uint8_t *pRxBuffPtr; /* Pointer to SmartCard Rx transfer Buffer */ + + uint16_t RxXferSize; /* SmartCard Rx Transfer size */ + + uint16_t RxXferCount; /* SmartCard Rx Transfer Counter */ + + DMA_HandleTypeDef *hdmatx; /* SmartCard Tx DMA Handle parameters */ + + DMA_HandleTypeDef *hdmarx; /* SmartCard Rx DMA Handle parameters */ + + HAL_LockTypeDef Lock; /* Locking object */ + + HAL_SMARTCARD_StateTypeDef State; /* SmartCard communication state */ + + HAL_SMARTCARD_ErrorTypeDef ErrorCode; /* SmartCard Error code */ + +}SMARTCARD_HandleTypeDef; + + +/* Exported constants --------------------------------------------------------*/ +/** @defgroup SMARTCARD_Exported_Constants + * @{ + */ + +/** @defgroup SMARTCARD_Word_Length SMARTCARD Word Length + * @{ + */ +#define SMARTCARD_WORDLENGTH_9B ((uint32_t)USART_CR1_M0) +#define IS_SMARTCARD_WORD_LENGTH(LENGTH) ((LENGTH) == SMARTCARD_WORDLENGTH_9B) +/** + * @} + */ + +/** @defgroup SMARTCARD_Stop_Bits SMARTCARD Stop Bits + * @{ + */ +#define SMARTCARD_STOPBITS_1_5 ((uint32_t)(USART_CR2_STOP)) +#define IS_SMARTCARD_STOPBITS(STOPBITS) ((STOPBITS) == SMARTCARD_STOPBITS_1_5) +/** + * @} + */ + +/** @defgroup SMARTCARD_Parity SMARTCARD Parity + * @{ + */ +#define SMARTCARD_PARITY_EVEN ((uint16_t)USART_CR1_PCE) +#define SMARTCARD_PARITY_ODD ((uint16_t)(USART_CR1_PCE | USART_CR1_PS)) +#define IS_SMARTCARD_PARITY(PARITY) (((PARITY) == SMARTCARD_PARITY_EVEN) || \ + ((PARITY) == SMARTCARD_PARITY_ODD)) +/** + * @} + */ + +/** @defgroup SMARTCARD_Mode SMARTCARD Transfer Mode + * @{ + */ +#define SMARTCARD_MODE_RX ((uint16_t)USART_CR1_RE) +#define SMARTCARD_MODE_TX ((uint16_t)USART_CR1_TE) +#define SMARTCARD_MODE_TX_RX ((uint16_t)(USART_CR1_TE |USART_CR1_RE)) +#define IS_SMARTCARD_MODE(MODE) ((((MODE) & (uint16_t)0xFFF3) == 0x00) && ((MODE) != (uint16_t)0x00)) +/** + * @} + */ + +/** @defgroup SMARTCARD_Clock_Polarity SMARTCARD Clock Polarity + * @{ + */ +#define SMARTCARD_POLARITY_LOW ((uint16_t)0x0000) +#define SMARTCARD_POLARITY_HIGH ((uint16_t)USART_CR2_CPOL) +#define IS_SMARTCARD_POLARITY(CPOL) (((CPOL) == SMARTCARD_POLARITY_LOW) || ((CPOL) == SMARTCARD_POLARITY_HIGH)) +/** + * @} + */ + +/** @defgroup SMARTCARD_Clock_Phase SMARTCARD Clock Phase + * @{ + */ +#define SMARTCARD_PHASE_1EDGE ((uint16_t)0x0000) +#define SMARTCARD_PHASE_2EDGE ((uint16_t)USART_CR2_CPHA) +#define IS_SMARTCARD_PHASE(CPHA) (((CPHA) == SMARTCARD_PHASE_1EDGE) || ((CPHA) == SMARTCARD_PHASE_2EDGE)) +/** + * @} + */ + +/** @defgroup SMARTCARD_Last_Bit SMARTCARD Last Bit + * @{ + */ +#define SMARTCARD_LASTBIT_DISABLED ((uint16_t)0x0000) +#define SMARTCARD_LASTBIT_ENABLED ((uint16_t)USART_CR2_LBCL) +#define IS_SMARTCARD_LASTBIT(LASTBIT) (((LASTBIT) == SMARTCARD_LASTBIT_DISABLED) || \ + ((LASTBIT) == SMARTCARD_LASTBIT_ENABLED)) +/** + * @} + */ + +/** @defgroup SMARTCARD_OneBit_Sampling SMARTCARD One Bit Sampling Method + * @{ + */ +#define SMARTCARD_ONEBIT_SAMPLING_DISABLED ((uint16_t)0x0000) +#define SMARTCARD_ONEBIT_SAMPLING_ENABLED ((uint16_t)USART_CR3_ONEBIT) +#define IS_SMARTCARD_ONEBIT_SAMPLING(ONEBIT) (((ONEBIT) == SMARTCARD_ONEBIT_SAMPLING_DISABLED) || \ + ((ONEBIT) == SMARTCARD_ONEBIT_SAMPLING_ENABLED)) +/** + * @} + */ + + +/** @defgroup SMARTCARD_NACK_Enable SMARTCARD NACK Enable + * @{ + */ +#define SMARTCARD_NACK_ENABLED ((uint16_t)USART_CR3_NACK) +#define SMARTCARD_NACK_DISABLED ((uint16_t)0x0000) +#define IS_SMARTCARD_NACK(NACK) (((NACK) == SMARTCARD_NACK_ENABLED) || \ + ((NACK) == SMARTCARD_NACK_DISABLED)) +/** + * @} + */ + +/** @defgroup SMARTCARD_Timeout_Enable SMARTCARD Timeout Enable + * @{ + */ +#define SMARTCARD_TIMEOUT_DISABLED ((uint32_t)0x00000000) +#define SMARTCARD_TIMEOUT_ENABLED ((uint32_t)USART_CR2_RTOEN) +#define IS_SMARTCARD_TIMEOUT(TIMEOUT) (((TIMEOUT) == SMARTCARD_TIMEOUT_DISABLED) || \ + ((TIMEOUT) == SMARTCARD_TIMEOUT_ENABLED)) +/** + * @} + */ + +/** @defgroup SMARTCARD_Advanced_Features_Initialization_Type SMARTCARD advanced feature initialization type + * @{ + */ +#define SMARTCARD_ADVFEATURE_NO_INIT ((uint32_t)0x00000000) +#define SMARTCARD_ADVFEATURE_TXINVERT_INIT ((uint32_t)0x00000001) +#define SMARTCARD_ADVFEATURE_RXINVERT_INIT ((uint32_t)0x00000002) +#define SMARTCARD_ADVFEATURE_DATAINVERT_INIT ((uint32_t)0x00000004) +#define SMARTCARD_ADVFEATURE_SWAP_INIT ((uint32_t)0x00000008) +#define SMARTCARD_ADVFEATURE_RXOVERRUNDISABLE_INIT ((uint32_t)0x00000010) +#define SMARTCARD_ADVFEATURE_DMADISABLEONERROR_INIT ((uint32_t)0x00000020) +#define SMARTCARD_ADVFEATURE_MSBFIRST_INIT ((uint32_t)0x00000080) +#define IS_SMARTCARD_ADVFEATURE_INIT(INIT) ((INIT) <= (SMARTCARD_ADVFEATURE_NO_INIT | \ + SMARTCARD_ADVFEATURE_TXINVERT_INIT | \ + SMARTCARD_ADVFEATURE_RXINVERT_INIT | \ + SMARTCARD_ADVFEATURE_DATAINVERT_INIT | \ + SMARTCARD_ADVFEATURE_SWAP_INIT | \ + SMARTCARD_ADVFEATURE_RXOVERRUNDISABLE_INIT | \ + SMARTCARD_ADVFEATURE_DMADISABLEONERROR_INIT | \ + SMARTCARD_ADVFEATURE_MSBFIRST_INIT)) +/** + * @} + */ + +/** @defgroup SMARTCARD_Tx_Inv SMARTCARD advanced feature TX pin active level inversion + * @{ + */ +#define SMARTCARD_ADVFEATURE_TXINV_DISABLE ((uint32_t)0x00000000) +#define SMARTCARD_ADVFEATURE_TXINV_ENABLE ((uint32_t)USART_CR2_TXINV) +#define IS_SMARTCARD_ADVFEATURE_TXINV(TXINV) (((TXINV) == SMARTCARD_ADVFEATURE_TXINV_DISABLE) || \ + ((TXINV) == SMARTCARD_ADVFEATURE_TXINV_ENABLE)) +/** + * @} + */ + +/** @defgroup SMARTCARD_Rx_Inv SMARTCARD advanced feature RX pin active level inversion + * @{ + */ +#define SMARTCARD_ADVFEATURE_RXINV_DISABLE ((uint32_t)0x00000000) +#define SMARTCARD_ADVFEATURE_RXINV_ENABLE ((uint32_t)USART_CR2_RXINV) +#define IS_SMARTCARD_ADVFEATURE_RXINV(RXINV) (((RXINV) == SMARTCARD_ADVFEATURE_RXINV_DISABLE) || \ + ((RXINV) == SMARTCARD_ADVFEATURE_RXINV_ENABLE)) +/** + * @} + */ + +/** @defgroup SMARTCARD_Data_Inv SMARTCARD advanced feature Binary Data inversion + * @{ + */ +#define SMARTCARD_ADVFEATURE_DATAINV_DISABLE ((uint32_t)0x00000000) +#define SMARTCARD_ADVFEATURE_DATAINV_ENABLE ((uint32_t)USART_CR2_DATAINV) +#define IS_SMARTCARD_ADVFEATURE_DATAINV(DATAINV) (((DATAINV) == SMARTCARD_ADVFEATURE_DATAINV_DISABLE) || \ + ((DATAINV) == SMARTCARD_ADVFEATURE_DATAINV_ENABLE)) +/** + * @} + */ + +/** @defgroup SMARTCARD_Rx_Tx_Swap SMARTCARD advanced feature RX TX pins swap + * @{ + */ +#define SMARTCARD_ADVFEATURE_SWAP_DISABLE ((uint32_t)0x00000000) +#define SMARTCARD_ADVFEATURE_SWAP_ENABLE ((uint32_t)USART_CR2_SWAP) +#define IS_SMARTCARD_ADVFEATURE_SWAP(SWAP) (((SWAP) == SMARTCARD_ADVFEATURE_SWAP_DISABLE) || \ + ((SWAP) == SMARTCARD_ADVFEATURE_SWAP_ENABLE)) +/** + * @} + */ + +/** @defgroup SMARTCARD_Overrun_Disable SMARTCARD advanced feature Overrun Disable + * @{ + */ +#define SMARTCARD_ADVFEATURE_OVERRUN_ENABLE ((uint32_t)0x00000000) +#define SMARTCARD_ADVFEATURE_OVERRUN_DISABLE ((uint32_t)USART_CR3_OVRDIS) +#define IS_SMARTCARD_OVERRUN(OVERRUN) (((OVERRUN) == SMARTCARD_ADVFEATURE_OVERRUN_ENABLE) || \ + ((OVERRUN) == SMARTCARD_ADVFEATURE_OVERRUN_DISABLE)) +/** + * @} + */ + +/** @defgroup SMARTCARD_DMA_Disable_on_Rx_Error SMARTCARD advanced feature DMA Disable on Rx Error + * @{ + */ +#define SMARTCARD_ADVFEATURE_DMA_ENABLEONRXERROR ((uint32_t)0x00000000) +#define SMARTCARD_ADVFEATURE_DMA_DISABLEONRXERROR ((uint32_t)USART_CR3_DDRE) +#define IS_SMARTCARD_ADVFEATURE_DMAONRXERROR(DMA) (((DMA) == SMARTCARD_ADVFEATURE_DMA_ENABLEONRXERROR) || \ + ((DMA) == SMARTCARD_ADVFEATURE_DMA_DISABLEONRXERROR)) +/** + * @} + */ + +/** @defgroup SMARTCARD_MSB_First SMARTCARD advanced feature MSB first + * @{ + */ +#define SMARTCARD_ADVFEATURE_MSBFIRST_DISABLE ((uint32_t)0x00000000) +#define SMARTCARD_ADVFEATURE_MSBFIRST_ENABLE ((uint32_t)USART_CR2_MSBFIRST) +#define IS_SMARTCARD_ADVFEATURE_MSBFIRST(MSBFIRST) (((MSBFIRST) == SMARTCARD_ADVFEATURE_MSBFIRST_DISABLE) || \ + ((MSBFIRST) == SMARTCARD_ADVFEATURE_MSBFIRST_ENABLE)) +/** + * @} + */ + +/** @defgroup SmartCard_Flags SMARTCARD Flags + * Elements values convention: 0xXXXX + * - 0xXXXX : Flag mask in the ISR register + * @{ + */ +#define SMARTCARD_FLAG_REACK ((uint32_t)0x00400000) +#define SMARTCARD_FLAG_TEACK ((uint32_t)0x00200000) +#define SMARTCARD_FLAG_BUSY ((uint32_t)0x00010000) +#define SMARTCARD_FLAG_EOBF ((uint32_t)0x00001000) +#define SMARTCARD_FLAG_RTOF ((uint32_t)0x00000800) +#define SMARTCARD_FLAG_TXE ((uint32_t)0x00000080) +#define SMARTCARD_FLAG_TC ((uint32_t)0x00000040) +#define SMARTCARD_FLAG_RXNE ((uint32_t)0x00000020) +#define SMARTCARD_FLAG_ORE ((uint32_t)0x00000008) +#define SMARTCARD_FLAG_NE ((uint32_t)0x00000004) +#define SMARTCARD_FLAG_FE ((uint32_t)0x00000002) +#define SMARTCARD_FLAG_PE ((uint32_t)0x00000001) +/** + * @} + */ + +/** @defgroup SMARTCARD_Interrupt_definition SMARTCARD Interrupts Definition + * Elements values convention: 0000ZZZZ0XXYYYYYb + * - YYYYY : Interrupt source position in the XX register (5bits) + * - XX : Interrupt source register (2bits) + * - 01: CR1 register + * - 10: CR2 register + * - 11: CR3 register + * - ZZZZ : Flag position in the ISR register(4bits) + * @{ + */ + +#define SMARTCARD_IT_PE ((uint16_t)0x0028) +#define SMARTCARD_IT_TXE ((uint16_t)0x0727) +#define SMARTCARD_IT_TC ((uint16_t)0x0626) +#define SMARTCARD_IT_RXNE ((uint16_t)0x0525) + +#define SMARTCARD_IT_ERR ((uint16_t)0x0060) +#define SMARTCARD_IT_ORE ((uint16_t)0x0300) +#define SMARTCARD_IT_NE ((uint16_t)0x0200) +#define SMARTCARD_IT_FE ((uint16_t)0x0100) + +#define SMARTCARD_IT_EOB ((uint16_t)0x0C3B) +#define SMARTCARD_IT_RTO ((uint16_t)0x0B3A) +/** + * @} + */ + + +/** @defgroup SMARTCARD_IT_CLEAR_Flags SMARTCARD Interruption Clear Flags + * @{ + */ +#define SMARTCARD_CLEAR_PEF USART_ICR_PECF /*!< Parity Error Clear Flag */ +#define SMARTCARD_CLEAR_FEF USART_ICR_FECF /*!< Framing Error Clear Flag */ +#define SMARTCARD_CLEAR_NEF USART_ICR_NCF /*!< Noise detected Clear Flag */ +#define SMARTCARD_CLEAR_OREF USART_ICR_ORECF /*!< OverRun Error Clear Flag */ +#define SMARTCARD_CLEAR_TCF USART_ICR_TCCF /*!< Transmission Complete Clear Flag */ +#define SMARTCARD_CLEAR_RTOF USART_ICR_RTOCF /*!< Receiver Time Out Clear Flag */ +#define SMARTCARD_CLEAR_EOBF USART_ICR_EOBCF /*!< End Of Block Clear Flag */ +/** + * @} + */ + +/** @defgroup SMARTCARD_Request_Parameters SMARTCARD Request Parameters + * @{ + */ +#define SMARTCARD_RXDATA_FLUSH_REQUEST ((uint16_t)USART_RQR_RXFRQ) /*!< Receive Data flush Request */ +#define SMARTCARD_TXDATA_FLUSH_REQUEST ((uint16_t)USART_RQR_TXFRQ) /*!< Transmit data flush Request */ +#define IS_SMARTCARD_REQUEST_PARAMETER(PARAM) (((PARAM) == SMARTCARD_RXDATA_FLUSH_REQUEST) || \ + ((PARAM) == SMARTCARD_TXDATA_FLUSH_REQUEST)) +/** + * @} + */ + + +/** @defgroup SMARTCARD_CR3_SCARCNT_LSB_POS SMARTCARD auto retry counter LSB position in CR3 register + * @{ + */ +#define SMARTCARD_CR3_SCARCNT_LSB_POS ((uint32_t) 17) +/** + * @} + */ + +/** @defgroup SMARTCARD_GTPR_GT_LSB_POS SMARTCARD guard time value LSB position in GTPR register + * @{ + */ +#define SMARTCARD_GTPR_GT_LSB_POS ((uint32_t) 8) +/** + * @} + */ + +/** @defgroup SMARTCARD_RTOR_BLEN_LSB_POS SMARTCARD block length LSB position in RTOR register + * @{ + */ +#define SMARTCARD_RTOR_BLEN_LSB_POS ((uint32_t) 24) +/** + * @} + */ + +/** @defgroup SMARTCARD_Interruption_Mask SMARTCARD interruptions flag mask + * @{ + */ +#define SMARTCARD_IT_MASK ((uint16_t)0x001F) +/** + * @} + */ + +/** + * @} + */ + +/* Exported macros -----------------------------------------------------------*/ +/** @defgroup SMARTCARD_Exported_Macros + * @{ + */ + +/** @brief Reset SMARTCARD handle state + * @param __HANDLE__: SMARTCARD handle. + * @retval None + */ +#define __HAL_SMARTCARD_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_SMARTCARD_STATE_RESET) + +/** @brief Checks whether the specified Smartcard flag is set or not. + * @param __HANDLE__: specifies the SMARTCARD Handle. + * The Handle Instance can be USARTx where x: 1, 2 or 3 to select the USART peripheral. + * @param __FLAG__: specifies the flag to check. + * This parameter can be one of the following values: + * @arg SMARTCARD_FLAG_REACK: Receive enable ackowledge flag + * @arg SMARTCARD_FLAG_TEACK: Transmit enable ackowledge flag + * @arg SMARTCARD_FLAG_BUSY: Busy flag + * @arg SMARTCARD_FLAG_EOBF: End of block flag + * @arg SMARTCARD_FLAG_RTOF: Receiver timeout flag + * @arg SMARTCARD_FLAG_TXE: Transmit data register empty flag + * @arg SMARTCARD_FLAG_TC: Transmission Complete flag + * @arg SMARTCARD_FLAG_RXNE: Receive data register not empty flag + * @arg SMARTCARD_FLAG_ORE: OverRun Error flag + * @arg SMARTCARD_FLAG_NE: Noise Error flag + * @arg SMARTCARD_FLAG_FE: Framing Error flag + * @arg SMARTCARD_FLAG_PE: Parity Error flag + * @retval The new state of __FLAG__ (TRUE or FALSE). + */ +#define __HAL_SMARTCARD_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->ISR & (__FLAG__)) == (__FLAG__)) + + +/** @brief Enables the specified SmartCard interrupt. + * @param __HANDLE__: specifies the SMARTCARD Handle. + * The Handle Instance can be USARTx where x: 1, 2 or 3 to select the USART peripheral. + * @param __INTERRUPT__: specifies the SMARTCARD interrupt to enable. + * This parameter can be one of the following values: + * @arg SMARTCARD_IT_EOBF: End Of Block interrupt + * @arg SMARTCARD_IT_RTOF: Receive TimeOut interrupt + * @arg SMARTCARD_IT_TXE: Transmit Data Register empty interrupt + * @arg SMARTCARD_IT_TC: Transmission complete interrupt + * @arg SMARTCARD_IT_RXNE: Receive Data register not empty interrupt + * @arg SMARTCARD_IT_PE: Parity Error interrupt + * @arg SMARTCARD_IT_ERR: Error interrupt(Frame error, noise error, overrun error) + * @retval None + */ +#define __HAL_SMARTCARD_ENABLE_IT(__HANDLE__, __INTERRUPT__) (((((uint8_t)(__INTERRUPT__)) >> 5U) == 1)? ((__HANDLE__)->Instance->CR1 |= (1U << ((__INTERRUPT__) & SMARTCARD_IT_MASK))): \ + ((((uint8_t)(__INTERRUPT__)) >> 5U) == 2)? ((__HANDLE__)->Instance->CR2 |= (1U << ((__INTERRUPT__) & SMARTCARD_IT_MASK))): \ + ((__HANDLE__)->Instance->CR3 |= (1U << ((__INTERRUPT__) & SMARTCARD_IT_MASK)))) + +/** @brief Disables the specified SmartCard interrupt. + * @param __HANDLE__: specifies the SMARTCARD Handle. + * The Handle Instance can be USARTx where x: 1, 2 or 3 to select the USART peripheral. + * @param __INTERRUPT__: specifies the SMARTCARD interrupt to disable. + * This parameter can be one of the following values: + * @arg SMARTCARD_IT_EOBF: End Of Block interrupt + * @arg SMARTCARD_IT_RTOF: Receive TimeOut interrupt + * @arg SMARTCARD_IT_TXE: Transmit Data Register empty interrupt + * @arg SMARTCARD_IT_TC: Transmission complete interrupt + * @arg SMARTCARD_IT_RXNE: Receive Data register not empty interrupt + * @arg SMARTCARD_IT_PE: Parity Error interrupt + * @arg SMARTCARD_IT_ERR: Error interrupt(Frame error, noise error, overrun error) + * @retval None + */ +#define __HAL_SMARTCARD_DISABLE_IT(__HANDLE__, __INTERRUPT__) (((((uint8_t)(__INTERRUPT__)) >> 5U) == 1)? ((__HANDLE__)->Instance->CR1 &= ~ (1U << ((__INTERRUPT__) & SMARTCARD_IT_MASK))): \ + ((((uint8_t)(__INTERRUPT__)) >> 5U) == 2)? ((__HANDLE__)->Instance->CR2 &= ~ (1U << ((__INTERRUPT__) & SMARTCARD_IT_MASK))): \ + ((__HANDLE__)->Instance->CR3 &= ~ (1U << ((__INTERRUPT__) & SMARTCARD_IT_MASK)))) + + +/** @brief Checks whether the specified SmartCard interrupt has occurred or not. + * @param __HANDLE__: specifies the SMARTCARD Handle. + * The Handle Instance can be USARTx where x: 1, 2 or 3 to select the USART peripheral. + * @param __IT__: specifies the SMARTCARD interrupt to check. + * This parameter can be one of the following values: + * @arg SMARTCARD_IT_EOBF: End Of Block interrupt + * @arg SMARTCARD_IT_RTOF: Receive TimeOut interrupt + * @arg SMARTCARD_IT_TXE: Transmit Data Register empty interrupt + * @arg SMARTCARD_IT_TC: Transmission complete interrupt + * @arg SMARTCARD_IT_RXNE: Receive Data register not empty interrupt + * @arg SMARTCARD_IT_ORE: OverRun Error interrupt + * @arg SMARTCARD_IT_NE: Noise Error interrupt + * @arg SMARTCARD_IT_FE: Framing Error interrupt + * @arg SMARTCARD_IT_PE: Parity Error interrupt + * @retval The new state of __IT__ (TRUE or FALSE). + */ +#define __HAL_SMARTCARD_GET_IT(__HANDLE__, __IT__) ((__HANDLE__)->Instance->ISR & ((uint32_t)1 << ((__IT__)>> 0x08))) + +/** @brief Checks whether the specified SmartCard interrupt interrupt source is enabled. + * @param __HANDLE__: specifies the SMARTCARD Handle. + * The Handle Instance can be USARTx where x: 1, 2 or 3 to select the USART peripheral. + * @param __IT__: specifies the SMARTCARD interrupt source to check. + * This parameter can be one of the following values: + * @arg SMARTCARD_IT_EOBF: End Of Block interrupt + * @arg SMARTCARD_IT_RTOF: Receive TimeOut interrupt + * @arg SMARTCARD_IT_TXE: Transmit Data Register empty interrupt + * @arg SMARTCARD_IT_TC: Transmission complete interrupt + * @arg SMARTCARD_IT_RXNE: Receive Data register not empty interrupt + * @arg SMARTCARD_IT_ORE: OverRun Error interrupt + * @arg SMARTCARD_IT_NE: Noise Error interrupt + * @arg SMARTCARD_IT_FE: Framing Error interrupt + * @arg SMARTCARD_IT_PE: Parity Error interrupt + * @retval The new state of __IT__ (TRUE or FALSE). + */ +#define __HAL_SMARTCARD_GET_IT_SOURCE(__HANDLE__, __IT__) ((((((uint8_t)(__IT__)) >> 5U) == 1)? (__HANDLE__)->Instance->CR1 : \ + (((((uint8_t)(__IT__)) >> 5U) == 2)? (__HANDLE__)->Instance->CR2 : \ + (__HANDLE__)->Instance->CR3)) & ((uint32_t)1 << (((uint16_t)(__IT__)) & SMARTCARD_IT_MASK))) + + +/** @brief Clears the specified SMARTCARD ISR flag, in setting the proper ICR register flag. + * @param __HANDLE__: specifies the SMARTCARD Handle. + * The Handle Instance can be USARTx where x: 1, 2 or 3 to select the USART peripheral. + * @param __IT_CLEAR__: specifies the interrupt clear register flag that needs to be set + * to clear the corresponding interrupt + * This parameter can be one of the following values: + * @arg USART_CLEAR_PEF: Parity Error Clear Flag + * @arg USART_CLEAR_FEF: Framing Error Clear Flag + * @arg USART_CLEAR_NEF: Noise detected Clear Flag + * @arg USART_CLEAR_OREF: OverRun Error Clear Flag + * @arg USART_CLEAR_TCF: Transmission Complete Clear Flag + * @arg USART_CLEAR_RTOF: Receiver Time Out Clear Flag + * @arg USART_CLEAR_EOBF: End Of Block Clear Flag + * @retval None + */ +#define __HAL_SMARTCARD_CLEAR_IT(__HANDLE__, __IT_CLEAR__) ((__HANDLE__)->Instance->ICR |= (uint32_t)(__IT_CLEAR__)) + +/** @brief Set a specific SMARTCARD request flag. + * @param __HANDLE__: specifies the SMARTCARD Handle. + * The Handle Instance can be USARTx where x: 1, 2 or 3 to select the USART peripheral. + * @param __REQ__: specifies the request flag to set + * This parameter can be one of the following values: + * @arg SMARTCARD_RXDATA_FLUSH_REQUEST: Receive Data flush Request + * @arg SMARTCARD_TXDATA_FLUSH_REQUEST: Transmit data flush Request + * + * @retval None + */ +#define __HAL_SMARTCARD_SEND_REQ(__HANDLE__, __REQ__) ((__HANDLE__)->Instance->RQR |= (uint16_t)(__REQ__)) + +/** @brief Enable the USART associated to the SMARTCARD Handle + * @param __HANDLE__: specifies the SMARTCARD Handle. + * The Handle Instance can be UARTx where x: 1, 2, 3 to select the USART peripheral + * @retval None + */ +#define __HAL_SMARTCARD_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 |= USART_CR1_UE) + +/** @brief Disable the USART associated to the SMARTCARD Handle + * @param __HANDLE__: specifies the SMARTCARD Handle. + * The Handle Instance can be UARTx where x: 1, 2, 3 to select the USART peripheral + * @retval None + */ +#define __HAL_SMARTCARD_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 &= ~USART_CR1_UE) + +/** @brief Check the Baud rate range. The maximum Baud Rate is derived from the + * maximum clock on F0 (i.e. 48 MHz) divided by the oversampling used + * on the SMARTCARD (i.e. 16) + * @param __BAUDRATE__: Baud rate set by the configuration function. + * @retval Test result (TRUE or FALSE) + */ +#define IS_SMARTCARD_BAUDRATE(__BAUDRATE__) ((__BAUDRATE__) < 4500001) + +/** @brief Check the block length range. The maximum SMARTCARD block length is 0xFF. + * @param __LENGTH__: block length. + * @retval Test result (TRUE or FALSE) + */ +#define IS_SMARTCARD_BLOCKLENGTH(__LENGTH__) ((__LENGTH__) <= 0xFF) + +/** @brief Check the receiver timeout value. The maximum SMARTCARD receiver timeout + * value is 0xFFFFFF. + * @param __TIMEOUTVALUE__: receiver timeout value. + * @retval Test result (TRUE or FALSE) + */ +#define IS_SMARTCARD_TIMEOUT_VALUE(__TIMEOUTVALUE__) ((__TIMEOUTVALUE__) <= 0xFFFFFF) + +/** @brief Check the SMARTCARD autoretry counter value. The maximum number of + * retransmissions is 0x7. + * @param __COUNT__: number of retransmissions + * @retval Test result (TRUE or FALSE) + */ +#define IS_SMARTCARD_AUTORETRY_COUNT(__COUNT__) ((__COUNT__) <= 0x7) + +/** + * @} + */ + +/* Include SMARTCARD HAL Extension module */ +#include "stm32f0xx_hal_smartcard_ex.h" + + +/* Exported functions --------------------------------------------------------*/ +/* Initialization and de-initialization functions ****************************/ +HAL_StatusTypeDef HAL_SMARTCARD_Init(SMARTCARD_HandleTypeDef *hsmartcard); +HAL_StatusTypeDef HAL_SMARTCARD_DeInit(SMARTCARD_HandleTypeDef *hsmartcard); +void HAL_SMARTCARD_MspInit(SMARTCARD_HandleTypeDef *hsmartcard); +void HAL_SMARTCARD_MspDeInit(SMARTCARD_HandleTypeDef *hsmartcard); + + +/* IO operation functions *****************************************************/ +HAL_StatusTypeDef HAL_SMARTCARD_Transmit(SMARTCARD_HandleTypeDef *hsmartcard, uint8_t *pData, uint16_t Size, uint32_t Timeout); +HAL_StatusTypeDef HAL_SMARTCARD_Receive(SMARTCARD_HandleTypeDef *hsmartcard, uint8_t *pData, uint16_t Size, uint32_t Timeout); +HAL_StatusTypeDef HAL_SMARTCARD_Transmit_IT(SMARTCARD_HandleTypeDef *hsmartcard, uint8_t *pData, uint16_t Size); +HAL_StatusTypeDef HAL_SMARTCARD_Receive_IT(SMARTCARD_HandleTypeDef *hsmartcard, uint8_t *pData, uint16_t Size); +HAL_StatusTypeDef HAL_SMARTCARD_Transmit_DMA(SMARTCARD_HandleTypeDef *hsmartcard, uint8_t *pData, uint16_t Size); +HAL_StatusTypeDef HAL_SMARTCARD_Receive_DMA(SMARTCARD_HandleTypeDef *hsmartcard, uint8_t *pData, uint16_t Size); +void HAL_SMARTCARD_IRQHandler(SMARTCARD_HandleTypeDef *hsmartcard); +void HAL_SMARTCARD_TxCpltCallback(SMARTCARD_HandleTypeDef *hsmartcard); +void HAL_SMARTCARD_RxCpltCallback(SMARTCARD_HandleTypeDef *hsmartcard); +void HAL_SMARTCARD_ErrorCallback(SMARTCARD_HandleTypeDef *hsmartcard); + +/* Peripheral Control functions ***********************************************/ +void SMARTCARD_AdvFeatureConfig(SMARTCARD_HandleTypeDef *hsmartcard); + +/* Peripheral State and Error functions ***************************************/ +HAL_SMARTCARD_StateTypeDef HAL_SMARTCARD_GetState(SMARTCARD_HandleTypeDef *hsmartcard); +uint32_t HAL_SMARTCARD_GetError(SMARTCARD_HandleTypeDef *hsmartcard); +/** + * @} + */ + +/** + * @} + */ + +#endif /* !defined(STM32F030x4) && !defined(STM32F030x6) && !defined(STM32F030x8) */ + +#ifdef __cplusplus +} +#endif + +#endif /* __STM32F0xx_HAL_SMARTCARD_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_smartcard_ex.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_smartcard_ex.c new file mode 100644 index 0000000000..f3836cb6c1 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_smartcard_ex.c @@ -0,0 +1,199 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_smartcard_ex.c + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief SMARTCARD HAL module driver. + * + * This file provides extended firmware functions to manage the following + * functionalities of the SmartCard. + * + Initialization and de-initialization function + * + Peripheral Control function + * + * + @verbatim + =============================================================================== + ##### How to use this driver ##### + =============================================================================== + [..] + The Extended SMARTCARD HAL driver can be used as follows: + + + (#) After having configured the SMARTCARD basic features with HAL_SMARTCARD_Init(), + then if required, program SMARTCARD advanced features (TX/RX pins swap, TimeOut, + auto-retry counter,...) in the hsmartcard AdvancedInit structure. + + + + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @defgroup SMARTCARDEx + * @brief SMARTCARD Extended HAL module driver + * @{ + */ +#ifdef HAL_SMARTCARD_MODULE_ENABLED + +#if !defined(STM32F030x6) && !defined(STM32F030x8) + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup SMARTCARDEx_Private_Functions + * @{ + */ + +/** @defgroup SMARTCARDEx_Group1 Extended Peripheral Control functions + * @brief Extended control functions + * +@verbatim + =============================================================================== + ##### Peripheral Control functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to initialize the SMARTCARD. + (+) HAL_SMARTCARDEx_BlockLength_Config() API allows to configure the Block Length on the fly + (+) HAL_SMARTCARDEx_TimeOut_Config() API allows to configure the receiver timeout value on the fly + (+) HAL_SMARTCARDEx_EnableReceiverTimeOut() API enables the receiver timeout feature + (+) HAL_SMARTCARDEx_DisableReceiverTimeOut() API disables the receiver timeout feature + +@endverbatim + * @{ + */ + + + + + +/** + * @brief Update on the fly the SMARTCARD block length in RTOR register + * @param hsmartcard: SMARTCARD handle + * @param BlockLength: SMARTCARD block length (8-bit long at most) + * @retval None + */ +void HAL_SMARTCARDEx_BlockLength_Config(SMARTCARD_HandleTypeDef *hsmartcard, uint8_t BlockLength) +{ + MODIFY_REG(hsmartcard->Instance->RTOR, USART_RTOR_BLEN, ((uint32_t)BlockLength << SMARTCARD_RTOR_BLEN_LSB_POS)); +} + +/** + * @brief Update on the fly the receiver timeout value in RTOR register + * @param hsmartcard: SMARTCARD handle + * @param TimeOutValue: receiver timeout value in number of baud blocks. The timeout + * value must be less or equal to 0x0FFFFFFFF. + * @retval None + */ +void HAL_SMARTCARDEx_TimeOut_Config(SMARTCARD_HandleTypeDef *hsmartcard, uint32_t TimeOutValue) +{ + assert_param(IS_SMARTCARD_TIMEOUT_VALUE(hsmartcard->Init.TimeOutValue)); + MODIFY_REG(hsmartcard->Instance->RTOR, USART_RTOR_RTO, TimeOutValue); +} + +/** + * @brief Enable the SMARTCARD receiver timeout feature + * @param hsmartcard: SMARTCARD handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMARTCARDEx_EnableReceiverTimeOut(SMARTCARD_HandleTypeDef *hsmartcard) +{ + + /* Process Locked */ + __HAL_LOCK(hsmartcard); + + hsmartcard->State = HAL_SMARTCARD_STATE_BUSY; + + /* Set the USART RTOEN bit */ + hsmartcard->Instance->CR2 |= USART_CR2_RTOEN; + + hsmartcard->State = HAL_SMARTCARD_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hsmartcard); + + return HAL_OK; +} + +/** + * @brief Disable the SMARTCARD receiver timeout feature + * @param hsmartcard: SMARTCARD handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMARTCARDEx_DisableReceiverTimeOut(SMARTCARD_HandleTypeDef *hsmartcard) +{ + + /* Process Locked */ + __HAL_LOCK(hsmartcard); + + hsmartcard->State = HAL_SMARTCARD_STATE_BUSY; + + /* Clear the USART RTOEN bit */ + hsmartcard->Instance->CR2 &= ~(USART_CR2_RTOEN); + + hsmartcard->State = HAL_SMARTCARD_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hsmartcard); + + return HAL_OK; +} + +/** + * @} + */ + +/** + * @} + */ + +#endif /* !defined(STM32F030x6) && !defined(STM32F030x8) */ + +#endif /* HAL_SMARTCARD_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_smartcard_ex.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_smartcard_ex.h new file mode 100644 index 0000000000..78287a2576 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_smartcard_ex.h @@ -0,0 +1,221 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_smartcard_ex.h + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief Header file of SMARTCARD HAL module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32F0xx_HAL_SMARTCARD_EX_H +#define __STM32F0xx_HAL_SMARTCARD_EX_H + +#ifdef __cplusplus + extern "C" { +#endif + +#if !defined(STM32F030x6) && !defined(STM32F030x8) + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal_def.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @addtogroup SMARTCARDEx + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/* Exported constants --------------------------------------------------------*/ +/* Exported macro ------------------------------------------------------------*/ + +/** @defgroup SMARTCARD_Extended_Exported_Macros + * @{ + */ + +/** @brief Reports the SMARTCARD clock source. + * @param __HANDLE__: specifies the SMARTCARD Handle + * @param __CLOCKSOURCE__ : output variable + * @retval the SMARTCARD clocking source, written in __CLOCKSOURCE__. + */ +#if defined(STM32F031x6) || defined(STM32F038xx) +#define __HAL_SMARTCARD_GETCLOCKSOURCE(__HANDLE__,__CLOCKSOURCE__) \ + do { \ + switch(__HAL_RCC_GET_USART1_SOURCE()) \ + { \ + case RCC_USART1CLKSOURCE_PCLK1: \ + (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_PCLK1; \ + break; \ + case RCC_USART1CLKSOURCE_HSI: \ + (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_HSI; \ + break; \ + case RCC_USART1CLKSOURCE_SYSCLK: \ + (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_SYSCLK; \ + break; \ + case RCC_USART1CLKSOURCE_LSE: \ + (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_LSE; \ + break; \ + default: \ + (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_UNDEFINED; \ + break; \ + } \ + } while(0) +#elif defined (STM32F030x8) || \ + defined (STM32F042x6) || defined (STM32F048xx) || \ + defined (STM32F051x8) || defined (STM32F058xx) +#define __HAL_SMARTCARD_GETCLOCKSOURCE(__HANDLE__,__CLOCKSOURCE__) \ + do { \ + if((__HANDLE__)->Instance == USART1) \ + { \ + switch(__HAL_RCC_GET_USART1_SOURCE()) \ + { \ + case RCC_USART1CLKSOURCE_PCLK1: \ + (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_PCLK1; \ + break; \ + case RCC_USART1CLKSOURCE_HSI: \ + (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_HSI; \ + break; \ + case RCC_USART1CLKSOURCE_SYSCLK: \ + (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_SYSCLK; \ + break; \ + case RCC_USART1CLKSOURCE_LSE: \ + (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_LSE; \ + break; \ + default: \ + (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_UNDEFINED; \ + break; \ + } \ + } \ + else if((__HANDLE__)->Instance == USART2) \ + { \ + (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_PCLK1; \ + } \ + else \ + { \ + (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_UNDEFINED; \ + } \ + } while(0) +#elif defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) +#define __HAL_SMARTCARD_GETCLOCKSOURCE(__HANDLE__,__CLOCKSOURCE__) \ + do { \ + if((__HANDLE__)->Instance == USART1) \ + { \ + switch(__HAL_RCC_GET_USART1_SOURCE()) \ + { \ + case RCC_USART1CLKSOURCE_PCLK1: \ + (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_PCLK1; \ + break; \ + case RCC_USART1CLKSOURCE_HSI: \ + (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_HSI; \ + break; \ + case RCC_USART1CLKSOURCE_SYSCLK: \ + (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_SYSCLK; \ + break; \ + case RCC_USART1CLKSOURCE_LSE: \ + (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_LSE; \ + break; \ + default: \ + (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_UNDEFINED; \ + break; \ + } \ + } \ + else if((__HANDLE__)->Instance == USART2) \ + { \ + switch(__HAL_RCC_GET_USART2_SOURCE()) \ + { \ + case RCC_USART2CLKSOURCE_PCLK1: \ + (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_PCLK1; \ + break; \ + case RCC_USART2CLKSOURCE_HSI: \ + (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_HSI; \ + break; \ + case RCC_USART2CLKSOURCE_SYSCLK: \ + (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_SYSCLK; \ + break; \ + case RCC_USART2CLKSOURCE_LSE: \ + (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_LSE; \ + break; \ + default: \ + (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_UNDEFINED; \ + break; \ + } \ + } \ + else if((__HANDLE__)->Instance == USART3) \ + { \ + (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_PCLK1; \ + } \ + else if((__HANDLE__)->Instance == USART4) \ + { \ + (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_PCLK1; \ + } \ + else \ + { \ + (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_UNDEFINED; \ + } \ + } while(0) +#endif /* defined(STM32F031x6) || defined(STM32F038xx) */ + +/** + * @} + */ + + +/* Exported functions --------------------------------------------------------*/ +/* Initialization and de-initialization functions ****************************/ +/* IO operation functions *****************************************************/ +/* Peripheral Control functions ***********************************************/ +void HAL_SMARTCARDEx_BlockLength_Config(SMARTCARD_HandleTypeDef *hsmartcard, uint8_t BlockLength); +void HAL_SMARTCARDEx_TimeOut_Config(SMARTCARD_HandleTypeDef *hsmartcard, uint32_t TimeOutValue); +HAL_StatusTypeDef HAL_SMARTCARDEx_EnableReceiverTimeOut(SMARTCARD_HandleTypeDef *hsmartcard); +HAL_StatusTypeDef HAL_SMARTCARDEx_DisableReceiverTimeOut(SMARTCARD_HandleTypeDef *hsmartcard); + +/* Peripheral State and Error functions ***************************************/ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* !defined(STM32F030x6) && !defined(STM32F030x8) */ + +#ifdef __cplusplus +} +#endif + +#endif /* __STM32F0xx_HAL_SMARTCARD_EX_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_smbus.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_smbus.c new file mode 100644 index 0000000000..a422af8cea --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_smbus.c @@ -0,0 +1,1902 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_smbus.c + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief SMBUS HAL module driver. + * + * This file provides firmware functions to manage the following + * functionalities of the System Management Bus (SMBus) peripheral, + * based on I2C principales of operation : + * + Initialization and de-initialization functions + * + IO operation functions + * + Peripheral State and Errors functions + * + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + The SMBUS HAL driver can be used as follows: + + (#) Declare a SMBUS_HandleTypeDef handle structure, for example: + SMBUS_HandleTypeDef hsmbus; + + (#)Initialize the SMBUS low level resources by implement the HAL_SMBUS_MspInit ()API: + (##) Enable the SMBUSx interface clock + (##) SMBUS pins configuration + (+++) Enable the clock for the SMBUS GPIOs + (+++) Configure SMBUS pins as alternate function open-drain + (##) NVIC configuration if you need to use interrupt process + (+++) Configure the SMBUSx interrupt priority + (+++) Enable the NVIC SMBUS IRQ Channel + + (#) Configure the Communication Clock Timing, Bus Timeout, Own Address1, Master Adressing Mode, + Dual Addressing mode, Own Address2, Own Address2 Mask, General call, Nostretch mode, + Peripheral mode and Packet Error Check mode in the hsmbus Init structure. + + (#) Initialize the SMBUS registers by calling the HAL_SMBUS_Init() API: + (+) These API's configures also the low level Hardware GPIO, CLOCK, CORTEX...etc) + by calling the customed HAL_SMBUS_MspInit(&hsmbus) API. + + (#) To check if target device is ready for communication, use the function HAL_SMBUS_IsDeviceReady() + + (#) For SMBUS IO operations, only one mode of operations is available within this driver : + + *** Interrupt mode IO operation *** + =================================== + [..] + (+) Transmit in master/host SMBUS mode an amount of data in non blocking mode using HAL_SMBUS_Master_Transmit_IT() + (++) At transmission end of transfer HAL_SMBUS_MasterTxCpltCallback is executed and user can + add his own code by customization of function pointer HAL_SMBUS_MasterTxCpltCallback + (+) Receive in master/host SMBUS mode an amount of data in non blocking mode using HAL_SMBUS_Master_Receive_IT() + (++) At reception end of transfer HAL_SMBUS_MasterRxCpltCallback is executed and user can + add his own code by customization of function pointer HAL_SMBUS_MasterRxCpltCallback + (+) Abort a master/host SMBUS process commnunication with Interrupt using HAL_SMBUS_Master_Abort_IT() + (++) The associated previous transfer callback is called at the end of abort process + (++) mean HAL_SMBUS_MasterTxCpltCallback in case of previous state was master transmit + (++) mean HAL_SMBUS_MasterRxCpltCallback in case of previous state was master receive + (+) Enable/disable the Address listen mode in slave/device or host/slave SMBUS mode + using HAL_SMBUS_Slave_Listen_IT() HAL_SMBUS_DisableListen_IT() + (++) When address slave/device SMBUS match, HAL_SMBUS_SlaveAddrCallback is executed and user can + add his own code to check the Address Match Code and the transmission direction request by master/host (Write/Read). + (++) At Listen mode end HAL_SMBUS_SlaveListenCpltCallback is executed and user can + add his own code by customization of function pointer HAL_SMBUS_SlaveListenCpltCallback + (+) Transmit in slave/device SMBUS mode an amount of data in non blocking mode using HAL_SMBUS_Slave_Transmit_IT() + (++) At transmission end of transfer HAL_SMBUS_SlaveTxCpltCallback is executed and user can + add his own code by customization of function pointer HAL_SMBUS_SlaveTxCpltCallback + (+) Receive in slave/device SMBUS mode an amount of data in non blocking mode using HAL_SMBUS_Slave_Receive_IT() + (++) At reception end of transfer HAL_SMBUS_SlaveRxCpltCallback is executed and user can + add his own code by customization of function pointer HAL_SMBUS_SlaveRxCpltCallback + (+) Enable/Disable the SMBUS alert mode using HAL_SMBUS_EnableAlert_IT() HAL_SMBUS_DisableAlert_IT() + (++) When SMBUS Alert is generated HAL_SMBUS_ErrorCallback() is executed and user can + add his own code by customization of function pointer HAL_SMBUS_ErrorCallback + to check the Alert Error Code using function HAL_SMBUS_GetError() + (+) Get HAL state machine or error values using HAL_SMBUS_GetState() or HAL_SMBUS_GetError() + (+) In case of transfer Error, HAL_SMBUS_ErrorCallback() function is executed and user can + add his own code by customization of function pointer HAL_SMBUS_ErrorCallback + to check the Error Code using function HAL_SMBUS_GetError() + + *** SMBUS HAL driver macros list *** + ================================== + [..] + Below the list of most used macros in SMBUS HAL driver. + + (+) __HAL_SMBUS_ENABLE: Enable the SMBUS peripheral + (+) __HAL_SMBUS_DISABLE: Disable the SMBUS peripheral + (+) __HAL_SMBUS_GET_FLAG : Checks whether the specified SMBUS flag is set or not + (+) __HAL_SMBUS_CLEAR_FLAG : Clears the specified SMBUS pending flag + (+) __HAL_SMBUS_ENABLE_IT: Enables the specified SMBUS interrupt + (+) __HAL_SMBUS_DISABLE_IT: Disables the specified SMBUS interrupt + + [..] + (@) You can refer to the SMBUS HAL driver header file for more useful macros + + + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @defgroup SMBUS + * @brief SMBUS HAL module driver + * @{ + */ + +#ifdef HAL_SMBUS_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +#define TIMING_CLEAR_MASK ((uint32_t)0xF0FFFFFF) /*Instance->ISR) +#define __SMBUS_CHECK_FLAG(__ISR__, __FLAG__) ((((__ISR__) & ((__FLAG__) & SMBUS_FLAG_MASK)) == ((__FLAG__) & SMBUS_FLAG_MASK))) + +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +static HAL_StatusTypeDef SMBUS_WaitOnFlagUntilTimeout(SMBUS_HandleTypeDef *hsmbus, uint32_t Flag, FlagStatus Status, uint32_t Timeout); + +static HAL_StatusTypeDef SMBUS_Enable_IRQ(SMBUS_HandleTypeDef *hsmbus, uint16_t InterruptRequest); +static HAL_StatusTypeDef SMBUS_Disable_IRQ(SMBUS_HandleTypeDef *hsmbus, uint16_t InterruptRequest); +static HAL_StatusTypeDef SMBUS_Master_ISR(SMBUS_HandleTypeDef *hsmbus); +static HAL_StatusTypeDef SMBUS_Slave_ISR(SMBUS_HandleTypeDef *hsmbus); + +static void SMBUS_TransferConfig(SMBUS_HandleTypeDef *hsmbus, uint16_t DevAddress, uint8_t Size, uint32_t Mode, uint32_t Request); + +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup SMBUS_Private_Functions + * @{ + */ + +/** @defgroup HAL_SMBUS_Group1 Initialization and de-initialization functions + * @brief Initialization and Configuration functions + * +@verbatim + =============================================================================== + ##### Initialization and de-initialization functions ##### + =============================================================================== + [..] This subsection provides a set of functions allowing to initialize and + de-initialiaze the SMBUSx peripheral: + + (+) User must Implement HAL_SMBUS_MspInit() function in which he configures + all related peripherals resources (CLOCK, GPIO, IT and NVIC ). + + (+) Call the function HAL_SMBUS_Init() to configure the selected device with + the selected configuration: + (++) Clock Timing + (++) Bus Timeout + (++) Analog Filer mode + (++) Own Address 1 + (++) Addressing mode (Master, Slave) + (++) Dual Addressing mode + (++) Own Address 2 + (++) Own Address 2 Mask + (++) General call mode + (++) Nostretch mode + (++) Packet Error Check mode + (++) Peripheral mode + + + (+) Call the function HAL_SMBUS_DeInit() to restore the default configuration + of the selected SMBUSx periperal. + +@endverbatim + * @{ + */ + +/** + * @brief Initializes the SMBUS according to the specified parameters + * in the SMBUS_InitTypeDef and create the associated handle. + * @param hsmbus : Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMBUS_Init(SMBUS_HandleTypeDef *hsmbus) +{ + /* Check the SMBUS handle allocation */ + if(hsmbus == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_SMBUS_ALL_INSTANCE(hsmbus->Instance)); + assert_param(IS_SMBUS_ANALOG_FILTER(hsmbus->Init.AnalogFilter)); + assert_param(IS_SMBUS_OWN_ADDRESS1(hsmbus->Init.OwnAddress1)); + assert_param(IS_SMBUS_ADDRESSING_MODE(hsmbus->Init.AddressingMode)); + assert_param(IS_SMBUS_DUAL_ADDRESS(hsmbus->Init.DualAddressMode)); + assert_param(IS_SMBUS_OWN_ADDRESS2(hsmbus->Init.OwnAddress2)); + assert_param(IS_SMBUS_OWN_ADDRESS2_MASK(hsmbus->Init.OwnAddress2Masks)); + assert_param(IS_SMBUS_GENERAL_CALL(hsmbus->Init.GeneralCallMode)); + assert_param(IS_SMBUS_NO_STRETCH(hsmbus->Init.NoStretchMode)); + assert_param(IS_SMBUS_PEC(hsmbus->Init.PacketErrorCheckMode)); + assert_param(IS_SMBUS_PERIPHERAL_MODE(hsmbus->Init.PeripheralMode)); + + if(hsmbus->State == HAL_SMBUS_STATE_RESET) + { + /* Init the low level hardware : GPIO, CLOCK, NVIC */ + HAL_SMBUS_MspInit(hsmbus); + } + + hsmbus->State = HAL_SMBUS_STATE_BUSY; + + /* Disable the selected SMBUS peripheral */ + __HAL_SMBUS_DISABLE(hsmbus); + + /*---------------------------- SMBUSx TIMINGR Configuration ------------------------*/ + /* Configure SMBUSx: Frequency range */ + hsmbus->Instance->TIMINGR = hsmbus->Init.Timing & TIMING_CLEAR_MASK; + + /*---------------------------- SMBUSx TIMEOUTR Configuration ------------------------*/ + /* Configure SMBUSx: Bus Timeout */ + hsmbus->Instance->TIMEOUTR &= ~I2C_TIMEOUTR_TIMOUTEN; + hsmbus->Instance->TIMEOUTR &= ~I2C_TIMEOUTR_TEXTEN; + hsmbus->Instance->TIMEOUTR = hsmbus->Init.SMBusTimeout; + + /*---------------------------- SMBUSx OAR1 Configuration -----------------------*/ + /* Configure SMBUSx: Own Address1 and ack own address1 mode */ + hsmbus->Instance->OAR1 &= ~I2C_OAR1_OA1EN; + + if(hsmbus->Init.OwnAddress1 != 0) + { + if(hsmbus->Init.AddressingMode == SMBUS_ADDRESSINGMODE_7BIT) + { + hsmbus->Instance->OAR1 = (I2C_OAR1_OA1EN | hsmbus->Init.OwnAddress1); + } + else /* SMBUS_ADDRESSINGMODE_10BIT */ + { + hsmbus->Instance->OAR1 = (I2C_OAR1_OA1EN | I2C_OAR1_OA1MODE | hsmbus->Init.OwnAddress1); + } + } + + /*---------------------------- SMBUSx CR2 Configuration ------------------------*/ + /* Configure SMBUSx: Addressing Master mode */ + if(hsmbus->Init.AddressingMode == SMBUS_ADDRESSINGMODE_10BIT) + { + hsmbus->Instance->CR2 = (I2C_CR2_ADD10); + } + /* Enable the AUTOEND by default, and enable NACK (should be disable only during Slave process) */ + /* AUTOEND and NACK bit will be manage during Transfer process */ + hsmbus->Instance->CR2 |= (I2C_CR2_AUTOEND | I2C_CR2_NACK); + + /*---------------------------- SMBUSx OAR2 Configuration -----------------------*/ + /* Configure SMBUSx: Dual mode and Own Address2 */ + hsmbus->Instance->OAR2 = (hsmbus->Init.DualAddressMode | hsmbus->Init.OwnAddress2 | (hsmbus->Init.OwnAddress2Masks << 8)); + + /*---------------------------- SMBUSx CR1 Configuration ------------------------*/ + /* Configure SMBUSx: Generalcall and NoStretch mode */ + hsmbus->Instance->CR1 = (hsmbus->Init.GeneralCallMode | hsmbus->Init.NoStretchMode | hsmbus->Init.PacketErrorCheckMode | hsmbus->Init.PeripheralMode | hsmbus->Init.AnalogFilter); + + /* Enable Slave Byte Control only in case of Packet Error Check is enabled and SMBUS Peripheral is set in Slave mode */ + if( (hsmbus->Init.PacketErrorCheckMode == SMBUS_PEC_ENABLED) + && ( (hsmbus->Init.PeripheralMode == SMBUS_PERIPHERAL_MODE_SMBUS_SLAVE) || (hsmbus->Init.PeripheralMode == SMBUS_PERIPHERAL_MODE_SMBUS_SLAVE_ARP) ) ) + { + hsmbus->Instance->CR1 |= I2C_CR1_SBC; + } + + /* Enable the selected SMBUS peripheral */ + __HAL_SMBUS_ENABLE(hsmbus); + + hsmbus->ErrorCode = HAL_SMBUS_ERROR_NONE; + hsmbus->PreviousState = HAL_SMBUS_STATE_READY; + hsmbus->State = HAL_SMBUS_STATE_READY; + + return HAL_OK; +} + +/** + * @brief DeInitializes the SMBUS peripheral. + * @param hsmbus : Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMBUS_DeInit(SMBUS_HandleTypeDef *hsmbus) +{ + /* Check the SMBUS handle allocation */ + if(hsmbus == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_SMBUS_ALL_INSTANCE(hsmbus->Instance)); + + hsmbus->State = HAL_SMBUS_STATE_BUSY; + + /* Disable the SMBUS Peripheral Clock */ + __HAL_SMBUS_DISABLE(hsmbus); + + /* DeInit the low level hardware: GPIO, CLOCK, NVIC */ + HAL_SMBUS_MspDeInit(hsmbus); + + hsmbus->ErrorCode = HAL_SMBUS_ERROR_NONE; + hsmbus->PreviousState = HAL_SMBUS_STATE_RESET; + hsmbus->State = HAL_SMBUS_STATE_RESET; + + /* Release Lock */ + __HAL_UNLOCK(hsmbus); + + return HAL_OK; +} + +/** + * @brief SMBUS MSP Init. + * @param hsmbus : Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @retval None + */ + __weak void HAL_SMBUS_MspInit(SMBUS_HandleTypeDef *hsmbus) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_SMBUS_MspInit could be implemented in the user file + */ +} + +/** + * @brief SMBUS MSP DeInit + * @param hsmbus : Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @retval None + */ + __weak void HAL_SMBUS_MspDeInit(SMBUS_HandleTypeDef *hsmbus) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_SMBUS_MspDeInit could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup HAL_SMBUS_Group2 IO operation functions + * @brief Data transfers functions + * +@verbatim + =============================================================================== + ##### IO operation functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to manage the SMBUS data + transfers. + + (#) Blocking mode function to check if device is ready for usage is : + (++) HAL_SMBUS_IsDeviceReady() + + (#) There is only one mode of transfer: + (++) No-Blocking mode : The communication is performed using Interrupts. + These functions return the status of the transfer startup. + The end of the data processing will be indicated through the + dedicated SMBUS IRQ when using Interrupt mode. + + (#) No-Blocking mode functions with Interrupt are : + (++) HAL_SMBUS_Master_Transmit_IT() + (++) HAL_SMBUS_Master_Receive_IT() + (++) HAL_SMBUS_Slave_Transmit_IT() + (++) HAL_SMBUS_Slave_Receive_IT() + (++) HAL_SMBUS_EnableListen_IT() + (++) HAL_SMBUS_DisableListen_IT() + (++) HAL_SMBUS_EnableAlert_IT() + (++) HAL_SMBUS_DisableAlert_IT() + + (#) A set of Transfer Complete Callbacks are provided in No_Blocking mode: + (++) HAL_SMBUS_MasterTxCpltCallback() + (++) HAL_SMBUS_MasterRxCpltCallback() + (++) HAL_SMBUS_SlaveTxCpltCallback() + (++) HAL_SMBUS_SlaveRxCpltCallback() + (++) HAL_SMBUS_AddrCallback() + (++) HAL_SMBUS_ListenCpltCallback() + (++) HAL_SMBUS_ErrorCallback() + +@endverbatim + * @{ + */ + +/** + * @brief Transmit in master/host SMBUS mode an amount of data in no-blocking mode with Interrupt + * @param hsmbus : Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @param DevAddress: Target device address + * @param pData: Pointer to data buffer + * @param Size: Amount of data to be sent + * @param XferOptions: Options of Transfer, value of @ref SMBUS_XferOptions_definition + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMBUS_Master_Transmit_IT(SMBUS_HandleTypeDef *hsmbus, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t XferOptions) +{ + /* Check the parameters */ + assert_param(IS_SMBUS_TRANSFER_OPTIONS_REQUEST(XferOptions)); + + if(hsmbus->State == HAL_SMBUS_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hsmbus); + + hsmbus->State = HAL_SMBUS_STATE_MASTER_BUSY_TX; + hsmbus->ErrorCode = HAL_SMBUS_ERROR_NONE; + /* Prepare transfer parameters */ + hsmbus->pBuffPtr = pData; + hsmbus->XferCount = Size; + hsmbus->XferOptions = XferOptions; + + /* In case of Quick command, remove autoend mode */ + /* Manage the stop generation by software */ + if(hsmbus->pBuffPtr == NULL) + { + hsmbus->XferOptions &= ~SMBUS_AUTOEND_MODE; + } + + if(Size > MAX_NBYTE_SIZE) + { + hsmbus->XferSize = MAX_NBYTE_SIZE; + } + else + { + hsmbus->XferSize = Size; + } + + /* Send Slave Address */ + /* Set NBYTES to write and reload if size > MAX_NBYTE_SIZE and generate RESTART */ + if( (hsmbus->XferSize == MAX_NBYTE_SIZE) && (hsmbus->XferSize < hsmbus->XferCount) ) + { + SMBUS_TransferConfig(hsmbus,DevAddress,hsmbus->XferSize, SMBUS_RELOAD_MODE | (hsmbus->XferOptions & SMBUS_SENDPEC_MODE), SMBUS_GENERATE_START_WRITE); + } + else + { + /* If transfer direction not change, do not generate Restart Condition */ + /* Mean Previous state is same as current state */ + if(hsmbus->PreviousState == HAL_SMBUS_STATE_MASTER_BUSY_TX) + { + SMBUS_TransferConfig(hsmbus,DevAddress,hsmbus->XferSize, hsmbus->XferOptions, SMBUS_NO_STARTSTOP); + } + /* Else transfer direction change, so generate Restart with new transfer direction */ + else + { + SMBUS_TransferConfig(hsmbus,DevAddress,hsmbus->XferSize, hsmbus->XferOptions, SMBUS_GENERATE_START_WRITE); + } + + /* If PEC mode is enable, size to transmit manage by SW part should be Size-1 byte, corresponding to PEC byte */ + /* PEC byte is automatically sent by HW block, no need to manage it in Transmit process */ + if(__HAL_SMBUS_GET_PEC_MODE(hsmbus) != RESET) + { + hsmbus->XferSize--; + hsmbus->XferCount--; + } + } + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + /* Note : The SMBUS interrupts must be enabled after unlocking current process + to avoid the risk of SMBUS interrupt handle execution before current + process unlock */ + SMBUS_Enable_IRQ(hsmbus, SMBUS_IT_TX); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive in master/host SMBUS mode an amount of data in no-blocking mode with Interrupt + * @param hsmbus : Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @param DevAddress: Target device address + * @param pData: Pointer to data buffer + * @param Size: Amount of data to be sent + * @param XferOptions: Options of Transfer, value of @ref SMBUS_XferOptions_definition + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMBUS_Master_Receive_IT(SMBUS_HandleTypeDef *hsmbus, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t XferOptions) +{ + /* Check the parameters */ + assert_param(IS_SMBUS_TRANSFER_OPTIONS_REQUEST(XferOptions)); + + if(hsmbus->State == HAL_SMBUS_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hsmbus); + + hsmbus->State = HAL_SMBUS_STATE_MASTER_BUSY_RX; + hsmbus->ErrorCode = HAL_SMBUS_ERROR_NONE; + + /* Prepare transfer parameters */ + hsmbus->pBuffPtr = pData; + hsmbus->XferCount = Size; + hsmbus->XferOptions = XferOptions; + + /* In case of Quick command, remove autoend mode */ + /* Manage the stop generation by software */ + if(hsmbus->pBuffPtr == NULL) + { + hsmbus->XferOptions &= ~SMBUS_AUTOEND_MODE; + } + + if(Size > MAX_NBYTE_SIZE) + { + hsmbus->XferSize = MAX_NBYTE_SIZE; + } + else + { + hsmbus->XferSize = Size; + } + + /* Send Slave Address */ + /* Set NBYTES to write and reload if size > MAX_NBYTE_SIZE and generate RESTART */ + if( (hsmbus->XferSize == MAX_NBYTE_SIZE) && (hsmbus->XferSize < hsmbus->XferCount) ) + { + SMBUS_TransferConfig(hsmbus,DevAddress,hsmbus->XferSize, SMBUS_RELOAD_MODE | (hsmbus->XferOptions & SMBUS_SENDPEC_MODE), SMBUS_GENERATE_START_READ); + } + else + { + /* If transfer direction not change, do not generate Restart Condition */ + /* Mean Previous state is same as current state */ + if(hsmbus->PreviousState == HAL_SMBUS_STATE_MASTER_BUSY_RX) + { + SMBUS_TransferConfig(hsmbus,DevAddress,hsmbus->XferSize, hsmbus->XferOptions, SMBUS_NO_STARTSTOP); + } + /* Else transfer direction change, so generate Restart with new transfer direction */ + else + { + SMBUS_TransferConfig(hsmbus,DevAddress,hsmbus->XferSize, hsmbus->XferOptions, SMBUS_GENERATE_START_READ); + } + } + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + /* Note : The SMBUS interrupts must be enabled after unlocking current process + to avoid the risk of SMBUS interrupt handle execution before current + process unlock */ + SMBUS_Enable_IRQ(hsmbus, SMBUS_IT_RX); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Abort a master/host SMBUS process commnunication with Interrupt + * @note : This abort can be called only if state is ready + * @param hsmbus : Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @param DevAddress: Target device address + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMBUS_Master_Abort_IT(SMBUS_HandleTypeDef *hsmbus, uint16_t DevAddress) +{ + if(hsmbus->State == HAL_SMBUS_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hsmbus); + + /* Keep the same state as previous */ + /* to perform as well the call of the corresponding end of transfer callback */ + if(hsmbus->PreviousState == HAL_SMBUS_STATE_MASTER_BUSY_TX) + { + hsmbus->State = HAL_SMBUS_STATE_MASTER_BUSY_TX; + } + else if(hsmbus->PreviousState == HAL_SMBUS_STATE_MASTER_BUSY_RX) + { + hsmbus->State = HAL_SMBUS_STATE_MASTER_BUSY_RX; + } + else + { + /* Wrong usage of abort function */ + /* This function should be used only in case of abort monitored by master device */ + return HAL_ERROR; + } + hsmbus->ErrorCode = HAL_SMBUS_ERROR_NONE; + + /* Set NBYTES to 1 to generate a dummy read on SMBUS peripheral */ + /* Set AUTOEND mode, this will generate a NACK then STOP condition to abort the current transfer */ + SMBUS_TransferConfig(hsmbus, DevAddress, 1, SMBUS_AUTOEND_MODE, SMBUS_NO_STARTSTOP); + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + /* Note : The SMBUS interrupts must be enabled after unlocking current process + to avoid the risk of SMBUS interrupt handle execution before current + process unlock */ + if(hsmbus->State == HAL_SMBUS_STATE_MASTER_BUSY_TX) + { + SMBUS_Enable_IRQ(hsmbus, SMBUS_IT_TX); + } + else if(hsmbus->State == HAL_SMBUS_STATE_MASTER_BUSY_RX) + { + SMBUS_Enable_IRQ(hsmbus, SMBUS_IT_RX); + } + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Transmit in slave/device SMBUS mode an amount of data in no-blocking mode with Interrupt + * @param hsmbus : Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @param pData: Pointer to data buffer + * @param Size: Amount of data to be sent + * @param XferOptions: Options of Transfer, value of @ref SMBUS_XferOptions_definition + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMBUS_Slave_Transmit_IT(SMBUS_HandleTypeDef *hsmbus, uint8_t *pData, uint16_t Size, uint32_t XferOptions) +{ + /* Check the parameters */ + assert_param(IS_SMBUS_TRANSFER_OPTIONS_REQUEST(XferOptions)); + + if(hsmbus->State == HAL_SMBUS_STATE_LISTEN) + { + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + /* Disable Interrupts, to prevent preemption during treatment in case of multicall */ + SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_ADDR | SMBUS_IT_TX); + + /* Process Locked */ + __HAL_LOCK(hsmbus); + + hsmbus->State |= HAL_SMBUS_STATE_SLAVE_BUSY_TX; + hsmbus->ErrorCode = HAL_SMBUS_ERROR_NONE; + + /* Enable Address Acknowledge */ + hsmbus->Instance->CR2 &= ~I2C_CR2_NACK; + + /* Prepare transfer parameters */ + hsmbus->pBuffPtr = pData; + hsmbus->XferSize = Size; + hsmbus->XferCount = Size; + hsmbus->XferOptions = XferOptions; + + if(Size > MAX_NBYTE_SIZE) + { + hsmbus->XferSize = MAX_NBYTE_SIZE; + } + else + { + hsmbus->XferSize = Size; + } + + /* Set NBYTES to write and reload if size > MAX_NBYTE_SIZE and generate RESTART */ + if( (hsmbus->XferSize == MAX_NBYTE_SIZE) && (hsmbus->XferSize < hsmbus->XferCount) ) + { + SMBUS_TransferConfig(hsmbus,0,hsmbus->XferSize, SMBUS_RELOAD_MODE | (hsmbus->XferOptions & SMBUS_SENDPEC_MODE), SMBUS_NO_STARTSTOP); + } + else + { + /* Set NBYTE to transmit */ + SMBUS_TransferConfig(hsmbus,0,hsmbus->XferSize, hsmbus->XferOptions, SMBUS_NO_STARTSTOP); + + /* If PEC mode is enable, size to transmit should be Size-1 byte, corresponding to PEC byte */ + /* PEC byte is automatically sent by HW block, no need to manage it in Transmit process */ + if(__HAL_SMBUS_GET_PEC_MODE(hsmbus) != RESET) + { + hsmbus->XferSize--; + hsmbus->XferCount--; + } + } + + /* Clear ADDR flag after prepare the transfer parameters */ + /* This action will generate an acknowledge to the HOST */ + __HAL_SMBUS_CLEAR_FLAG(hsmbus,SMBUS_FLAG_ADDR); + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + /* Note : The SMBUS interrupts must be enabled after unlocking current process + to avoid the risk of SMBUS interrupt handle execution before current + process unlock */ + /* REnable ADDR interrupt */ + SMBUS_Enable_IRQ(hsmbus, SMBUS_IT_TX | SMBUS_IT_ADDR); + + return HAL_OK; + } + else + { + return HAL_ERROR; + } +} + +/** + * @brief Receive in slave/device SMBUS mode an amount of data in no-blocking mode with Interrupt + * @param hsmbus : Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @param pData: Pointer to data buffer + * @param Size: Amount of data to be sent + * @param XferOptions: Options of Transfer, value of @ref SMBUS_XferOptions_definition + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMBUS_Slave_Receive_IT(SMBUS_HandleTypeDef *hsmbus, uint8_t *pData, uint16_t Size, uint32_t XferOptions) +{ + /* Check the parameters */ + assert_param(IS_SMBUS_TRANSFER_OPTIONS_REQUEST(XferOptions)); + + if(hsmbus->State == HAL_SMBUS_STATE_LISTEN) + { + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + /* Disable Interrupts, to prevent preemption during treatment in case of multicall */ + SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_ADDR | SMBUS_IT_RX); + + /* Process Locked */ + __HAL_LOCK(hsmbus); + + hsmbus->State |= HAL_SMBUS_STATE_SLAVE_BUSY_RX; + hsmbus->ErrorCode = HAL_SMBUS_ERROR_NONE; + + /* Enable Address Acknowledge */ + hsmbus->Instance->CR2 &= ~I2C_CR2_NACK; + + /* Prepare transfer parameters */ + hsmbus->pBuffPtr = pData; + hsmbus->XferSize = Size; + hsmbus->XferCount = Size; + hsmbus->XferOptions = XferOptions; + + /* Set NBYTE to receive */ + /* If XferSize equal "1", or XferSize equal "2" with PEC requested (mean 1 data byte + 1 PEC byte */ + /* no need to set RELOAD bit mode, a ACK will be automatically generated in that case */ + /* else need to set RELOAD bit mode to generate an automatic ACK at each byte Received */ + /* This RELOAD bit will be reset for last BYTE to be receive in SMBUS_Slave_ISR */ + if((hsmbus->XferSize == 1) || ((hsmbus->XferSize == 2) && (__HAL_SMBUS_GET_PEC_MODE(hsmbus) != RESET))) + { + SMBUS_TransferConfig(hsmbus,0,hsmbus->XferSize, hsmbus->XferOptions, SMBUS_NO_STARTSTOP); + } + else + { + SMBUS_TransferConfig(hsmbus,0, 1, hsmbus->XferOptions | SMBUS_RELOAD_MODE, SMBUS_NO_STARTSTOP); + } + + /* Clear ADDR flag after prepare the transfer parameters */ + /* This action will generate an acknowledge to the HOST */ + __HAL_SMBUS_CLEAR_FLAG(hsmbus,SMBUS_FLAG_ADDR); + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + /* Note : The SMBUS interrupts must be enabled after unlocking current process + to avoid the risk of SMBUS interrupt handle execution before current + process unlock */ + /* REnable ADDR interrupt */ + SMBUS_Enable_IRQ(hsmbus, SMBUS_IT_RX | SMBUS_IT_ADDR); + + return HAL_OK; + } + else + { + return HAL_ERROR; + } +} + +/** + * @brief This function enable the Address listen mode + * @param hsmbus : Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMBUS_Slave_Listen_IT(SMBUS_HandleTypeDef *hsmbus) +{ + hsmbus->State = HAL_SMBUS_STATE_LISTEN; + + /* Enable the Address Match interrupt */ + SMBUS_Enable_IRQ(hsmbus, SMBUS_IT_ADDR); + + return HAL_OK; +} + +/** + * @brief This function disable the Address listen mode + * @param hsmbus : Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMBUS_DisableListen_IT(SMBUS_HandleTypeDef *hsmbus) +{ + /* Disable Address listen mode only if a transfer is not ongoing */ + if(hsmbus->State == HAL_SMBUS_STATE_LISTEN) + { + hsmbus->State = HAL_SMBUS_STATE_READY; + + /* Disable the Address Match interrupt */ + SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_ADDR); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief This function enable the SMBUS alert mode. + * @param hsmbus : pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUSx peripheral. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMBUS_EnableAlert_IT(SMBUS_HandleTypeDef *hsmbus) +{ + /* Enable SMBus alert */ + hsmbus->Instance->CR1 |= I2C_CR1_ALERTEN; + + /* Clear ALERT flag */ + __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_ALERT); + + /* Enable Alert Interrupt */ + SMBUS_Enable_IRQ(hsmbus, SMBUS_IT_ALERT); + + return HAL_OK; +} +/** + * @brief This function disable the SMBUS alert mode. + * @param hsmbus : pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUSx peripheral. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMBUS_DisableAlert_IT(SMBUS_HandleTypeDef *hsmbus) +{ + /* Enable SMBus alert */ + hsmbus->Instance->CR1 &= ~I2C_CR1_ALERTEN; + + /* Disable Alert Interrupt */ + SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_ALERT); + + return HAL_OK; +} +/** + * @brief Checks if target device is ready for communication. + * @note This function is used with Memory devices + * @param hsmbus : Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @param DevAddress: Target device address + * @param Trials: Number of trials + * @param Timeout: Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMBUS_IsDeviceReady(SMBUS_HandleTypeDef *hsmbus, uint16_t DevAddress, uint32_t Trials, uint32_t Timeout) +{ + uint32_t tickstart = 0; + + __IO uint32_t SMBUS_Trials = 0; + + if(hsmbus->State == HAL_SMBUS_STATE_READY) + { + if(__HAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_BUSY) != RESET) + { + return HAL_BUSY; + } + + /* Process Locked */ + __HAL_LOCK(hsmbus); + + hsmbus->State = HAL_SMBUS_STATE_BUSY; + hsmbus->ErrorCode = HAL_SMBUS_ERROR_NONE; + + do + { + /* Generate Start */ + hsmbus->Instance->CR2 = __HAL_SMBUS_GENERATE_START(hsmbus->Init.AddressingMode,DevAddress); + + /* No need to Check TC flag, with AUTOEND mode the stop is automatically generated */ + /* Wait until STOPF flag is set or a NACK flag is set*/ + tickstart = HAL_GetTick(); + while((__HAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_STOPF) == RESET) && (__HAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_AF) == RESET) && (hsmbus->State != HAL_SMBUS_STATE_TIMEOUT)) + { + if(Timeout != HAL_MAX_DELAY) + { + if((HAL_GetTick()-tickstart) >= Timeout) + { + /* Device is ready */ + hsmbus->State = HAL_SMBUS_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + return HAL_TIMEOUT; + } + } + } + + /* Check if the NACKF flag has not been set */ + if (__HAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_AF) == RESET) + { + /* Wait until STOPF flag is reset */ + if(SMBUS_WaitOnFlagUntilTimeout(hsmbus, SMBUS_FLAG_STOPF, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + /* Clear STOP Flag */ + __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_STOPF); + + /* Device is ready */ + hsmbus->State = HAL_SMBUS_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + return HAL_OK; + } + else + { + /* Wait until STOPF flag is reset */ + if(SMBUS_WaitOnFlagUntilTimeout(hsmbus, SMBUS_FLAG_STOPF, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + /* Clear NACK Flag */ + __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_AF); + + /* Clear STOP Flag, auto generated with autoend*/ + __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_STOPF); + } + + /* Check if the maximum allowed numbe of trials has bee reached */ + if (SMBUS_Trials++ == Trials) + { + /* Generate Stop */ + hsmbus->Instance->CR2 |= I2C_CR2_STOP; + + /* Wait until STOPF flag is reset */ + if(SMBUS_WaitOnFlagUntilTimeout(hsmbus, SMBUS_FLAG_STOPF, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + /* Clear STOP Flag */ + __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_STOPF); + } + }while(SMBUS_Trials++ < Trials); + + hsmbus->State = HAL_SMBUS_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + return HAL_TIMEOUT; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief This function handles SMBUS event interrupt request. + * @param hsmbus : Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @retval None + */ +void HAL_SMBUS_EV_IRQHandler(SMBUS_HandleTypeDef *hsmbus) +{ + uint32_t tmpisrvalue = 0; + + /* Use a local variable to store the current ISR flags */ + /* This action will avoid a wrong treatment due to ISR flags change during interrupt handler */ + tmpisrvalue = __SMBUS_GET_ISR_REG(hsmbus); + + /* SMBUS in mode Transmitter ---------------------------------------------------*/ + if (((__SMBUS_CHECK_FLAG(tmpisrvalue, SMBUS_FLAG_TXIS) != RESET) || (__SMBUS_CHECK_FLAG(tmpisrvalue, SMBUS_FLAG_TCR) != RESET) || (__SMBUS_CHECK_FLAG(tmpisrvalue, SMBUS_FLAG_TC) != RESET) || (__SMBUS_CHECK_FLAG(tmpisrvalue, SMBUS_FLAG_STOPF) != RESET) || (__SMBUS_CHECK_FLAG(tmpisrvalue, SMBUS_FLAG_AF) != RESET)) && (__HAL_SMBUS_GET_IT_SOURCE(hsmbus, (SMBUS_IT_TCI| SMBUS_IT_STOPI| SMBUS_IT_NACKI | SMBUS_IT_TXI)) != RESET)) + { + /* Slave mode selected */ + if ((hsmbus->State & HAL_SMBUS_STATE_SLAVE_BUSY_TX) == HAL_SMBUS_STATE_SLAVE_BUSY_TX) + { + SMBUS_Slave_ISR(hsmbus); + } + /* Master mode selected */ + else if((hsmbus->State & HAL_SMBUS_STATE_MASTER_BUSY_TX) == HAL_SMBUS_STATE_MASTER_BUSY_TX) + { + SMBUS_Master_ISR(hsmbus); + } + } + + /* SMBUS in mode Receiver ----------------------------------------------------*/ + if (((__SMBUS_CHECK_FLAG(tmpisrvalue, SMBUS_FLAG_RXNE) != RESET) || (__SMBUS_CHECK_FLAG(tmpisrvalue, SMBUS_FLAG_TCR) != RESET) || (__SMBUS_CHECK_FLAG(tmpisrvalue, SMBUS_FLAG_TC) != RESET) || (__SMBUS_CHECK_FLAG(tmpisrvalue, SMBUS_FLAG_STOPF) != RESET) || (__SMBUS_CHECK_FLAG(tmpisrvalue, SMBUS_FLAG_AF) != RESET)) && (__HAL_SMBUS_GET_IT_SOURCE(hsmbus, (SMBUS_IT_TCI| SMBUS_IT_STOPI| SMBUS_IT_NACKI | SMBUS_IT_RXI)) != RESET)) + { + /* Slave mode selected */ + if ((hsmbus->State & HAL_SMBUS_STATE_SLAVE_BUSY_RX) == HAL_SMBUS_STATE_SLAVE_BUSY_RX) + { + SMBUS_Slave_ISR(hsmbus); + } + /* Master mode selected */ + else if((hsmbus->State & HAL_SMBUS_STATE_MASTER_BUSY_RX) == HAL_SMBUS_STATE_MASTER_BUSY_RX) + { + SMBUS_Master_ISR(hsmbus); + } + } + + /* SMBUS in mode Listener Only --------------------------------------------------*/ + if (((__SMBUS_CHECK_FLAG(tmpisrvalue, SMBUS_FLAG_ADDR) != RESET) || (__SMBUS_CHECK_FLAG(tmpisrvalue, SMBUS_FLAG_STOPF) != RESET) || (__SMBUS_CHECK_FLAG(tmpisrvalue, SMBUS_FLAG_AF) != RESET)) + && ((__HAL_SMBUS_GET_IT_SOURCE(hsmbus, SMBUS_IT_ADDRI) != RESET) || (__HAL_SMBUS_GET_IT_SOURCE(hsmbus, SMBUS_IT_STOPI) != RESET) || (__HAL_SMBUS_GET_IT_SOURCE(hsmbus, SMBUS_IT_NACKI) != RESET))) + { + if (hsmbus->State == HAL_SMBUS_STATE_LISTEN) + { + SMBUS_Slave_ISR(hsmbus); + } + } +} + +/** + * @brief This function handles SMBUS error interrupt request. + * @param hsmbus : Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @retval None + */ +void HAL_SMBUS_ER_IRQHandler(SMBUS_HandleTypeDef *hsmbus) +{ + /* SMBUS Bus error interrupt occurred ------------------------------------*/ + if((__HAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_BERR) != RESET) && (__HAL_SMBUS_GET_IT_SOURCE(hsmbus, SMBUS_IT_ERRI) != RESET)) + { + hsmbus->ErrorCode |= HAL_SMBUS_ERROR_BERR; + + /* Clear BERR flag */ + __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_BERR); + } + + /* SMBUS Over-Run/Under-Run interrupt occurred ----------------------------------------*/ + if((__HAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_OVR) != RESET) && (__HAL_SMBUS_GET_IT_SOURCE(hsmbus, SMBUS_IT_ERRI) != RESET)) + { + hsmbus->ErrorCode |= HAL_SMBUS_ERROR_OVR; + + /* Clear OVR flag */ + __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_OVR); + } + + /* SMBUS Arbitration Loss error interrupt occurred ------------------------------------*/ + if((__HAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_ARLO) != RESET) && (__HAL_SMBUS_GET_IT_SOURCE(hsmbus, SMBUS_IT_ERRI) != RESET)) + { + hsmbus->ErrorCode |= HAL_SMBUS_ERROR_ARLO; + + /* Clear ARLO flag */ + __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_ARLO); + } + + /* SMBUS Timeout error interrupt occurred ---------------------------------------------*/ + if((__HAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_TIMEOUT) != RESET) && (__HAL_SMBUS_GET_IT_SOURCE(hsmbus, SMBUS_IT_ERRI) != RESET)) + { + hsmbus->ErrorCode |= HAL_SMBUS_ERROR_BUSTIMEOUT; + + /* Clear TIMEOUT flag */ + __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_TIMEOUT); + } + + /* SMBUS Alert error interrupt occurred -----------------------------------------------*/ + if((__HAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_ALERT) != RESET) && (__HAL_SMBUS_GET_IT_SOURCE(hsmbus, SMBUS_IT_ERRI) != RESET)) + { + hsmbus->ErrorCode |= HAL_SMBUS_ERROR_ALERT; + + /* Clear ALERT flag */ + __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_ALERT); + } + + /* SMBUS Packet Error Check error interrupt occurred ----------------------------------*/ + if((__HAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_PECERR) != RESET) && (__HAL_SMBUS_GET_IT_SOURCE(hsmbus, SMBUS_IT_ERRI) != RESET)) + { + hsmbus->ErrorCode |= HAL_SMBUS_ERROR_PECERR; + + /* Clear PEC error flag */ + __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_PECERR); + } + + /* Call the Error Callback in case of Error detected */ + if((hsmbus->ErrorCode != HAL_SMBUS_ERROR_NONE)&&(hsmbus->ErrorCode != HAL_SMBUS_ERROR_ACKF)) + { + /* Do not Reset the the HAL state in case of ALERT error */ + if((hsmbus->ErrorCode & HAL_SMBUS_ERROR_ALERT) != HAL_SMBUS_ERROR_ALERT) + { + /* Reset only HAL_SMBUS_STATE_SLAVE_BUSY_XX and HAL_SMBUS_STATE_MASTER_BUSY_XX */ + /* keep HAL_SMBUS_STATE_LISTEN if set */ + hsmbus->State &= ~((uint32_t)(HAL_SMBUS_STATE_MASTER_BUSY_RX | HAL_SMBUS_STATE_MASTER_BUSY_TX | HAL_SMBUS_STATE_SLAVE_BUSY_RX | HAL_SMBUS_STATE_SLAVE_BUSY_TX)); + } + + /* Call the Error callback to prevent upper layer */ + HAL_SMBUS_ErrorCallback(hsmbus); + } +} + +/** + * @brief Master Tx Transfer completed callbacks. + * @param hsmbus : Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @retval None + */ + __weak void HAL_SMBUS_MasterTxCpltCallback(SMBUS_HandleTypeDef *hsmbus) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_SMBUS_TxCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Master Rx Transfer completed callbacks. + * @param hsmbus : Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @retval None + */ +__weak void HAL_SMBUS_MasterRxCpltCallback(SMBUS_HandleTypeDef *hsmbus) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_SMBUS_TxCpltCallback could be implemented in the user file + */ +} + +/** @brief Slave Tx Transfer completed callbacks. + * @param hsmbus : Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @retval None + */ + __weak void HAL_SMBUS_SlaveTxCpltCallback(SMBUS_HandleTypeDef *hsmbus) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_SMBUS_TxCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Slave Rx Transfer completed callbacks. + * @param hsmbus : Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @retval None + */ +__weak void HAL_SMBUS_SlaveRxCpltCallback(SMBUS_HandleTypeDef *hsmbus) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_SMBUS_TxCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Slave Address Match callbacks. + * @param hsmbus : Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @param TransferDirection: Master request Transfer Direction (Write/Read) + * @param AddrMatchCode: Address Match Code + * @retval None + */ +__weak void HAL_SMBUS_SlaveAddrCallback(SMBUS_HandleTypeDef *hsmbus, uint8_t TransferDirection, uint16_t AddrMatchCode) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_SMBUS_SlaveAddrCallback could be implemented in the user file + */ +} + +/** + * @brief Listen Complete callbacks. + * @param hsmbus : Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @retval None + */ +__weak void HAL_SMBUS_SlaveListenCpltCallback(SMBUS_HandleTypeDef *hsmbus) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_SMBUS_SlaveListenCpltCallback could be implemented in the user file + */ +} + +/** + * @brief SMBUS error callbacks. + * @param hsmbus : Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @retval None + */ + __weak void HAL_SMBUS_ErrorCallback(SMBUS_HandleTypeDef *hsmbus) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_SMBUS_ErrorCallback could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup HAL_SMBUS_Group3 Peripheral State and Errors functions + * @brief Peripheral State and Errors functions + * +@verbatim + =============================================================================== + ##### Peripheral State and Errors functions ##### + =============================================================================== + [..] + This subsection permit to get in run-time the status of the peripheral + and the data flow. + +@endverbatim + * @{ + */ + +/** + * @brief Returns the SMBUS state. + * @param hsmbus : SMBUS handle + * @retval HAL state + */ +HAL_SMBUS_StateTypeDef HAL_SMBUS_GetState(SMBUS_HandleTypeDef *hsmbus) +{ + return hsmbus->State; +} + +/** +* @brief Return the SMBUS error code +* @param hsmbus : pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. +* @retval SMBUS Error Code +*/ +uint32_t HAL_SMBUS_GetError(SMBUS_HandleTypeDef *hsmbus) +{ + return hsmbus->ErrorCode; +} + +/** + * @} + */ + +/** + * @brief Interrupt Sub-Routine which handle the Interrupt Flags Master Mode + * @param hsmbus : Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @retval HAL status + */ +static HAL_StatusTypeDef SMBUS_Master_ISR(SMBUS_HandleTypeDef *hsmbus) +{ + uint16_t DevAddress; + + /* Process Locked */ + __HAL_LOCK(hsmbus); + + if(__HAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_AF) != RESET) + { + /* Clear NACK Flag */ + __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_AF); + + /* Set corresponding Error Code */ + /* No need to generate STOP, it is automatically done */ + hsmbus->ErrorCode |= HAL_SMBUS_ERROR_ACKF; + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + /* Call the Error callback to prevent upper layer */ + HAL_SMBUS_ErrorCallback(hsmbus); + } + else if(__HAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_STOPF) != RESET) + { + + /* Call the corresponding callback to inform upper layer of End of Transfer */ + if(hsmbus->State == HAL_SMBUS_STATE_MASTER_BUSY_TX) + { + /* Disable Interrupt */ + SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_TX); + + /* Clear STOP Flag */ + __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_STOPF); + + /* Clear Configuration Register 2 */ + __HAL_SMBUS_RESET_CR2(hsmbus); + + /* Flush remaining data in Fifo register in case of error occurs before TXEmpty */ + /* Disable the selected SMBUS peripheral */ + __HAL_SMBUS_DISABLE(hsmbus); + + hsmbus->PreviousState = HAL_SMBUS_STATE_READY; + hsmbus->State = HAL_SMBUS_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + /* REenable the selected SMBUS peripheral */ + __HAL_SMBUS_ENABLE(hsmbus); + + HAL_SMBUS_MasterTxCpltCallback(hsmbus); + } + else if(hsmbus->State == HAL_SMBUS_STATE_MASTER_BUSY_RX) + { + /* Disable Interrupt */ + SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_RX); + + /* Clear STOP Flag */ + __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_STOPF); + + /* Clear Configuration Register 2 */ + __HAL_SMBUS_RESET_CR2(hsmbus); + + hsmbus->PreviousState = HAL_SMBUS_STATE_READY; + hsmbus->State = HAL_SMBUS_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + HAL_SMBUS_MasterRxCpltCallback(hsmbus); + } + } + else if(__HAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_RXNE) != RESET) + { + /* Read data from RXDR */ + (*hsmbus->pBuffPtr++) = hsmbus->Instance->RXDR; + hsmbus->XferSize--; + hsmbus->XferCount--; + } + else if(__HAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_TXIS) != RESET) + { + /* Write data to TXDR */ + hsmbus->Instance->TXDR = (*hsmbus->pBuffPtr++); + hsmbus->XferSize--; + hsmbus->XferCount--; + } + else if(__HAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_TCR) != RESET) + { + if((hsmbus->XferSize == 0)&&(hsmbus->XferCount!=0)) + { + DevAddress = (hsmbus->Instance->CR2 & I2C_CR2_SADD); + + if(hsmbus->XferCount > MAX_NBYTE_SIZE) + { + SMBUS_TransferConfig(hsmbus, DevAddress, MAX_NBYTE_SIZE, (SMBUS_RELOAD_MODE | (hsmbus->XferOptions & SMBUS_SENDPEC_MODE)), SMBUS_NO_STARTSTOP); + hsmbus->XferSize = MAX_NBYTE_SIZE; + } + else + { + hsmbus->XferSize = hsmbus->XferCount; + SMBUS_TransferConfig(hsmbus,DevAddress,hsmbus->XferSize, hsmbus->XferOptions, SMBUS_NO_STARTSTOP); + /* If PEC mode is enable, size to transmit should be Size-1 byte, corresponding to PEC byte */ + /* PEC byte is automatically sent by HW block, no need to manage it in Transmit process */ + if(__HAL_SMBUS_GET_PEC_MODE(hsmbus) != RESET) + { + hsmbus->XferSize--; + hsmbus->XferCount--; + } + } + } + else if((hsmbus->XferSize == 0)&&(hsmbus->XferCount==0)) + { + /* Call TxCpltCallback if no stop mode is set */ + if(__HAL_SMBUS_GET_STOP_MODE(hsmbus) != SMBUS_AUTOEND_MODE) + { + /* Call the corresponding callback to inform upper layer of End of Transfer */ + if(hsmbus->State == HAL_SMBUS_STATE_MASTER_BUSY_TX) + { + /* Disable Interrupt */ + SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_TX); + hsmbus->PreviousState = hsmbus->State; + hsmbus->State = HAL_SMBUS_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + HAL_SMBUS_MasterTxCpltCallback(hsmbus); + } + else if(hsmbus->State == HAL_SMBUS_STATE_MASTER_BUSY_RX) + { + SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_RX); + hsmbus->PreviousState = hsmbus->State; + hsmbus->State = HAL_SMBUS_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + HAL_SMBUS_MasterRxCpltCallback(hsmbus); + } + } + } + } + else if(__HAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_TC) != RESET) + { + if(hsmbus->XferCount == 0) + { + /* Specific use case for Quick command */ + if(hsmbus->pBuffPtr == NULL) + { + /* Generate a Stop command */ + hsmbus->Instance->CR2 |= I2C_CR2_STOP; + } + /* Call TxCpltCallback if no stop mode is set */ + else if(__HAL_SMBUS_GET_STOP_MODE(hsmbus) != SMBUS_AUTOEND_MODE) + { + /* No Generate Stop, to permit restart mode */ + /* The stop will be done at the end of transfer, when SMBUS_AUTOEND_MODE enable */ + + /* Call the corresponding callback to inform upper layer of End of Transfer */ + if(hsmbus->State == HAL_SMBUS_STATE_MASTER_BUSY_TX) + { + /* Disable Interrupt */ + SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_TX); + hsmbus->PreviousState = hsmbus->State; + hsmbus->State = HAL_SMBUS_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + HAL_SMBUS_MasterTxCpltCallback(hsmbus); + } + else if(hsmbus->State == HAL_SMBUS_STATE_MASTER_BUSY_RX) + { + SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_RX); + hsmbus->PreviousState = hsmbus->State; + hsmbus->State = HAL_SMBUS_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + HAL_SMBUS_MasterRxCpltCallback(hsmbus); + } + } + } + } + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + return HAL_OK; +} +/** + * @brief Interrupt Sub-Routine which handle the Interrupt Flags Slave Mode + * @param hsmbus : Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @retval HAL status + */ +static HAL_StatusTypeDef SMBUS_Slave_ISR(SMBUS_HandleTypeDef *hsmbus) +{ + uint8_t TransferDirection = 0; + uint16_t SlaveAddrCode = 0; + + /* Process Locked */ + __HAL_LOCK(hsmbus); + + if(__HAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_AF) != RESET) + { + /* Check that SMBUS transfer finished */ + /* if yes, normal usecase, a NACK is sent by the HOST when Transfer is finished */ + /* Mean XferCount == 0*/ + /* So clear Flag NACKF only */ + if(hsmbus->XferCount == 0) + { + /* Clear NACK Flag */ + __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_AF); + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + } + else + { + /* if no, error usecase, a Non-Acknowledge of last Data is generated by the HOST*/ + /* Clear NACK Flag */ + __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_AF); + + /* Set HAL State to "Idle" State, mean to LISTEN state */ + /* So reset Slave Busy state */ + hsmbus->PreviousState = hsmbus->State; + hsmbus->State &= ~((uint32_t)HAL_SMBUS_STATE_SLAVE_BUSY_TX); + hsmbus->State &= ~((uint32_t)HAL_SMBUS_STATE_SLAVE_BUSY_RX); + + /* Disable RX/TX Interrupts, keep only ADDR Interrupt */ + SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_RX | SMBUS_IT_TX); + + /* Set ErrorCode corresponding to a Non-Acknowledge */ + hsmbus->ErrorCode |= HAL_SMBUS_ERROR_ACKF; + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + /* Call the Error callback to prevent upper layer */ + HAL_SMBUS_ErrorCallback(hsmbus); + } + } + else if(__HAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_ADDR) != RESET) + { + TransferDirection = __HAL_SMBUS_GET_DIR(hsmbus); + SlaveAddrCode = __HAL_SMBUS_GET_ADDR_MATCH(hsmbus); + + /* Disable ADDR interrupt to prevent multiple ADDRInterrupt*/ + /* Other ADDRInterrupt will be treat in next Listen usecase */ + __HAL_SMBUS_DISABLE_IT(hsmbus, SMBUS_IT_ADDRI); + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + /* Call Slave Addr callback */ + HAL_SMBUS_SlaveAddrCallback(hsmbus, TransferDirection, SlaveAddrCode); + } + else if((__HAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_RXNE) != RESET) || (__HAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_TCR) != RESET)) + { + if( (hsmbus->State & HAL_SMBUS_STATE_SLAVE_BUSY_RX) == HAL_SMBUS_STATE_SLAVE_BUSY_RX) + { + /* Read data from RXDR */ + (*hsmbus->pBuffPtr++) = hsmbus->Instance->RXDR; + hsmbus->XferSize--; + hsmbus->XferCount--; + + if(hsmbus->XferCount == 1) + { + /* Receive last Byte, can be PEC byte in case of PEC BYTE enabled */ + /* or only the last Byte of Transfer */ + /* So reset the RELOAD bit mode */ + hsmbus->XferOptions &= ~SMBUS_RELOAD_MODE; + SMBUS_TransferConfig(hsmbus,0 ,1 , hsmbus->XferOptions, SMBUS_NO_STARTSTOP); + } + else if(hsmbus->XferCount == 0) + { + /* Last Byte is received, disable Interrupt */ + SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_RX); + + /* Remove HAL_SMBUS_STATE_SLAVE_BUSY_RX, keep only HAL_SMBUS_STATE_LISTEN */ + hsmbus->PreviousState = hsmbus->State; + hsmbus->State &= ~((uint32_t)HAL_SMBUS_STATE_SLAVE_BUSY_RX); + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + /* Call the Rx complete callback to inform upper layer of the end of receive process */ + HAL_SMBUS_SlaveRxCpltCallback(hsmbus); + } + else + { + /* Set Reload for next Bytes */ + SMBUS_TransferConfig(hsmbus,0, 1, SMBUS_RELOAD_MODE | (hsmbus->XferOptions & SMBUS_SENDPEC_MODE), SMBUS_NO_STARTSTOP); + + /* Ack last Byte Read */ + hsmbus->Instance->CR2 &= ~I2C_CR2_NACK; + } + } + else if( (hsmbus->State & HAL_SMBUS_STATE_SLAVE_BUSY_TX) == HAL_SMBUS_STATE_SLAVE_BUSY_TX) + { + if((hsmbus->XferSize == 0)&&(hsmbus->XferCount!=0)) + { + if(hsmbus->XferCount > MAX_NBYTE_SIZE) + { + SMBUS_TransferConfig(hsmbus, 0, MAX_NBYTE_SIZE, (SMBUS_RELOAD_MODE | (hsmbus->XferOptions & SMBUS_SENDPEC_MODE)), SMBUS_NO_STARTSTOP); + hsmbus->XferSize = MAX_NBYTE_SIZE; + } + else + { + hsmbus->XferSize = hsmbus->XferCount; + SMBUS_TransferConfig(hsmbus, 0, hsmbus->XferSize, hsmbus->XferOptions, SMBUS_NO_STARTSTOP); + /* If PEC mode is enable, size to transmit should be Size-1 byte, corresponding to PEC byte */ + /* PEC byte is automatically sent by HW block, no need to manage it in Transmit process */ + if(__HAL_SMBUS_GET_PEC_MODE(hsmbus) != RESET) + { + hsmbus->XferSize--; + hsmbus->XferCount--; + } + } + } + } + } + else if(__HAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_TXIS) != RESET) + { + /* Write data to TXDR only if XferCount not reach "0" */ + /* A TXIS flag can be set, during STOP treatment */ + /* Check if all Datas have already been sent */ + /* If it is the case, this last write in TXDR is not sent, correspond to a dummy TXIS event */ + if(hsmbus->XferCount > 0) + { + /* Write data to TXDR */ + hsmbus->Instance->TXDR = (*hsmbus->pBuffPtr++); + hsmbus->XferCount--; + hsmbus->XferSize--; + } + + if(hsmbus->XferCount == 0) + { + /* Last Byte is Transmitted */ + /* Remove HAL_SMBUS_STATE_SLAVE_BUSY_TX, keep only HAL_SMBUS_STATE_LISTEN */ + SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_TX); + hsmbus->PreviousState = hsmbus->State; + hsmbus->State &= ~((uint32_t)HAL_SMBUS_STATE_SLAVE_BUSY_TX); + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + /* Call the Tx complete callback to inform upper layer of the end of transmit process */ + HAL_SMBUS_SlaveTxCpltCallback(hsmbus); + } + } + + /* Check if STOPF is set */ + if(__HAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_STOPF) != RESET) + { + if((hsmbus->State & HAL_SMBUS_STATE_LISTEN) == HAL_SMBUS_STATE_LISTEN) + { + /* Disable RX and TX Interrupts */ + SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_RX | SMBUS_IT_TX); + + /* Disable ADDR Interrupt */ + SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_ADDR); + + /* Disable Address Acknowledge */ + hsmbus->Instance->CR2 |= I2C_CR2_NACK; + + /* Clear Configuration Register 2 */ + __HAL_SMBUS_RESET_CR2(hsmbus); + + /* Clear STOP Flag */ + __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_STOPF); + + /* Clear ADDR flag */ + __HAL_SMBUS_CLEAR_FLAG(hsmbus,SMBUS_FLAG_ADDR); + + hsmbus->XferOptions = 0; + hsmbus->PreviousState = hsmbus->State; + hsmbus->State = HAL_SMBUS_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + /* Call the Listen Complete callback, to prevent upper layer of the end of Listen usecase */ + HAL_SMBUS_SlaveListenCpltCallback(hsmbus); + } + } + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + return HAL_OK; +} +/** + * @brief Manage the enabling of Interrupts + * @param hsmbus : Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @param InterruptRequest : Value of @ref SMBUS_Interrupt_configuration_definition. + * @retval HAL status + */ +static HAL_StatusTypeDef SMBUS_Enable_IRQ(SMBUS_HandleTypeDef *hsmbus, uint16_t InterruptRequest) +{ + uint32_t tmpisr = 0; + + if((InterruptRequest & SMBUS_IT_ALERT) == SMBUS_IT_ALERT) + { + /* Enable ERR interrupt */ + tmpisr |= SMBUS_IT_ERRI; + } + + if((InterruptRequest & SMBUS_IT_ADDR) == SMBUS_IT_ADDR) + { + /* Enable ADDR, STOP interrupt */ + tmpisr |= SMBUS_IT_ADDRI | SMBUS_IT_STOPI | SMBUS_IT_NACKI | SMBUS_IT_ERRI; + } + + if((InterruptRequest & SMBUS_IT_TX) == SMBUS_IT_TX) + { + /* Enable ERR, TC, STOP, NACK, RXI interrupt */ + tmpisr |= SMBUS_IT_ERRI | SMBUS_IT_TCI | SMBUS_IT_STOPI | SMBUS_IT_NACKI | SMBUS_IT_TXI; + } + + if((InterruptRequest & SMBUS_IT_RX) == SMBUS_IT_RX) + { + /* Enable ERR, TC, STOP, NACK, TXI interrupt */ + tmpisr |= SMBUS_IT_ERRI | SMBUS_IT_TCI | SMBUS_IT_STOPI | SMBUS_IT_NACKI | SMBUS_IT_RXI; + } + + /* Enable interrupts only at the end */ + /* to avoid the risk of SMBUS interrupt handle execution before */ + /* all interrupts requested done */ + __HAL_SMBUS_ENABLE_IT(hsmbus, tmpisr); + + return HAL_OK; +} +/** + * @brief Manage the disabling of Interrupts + * @param hsmbus : Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @param InterruptRequest : Value of @ref SMBUS_Interrupt_configuration_definition. + * @retval HAL status + */ +static HAL_StatusTypeDef SMBUS_Disable_IRQ(SMBUS_HandleTypeDef *hsmbus, uint16_t InterruptRequest) +{ + uint32_t tmpisr = 0; + + if( ((InterruptRequest & SMBUS_IT_ALERT) == SMBUS_IT_ALERT) && (hsmbus->State == HAL_SMBUS_STATE_READY) ) + { + /* Disable ERR interrupt */ + tmpisr |= SMBUS_IT_ERRI; + } + + if((InterruptRequest & SMBUS_IT_TX) == SMBUS_IT_TX) + { + /* Disable TC, STOP, NACK, TXI interrupt */ + tmpisr |= SMBUS_IT_TCI | SMBUS_IT_TXI; + + if((__HAL_SMBUS_GET_ALERT_ENABLED(hsmbus) == RESET) + && ((hsmbus->State & HAL_SMBUS_STATE_LISTEN) != HAL_SMBUS_STATE_LISTEN)) + { + /* Disable ERR interrupt */ + tmpisr |= SMBUS_IT_ERRI; + } + + if((hsmbus->State & HAL_SMBUS_STATE_LISTEN) != HAL_SMBUS_STATE_LISTEN) + { + /* Disable STOPI, NACKI */ + tmpisr |= SMBUS_IT_STOPI | SMBUS_IT_NACKI; + } + } + + if((InterruptRequest & SMBUS_IT_RX) == SMBUS_IT_RX) + { + /* Disable TC, STOP, NACK, RXI interrupt */ + tmpisr |= SMBUS_IT_TCI | SMBUS_IT_RXI; + + if((__HAL_SMBUS_GET_ALERT_ENABLED(hsmbus) == RESET) + && ((hsmbus->State & HAL_SMBUS_STATE_LISTEN) != HAL_SMBUS_STATE_LISTEN)) + { + /* Disable ERR interrupt */ + tmpisr |= SMBUS_IT_ERRI; + } + + if((hsmbus->State & HAL_SMBUS_STATE_LISTEN) != HAL_SMBUS_STATE_LISTEN) + { + /* Disable STOPI, NACKI */ + tmpisr |= SMBUS_IT_STOPI | SMBUS_IT_NACKI; + } + } + + if((InterruptRequest & SMBUS_IT_ADDR) == SMBUS_IT_ADDR) + { + /* Enable ADDR, STOP interrupt */ + tmpisr |= SMBUS_IT_ADDRI | SMBUS_IT_STOPI | SMBUS_IT_NACKI; + + if(__HAL_SMBUS_GET_ALERT_ENABLED(hsmbus) == RESET) + { + /* Disable ERR interrupt */ + tmpisr |= SMBUS_IT_ERRI; + } + } + + /* Disable interrupts only at the end */ + /* to avoid a breaking situation like at "t" time */ + /* all disable interrupts request are not done */ + __HAL_SMBUS_DISABLE_IT(hsmbus, tmpisr); + + return HAL_OK; +} +/** + * @brief This function handles SMBUS Communication Timeout. + * @param hsmbus : Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @param Flag: specifies the SMBUS flag to check. + * @param Status: The new Flag status (SET or RESET). + * @param Timeout: Timeout duration + * @retval HAL status + */ +static HAL_StatusTypeDef SMBUS_WaitOnFlagUntilTimeout(SMBUS_HandleTypeDef *hsmbus, uint32_t Flag, FlagStatus Status, uint32_t Timeout) +{ + uint32_t tickstart = HAL_GetTick(); + + /* Wait until flag is set */ + if(Status == RESET) + { + while(__HAL_SMBUS_GET_FLAG(hsmbus, Flag) == RESET) + { + /* Check for the Timeout */ + if(Timeout != HAL_MAX_DELAY) + { + if((HAL_GetTick()-tickstart) >= Timeout) + { + hsmbus->PreviousState = hsmbus->State; + hsmbus->State= HAL_SMBUS_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + return HAL_TIMEOUT; + } + } + } + } + else + { + while(__HAL_SMBUS_GET_FLAG(hsmbus, Flag) != RESET) + { + /* Check for the Timeout */ + if(Timeout != HAL_MAX_DELAY) + { + if((HAL_GetTick()-tickstart) >= Timeout) + { + hsmbus->PreviousState = hsmbus->State; + hsmbus->State= HAL_SMBUS_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + return HAL_TIMEOUT; + } + } + } + } + return HAL_OK; +} + +/** + * @brief Handles SMBUSx communication when starting transfer or during transfer (TC or TCR flag are set). + * @param hsmbus: SMBUS handle. + * @param DevAddress: specifies the slave address to be programmed. + * @param Size: specifies the number of bytes to be programmed. + * This parameter must be a value between 0 and 255. + * @param Mode: new state of the SMBUS START condition generation. + * This parameter can be one or a combination of the following values: + * @arg SMBUS_NO_MODE: No specific mode enabled. + * @arg SMBUS_RELOAD_MODE: Enable Reload mode. + * @arg SMBUS_AUTOEND_MODE: Enable Automatic end mode. + * @arg SMBUS_SOFTEND_MODE: Enable Software end mode and Reload mode. + * @param Request: new state of the SMBUS START condition generation. + * This parameter can be one of the following values: + * @arg SMBUS_NO_STARTSTOP: Don't Generate stop and start condition. + * @arg SMBUS_GENERATE_STOP: Generate stop condition (Size should be set to 0). + * @arg SMBUS_GENERATE_START_READ: Generate Restart for read request. + * @arg SMBUS_GENERATE_START_WRITE: Generate Restart for write request. + * @retval None + */ +static void SMBUS_TransferConfig(SMBUS_HandleTypeDef *hsmbus, uint16_t DevAddress, uint8_t Size, uint32_t Mode, uint32_t Request) +{ + uint32_t tmpreg = 0; + + /* Check the parameters */ + assert_param(IS_SMBUS_ALL_INSTANCE(hsmbus->Instance)); + assert_param(IS_SMBUS_TRANSFER_MODE(Mode)); + assert_param(IS_SMBUS_TRANSFER_REQUEST(Request)); + + /* Get the CR2 register value */ + tmpreg = hsmbus->Instance->CR2; + + /* clear tmpreg specific bits */ + tmpreg &= (uint32_t)~((uint32_t)(I2C_CR2_SADD | I2C_CR2_NBYTES | I2C_CR2_RELOAD | I2C_CR2_AUTOEND | I2C_CR2_RD_WRN | I2C_CR2_START | I2C_CR2_STOP | I2C_CR2_PECBYTE)); + + /* update tmpreg */ + tmpreg |= (uint32_t)(((uint32_t)DevAddress & I2C_CR2_SADD) | (((uint32_t)Size << 16 ) & I2C_CR2_NBYTES) | \ + (uint32_t)Mode | (uint32_t)Request); + + /* update CR2 register */ + hsmbus->Instance->CR2 = tmpreg; +} + +/** + * @} + */ + +#endif /* HAL_SMBUS_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_smbus.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_smbus.h new file mode 100644 index 0000000000..9aac2fdde9 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_smbus.h @@ -0,0 +1,573 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_smbus.h + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief Header file of SMBUS HAL module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32F0xx_HAL_SMBUS_H +#define __STM32F0xx_HAL_SMBUS_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal_def.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @addtogroup SMBUS + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ + +/** + * @brief SMBUS Configuration Structure definition + */ +typedef struct +{ + uint32_t Timing; /*!< Specifies the SMBUS_TIMINGR_register value. + This parameter calculated by referring to SMBUS initialization + section in Reference manual */ + uint32_t AnalogFilter; /*!< Specifies if Analog Filter is enable or not. + This parameter can be a a value of @ref SMBUS_Analog_Filter */ + + uint32_t OwnAddress1; /*!< Specifies the first device own address. + This parameter can be a 7-bit or 10-bit address. */ + + uint32_t AddressingMode; /*!< Specifies if 7-bit or 10-bit addressing mode for master is selected. + This parameter can be a value of @ref SMBUS_addressing_mode */ + + uint32_t DualAddressMode; /*!< Specifies if dual addressing mode is selected. + This parameter can be a value of @ref SMBUS_dual_addressing_mode */ + + uint32_t OwnAddress2; /*!< Specifies the second device own address if dual addressing mode is selected + This parameter can be a 7-bit address. */ + + uint32_t OwnAddress2Masks; /*!< Specifies the acknoledge mask address second device own address if dual addressing mode is selected + This parameter can be a value of @ref SMBUS_own_address2_masks. */ + + uint32_t GeneralCallMode; /*!< Specifies if general call mode is selected. + This parameter can be a value of @ref SMBUS_general_call_addressing_mode. */ + + uint32_t NoStretchMode; /*!< Specifies if nostretch mode is selected. + This parameter can be a value of @ref SMBUS_nostretch_mode */ + + uint32_t PacketErrorCheckMode; /*!< Specifies if Packet Error Check mode is selected. + This parameter can be a value of @ref SMBUS_packet_error_check_mode */ + + uint32_t PeripheralMode; /*!< Specifies which mode of Periphal is selected. + This parameter can be a value of @ref SMBUS_peripheral_mode */ + + uint32_t SMBusTimeout; /*!< Specifies the content of the 32 Bits SMBUS_TIMEOUT_register value. + (Enable bits and different timeout values) + This parameter calculated by referring to SMBUS initialization + section in Reference manual */ +} SMBUS_InitTypeDef; + +/** + * @brief HAL State structures definition + */ +typedef enum +{ + HAL_SMBUS_STATE_RESET = 0x00, /*!< SMBUS not yet initialized or disabled */ + HAL_SMBUS_STATE_READY = 0x01, /*!< SMBUS initialized and ready for use */ + HAL_SMBUS_STATE_BUSY = 0x02, /*!< SMBUS internal process is ongoing */ + HAL_SMBUS_STATE_MASTER_BUSY_TX = 0x12, /*!< Master Data Transmission process is ongoing */ + HAL_SMBUS_STATE_MASTER_BUSY_RX = 0x22, /*!< Master Data Reception process is ongoing */ + HAL_SMBUS_STATE_SLAVE_BUSY_TX = 0x32, /*!< Slave Data Transmission process is ongoing */ + HAL_SMBUS_STATE_SLAVE_BUSY_RX = 0x42, /*!< Slave Data Reception process is ongoing */ + HAL_SMBUS_STATE_TIMEOUT = 0x03, /*!< Timeout state */ + HAL_SMBUS_STATE_ERROR = 0x04, /*!< Reception process is ongoing */ + HAL_SMBUS_STATE_SLAVE_LISTEN = 0x08, /*!< Address Listen Mode is ongoing */ + /* Aliases for inter STM32 series compatibility */ + HAL_SMBUS_STATE_LISTEN = HAL_SMBUS_STATE_SLAVE_LISTEN +}HAL_SMBUS_StateTypeDef; + +/** + * @brief HAL SMBUS Error Code structure definition + */ +typedef enum +{ + HAL_SMBUS_ERROR_NONE = 0x00, /*!< No error */ + HAL_SMBUS_ERROR_BERR = 0x01, /*!< BERR error */ + HAL_SMBUS_ERROR_ARLO = 0x02, /*!< ARLO error */ + HAL_SMBUS_ERROR_ACKF = 0x04, /*!< ACKF error */ + HAL_SMBUS_ERROR_OVR = 0x08, /*!< OVR error */ + HAL_SMBUS_ERROR_HALTIMEOUT = 0x10, /*!< Timeout error */ + HAL_SMBUS_ERROR_BUSTIMEOUT = 0x20, /*!< Bus Timeout error */ + HAL_SMBUS_ERROR_ALERT = 0x40, /*!< Alert error */ + HAL_SMBUS_ERROR_PECERR = 0x80 /*!< PEC error */ + +}HAL_SMBUS_ErrorTypeDef; + +/** + * @brief SMBUS handle Structure definition + */ +typedef struct +{ + I2C_TypeDef *Instance; /*!< SMBUS registers base address */ + + SMBUS_InitTypeDef Init; /*!< SMBUS communication parameters */ + + uint8_t *pBuffPtr; /*!< Pointer to SMBUS transfer buffer */ + + uint16_t XferSize; /*!< SMBUS transfer size */ + + __IO uint16_t XferCount; /*!< SMBUS transfer counter */ + + __IO uint32_t XferOptions; /*!< SMBUS transfer options */ + + __IO HAL_SMBUS_StateTypeDef PreviousState; /*!< SMBUS communication Previous tate */ + + HAL_LockTypeDef Lock; /*!< SMBUS locking object */ + + __IO HAL_SMBUS_StateTypeDef State; /*!< SMBUS communication state */ + + __IO HAL_SMBUS_ErrorTypeDef ErrorCode; /*!< SMBUS Error code */ + +}SMBUS_HandleTypeDef; + +/* Exported constants --------------------------------------------------------*/ + +/** @defgroup SMBUS_Exported_Constants + * @{ + */ + +/** @defgroup SMBUS_Analog_Filter + * @{ + */ +#define SMBUS_ANALOGFILTER_ENABLED ((uint32_t)0x00000000) +#define SMBUS_ANALOGFILTER_DISABLED I2C_CR1_ANFOFF + +#define IS_SMBUS_ANALOG_FILTER(FILTER) (((FILTER) == SMBUS_ANALOGFILTER_ENABLED) || \ + ((FILTER) == SMBUS_ANALOGFILTER_DISABLED)) +/** + * @} + */ + +/** @defgroup SMBUS_addressing_mode + * @{ + */ +#define SMBUS_ADDRESSINGMODE_7BIT ((uint32_t)0x00000001) +#define SMBUS_ADDRESSINGMODE_10BIT ((uint32_t)0x00000002) + +#define IS_SMBUS_ADDRESSING_MODE(MODE) (((MODE) == SMBUS_ADDRESSINGMODE_7BIT) || \ + ((MODE) == SMBUS_ADDRESSINGMODE_10BIT)) +/** + * @} + */ + +/** @defgroup SMBUS_dual_addressing_mode + * @{ + */ + +#define SMBUS_DUALADDRESS_DISABLED ((uint32_t)0x00000000) +#define SMBUS_DUALADDRESS_ENABLED I2C_OAR2_OA2EN + +#define IS_SMBUS_DUAL_ADDRESS(ADDRESS) (((ADDRESS) == SMBUS_DUALADDRESS_DISABLED) || \ + ((ADDRESS) == SMBUS_DUALADDRESS_ENABLED)) +/** + * @} + */ + +/** @defgroup SMBUS_own_address2_masks + * @{ + */ + +#define SMBUS_OA2_NOMASK ((uint8_t)0x00) +#define SMBUS_OA2_MASK01 ((uint8_t)0x01) +#define SMBUS_OA2_MASK02 ((uint8_t)0x02) +#define SMBUS_OA2_MASK03 ((uint8_t)0x03) +#define SMBUS_OA2_MASK04 ((uint8_t)0x04) +#define SMBUS_OA2_MASK05 ((uint8_t)0x05) +#define SMBUS_OA2_MASK06 ((uint8_t)0x06) +#define SMBUS_OA2_MASK07 ((uint8_t)0x07) + +#define IS_SMBUS_OWN_ADDRESS2_MASK(MASK) (((MASK) == SMBUS_OA2_NOMASK) || \ + ((MASK) == SMBUS_OA2_MASK01) || \ + ((MASK) == SMBUS_OA2_MASK02) || \ + ((MASK) == SMBUS_OA2_MASK03) || \ + ((MASK) == SMBUS_OA2_MASK04) || \ + ((MASK) == SMBUS_OA2_MASK05) || \ + ((MASK) == SMBUS_OA2_MASK06) || \ + ((MASK) == SMBUS_OA2_MASK07)) +/** + * @} + */ + + +/** @defgroup SMBUS_general_call_addressing_mode + * @{ + */ +#define SMBUS_GENERALCALL_DISABLED ((uint32_t)0x00000000) +#define SMBUS_GENERALCALL_ENABLED I2C_CR1_GCEN + +#define IS_SMBUS_GENERAL_CALL(CALL) (((CALL) == SMBUS_GENERALCALL_DISABLED) || \ + ((CALL) == SMBUS_GENERALCALL_ENABLED)) +/** + * @} + */ + +/** @defgroup SMBUS_nostretch_mode + * @{ + */ +#define SMBUS_NOSTRETCH_DISABLED ((uint32_t)0x00000000) +#define SMBUS_NOSTRETCH_ENABLED I2C_CR1_NOSTRETCH + +#define IS_SMBUS_NO_STRETCH(STRETCH) (((STRETCH) == SMBUS_NOSTRETCH_DISABLED) || \ + ((STRETCH) == SMBUS_NOSTRETCH_ENABLED)) +/** + * @} + */ + +/** @defgroup SMBUS_packet_error_check_mode + * @{ + */ +#define SMBUS_PEC_DISABLED ((uint32_t)0x00000000) +#define SMBUS_PEC_ENABLED I2C_CR1_PECEN + +#define IS_SMBUS_PEC(PEC) (((PEC) == SMBUS_PEC_DISABLED) || \ + ((PEC) == SMBUS_PEC_ENABLED)) +/** + * @} + */ + +/** @defgroup SMBUS_peripheral_mode + * @{ + */ +#define SMBUS_PERIPHERAL_MODE_SMBUS_HOST (uint32_t)(I2C_CR1_SMBHEN) +#define SMBUS_PERIPHERAL_MODE_SMBUS_SLAVE (uint32_t)(0x00000000) +#define SMBUS_PERIPHERAL_MODE_SMBUS_SLAVE_ARP (uint32_t)(I2C_CR1_SMBDEN) + +#define IS_SMBUS_PERIPHERAL_MODE(MODE) (((MODE) == SMBUS_PERIPHERAL_MODE_SMBUS_HOST) || \ + ((MODE) == SMBUS_PERIPHERAL_MODE_SMBUS_SLAVE) || \ + ((MODE) == SMBUS_PERIPHERAL_MODE_SMBUS_SLAVE_ARP)) +/** + * @} + */ + +/** @defgroup SMBUS_ReloadEndMode_definition + * @{ + */ + +#define SMBUS_SOFTEND_MODE ((uint32_t)0x00000000) +#define SMBUS_RELOAD_MODE I2C_CR2_RELOAD +#define SMBUS_AUTOEND_MODE I2C_CR2_AUTOEND +#define SMBUS_SENDPEC_MODE I2C_CR2_PECBYTE + +#define IS_SMBUS_TRANSFER_MODE(MODE) (((MODE) == SMBUS_RELOAD_MODE) || \ + ((MODE) == SMBUS_AUTOEND_MODE) || \ + ((MODE) == SMBUS_SOFTEND_MODE) || \ + ((MODE) == (SMBUS_RELOAD_MODE | SMBUS_SENDPEC_MODE)) || \ + ((MODE) == (SMBUS_AUTOEND_MODE | SMBUS_SENDPEC_MODE)) || \ + ((MODE) == (SMBUS_AUTOEND_MODE | SMBUS_RELOAD_MODE)) || \ + ((MODE) == (SMBUS_AUTOEND_MODE | SMBUS_SENDPEC_MODE | SMBUS_RELOAD_MODE ))) + +/** + * @} + */ + +/** @defgroup SMBUS_StartStopMode_definition + * @{ + */ + +#define SMBUS_NO_STARTSTOP ((uint32_t)0x00000000) +#define SMBUS_GENERATE_STOP I2C_CR2_STOP +#define SMBUS_GENERATE_START_READ (uint32_t)(I2C_CR2_START | I2C_CR2_RD_WRN) +#define SMBUS_GENERATE_START_WRITE I2C_CR2_START + +#define IS_SMBUS_TRANSFER_REQUEST(REQUEST) (((REQUEST) == SMBUS_GENERATE_STOP) || \ + ((REQUEST) == SMBUS_GENERATE_START_READ) || \ + ((REQUEST) == SMBUS_GENERATE_START_WRITE) || \ + ((REQUEST) == SMBUS_NO_STARTSTOP)) + +/** + * @} + */ + +/** @defgroup SMBUS_XferOptions_definition + * @{ + */ + +#define SMBUS_FIRST_FRAME ((uint32_t)(SMBUS_SOFTEND_MODE)) +#define SMBUS_NEXT_FRAME ((uint32_t)(SMBUS_RELOAD_MODE | SMBUS_SOFTEND_MODE)) +#define SMBUS_FIRST_AND_LAST_FRAME_NO_PEC SMBUS_AUTOEND_MODE +#define SMBUS_LAST_FRAME_NO_PEC SMBUS_AUTOEND_MODE +#define SMBUS_FIRST_AND_LAST_FRAME_WITH_PEC ((uint32_t)(SMBUS_AUTOEND_MODE | SMBUS_SENDPEC_MODE)) +#define SMBUS_LAST_FRAME_WITH_PEC ((uint32_t)(SMBUS_AUTOEND_MODE | SMBUS_SENDPEC_MODE)) + +#define IS_SMBUS_TRANSFER_OPTIONS_REQUEST(REQUEST) (((REQUEST) == SMBUS_FIRST_FRAME) || \ + ((REQUEST) == SMBUS_NEXT_FRAME) || \ + ((REQUEST) == SMBUS_FIRST_AND_LAST_FRAME_NO_PEC) || \ + ((REQUEST) == SMBUS_LAST_FRAME_NO_PEC) || \ + ((REQUEST) == SMBUS_FIRST_AND_LAST_FRAME_WITH_PEC) || \ + ((REQUEST) == SMBUS_LAST_FRAME_WITH_PEC)) + +/** + * @} + */ + +/** @defgroup SMBUS_Interrupt_configuration_definition + * @brief SMBUS Interrupt definition + * Elements values convention: 0xXXXXXXXX + * - XXXXXXXX : Interrupt control mask + * @{ + */ +#define SMBUS_IT_ERRI I2C_CR1_ERRIE +#define SMBUS_IT_TCI I2C_CR1_TCIE +#define SMBUS_IT_STOPI I2C_CR1_STOPIE +#define SMBUS_IT_NACKI I2C_CR1_NACKIE +#define SMBUS_IT_ADDRI I2C_CR1_ADDRIE +#define SMBUS_IT_RXI I2C_CR1_RXIE +#define SMBUS_IT_TXI I2C_CR1_TXIE +#define SMBUS_IT_TX (SMBUS_IT_ERRI | SMBUS_IT_TCI | SMBUS_IT_STOPI | SMBUS_IT_NACKI | SMBUS_IT_TXI) +#define SMBUS_IT_RX (SMBUS_IT_ERRI | SMBUS_IT_TCI | SMBUS_IT_NACKI | SMBUS_IT_RXI) +#define SMBUS_IT_ALERT (SMBUS_IT_ERRI) +#define SMBUS_IT_ADDR (SMBUS_IT_ADDRI | SMBUS_IT_STOPI | SMBUS_IT_NACKI) +/** + * @} + */ + +/** @defgroup SMBUS_Flag_definition + * @brief Flag definition + * Elements values convention: 0xXXXXYYYY + * - XXXXXXXX : Flag mask + * @{ + */ + +#define SMBUS_FLAG_TXE I2C_ISR_TXE +#define SMBUS_FLAG_TXIS I2C_ISR_TXIS +#define SMBUS_FLAG_RXNE I2C_ISR_RXNE +#define SMBUS_FLAG_ADDR I2C_ISR_ADDR +#define SMBUS_FLAG_AF I2C_ISR_NACKF +#define SMBUS_FLAG_STOPF I2C_ISR_STOPF +#define SMBUS_FLAG_TC I2C_ISR_TC +#define SMBUS_FLAG_TCR I2C_ISR_TCR +#define SMBUS_FLAG_BERR I2C_ISR_BERR +#define SMBUS_FLAG_ARLO I2C_ISR_ARLO +#define SMBUS_FLAG_OVR I2C_ISR_OVR +#define SMBUS_FLAG_PECERR I2C_ISR_PECERR +#define SMBUS_FLAG_TIMEOUT I2C_ISR_TIMEOUT +#define SMBUS_FLAG_ALERT I2C_ISR_ALERT +#define SMBUS_FLAG_BUSY I2C_ISR_BUSY +#define SMBUS_FLAG_DIR I2C_ISR_DIR +/** + * @} + */ + +/** + * @} + */ + +/* Exported macros ------------------------------------------------------------*/ +/** @defgroup SMBUS_Exported_Macros + * @{ + */ + +/** @brief Reset SMBUS handle state + * @param __HANDLE__: SMBUS handle. + * @retval None + */ +#define __HAL_SMBUS_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_SMBUS_STATE_RESET) + +/** @brief Enable or disable the specified SMBUS interrupts. + * @param __HANDLE__: specifies the SMBUS Handle. + * This parameter can be SMBUS where x: 1 or 2 to select the SMBUS peripheral. + * @param __INTERRUPT__: specifies the interrupt source to enable or disable. + * This parameter can be one of the following values: + * @arg SMBUS_IT_ERRI: Errors interrupt enable + * @arg SMBUS_IT_TCI: Transfer complete interrupt enable + * @arg SMBUS_IT_STOPI: STOP detection interrupt enable + * @arg SMBUS_IT_NACKI: NACK received interrupt enable + * @arg SMBUS_IT_ADDRI: Address match interrupt enable + * @arg SMBUS_IT_RXI: RX interrupt enable + * @arg SMBUS_IT_TXI: TX interrupt enable + * + * @retval None + */ + +#define __HAL_SMBUS_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR1 |= (__INTERRUPT__)) +#define __HAL_SMBUS_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR1 &= (~(__INTERRUPT__))) + +/** @brief Checks if the specified SMBUS interrupt source is enabled or disabled. + * @param __HANDLE__: specifies the SMBUS Handle. + * This parameter can be SMBUS where x: 1 or 2 to select the SMBUS peripheral. + * @param __INTERRUPT__: specifies the SMBUS interrupt source to check. + * This parameter can be one of the following values: + * @arg SMBUS_IT_ERRI: Errors interrupt enable + * @arg SMBUS_IT_TCI: Transfer complete interrupt enable + * @arg SMBUS_IT_STOPI: STOP detection interrupt enable + * @arg SMBUS_IT_NACKI: NACK received interrupt enable + * @arg SMBUS_IT_ADDRI: Address match interrupt enable + * @arg SMBUS_IT_RXI: RX interrupt enable + * @arg SMBUS_IT_TXI: TX interrupt enable + * + * @retval The new state of __IT__ (TRUE or FALSE). + */ +#define __HAL_SMBUS_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((((__HANDLE__)->Instance->CR1 & (__INTERRUPT__)) == (__INTERRUPT__)) ? SET : RESET) + +/** @brief Checks whether the specified SMBUS flag is set or not. + * @param __HANDLE__: specifies the SMBUS Handle. + * This parameter can be SMBUS where x: 1 or 2 to select the SMBUS peripheral. + * @param __FLAG__: specifies the flag to check. + * This parameter can be one of the following values: + * @arg SMBUS_FLAG_TXE: Transmit data register empty + * @arg SMBUS_FLAG_TXIS: Transmit interrupt status + * @arg SMBUS_FLAG_RXNE: Receive data register not empty + * @arg SMBUS_FLAG_ADDR: Address matched (slave mode) + * @arg SMBUS_FLAG_AF: NACK received flag + * @arg SMBUS_FLAG_STOPF: STOP detection flag + * @arg SMBUS_FLAG_TC: Transfer complete (master mode) + * @arg SMBUS_FLAG_TCR: Transfer complete reload + * @arg SMBUS_FLAG_BERR: Bus error + * @arg SMBUS_FLAG_ARLO: Arbitration lost + * @arg SMBUS_FLAG_OVR: Overrun/Underrun + * @arg SMBUS_FLAG_PECERR: PEC error in reception + * @arg SMBUS_FLAG_TIMEOUT: Timeout or Tlow detection flag + * @arg SMBUS_FLAG_ALERT: SMBus alert + * @arg SMBUS_FLAG_BUSY: Bus busy + * @arg SMBUS_FLAG_DIR: Transfer direction (slave mode) + * + * @retval The new state of __FLAG__ (TRUE or FALSE). + */ +#define SMBUS_FLAG_MASK ((uint32_t)0x0001FFFF) +#define __HAL_SMBUS_GET_FLAG(__HANDLE__, __FLAG__) (((((__HANDLE__)->Instance->ISR) & ((__FLAG__) & SMBUS_FLAG_MASK)) == ((__FLAG__) & SMBUS_FLAG_MASK))) + +/** @brief Clears the SMBUS pending flags which are cleared by writing 1 in a specific bit. + * @param __HANDLE__: specifies the SMBUS Handle. + * This parameter can be SMBUS where x: 1 or 2 to select the SMBUS peripheral. + * @param __FLAG__: specifies the flag to clear. + * This parameter can be any combination of the following values: + * @arg SMBUS_FLAG_ADDR: Address matched (slave mode) + * @arg SMBUS_FLAG_AF: NACK received flag + * @arg SMBUS_FLAG_STOPF: STOP detection flag + * @arg SMBUS_FLAG_BERR: Bus error + * @arg SMBUS_FLAG_ARLO: Arbitration lost + * @arg SMBUS_FLAG_OVR: Overrun/Underrun + * @arg SMBUS_FLAG_PECERR: PEC error in reception + * @arg SMBUS_FLAG_TIMEOUT: Timeout or Tlow detection flag + * @arg SMBUS_FLAG_ALERT: SMBus alert + * + * @retval None + */ +#define __HAL_SMBUS_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->ICR |= ((__FLAG__) & SMBUS_FLAG_MASK)) + + +#define __HAL_SMBUS_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 |= I2C_CR1_PE) +#define __HAL_SMBUS_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 &= ~I2C_CR1_PE) + +#define __HAL_SMBUS_RESET_CR1(__HANDLE__) ((__HANDLE__)->Instance->CR1 &= (uint32_t)~((uint32_t)(I2C_CR1_SMBHEN | I2C_CR1_SMBDEN | I2C_CR1_PECEN))) +#define __HAL_SMBUS_RESET_CR2(__HANDLE__) ((__HANDLE__)->Instance->CR2 &= (uint32_t)~((uint32_t)(I2C_CR2_SADD | I2C_CR2_HEAD10R | I2C_CR2_NBYTES | I2C_CR2_RELOAD | I2C_CR2_RD_WRN))) + +#define __HAL_SMBUS_GENERATE_START(__ADDMODE__,__ADDRESS__) (((__ADDMODE__) == SMBUS_ADDRESSINGMODE_7BIT) ? (uint32_t)((((uint32_t)(__ADDRESS__) & (I2C_CR2_SADD)) | (I2C_CR2_START) | (I2C_CR2_AUTOEND)) & (~I2C_CR2_RD_WRN)) : \ + (uint32_t)((((uint32_t)(__ADDRESS__) & (I2C_CR2_SADD)) | (I2C_CR2_ADD10) | (I2C_CR2_START)) & (~I2C_CR2_RD_WRN))) + +#define __HAL_SMBUS_GET_ADDR_MATCH(__HANDLE__) (((__HANDLE__)->Instance->ISR & I2C_ISR_ADDCODE) >> 17) +#define __HAL_SMBUS_GET_DIR(__HANDLE__) (((__HANDLE__)->Instance->ISR & I2C_ISR_DIR) >> 16) +#define __HAL_SMBUS_GET_STOP_MODE(__HANDLE__) ((__HANDLE__)->Instance->CR2 & I2C_CR2_AUTOEND) +#define __HAL_SMBUS_GET_PEC_MODE(__HANDLE__) ((__HANDLE__)->Instance->CR2 & I2C_CR2_PECBYTE) +#define __HAL_SMBUS_GET_ALERT_ENABLED(__HANDLE__) ((__HANDLE__)->Instance->CR1 & I2C_CR1_ALERTEN) +#define __HAL_SMBUS_GENERATE_NACK(__HANDLE__) ((__HANDLE__)->Instance->CR2 |= I2C_CR2_NACK) + +#define IS_SMBUS_OWN_ADDRESS1(ADDRESS1) ((ADDRESS1) <= (uint32_t)0x000003FF) +#define IS_SMBUS_OWN_ADDRESS2(ADDRESS2) ((ADDRESS2) <= (uint16_t)0x00FF) +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/* Initialization and de-initialization functions **********************************/ +HAL_StatusTypeDef HAL_SMBUS_Init(SMBUS_HandleTypeDef *hsmbus); +HAL_StatusTypeDef HAL_SMBUS_DeInit (SMBUS_HandleTypeDef *hsmbus); +void HAL_SMBUS_MspInit(SMBUS_HandleTypeDef *hsmbus); +void HAL_SMBUS_MspDeInit(SMBUS_HandleTypeDef *hsmbus); + +/* IO operation functions *****************************************************/ +HAL_StatusTypeDef HAL_SMBUS_EnableAlert_IT(SMBUS_HandleTypeDef *hsmbus); +HAL_StatusTypeDef HAL_SMBUS_DisableAlert_IT(SMBUS_HandleTypeDef *hsmbus); +HAL_StatusTypeDef HAL_SMBUS_Slave_Listen_IT(SMBUS_HandleTypeDef *hsmbus); +HAL_StatusTypeDef HAL_SMBUS_DisableListen_IT(SMBUS_HandleTypeDef *hsmbus); +/* Aliases for new API and to insure inter STM32 series compatibility */ +#define HAL_SMBUS_EnableListen_IT HAL_SMBUS_Slave_Listen_IT + +/******* Blocking mode: Polling */ +HAL_StatusTypeDef HAL_SMBUS_IsDeviceReady(SMBUS_HandleTypeDef *hsmbus, uint16_t DevAddress, uint32_t Trials, uint32_t Timeout); + + /******* Non-Blocking mode: Interrupt */ +HAL_StatusTypeDef HAL_SMBUS_Master_Transmit_IT(SMBUS_HandleTypeDef *hsmbus, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t XferOptions); +HAL_StatusTypeDef HAL_SMBUS_Master_Receive_IT(SMBUS_HandleTypeDef *hsmbus, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t XferOptions); +HAL_StatusTypeDef HAL_SMBUS_Master_Abort_IT(SMBUS_HandleTypeDef *hsmbus, uint16_t DevAddress); +HAL_StatusTypeDef HAL_SMBUS_Slave_Transmit_IT(SMBUS_HandleTypeDef *hsmbus, uint8_t *pData, uint16_t Size, uint32_t XferOptions); +HAL_StatusTypeDef HAL_SMBUS_Slave_Receive_IT(SMBUS_HandleTypeDef *hsmbus, uint8_t *pData, uint16_t Size, uint32_t XferOptions); + + /******* SMBUS IRQHandler and Callbacks used in non blocking modes (Interrupt) */ +void HAL_SMBUS_EV_IRQHandler(SMBUS_HandleTypeDef *hsmbus); +void HAL_SMBUS_ER_IRQHandler(SMBUS_HandleTypeDef *hsmbus); +void HAL_SMBUS_MasterTxCpltCallback(SMBUS_HandleTypeDef *hsmbus); +void HAL_SMBUS_MasterRxCpltCallback(SMBUS_HandleTypeDef *hsmbus); +void HAL_SMBUS_SlaveTxCpltCallback(SMBUS_HandleTypeDef *hsmbus); +void HAL_SMBUS_SlaveRxCpltCallback(SMBUS_HandleTypeDef *hsmbus); +void HAL_SMBUS_SlaveAddrCallback(SMBUS_HandleTypeDef *hsmbus, uint8_t TransferDirection, uint16_t AddrMatchCode); +void HAL_SMBUS_SlaveListenCpltCallback(SMBUS_HandleTypeDef *hsmbus); +/* Aliases for new API and to insure inter STM32 series compatibility */ +#define HAL_SMBUS_AddrCallback HAL_SMBUS_SlaveAddrCallback +#define HAL_SMBUS_ListenCpltCallback HAL_SMBUS_SlaveListenCpltCallback + +void HAL_SMBUS_ErrorCallback(SMBUS_HandleTypeDef *hsmbus); + +/* Peripheral State and Errors functions **************************************************/ +HAL_SMBUS_StateTypeDef HAL_SMBUS_GetState(SMBUS_HandleTypeDef *hsmbus); +uint32_t HAL_SMBUS_GetError(SMBUS_HandleTypeDef *hsmbus); + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + + +#endif /* __STM32F0xx_HAL_SMBUS_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_spi.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_spi.c new file mode 100644 index 0000000000..5142d87e41 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_spi.c @@ -0,0 +1,2436 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_spi.c + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief SPI HAL module driver. + * + * This file provides firmware functions to manage the following + * functionalities of the SPI peripheral: + * + Initialization/de-initialization functions + * + I/O operation functions + * + Peripheral Control functions + * + Peripheral State functions + * + @verbatim +=============================================================================== + ##### How to use this driver ##### + =============================================================================== + [..] + The SPI HAL driver can be used as follows: + + (#) Declare a SPI_HandleTypeDef handle structure, for example: + SPI_HandleTypeDef hspi; + + (#)Initialize the SPI low level resources by implement the HAL_SPI_MspInit ()API: + (##) Enable the SPIx interface clock + (##) SPI pins configuration + (+) Enable the clock for the SPI GPIOs + (+) Configure these SPI pins as alternate function push-pull + (##) NVIC configuration if you need to use interrupt process + (+) Configure the SPIx interrupt priority + (+) Enable the NVIC SPI IRQ handle + (##) DMA Configuration if you need to use DMA process + (+) Declare a DMA_HandleTypeDef handle structure for the transmit or receive stream + (+) Enable the DMAx interface clock using + (+) Configure the DMA handle parameters + (+) Configure the DMA Tx or Rx Stream + (+) Associate the initilalized hdma_tx handle to the hspi DMA Tx or Rx handle + (+) Configure the priority and enable the NVIC for the transfer complete interrupt on the DMA Tx or Rx Stream + + (#) Program the Mode, BidirectionalMode , Data size, Baudrate Prescaler, NSS + management, Clock polarity and phase, FirstBit and CRC configuration in the hspi Init structure. + + (#) Initialize the SPI registers by calling the HAL_SPI_Init() API: + (+) These API's configures also the low level Hardware GPIO, CLOCK, CORTEX...etc) + by calling the customed HAL_SPI_MspInit(&hspi) API. + + + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @defgroup SPI + * @brief SPI HAL module driver + * @{ + */ +#ifdef HAL_SPI_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +#define SPI_DEFAULT_TIMEOUT 50 +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +static void HAL_SPI_DMATransmitCplt(DMA_HandleTypeDef *hdma); +static void HAL_SPI_DMAReceiveCplt(DMA_HandleTypeDef *hdma); +static void HAL_SPI_DMATransmitReceiveCplt(DMA_HandleTypeDef *hdma); +static void HAL_SPI_DMAError(DMA_HandleTypeDef *hdma); +static HAL_StatusTypeDef SPI_WaitFlagStateUntilTimeout(SPI_HandleTypeDef *hspi, uint32_t Flag, uint32_t State, uint32_t Timeout); +static HAL_StatusTypeDef SPI_WaitFifoStateUntilTimeout(SPI_HandleTypeDef *hspi, uint32_t Fifo, uint32_t State, uint32_t Timeout); +static void SPI_TxISR_8BIT(struct __SPI_HandleTypeDef *hspi); +static void SPI_TxISR_16BIT(struct __SPI_HandleTypeDef *hspi); +static void SPI_RxISR_8BIT(struct __SPI_HandleTypeDef *hspi); +static void SPI_RxISR_8BITCRC(struct __SPI_HandleTypeDef *hspi); +static void SPI_RxISR_16BIT(struct __SPI_HandleTypeDef *hspi); +static void SPI_RxISR_16BITCRC(struct __SPI_HandleTypeDef *hspi); +static void SPI_2linesRxISR_8BIT(struct __SPI_HandleTypeDef *hspi); +static void SPI_2linesRxISR_8BITCRC(struct __SPI_HandleTypeDef *hspi); +static void SPI_2linesTxISR_8BIT(struct __SPI_HandleTypeDef *hspi); +static void SPI_2linesTxISR_16BIT(struct __SPI_HandleTypeDef *hspi); +static void SPI_2linesRxISR_16BIT(struct __SPI_HandleTypeDef *hspi); +static void SPI_2linesRxISR_16BITCRC(struct __SPI_HandleTypeDef *hspi); +static void SPI_CloseRxTx_ISR(SPI_HandleTypeDef *hspi); +static void SPI_CloseRx_ISR(SPI_HandleTypeDef *hspi); +static void SPI_CloseTx_ISR(SPI_HandleTypeDef *hspi); +static HAL_StatusTypeDef SPI_EndRxTransaction(SPI_HandleTypeDef *hspi, uint32_t Timeout); +static HAL_StatusTypeDef SPI_EndRxTxTransaction(SPI_HandleTypeDef *hspi, uint32_t Timeout); + +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup SPI_Private_Functions + * @{ + */ + +/** @defgroup HAL_SPI_Group1 Initialization/de-initialization functions + * @brief Initialization and Configuration functions + * +@verbatim + =============================================================================== + ##### Initialization/de-initialization functions ##### + =============================================================================== + [..] This subsection provides a set of functions allowing to initialize and + de-initialiaze the SPIx peripheral: + + (+) User must Implement HAL_SPI_MspInit() function in which he configures + all related peripherals resources (CLOCK, GPIO, DMA, IT and NVIC ). + + (+) Call the function HAL_SPI_Init() to configure the selected device with + the selected configuration: + (++) Mode + (++) Direction + (++) Data Size + (++) Clock Polarity and Phase + (++) NSS Management + (++) BaudRate Prescaler + (++) FirstBit + (++) TIMode + (++) CRC Calculation + (++) CRC Polynomial if CRC enabled + (++) CRC Length, used only with Data8 and Data16 + (++) FIFO reception threshold + + (+) Call the function HAL_SPI_DeInit() to restore the default configuration + of the selected SPIx periperal. + +@endverbatim + * @{ + */ + +/** + * @brief Initializes the SPI according to the specified parameters + * in the SPI_InitTypeDef and create the associated handle. + * @param hspi: SPI handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SPI_Init(SPI_HandleTypeDef *hspi) +{ + uint32_t frxth; + + /* Check the SPI handle allocation */ + if(hspi == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_SPI_ALL_INSTANCE(hspi->Instance)); + assert_param(IS_SPI_MODE(hspi->Init.Mode)); + assert_param(IS_SPI_DIRECTION(hspi->Init.Direction)); + assert_param(IS_SPI_DATASIZE(hspi->Init.DataSize)); + assert_param(IS_SPI_CPOL(hspi->Init.CLKPolarity)); + assert_param(IS_SPI_CPHA(hspi->Init.CLKPhase)); + assert_param(IS_SPI_NSS(hspi->Init.NSS)); + assert_param(IS_SPI_NSSP(hspi->Init.NSSPMode)); + assert_param(IS_SPI_BAUDRATE_PRESCALER(hspi->Init.BaudRatePrescaler)); + assert_param(IS_SPI_FIRST_BIT(hspi->Init.FirstBit)); + assert_param(IS_SPI_TIMODE(hspi->Init.TIMode)); + assert_param(IS_SPI_CRC_CALCULATION(hspi->Init.CRCCalculation)); + assert_param(IS_SPI_CRC_POLYNOMIAL(hspi->Init.CRCPolynomial)); + assert_param(IS_SPI_CRC_LENGTH(hspi->Init.CRCLength)); + + hspi->State = HAL_SPI_STATE_BUSY; + + /* Init the low level hardware : GPIO, CLOCK, NVIC... */ + HAL_SPI_MspInit(hspi); + + /* Disable the selected SPI peripheral */ + __HAL_SPI_DISABLE(hspi); + + /* Align by default the rs fifo threshold on the data size */ + if(hspi->Init.DataSize > SPI_DATASIZE_8BIT) + { + frxth = SPI_RXFIFO_THRESHOLD_HF; + } + else + { + frxth = SPI_RXFIFO_THRESHOLD_QF; + } + + /* CRC calculation is valid only for 16Bit and 8 Bit */ + if(( hspi->Init.DataSize != SPI_DATASIZE_16BIT ) && ( hspi->Init.DataSize != SPI_DATASIZE_8BIT )) + { + /* CRC must be disabled */ + hspi->Init.CRCCalculation = SPI_CRCCALCULATION_DISABLED; + } + + /* Align the CRC Length on the data size */ + if( hspi->Init.CRCLength == SPI_CRC_LENGTH_DATASIZE) + { + /* CRC Lengtht aligned on the data size : value set by default */ + if(hspi->Init.DataSize > SPI_DATASIZE_8BIT) + { + hspi->Init.CRCLength = SPI_CRC_LENGTH_16BIT; + } + else + { + hspi->Init.CRCLength = SPI_CRC_LENGTH_8BIT; + } + } + + /*---------------------------- SPIx CR1 & CR2 Configuration ------------------------*/ + /* Configure : SPI Mode, Communication Mode, Clock polarity and phase, NSS management, + Communication speed, First bit, CRC calculation state, CRC Length */ + hspi->Instance->CR1 = (hspi->Init.Mode | hspi->Init.Direction | + hspi->Init.CLKPolarity | hspi->Init.CLKPhase | (hspi->Init.NSS & SPI_CR1_SSM) | + hspi->Init.BaudRatePrescaler | hspi->Init.FirstBit | hspi->Init.CRCCalculation); + + if( hspi->Init.CRCLength == SPI_CRC_LENGTH_16BIT) + { + hspi->Instance->CR1|= SPI_CR1_CRCL; + } + + /* Configure : NSS management */ + /* Configure : Rx Fifo Threshold */ + hspi->Instance->CR2 = (((hspi->Init.NSS >> 16) & SPI_CR2_SSOE) | hspi->Init.TIMode | hspi->Init.NSSPMode | + hspi->Init.DataSize ) | frxth; + + /*---------------------------- SPIx CRCPOLY Configuration --------------------*/ + /* Configure : CRC Polynomial */ + hspi->Instance->CRCPR = hspi->Init.CRCPolynomial; + + /* Activate the SPI mode (Make sure that I2SMOD bit in I2SCFGR register is reset) */ + hspi->Instance->I2SCFGR &= (uint16_t)(~SPI_I2SCFGR_I2SMOD); + + hspi->ErrorCode = HAL_SPI_ERROR_NONE; + hspi->State= HAL_SPI_STATE_READY; + + return HAL_OK; +} + +/** + * @brief DeInitializes the SPI peripheral + * @param hspi: SPI handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SPI_DeInit(SPI_HandleTypeDef *hspi) +{ + /* Check the SPI handle allocation */ + if(hspi == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_SPI_ALL_INSTANCE(hspi->Instance)); + + hspi->State = HAL_SPI_STATE_BUSY; + + /* Disable the SPI Peripheral Clock */ + __HAL_SPI_DISABLE(hspi); + + /* DeInit the low level hardware: GPIO, CLOCK, NVIC... */ + HAL_SPI_MspDeInit(hspi); + + hspi->ErrorCode = HAL_SPI_ERROR_NONE; + hspi->State = HAL_SPI_STATE_RESET; + + __HAL_UNLOCK(hspi); + + return HAL_OK; +} + +/** + * @brief SPI MSP Init + * @param hspi: SPI handle + * @retval None + */ + __weak void HAL_SPI_MspInit(SPI_HandleTypeDef *hspi) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_SPI_MspInit could be implenetd in the user file + */ +} + +/** + * @brief SPI MSP DeInit + * @param hspi: SPI handle + * @retval None + */ + __weak void HAL_SPI_MspDeInit(SPI_HandleTypeDef *hspi) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_SPI_MspDeInit could be implenetd in the user file + */ +} + +/** + * @} + */ + +/** @defgroup HAL_SPI_Group2 I/O operation functions + * @brief Data transfers functions + * +@verbatim + =============================================================================== + ##### I/O operation functions ##### + =============================================================================== + This subsection provides a set of functions allowing to manage the SPI + data transfers. + + [..] The SPI supports master and slave mode : + + (#) There are two mode of transfer: + (+) Blocking mode: The communication is performed in polling mode. + The HAL status of all data processing is returned by the same function + after finishing transfer. + (+) No-Blocking mode: The communication is performed using Interrupts + or DMA, These API's return the HAL status. + The end of the data processing will be indicated through the + dedicated SPI IRQ when using Interrupt mode or the DMA IRQ when + using DMA mode. + The HAL_SPI_TxCpltCallback(), HAL_SPI_RxCpltCallback() and HAL_SPI_TxRxCpltCallback() user callbacks + will be executed respectivelly at the end of the transmit or Receive process + The HAL_SPI_ErrorCallback()user callback will be executed when a communication error is detected + + (#) Blocking mode API's are : + (+) HAL_SPI_Transmit()in 1Line (simplex) and 2Lines (full duplex) mode + (+) HAL_SPI_Receive() in 1Line (simplex) and 2Lines (full duplex) mode + (+) HAL_SPI_TransmitReceive() in full duplex mode + + (#) Non-Blocking mode API's with Interrupt are : + (+) HAL_SPI_Transmit_IT()in 1Line (simplex) and 2Lines (full duplex) mode + (+) HAL_SPI_Receive_IT() in 1Line (simplex) and 2Lines (full duplex) mode + (+) HAL_SPI_TransmitReceive_IT()in full duplex mode + (+) HAL_SPI_IRQHandler() + + (#) No-Blocking mode functions with DMA are : + (+) HAL_SPI_Transmit_DMA()in 1Line (simplex) and 2Lines (full duplex) mode + (+) HAL_SPI_Receive_DMA() in 1Line (simplex) and 2Lines (full duplex) mode + (+) HAL_SPI_TransmitReceie_DMA() in full duplex mode + + (#) A set of Transfer Complete Callbacks are provided in No_Blocking mode: + (+) HAL_SPI_TxCpltCallback() + (+) HAL_SPI_RxCpltCallback() + (+) HAL_SPI_ErrorCallback() + (+) HAL_SPI_TxRxCpltCallback() + +@endverbatim + * @{ + */ + +/** + * @brief Transmit an amount of data in blocking mode + * @param hspi: SPI handle + * @param pData: pointer to data buffer + * @param Size: amount of data to be sent + * @param Timeout: Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SPI_Transmit(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size, uint32_t Timeout) +{ + assert_param(IS_SPI_DIRECTION_2LINES_OR_1LINE(hspi->Init.Direction)); + + if(hspi->State != HAL_SPI_STATE_READY) + { + return HAL_BUSY; + } + + if((pData == NULL ) || (Size == 0)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(hspi); + + /* Set the transaction information */ + hspi->State = HAL_SPI_STATE_BUSY_TX; + hspi->ErrorCode = HAL_SPI_ERROR_NONE; + hspi->pTxBuffPtr = pData; + hspi->TxXferSize = Size; + hspi->TxXferCount = Size; + hspi->pRxBuffPtr = NULL; + hspi->RxXferSize = 0; + hspi->RxXferCount = 0; + + /* Reset CRC Calculation */ + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED) + { + __HAL_SPI_RESET_CRC(hspi); + } + + /* Configure communication direction : 1Line */ + if(hspi->Init.Direction == SPI_DIRECTION_1LINE) + { + __HAL_SPI_1LINE_TX(hspi); + } + + /* Check if the SPI is already enabled */ + if((hspi->Instance->CR1 & SPI_CR1_SPE) != SPI_CR1_SPE) + { + /* Enable SPI peripheral */ + __HAL_SPI_ENABLE(hspi); + } + + /* Transmit data in 16 Bit mode */ + if(hspi->Init.DataSize > SPI_DATASIZE_8BIT) + { + while (hspi->TxXferCount > 0) + { + /* Wait until TXE flag is set to send data */ + if(SPI_WaitFlagStateUntilTimeout(hspi,SPI_FLAG_TXE,SPI_FLAG_TXE,Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + hspi->Instance->DR = *((uint16_t *)hspi->pTxBuffPtr); + hspi->pTxBuffPtr += sizeof(uint16_t); + hspi->TxXferCount--; + } + } + /* Transmit data in 8 Bit mode */ + else + { + while (hspi->TxXferCount > 0) + { + if(hspi->TxXferCount != 0x1) + { + /* Wait until TXE flag is set to send data */ + if(SPI_WaitFlagStateUntilTimeout(hspi,SPI_FLAG_TXE,SPI_FLAG_TXE,Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + hspi->Instance->DR = *((uint16_t*)hspi->pTxBuffPtr); + hspi->pTxBuffPtr += sizeof(uint16_t); + hspi->TxXferCount -= 2; + } + else + { + /* Wait until TXE flag is set to send data */ + if(SPI_WaitFlagStateUntilTimeout(hspi,SPI_FLAG_TXE,SPI_FLAG_TXE,Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + *((__IO uint8_t*)&hspi->Instance->DR) = (*hspi->pTxBuffPtr++); + hspi->TxXferCount--; + } + } + } + + /* Enable CRC Transmission */ + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED) + { + hspi->Instance->CR1|= SPI_CR1_CRCNEXT; + } + + /* Check the end of the transaction */ + if(SPI_EndRxTxTransaction(hspi,Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + /* Clear OVERUN flag in 2 Lines communication mode because received is not read */ + if(hspi->Init.Direction == SPI_DIRECTION_2LINES) + { + __HAL_SPI_CLEAR_OVRFLAG(hspi); + } + + hspi->State = HAL_SPI_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hspi); + + if(hspi->ErrorCode != HAL_SPI_ERROR_NONE) + { + return HAL_ERROR; + } + else + { + return HAL_OK; + } +} + +/** + * @brief Receive an amount of data in blocking mode + * @param hspi: SPI handle + * @param pData: pointer to data buffer + * @param Size: amount of data to be sent + * @param Timeout: Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SPI_Receive(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size, uint32_t Timeout) +{ + __IO uint16_t tmpreg; + + if(hspi->State != HAL_SPI_STATE_READY) + { + return HAL_BUSY; + } + + if((pData == NULL ) || (Size == 0)) + { + return HAL_ERROR; + } + + if((hspi->Init.Mode == SPI_MODE_MASTER) && (hspi->Init.Direction == SPI_DIRECTION_2LINES)) + { + /* the receive process is not supported in 2Lines direction master mode */ + /* in this case we call the transmitReceive process */ + return HAL_SPI_TransmitReceive(hspi,pData,pData,Size,Timeout); + } + + /* Process Locked */ + __HAL_LOCK(hspi); + + hspi->State = HAL_SPI_STATE_BUSY_RX; + hspi->ErrorCode = HAL_SPI_ERROR_NONE; + hspi->pRxBuffPtr = pData; + hspi->RxXferSize = Size; + hspi->RxXferCount = Size; + hspi->pTxBuffPtr = NULL; + hspi->TxXferSize = 0; + hspi->TxXferCount = 0; + + /* Reset CRC Calculation */ + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED) + { + __HAL_SPI_RESET_CRC(hspi); + } + + /* Set the Rx Fido thresold */ + if(hspi->Init.DataSize > SPI_DATASIZE_8BIT) + { + /* set fiforxthresold according the reception data lenght: 16bit */ + CLEAR_BIT(hspi->Instance->CR2, SPI_RXFIFO_THRESHOLD); + } + else + { + /* set fiforxthresold according the reception data lenght: 8bit */ + SET_BIT(hspi->Instance->CR2, SPI_RXFIFO_THRESHOLD); + } + + /* Configure communication direction 1Line and enabled SPI if needed */ + if(hspi->Init.Direction == SPI_DIRECTION_1LINE) + { + __HAL_SPI_1LINE_RX(hspi); + } + + /* Check if the SPI is already enabled */ + if((hspi->Instance->CR1 & SPI_CR1_SPE) != SPI_CR1_SPE) + { + /* Enable SPI peripheral */ + __HAL_SPI_ENABLE(hspi); + } + + /* Receive data in 8 Bit mode */ + if(hspi->Init.DataSize <= SPI_DATASIZE_8BIT) + { + while(hspi->RxXferCount > 1) + { + /* Wait until the RXNE flag */ + if(SPI_WaitFlagStateUntilTimeout(hspi, SPI_FLAG_RXNE, SPI_FLAG_RXNE, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + (*hspi->pRxBuffPtr++)= *(__IO uint8_t *)&hspi->Instance->DR; + hspi->RxXferCount--; + } + } + else /* Receive data in 16 Bit mode */ + { + while(hspi->RxXferCount > 1 ) + { + /* Wait until RXNE flag is reset to read data */ + if(SPI_WaitFlagStateUntilTimeout(hspi, SPI_FLAG_RXNE, SPI_FLAG_RXNE, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + *((uint16_t*)hspi->pRxBuffPtr) = hspi->Instance->DR; + hspi->pRxBuffPtr += sizeof(uint16_t); + hspi->RxXferCount--; + } + } + + /* Enable CRC Transmission */ + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED) + { + hspi->Instance->CR1 |= SPI_CR1_CRCNEXT; + } + + /* Wait until RXNE flag is set */ + if(SPI_WaitFlagStateUntilTimeout(hspi, SPI_FLAG_RXNE, SPI_FLAG_RXNE, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + /* Receive last data in 16 Bit mode */ + if(hspi->Init.DataSize > SPI_DATASIZE_8BIT) + { + *((uint16_t*)hspi->pRxBuffPtr) = hspi->Instance->DR; + hspi->pRxBuffPtr += sizeof(uint16_t); + } + /* Receive last data in 8 Bit mode */ + else + { + (*hspi->pRxBuffPtr++) = *(__IO uint8_t *)&hspi->Instance->DR; + } + hspi->RxXferCount--; + + /* Read CRC from DR to close CRC calculation process */ + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED) + { + /* Wait until TXE flag */ + if(SPI_WaitFlagStateUntilTimeout(hspi, SPI_FLAG_RXNE, SPI_FLAG_RXNE, Timeout) != HAL_OK) + { + /* Erreur on the CRC reception */ + hspi->ErrorCode|= HAL_SPI_ERROR_CRC; + } + if(hspi->Init.DataSize > SPI_DATASIZE_8BIT) + { + tmpreg = hspi->Instance->DR; + } + else + { + tmpreg = *(__IO uint8_t *)&hspi->Instance->DR; + if((hspi->Init.DataSize == SPI_DATASIZE_8BIT) && (hspi->Init.CRCLength == SPI_CRC_LENGTH_16BIT)) + { + if(SPI_WaitFlagStateUntilTimeout(hspi, SPI_FLAG_RXNE, SPI_FLAG_RXNE, Timeout) != HAL_OK) + { + /* Erreur on the CRC reception */ + hspi->ErrorCode|= HAL_SPI_ERROR_CRC; + } + tmpreg = *(__IO uint8_t *)&hspi->Instance->DR; + } + } + } + + /* Check the end of the transaction */ + if(SPI_EndRxTransaction(hspi,Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + hspi->State = HAL_SPI_STATE_READY; + + /* Check if CRC error occurred */ + if(__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_CRCERR) != RESET) + { + hspi->ErrorCode|= HAL_SPI_ERROR_CRC; + __HAL_SPI_CLEAR_CRCERRFLAG(hspi); + + /* Process Unlocked */ + __HAL_UNLOCK(hspi); + return HAL_ERROR; + } + + /* Process Unlocked */ + __HAL_UNLOCK(hspi); + + if(hspi->ErrorCode != HAL_SPI_ERROR_NONE) + { + return HAL_ERROR; + } + else + { + return HAL_OK; + } +} + +/** + * @brief Transmit and Receive an amount of data in blocking mode + * @param hspi: SPI handle + * @param pTxData: pointer to transmission data buffer + * @param pRxData: pointer to reception data buffer to be + * @param Size: amount of data to be sent + * @param Timeout: Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size, uint32_t Timeout) +{ + __IO uint16_t tmpreg = 0; + uint32_t tickstart = 0; + + assert_param(IS_SPI_DIRECTION_2LINES(hspi->Init.Direction)); + + if(hspi->State != HAL_SPI_STATE_READY) + { + return HAL_BUSY; + } + + if((pTxData == NULL) || (pRxData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + tickstart = HAL_GetTick(); + + /* Process Locked */ + __HAL_LOCK(hspi); + + hspi->State = HAL_SPI_STATE_BUSY_TX_RX; + hspi->ErrorCode = HAL_SPI_ERROR_NONE; + hspi->pRxBuffPtr = pRxData; + hspi->RxXferCount = Size; + hspi->RxXferSize = Size; + hspi->pTxBuffPtr = pTxData; + hspi->TxXferCount = Size; + hspi->TxXferSize = Size; + + /* Reset CRC Calculation */ + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED) + { + __HAL_SPI_RESET_CRC(hspi); + } + + /* Set the Rx Fido threshold */ + if((hspi->Init.DataSize > SPI_DATASIZE_8BIT) || (hspi->RxXferCount > 1)) + { + /* set fiforxthreshold according the reception data lenght: 16bit */ + CLEAR_BIT(hspi->Instance->CR2, SPI_RXFIFO_THRESHOLD); + } + else + { + /* set fiforxthreshold according the reception data lenght: 8bit */ + SET_BIT(hspi->Instance->CR2, SPI_RXFIFO_THRESHOLD); + } + + /* Check if the SPI is already enabled */ + if((hspi->Instance->CR1 &SPI_CR1_SPE) != SPI_CR1_SPE) + { + /* Enable SPI peripheral */ + __HAL_SPI_ENABLE(hspi); + } + + /* Transmit and Receive data in 16 Bit mode */ + if(hspi->Init.DataSize > SPI_DATASIZE_8BIT) + { + while ((hspi->TxXferCount > 0 ) || (hspi->RxXferCount > 0)) + { + /* Wait until TXE flag */ + if((hspi->TxXferCount > 0) && ((hspi->Instance->SR & SPI_FLAG_TXE) == SPI_FLAG_TXE)) + { + hspi->Instance->DR = *((uint16_t *)hspi->pTxBuffPtr); + hspi->pTxBuffPtr += sizeof(uint16_t); + hspi->TxXferCount--; + + /* Enable CRC Transmission */ + if((hspi->TxXferCount == 0) && (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED)) + { + SET_BIT(hspi->Instance->CR1, SPI_CR1_CRCNEXT); + } + } + + /* Wait until RXNE flag */ + if((hspi->RxXferCount > 0) && ((hspi->Instance->SR & SPI_FLAG_RXNE) == SPI_FLAG_RXNE)) + { + *((uint16_t *)hspi->pRxBuffPtr) = hspi->Instance->DR; + hspi->pRxBuffPtr += sizeof(uint16_t); + hspi->RxXferCount--; + } + if((Timeout != HAL_MAX_DELAY) && ((int32_t)(HAL_GetTick()-tickstart) >= Timeout)) + { + hspi->State = HAL_SPI_STATE_READY; + __HAL_UNLOCK(hspi); + return HAL_TIMEOUT; + } + } + } + /* Transmit and Receive data in 8 Bit mode */ + else + { + while((hspi->TxXferCount > 0) || (hspi->RxXferCount > 0)) + { + /* check if TXE flag is set to send data */ + if((hspi->TxXferCount > 0) && ((hspi->Instance->SR & SPI_FLAG_TXE) == SPI_FLAG_TXE)) + { + if(hspi->TxXferCount > 2) + { + hspi->Instance->DR = *((uint16_t*)hspi->pTxBuffPtr); + hspi->pTxBuffPtr += sizeof(uint16_t); + hspi->TxXferCount -= 2; + } + else + { + *(__IO uint8_t *)&hspi->Instance->DR = (*hspi->pTxBuffPtr++); + hspi->TxXferCount--; + } + + /* Enable CRC Transmission */ + if((hspi->TxXferCount == 0) && (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED)) + { + SET_BIT(hspi->Instance->CR1, SPI_CR1_CRCNEXT); + } + } + + /* Wait until RXNE flag is reset */ + if((hspi->RxXferCount > 0) && ((hspi->Instance->SR & SPI_FLAG_RXNE) == SPI_FLAG_RXNE)) + { + if(hspi->RxXferCount > 1) + { + *((uint16_t*)hspi->pRxBuffPtr) = hspi->Instance->DR; + hspi->pRxBuffPtr += sizeof(uint16_t); + hspi->RxXferCount -= 2; + if(hspi->RxXferCount <= 1) + { + /* set fiforxthresold before to switch on 8 bit data size */ + SET_BIT(hspi->Instance->CR2, SPI_RXFIFO_THRESHOLD); + } + } + else + { + (*hspi->pRxBuffPtr++) = *(__IO uint8_t *)&hspi->Instance->DR; + hspi->RxXferCount--; + } + } + if((Timeout != HAL_MAX_DELAY) && ((int32_t)(HAL_GetTick()-tickstart) >= Timeout)) + { + hspi->State = HAL_SPI_STATE_READY; + __HAL_UNLOCK(hspi); + return HAL_TIMEOUT; + } + } + } + + /* Read CRC from DR to close CRC calculation process */ + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED) + { + /* Wait until TXE flag */ + if(SPI_WaitFlagStateUntilTimeout(hspi, SPI_FLAG_TXE, SPI_FLAG_TXE, Timeout) != HAL_OK) + { + /* Erreur on the CRC reception */ + hspi->ErrorCode|= HAL_SPI_ERROR_CRC; + } + + if(hspi->Init.DataSize == SPI_DATASIZE_16BIT) + { + tmpreg = hspi->Instance->DR; + } + else + { + tmpreg = *(__IO uint8_t *)&hspi->Instance->DR; + if(hspi->Init.CRCLength == SPI_CRC_LENGTH_16BIT) + { + if(SPI_WaitFlagStateUntilTimeout(hspi, SPI_FLAG_TXE, SPI_FLAG_TXE, Timeout) != HAL_OK) + { + /* Erreur on the CRC reception */ + hspi->ErrorCode|= HAL_SPI_ERROR_CRC; + } + tmpreg = *(__IO uint8_t *)&hspi->Instance->DR; + } + } + } + + /* Check the end of the transaction */ + if(SPI_EndRxTxTransaction(hspi,Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + hspi->State = HAL_SPI_STATE_READY; + + /* Check if CRC error occurred */ + if(__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_CRCERR) != RESET) + { + hspi->ErrorCode|= HAL_SPI_ERROR_CRC; + /* Clear CRC Flag */ + __HAL_SPI_CLEAR_CRCERRFLAG(hspi); + + /* Process Unlocked */ + __HAL_UNLOCK(hspi); + + return HAL_ERROR; + } + + /* Process Unlocked */ + __HAL_UNLOCK(hspi); + + if(hspi->ErrorCode != HAL_SPI_ERROR_NONE) + { + return HAL_ERROR; + } + else + { + return HAL_OK; + } +} + +/** + * @brief Transmit an amount of data in no-blocking mode with Interrupt + * @param hspi: SPI handle + * @param pData: pointer to data buffer + * @param Size: amount of data to be sent + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SPI_Transmit_IT(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size) +{ + assert_param(IS_SPI_DIRECTION_2LINES_OR_1LINE(hspi->Init.Direction)); + + if(hspi->State == HAL_SPI_STATE_READY) + { + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(hspi); + + hspi->State = HAL_SPI_STATE_BUSY_TX; + hspi->ErrorCode = HAL_SPI_ERROR_NONE; + hspi->pTxBuffPtr = pData; + hspi->TxXferSize = Size; + hspi->TxXferCount = Size; + hspi->pRxBuffPtr = NULL; + hspi->RxXferSize = 0; + hspi->RxXferCount = 0; + + /* Set the function for IT treatement */ + if(hspi->Init.DataSize > SPI_DATASIZE_8BIT ) + { + hspi->RxISR = NULL; + hspi->TxISR = SPI_TxISR_16BIT; + } + else + { + hspi->RxISR = NULL; + hspi->TxISR = SPI_TxISR_8BIT; + } + + /* Configure communication direction : 1Line */ + if(hspi->Init.Direction == SPI_DIRECTION_1LINE) + { + __HAL_SPI_1LINE_TX(hspi); + } + + /* Reset CRC Calculation */ + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED) + { + __HAL_SPI_RESET_CRC(hspi); + } + + /* Enable TXE and ERR interrupt */ + __HAL_SPI_ENABLE_IT(hspi,(SPI_IT_TXE)); + + /* Process Unlocked */ + __HAL_UNLOCK(hspi); + + /* Note : The SPI must be enabled after unlocking current process + to avoid the risk of SPI interrupt handle execution before current + process unlock */ + + /* Check if the SPI is already enabled */ + if((hspi->Instance->CR1 &SPI_CR1_SPE) != SPI_CR1_SPE) + { + /* Enable SPI peripheral */ + __HAL_SPI_ENABLE(hspi); + } + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive an amount of data in no-blocking mode with Interrupt + * @param hspi: SPI handle + * @param pData: pointer to data buffer + * @param Size: amount of data to be sent + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SPI_Receive_IT(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size) +{ + if(hspi->State == HAL_SPI_STATE_READY) + { + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(hspi); + + /* Configure communication */ + hspi->State = HAL_SPI_STATE_BUSY_RX; + hspi->ErrorCode = HAL_SPI_ERROR_NONE; + hspi->pRxBuffPtr = pData; + hspi->RxXferSize = Size; + hspi->RxXferCount = Size; + hspi->pTxBuffPtr = NULL; + hspi->TxXferSize = 0; + hspi->TxXferCount = 0; + + if((hspi->Init.Mode == SPI_MODE_MASTER) && (hspi->Init.Direction == SPI_DIRECTION_2LINES)) + { + /* Process Unlocked */ + __HAL_UNLOCK(hspi); + /* the receive process is not supported in 2Lines direction master mode */ + /* in this we call the transmitReceive process */ + return HAL_SPI_TransmitReceive_IT(hspi,pData,pData,Size); + } + + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED) + { + hspi->CRCSize = 1; + if((hspi->Init.DataSize <= SPI_DATASIZE_8BIT) && (hspi->Init.CRCLength == SPI_CRC_LENGTH_16BIT)) + { + hspi->CRCSize = 2; + } + } + else + { + hspi->CRCSize = 0; + } + + /* check the data size to adapt Rx threshold and the set the function for IT treatement */ + if(hspi->Init.DataSize > SPI_DATASIZE_8BIT ) + { + /* set fiforxthresold according the reception data lenght: 16 bit */ + CLEAR_BIT(hspi->Instance->CR2, SPI_RXFIFO_THRESHOLD); + hspi->RxISR = SPI_RxISR_16BIT; + hspi->TxISR = NULL; + } + else + { + /* set fiforxthresold according the reception data lenght: 8 bit */ + SET_BIT(hspi->Instance->CR2, SPI_RXFIFO_THRESHOLD); + hspi->RxISR = SPI_RxISR_8BIT; + hspi->TxISR = NULL; + } + + /* Configure communication direction : 1Line */ + if(hspi->Init.Direction == SPI_DIRECTION_1LINE) + { + __HAL_SPI_1LINE_RX(hspi); + } + + /* Reset CRC Calculation */ + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED) + { + __HAL_SPI_RESET_CRC(hspi); + } + + /* Enable TXE and ERR interrupt */ + __HAL_SPI_ENABLE_IT(hspi, (SPI_IT_RXNE | SPI_IT_ERR)); + + /* Process Unlocked */ + __HAL_UNLOCK(hspi); + + /* Note : The SPI must be enabled after unlocking current process + to avoid the risk of SPI interrupt handle execution before current + process unlock */ + + /* Check if the SPI is already enabled */ + if((hspi->Instance->CR1 & SPI_CR1_SPE) != SPI_CR1_SPE) + { + /* Enable SPI peripheral */ + __HAL_SPI_ENABLE(hspi); + } + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Transmit and Receive an amount of data in no-blocking mode with Interrupt + * @param hspi: SPI handle + * @param pTxData: pointer to transmission data buffer + * @param pRxData: pointer to reception data buffer to be + * @param Size: amount of data to be sent + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SPI_TransmitReceive_IT(SPI_HandleTypeDef *hspi, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size) +{ + assert_param(IS_SPI_DIRECTION_2LINES(hspi->Init.Direction)); + + if((hspi->State == HAL_SPI_STATE_READY) || \ + ((hspi->Init.Mode == SPI_MODE_MASTER) && (hspi->Init.Direction == SPI_DIRECTION_2LINES) && (hspi->State == HAL_SPI_STATE_BUSY_RX))) + { + if((pTxData == NULL ) || (pRxData == NULL ) || (Size == 0)) + { + return HAL_ERROR; + } + + /* Process locked */ + __HAL_LOCK(hspi); + + hspi->CRCSize = 0; + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED) + { + hspi->CRCSize = 1; + if((hspi->Init.DataSize <= SPI_DATASIZE_8BIT) && (hspi->Init.CRCLength == SPI_CRC_LENGTH_16BIT)) + { + hspi->CRCSize = 2; + } + } + + if(hspi->State != HAL_SPI_STATE_BUSY_RX) + { + hspi->State = HAL_SPI_STATE_BUSY_TX_RX; + } + + hspi->ErrorCode = HAL_SPI_ERROR_NONE; + hspi->pTxBuffPtr = pTxData; + hspi->TxXferSize = Size; + hspi->TxXferCount = Size; + hspi->pRxBuffPtr = pRxData; + hspi->RxXferSize = Size; + hspi->RxXferCount = Size; + + /* Set the function for IT treatement */ + if(hspi->Init.DataSize > SPI_DATASIZE_8BIT ) + { + hspi->RxISR = SPI_2linesRxISR_16BIT; + hspi->TxISR = SPI_2linesTxISR_16BIT; + } + else + { + hspi->RxISR = SPI_2linesRxISR_8BIT; + hspi->TxISR = SPI_2linesTxISR_8BIT; + } + + /* Reset CRC Calculation */ + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED) + { + __HAL_SPI_RESET_CRC(hspi); + } + + /* check if packing mode is enabled and if there is more than 2 data to receive */ + if((hspi->Init.DataSize > SPI_DATASIZE_8BIT) || (hspi->RxXferCount >= 2)) + { + /* set fiforxthresold according the reception data lenght: 16 bit */ + CLEAR_BIT(hspi->Instance->CR2, SPI_RXFIFO_THRESHOLD); + } + else + { + /* set fiforxthresold according the reception data lenght: 8 bit */ + SET_BIT(hspi->Instance->CR2, SPI_RXFIFO_THRESHOLD); + } + + /* Enable TXE, RXNE and ERR interrupt */ + __HAL_SPI_ENABLE_IT(hspi, (SPI_IT_TXE | SPI_IT_RXNE | SPI_IT_ERR)); + + /* Process Unlocked */ + __HAL_UNLOCK(hspi); + + /* Check if the SPI is already enabled */ + if((hspi->Instance->CR1 & SPI_CR1_SPE) != SPI_CR1_SPE) + { + /* Enable SPI peripheral */ + __HAL_SPI_ENABLE(hspi); + } + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Transmit an amount of data in no-blocking mode with DMA + * @param hspi: SPI handle + * @param pData: pointer to data buffer + * @param Size: amount of data to be sent + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SPI_Transmit_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size) +{ + assert_param(IS_SPI_DIRECTION_2LINES_OR_1LINE(hspi->Init.Direction)); + + if(hspi->State != HAL_SPI_STATE_READY) + { + return HAL_BUSY; + } + + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(hspi); + + hspi->State = HAL_SPI_STATE_BUSY_TX; + hspi->ErrorCode = HAL_SPI_ERROR_NONE; + hspi->pTxBuffPtr = pData; + hspi->TxXferSize = Size; + hspi->TxXferCount = Size; + hspi->pRxBuffPtr = NULL; + hspi->RxXferSize = 0; + hspi->RxXferCount = 0; + + /* Configure communication direction : 1Line */ + if(hspi->Init.Direction == SPI_DIRECTION_1LINE) + { + __HAL_SPI_1LINE_TX(hspi); + } + + /* Reset CRC Calculation */ + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED) + { + __HAL_SPI_RESET_CRC(hspi); + } + + /* Set the SPI TxDMA transfert complete callback */ + hspi->hdmatx->XferCpltCallback = HAL_SPI_DMATransmitCplt; + + /* Set the DMA error callback */ + hspi->hdmatx->XferErrorCallback = HAL_SPI_DMAError; + + CLEAR_BIT(hspi->Instance->CR2, SPI_CR2_LDMATX); + /* packing mode is enabled only if the DMA setting is HALWORD */ + if((hspi->Init.DataSize <= SPI_DATASIZE_8BIT) && (hspi->hdmatx->Init.MemDataAlignment == DMA_MDATAALIGN_HALFWORD)) + { + /* Check the even/odd of the data size + crc if enabled */ + if((hspi->TxXferCount & 0x1) == 0) + { + CLEAR_BIT(hspi->Instance->CR2, SPI_CR2_LDMATX); + hspi->TxXferCount = (hspi->TxXferCount >> 1); + } + else + { + SET_BIT(hspi->Instance->CR2, SPI_CR2_LDMATX); + hspi->TxXferCount = (hspi->TxXferCount >> 1) + 1; + } + } + + /* Enable the Tx DMA channel */ + HAL_DMA_Start_IT(hspi->hdmatx, (uint32_t)hspi->pTxBuffPtr, (uint32_t)&hspi->Instance->DR, hspi->TxXferCount); + + /* Check if the SPI is already enabled */ + if((hspi->Instance->CR1 &SPI_CR1_SPE) != SPI_CR1_SPE) + { + /* Enable SPI peripheral */ + __HAL_SPI_ENABLE(hspi); + } + + /* Enable Tx DMA Request */ + hspi->Instance->CR2 |= SPI_CR2_TXDMAEN; + + /* Process Unlocked */ + __HAL_UNLOCK(hspi); + + return HAL_OK; +} + +/** +* @brief Receive an amount of data in no-blocking mode with DMA +* @param hspi: SPI handle +* @param pData: pointer to data buffer +* @param Size: amount of data to be sent +* @retval HAL status +*/ +HAL_StatusTypeDef HAL_SPI_Receive_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size) +{ + if(hspi->State != HAL_SPI_STATE_READY) + { + return HAL_BUSY; + } + + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(hspi); + + hspi->State = HAL_SPI_STATE_BUSY_RX; + hspi->ErrorCode = HAL_SPI_ERROR_NONE; + hspi->pRxBuffPtr = pData; + hspi->RxXferSize = Size; + hspi->RxXferCount = Size; + hspi->pTxBuffPtr = NULL; + hspi->TxXferSize = 0; + hspi->TxXferCount = 0; + + if((hspi->Init.Mode == SPI_MODE_MASTER) && (hspi->Init.Direction == SPI_DIRECTION_2LINES)) + { + /* Process Unlocked */ + __HAL_UNLOCK(hspi); + /* the receive process is not supported in 2Lines direction master mode */ + /* in this case we call the transmitReceive process */ + return HAL_SPI_TransmitReceive_DMA(hspi,pData,pData,Size); + } + + /* Configure communication direction : 1Line */ + if(hspi->Init.Direction == SPI_DIRECTION_1LINE) + { + __HAL_SPI_1LINE_RX(hspi); + } + + /* Reset CRC Calculation */ + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED) + { + __HAL_SPI_RESET_CRC(hspi); + } + + /* packing mode management is enabled by the DMA settings */ + if((hspi->Init.DataSize <= SPI_DATASIZE_8BIT) && (hspi->hdmarx->Init.MemDataAlignment == DMA_MDATAALIGN_HALFWORD)) + { + /* Process Locked */ + __HAL_UNLOCK(hspi); + /* Restriction the DMA data received is not allowed in this mode */ + return HAL_ERROR; + } + + CLEAR_BIT(hspi->Instance->CR2, SPI_CR2_LDMARX); + if( hspi->Init.DataSize > SPI_DATASIZE_8BIT) + { + /* set fiforxthresold according the reception data lenght: 16bit */ + CLEAR_BIT(hspi->Instance->CR2, SPI_RXFIFO_THRESHOLD); + } + else + { + /* set fiforxthresold according the reception data lenght: 8bit */ + SET_BIT(hspi->Instance->CR2, SPI_RXFIFO_THRESHOLD); + } + + /* Set the SPI Rx DMA transfert complete callback */ + hspi->hdmarx->XferCpltCallback = HAL_SPI_DMAReceiveCplt; + + /* Set the DMA error callback */ + hspi->hdmarx->XferErrorCallback = HAL_SPI_DMAError; + + /* Enable Rx DMA Request */ + hspi->Instance->CR2 |= SPI_CR2_RXDMAEN; + + /* Enable the Rx DMA channel */ + HAL_DMA_Start_IT(hspi->hdmarx, (uint32_t)&hspi->Instance->DR, (uint32_t)hspi->pRxBuffPtr, hspi->RxXferCount); + + /* Process Unlocked */ + __HAL_UNLOCK(hspi); + + /* Check if the SPI is already enabled */ + if((hspi->Instance->CR1 & SPI_CR1_SPE) != SPI_CR1_SPE) + { + /* Enable SPI peripheral */ + __HAL_SPI_ENABLE(hspi); + } + + return HAL_OK; +} + +/** + * @brief Transmit and Receive an amount of data in no-blocking mode with DMA + * @param hspi: SPI handle + * @param pTxData: pointer to transmission data buffer + * @param pRxData: pointer to reception data buffer to be + * @param Size: amount of data to be sent + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SPI_TransmitReceive_DMA(SPI_HandleTypeDef *hspi, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size) +{ + assert_param(IS_SPI_DIRECTION_2LINES(hspi->Init.Direction)); + + if((hspi->State == HAL_SPI_STATE_READY) || + ((hspi->Init.Mode == SPI_MODE_MASTER) && (hspi->Init.Direction == SPI_DIRECTION_2LINES) && (hspi->State == HAL_SPI_STATE_BUSY_RX))) + { + if((pTxData == NULL ) || (pRxData == NULL ) || (Size == 0)) + { + return HAL_ERROR; + } + + /* Process locked */ + __HAL_LOCK(hspi); + + /* check if the transmit Receive function is not called by a receive master */ + if(hspi->State != HAL_SPI_STATE_BUSY_RX) + { + hspi->State = HAL_SPI_STATE_BUSY_TX_RX; + } + + hspi->ErrorCode = HAL_SPI_ERROR_NONE; + hspi->pTxBuffPtr = (uint8_t *)pTxData; + hspi->TxXferSize = Size; + hspi->TxXferCount = Size; + hspi->pRxBuffPtr = (uint8_t *)pRxData; + hspi->RxXferSize = Size; + hspi->RxXferCount = Size; + + /* Reset CRC Calculation + increase the rxsize */ + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED) + { + __HAL_SPI_RESET_CRC(hspi); + } + + /* Reset the threshold bit */ + CLEAR_BIT(hspi->Instance->CR2, SPI_CR2_LDMATX); + CLEAR_BIT(hspi->Instance->CR2, SPI_CR2_LDMARX); + + /* the packing mode management is enabled by the DMA settings according the spi data size */ + if(hspi->Init.DataSize > SPI_DATASIZE_8BIT) + { + /* set fiforxthreshold according the reception data lenght: 16bit */ + CLEAR_BIT(hspi->Instance->CR2, SPI_RXFIFO_THRESHOLD); + } + else + { + /* set fiforxthresold according the reception data lenght: 8bit */ + SET_BIT(hspi->Instance->CR2, SPI_RXFIFO_THRESHOLD); + + if(hspi->hdmatx->Init.MemDataAlignment == DMA_MDATAALIGN_HALFWORD) + { + if((hspi->TxXferSize & 0x1) == 0x0 ) + { + CLEAR_BIT(hspi->Instance->CR2, SPI_CR2_LDMATX); + hspi->TxXferCount = hspi->TxXferCount >> 1; + } + else + { + SET_BIT(hspi->Instance->CR2, SPI_CR2_LDMATX); + hspi->TxXferCount = (hspi->TxXferCount >> 1) + 1; + } + } + + if(hspi->hdmarx->Init.MemDataAlignment == DMA_MDATAALIGN_HALFWORD) + { + /* set fiforxthresold according the reception data lenght: 16bit */ + CLEAR_BIT(hspi->Instance->CR2, SPI_RXFIFO_THRESHOLD); + + /* Size must include the CRC lenght */ + if((hspi->RxXferCount & 0x1) == 0x0 ) + { + CLEAR_BIT(hspi->Instance->CR2, SPI_CR2_LDMARX); + hspi->RxXferCount = hspi->RxXferCount >> 1; + } + else + { + SET_BIT(hspi->Instance->CR2, SPI_CR2_LDMARX); + hspi->RxXferCount = (hspi->RxXferCount >> 1) + 1; + } + } + } + + /* Set the SPI Rx DMA transfer complete callback because the last generated transfer request is + the reception request (RXNE) */ + if(hspi->State == HAL_SPI_STATE_BUSY_RX) + { + hspi->hdmarx->XferCpltCallback = HAL_SPI_DMAReceiveCplt; + } + else + { + hspi->hdmarx->XferCpltCallback = HAL_SPI_DMATransmitReceiveCplt; + } + /* Set the DMA error callback */ + hspi->hdmarx->XferErrorCallback = HAL_SPI_DMAError; + + /* Enable Rx DMA Request */ + hspi->Instance->CR2 |= SPI_CR2_RXDMAEN; + + /* Enable the Rx DMA channel */ + HAL_DMA_Start_IT(hspi->hdmarx, (uint32_t)&hspi->Instance->DR, (uint32_t) hspi->pRxBuffPtr, hspi->RxXferCount); + + /* Set the SPI Tx DMA transfer complete callback as NULL because the communication closing + is performed in DMA reception complete callback */ + hspi->hdmatx->XferCpltCallback = NULL; + + /* Set the DMA error callback */ + hspi->hdmatx->XferErrorCallback = HAL_SPI_DMAError; + + /* Enable the Tx DMA channel */ + HAL_DMA_Start_IT(hspi->hdmatx, (uint32_t)hspi->pTxBuffPtr, (uint32_t)&hspi->Instance->DR, hspi->TxXferCount); + + /* Check if the SPI is already enabled */ + if((hspi->Instance->CR1 &SPI_CR1_SPE) != SPI_CR1_SPE) + { + /* Enable SPI peripheral */ + __HAL_SPI_ENABLE(hspi); + } + + /* Enable Tx DMA Request */ + hspi->Instance->CR2 |= SPI_CR2_TXDMAEN; + + /* Process Unlocked */ + __HAL_UNLOCK(hspi); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief This function handles SPI interrupt request. + * @param hspi: SPI handle + * @retval HAL status + */ +void HAL_SPI_IRQHandler(SPI_HandleTypeDef *hspi) +{ + /* SPI in mode Receiver ----------------------------------------------------*/ + if((__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_OVR) == RESET) && + (__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_RXNE) != RESET) && (__HAL_SPI_GET_IT_SOURCE(hspi, SPI_IT_RXNE) != RESET)) + { + hspi->RxISR(hspi); + return; + } + + /* SPI in mode Tramitter ---------------------------------------------------*/ + if((__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_TXE) != RESET) && (__HAL_SPI_GET_IT_SOURCE(hspi, SPI_IT_TXE) != RESET)) + { + hspi->TxISR(hspi); + return; + } + + /* SPI in Erreur Treatment ---------------------------------------------------*/ + if((hspi->Instance->SR & (SPI_FLAG_MODF | SPI_FLAG_OVR | SPI_FLAG_FRE)) != RESET) + { + /* SPI Overrun error interrupt occured -------------------------------------*/ + if(__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_OVR) != RESET) + { + if(hspi->State != HAL_SPI_STATE_BUSY_TX) + { + hspi->ErrorCode |= HAL_SPI_ERROR_OVR; + __HAL_SPI_CLEAR_OVRFLAG(hspi); + } + else + { + return; + } + } + + /* SPI Mode Fault error interrupt occured -------------------------------------*/ + if(__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_MODF) != RESET) + { + hspi->ErrorCode |= HAL_SPI_ERROR_MODF; + __HAL_SPI_CLEAR_MODFFLAG(hspi); + } + + /* SPI Frame error interrupt occured ----------------------------------------*/ + if(__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_FRE) != RESET) + { + hspi->ErrorCode |= HAL_SPI_ERROR_FRE; + __HAL_SPI_CLEAR_FREFLAG(hspi); + } + + __HAL_SPI_DISABLE_IT(hspi, SPI_IT_RXNE | SPI_IT_TXE | SPI_IT_ERR); + HAL_SPI_ErrorCallback(hspi); + + return; + } +} + +/** + * @brief DMA SPI transmit process complete callback + * @param hdma : DMA handle + * @retval None + */ +static void HAL_SPI_DMATransmitCplt(DMA_HandleTypeDef *hdma) +{ + SPI_HandleTypeDef* hspi = ( SPI_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + + /* Disable Tx DMA Request */ + hspi->Instance->CR2 &= (uint32_t)(~SPI_CR2_TXDMAEN); + + /* Check the end of the transaction */ + SPI_EndRxTxTransaction(hspi,SPI_DEFAULT_TIMEOUT); + + /* Clear OVERUN flag in 2 Lines communication mode because received data is not read */ + if(hspi->Init.Direction == SPI_DIRECTION_2LINES) + { + __HAL_SPI_CLEAR_OVRFLAG(hspi); + } + + hspi->TxXferCount = 0; + hspi->State = HAL_SPI_STATE_READY; + + /* Check if CRC error occurred or Error code */ + if(__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_CRCERR) != RESET) + { + hspi->ErrorCode|= HAL_SPI_ERROR_CRC; + __HAL_SPI_CLEAR_CRCERRFLAG(hspi); + HAL_SPI_ErrorCallback(hspi); + } + else + { + if(hspi->ErrorCode == HAL_SPI_ERROR_NONE) + { + HAL_SPI_TxCpltCallback(hspi); + } + else + { + HAL_SPI_ErrorCallback(hspi); + } + } +} + +/** + * @brief DMA SPI receive process complete callback + * @param hdma : DMA handle + * @retval None + */ +static void HAL_SPI_DMAReceiveCplt(DMA_HandleTypeDef *hdma) +{ + __IO uint16_t tmpreg; + SPI_HandleTypeDef* hspi = ( SPI_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + + /* CRC handling */ + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED) + { + /* Wait until TXE flag */ + if(SPI_WaitFlagStateUntilTimeout(hspi, SPI_FLAG_RXNE, SPI_FLAG_RXNE, SPI_DEFAULT_TIMEOUT) != HAL_OK) + { + /* Erreur on the CRC reception */ + hspi->ErrorCode|= HAL_SPI_ERROR_CRC; + } + if(hspi->Init.DataSize > SPI_DATASIZE_8BIT) + { + tmpreg = hspi->Instance->DR; + } + else + { + tmpreg = *(__IO uint8_t *)&hspi->Instance->DR; + if(hspi->Init.CRCLength == SPI_CRC_LENGTH_16BIT) + { + if(SPI_WaitFlagStateUntilTimeout(hspi, SPI_FLAG_RXNE, SPI_FLAG_RXNE, SPI_DEFAULT_TIMEOUT) != HAL_OK) + { + /* Erreur on the CRC reception */ + hspi->ErrorCode|= HAL_SPI_ERROR_CRC; + } + tmpreg = *(__IO uint8_t *)&hspi->Instance->DR; + } + } + } + + /* Disable Rx DMA Request */ + hspi->Instance->CR2 &= (uint32_t)(~SPI_CR2_RXDMAEN); + /* Disable Tx DMA Request (done by default to handle the case master rx direction 2 lines) */ + hspi->Instance->CR2 &= (uint32_t)(~SPI_CR2_TXDMAEN); + + /* Check the end of the transaction */ + SPI_EndRxTransaction(hspi,SPI_DEFAULT_TIMEOUT); + + hspi->RxXferCount = 0; + hspi->State = HAL_SPI_STATE_READY; + + /* Check if CRC error occurred */ + if(__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_CRCERR) != RESET) + { + hspi->ErrorCode|= HAL_SPI_ERROR_CRC; + __HAL_SPI_CLEAR_CRCERRFLAG(hspi); + HAL_SPI_RxCpltCallback(hspi); + } + else + { + if(hspi->ErrorCode == HAL_SPI_ERROR_NONE) + { + HAL_SPI_RxCpltCallback(hspi); + } + else + { + HAL_SPI_ErrorCallback(hspi); + } + } +} + +/** + * @brief DMA SPI transmit receive process complete callback + * @param hdma : DMA handle + * @retval None + */ + +static void HAL_SPI_DMATransmitReceiveCplt(DMA_HandleTypeDef *hdma) +{ + __IO int16_t tmpreg; + SPI_HandleTypeDef* hspi = ( SPI_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + + /* CRC handling */ + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED) + { + if((hspi->Init.DataSize == SPI_DATASIZE_8BIT) && (hspi->Init.CRCLength == SPI_CRC_LENGTH_8BIT)) + { + if(SPI_WaitFifoStateUntilTimeout(hspi, SPI_FLAG_FRLVL, SPI_FRLVL_QUARTER_FULL, SPI_DEFAULT_TIMEOUT) != HAL_OK) + { + /* Erreur on the CRC reception */ + hspi->ErrorCode|= HAL_SPI_ERROR_CRC; + } + tmpreg = *(__IO uint8_t *)&hspi->Instance->DR; + } + else + { + if(SPI_WaitFifoStateUntilTimeout(hspi, SPI_FLAG_FRLVL, SPI_FRLVL_HALF_FULL, SPI_DEFAULT_TIMEOUT) != HAL_OK) + { + /* Erreur on the CRC reception */ + hspi->ErrorCode|= HAL_SPI_ERROR_CRC; + } + tmpreg = hspi->Instance->DR; + } + } + + /* Check the end of the transaction */ + SPI_EndRxTxTransaction(hspi,SPI_DEFAULT_TIMEOUT); + + /* Disable Tx DMA Request */ + CLEAR_BIT(hspi->Instance->CR2, SPI_CR2_TXDMAEN); + + /* Disable Rx DMA Request */ + CLEAR_BIT(hspi->Instance->CR2, SPI_CR2_RXDMAEN); + + hspi->TxXferCount = 0; + hspi->RxXferCount = 0; + hspi->State = HAL_SPI_STATE_READY; + + /* Check if CRC error occurred */ + if(__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_CRCERR) != RESET) + { + hspi->ErrorCode = HAL_SPI_ERROR_CRC; + __HAL_SPI_CLEAR_CRCERRFLAG(hspi); + HAL_SPI_ErrorCallback(hspi); + } + else + { + if(hspi->ErrorCode == HAL_SPI_ERROR_NONE) + { + HAL_SPI_TxRxCpltCallback(hspi); + } + else + { + HAL_SPI_ErrorCallback(hspi); + } + } +} + +/** + * @brief DMA SPI communication error callback + * @param hdma : DMA handle + * @retval None + */ +static void HAL_SPI_DMAError(DMA_HandleTypeDef *hdma) +{ + SPI_HandleTypeDef* hspi = ( SPI_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + hspi->TxXferCount = 0; + hspi->RxXferCount = 0; + hspi->ErrorCode|= HAL_SPI_ERROR_DMA; + hspi->State = HAL_SPI_STATE_READY; + HAL_SPI_ErrorCallback(hspi); +} + +/** + * @brief Rx Handler for Transmit and Receive in Interrupt mode + * @param hspi: SPI handle + */ +static void SPI_2linesRxISR_8BIT(struct __SPI_HandleTypeDef *hspi) +{ + /* Receive data in packing mode */ + if(hspi->RxXferCount > 1) + { + *((uint16_t*)hspi->pRxBuffPtr) = hspi->Instance->DR; + hspi->pRxBuffPtr += sizeof(uint16_t); + hspi->RxXferCount -= 2; + if(hspi->RxXferCount == 1) + { + /* set fiforxthresold according the reception data lenght: 8bit */ + SET_BIT(hspi->Instance->CR2, SPI_RXFIFO_THRESHOLD); + } + } + /* Receive data in 8 Bit mode */ + else + { + *hspi->pRxBuffPtr++ = *((__IO uint8_t *)&hspi->Instance->DR); + hspi->RxXferCount--; + } + + /* check end of the reception */ + if(hspi->RxXferCount == 0) + { + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED) + { + hspi->RxISR = SPI_2linesRxISR_8BITCRC; + return; + } + + /* Disable RXNE interrupt */ + __HAL_SPI_DISABLE_IT(hspi, SPI_IT_RXNE); + + if(hspi->TxXferCount == 0) + { + SPI_CloseRxTx_ISR(hspi); + } + } +} + +/** + * @brief Rx Handler for Transmit and Receive in Interrupt mode + * @param hspi: SPI handle + */ +static void SPI_2linesRxISR_8BITCRC(struct __SPI_HandleTypeDef *hspi) +{ + __IO uint8_t tmpreg; + + tmpreg = *((__IO uint8_t *)&hspi->Instance->DR); + hspi->CRCSize--; + + /* check end of the reception */ + if(hspi->CRCSize == 0) + { + /* Disable RXNE interrupt */ + __HAL_SPI_DISABLE_IT(hspi, SPI_IT_RXNE); + + if(hspi->TxXferCount == 0) + { + SPI_CloseRxTx_ISR(hspi); + } + } +} + +/** + * @brief Tx Handler for Transmit and Receive in Interrupt mode + * @param hspi: SPI handle + */ +static void SPI_2linesTxISR_8BIT(struct __SPI_HandleTypeDef *hspi) +{ + /* Transmit data in packing Bit mode */ + if(hspi->TxXferCount >= 2) + { + hspi->Instance->DR = *((uint16_t *)hspi->pTxBuffPtr); + hspi->pTxBuffPtr += sizeof(uint16_t); + hspi->TxXferCount -= 2; + } + /* Transmit data in 8 Bit mode */ + else + { + *(__IO uint8_t *)&hspi->Instance->DR = (*hspi->pTxBuffPtr++); + hspi->TxXferCount--; + } + + /* check the end of the transmission */ + if(hspi->TxXferCount == 0) + { + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED) + { + hspi->Instance->CR1 |= SPI_CR1_CRCNEXT; + } + /* Disable TXE interrupt */ + __HAL_SPI_DISABLE_IT(hspi, SPI_IT_TXE); + + if(hspi->RxXferCount == 0) + { + SPI_CloseRxTx_ISR(hspi); + } + } +} + +/** + * @brief Rx 16Bit Handler for Transmit and Receive in Interrupt mode + * @param hspi: SPI handle + */ +static void SPI_2linesRxISR_16BIT(struct __SPI_HandleTypeDef *hspi) +{ + /* Receive data in 16 Bit mode */ + *((uint16_t*)hspi->pRxBuffPtr) = hspi->Instance->DR; + hspi->pRxBuffPtr += sizeof(uint16_t); + hspi->RxXferCount--; + + if(hspi->RxXferCount == 0) + { + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED) + { + hspi->RxISR = SPI_2linesRxISR_16BITCRC; + return; + } + + /* Disable RXNE interrupt */ + __HAL_SPI_DISABLE_IT(hspi, SPI_IT_RXNE); + + if(hspi->TxXferCount == 0) + { + SPI_CloseRxTx_ISR(hspi); + } + } +} + +/** + * @brief Manage the CRC 16bit receive for Transmit and Receive in Interrupt mode + * @param hspi: SPI handle + */ +static void SPI_2linesRxISR_16BITCRC(struct __SPI_HandleTypeDef *hspi) +{ + __IO uint16_t tmpreg; + /* Receive data in 16 Bit mode */ + tmpreg = hspi->Instance->DR; + + /* Disable RXNE interrupt */ + __HAL_SPI_DISABLE_IT(hspi, SPI_IT_RXNE); + + SPI_CloseRxTx_ISR(hspi); +} + +/** + * @brief Tx Handler for Transmit and Receive in Interrupt mode + * @param hspi: SPI handle + */ +static void SPI_2linesTxISR_16BIT(struct __SPI_HandleTypeDef *hspi) +{ + /* Transmit data in 16 Bit mode */ + hspi->Instance->DR = *((uint16_t *)hspi->pTxBuffPtr); + hspi->pTxBuffPtr += sizeof(uint16_t); + hspi->TxXferCount--; + + /* Enable CRC Transmission */ + if(hspi->TxXferCount == 0) + { + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED) + { + hspi->Instance->CR1 |= SPI_CR1_CRCNEXT; + } + /* Disable TXE interrupt */ + __HAL_SPI_DISABLE_IT(hspi, SPI_IT_TXE); + + if(hspi->RxXferCount == 0) + { + SPI_CloseRxTx_ISR(hspi); + } + } +} + +/** + * @brief Manage the CRC receive in Interrupt context + * @param hspi: SPI handle + */ +static void SPI_RxISR_8BITCRC(struct __SPI_HandleTypeDef *hspi) +{ + __IO uint8_t tmpreg; + tmpreg = *((__IO uint8_t*)&hspi->Instance->DR); + hspi->CRCSize--; + + if(hspi->CRCSize == 0) + { + SPI_CloseRx_ISR(hspi); + } +} + +/** + * @brief Manage the recieve in Interrupt context + * @param hspi: SPI handle + */ +static void SPI_RxISR_8BIT(struct __SPI_HandleTypeDef *hspi) +{ + *hspi->pRxBuffPtr++ = (*(__IO uint8_t *)&hspi->Instance->DR); + hspi->RxXferCount--; + + /* Enable CRC Transmission */ + if((hspi->RxXferCount == 1) && (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED)) + { + hspi->Instance->CR1 |= SPI_CR1_CRCNEXT; + } + + if(hspi->RxXferCount == 0) + { + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED) + { + hspi->RxISR = SPI_RxISR_8BITCRC; + return; + } + SPI_CloseRx_ISR(hspi); + } +} + +/** + * @brief Manage the CRC 16bit recieve in Interrupt context + * @param hspi: SPI handle + */ +static void SPI_RxISR_16BITCRC(struct __SPI_HandleTypeDef *hspi) +{ + __IO uint16_t tmpreg; + + tmpreg = hspi->Instance->DR; + + /* Disable RXNE and ERR interrupt */ + __HAL_SPI_DISABLE_IT(hspi, (SPI_IT_RXNE | SPI_IT_ERR)); + + SPI_CloseRx_ISR(hspi); +} + +/** + * @brief Manage the 16Bit recieve in Interrupt context + * @param hspi: SPI handle + */ +static void SPI_RxISR_16BIT(struct __SPI_HandleTypeDef *hspi) +{ + *((uint16_t *)hspi->pRxBuffPtr) = hspi->Instance->DR; + hspi->pRxBuffPtr += sizeof(uint16_t); + hspi->RxXferCount--; + + /* Enable CRC Transmission */ + if((hspi->RxXferCount == 1) && (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED)) + { + hspi->Instance->CR1 |= SPI_CR1_CRCNEXT; + } + + if(hspi->RxXferCount == 0) + { + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED) + { + hspi->RxISR = SPI_RxISR_16BITCRC; + return; + } + SPI_CloseRx_ISR(hspi); + } +} + +/** + * @brief Handle the data 8Bit transmit in Interrupt mode + * @param hspi: SPI handle + */ +static void SPI_TxISR_8BIT(struct __SPI_HandleTypeDef *hspi) +{ + *(__IO uint8_t *)&hspi->Instance->DR = (*hspi->pTxBuffPtr++); + hspi->TxXferCount--; + + if(hspi->TxXferCount == 0) + { + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED) + { + /* Enable CRC Transmission */ + hspi->Instance->CR1 |= SPI_CR1_CRCNEXT; + } + SPI_CloseTx_ISR(hspi); + } +} + +/** + * @brief Handle the data 16Bit transmit in Interrupt mode + * @param hspi: SPI handle + */ +static void SPI_TxISR_16BIT(struct __SPI_HandleTypeDef *hspi) +{ + /* Transmit data in 16 Bit mode */ + hspi->Instance->DR = *((uint16_t *)hspi->pTxBuffPtr); + hspi->pTxBuffPtr += sizeof(uint16_t); + hspi->TxXferCount--; + + if(hspi->TxXferCount == 0) + { + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED) + { + /* Enable CRC Transmission */ + hspi->Instance->CR1 |= SPI_CR1_CRCNEXT; + } + SPI_CloseTx_ISR(hspi); + } +} + +/** + * @brief This function handles SPI Communication Timeout. + * @param hspi: SPI handle + * @param Flag : SPI flag to check + * @param State : flag state to check + * @param Timeout : Timeout duration + * @retval HAL status + */ +static HAL_StatusTypeDef SPI_WaitFlagStateUntilTimeout(SPI_HandleTypeDef *hspi, uint32_t Flag, uint32_t State, uint32_t Timeout) +{ + uint32_t tickstart = HAL_GetTick(); + + while((hspi->Instance->SR & Flag) != State) + { + if(Timeout != HAL_MAX_DELAY) + { + if((HAL_GetTick()-tickstart) >= Timeout) + { + /* Disable the SPI and reset the CRC: the CRC value should be cleared + on both master and slave sides in order to resynchronize the master + and slave for their respective CRC calculation */ + + /* Disable TXE, RXNE and ERR interrupts for the interrupt process */ + __HAL_SPI_DISABLE_IT(hspi, (SPI_IT_TXE | SPI_IT_RXNE | SPI_IT_ERR)); + + if((hspi->Init.Mode == SPI_MODE_MASTER)&&((hspi->Init.Direction == SPI_DIRECTION_1LINE)||(hspi->Init.Direction == SPI_DIRECTION_2LINES_RXONLY))) + { + /* Disable SPI peripheral */ + __HAL_SPI_DISABLE(hspi); + } + + /* Reset CRC Calculation */ + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED) + { + __HAL_SPI_RESET_CRC(hspi); + } + + hspi->State= HAL_SPI_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hspi); + + return HAL_TIMEOUT; + } + } + } + + return HAL_OK; +} + +/** + * @brief This function handles SPI Communication Timeout. + * @param hspi: SPI handle + * @param Fifo: Fifo to check + * @param State: Fifo state to check + * @param Timeout : Timeout duration + * @retval HAL status + */ +static HAL_StatusTypeDef SPI_WaitFifoStateUntilTimeout(SPI_HandleTypeDef *hspi, uint32_t Fifo, uint32_t State, uint32_t Timeout) +{ + __IO uint8_t tmpreg; + uint32_t tickstart = HAL_GetTick(); + + while((hspi->Instance->SR & Fifo) != State) + { + if((Fifo == SPI_SR_FRLVL) && (State == SPI_FRLVL_EMPTY)) + { + tmpreg = *((__IO uint8_t*)&hspi->Instance->DR); + } + if(Timeout != HAL_MAX_DELAY) + { + if((HAL_GetTick()-tickstart) >= Timeout) + { + /* Disable the SPI and reset the CRC: the CRC value should be cleared + on both master and slave sides in order to resynchronize the master + and slave for their respective CRC calculation */ + + /* Disable TXE, RXNE and ERR interrupts for the interrupt process */ + __HAL_SPI_DISABLE_IT(hspi, (SPI_IT_TXE | SPI_IT_RXNE | SPI_IT_ERR)); + + if((hspi->Init.Mode == SPI_MODE_MASTER)&&((hspi->Init.Direction == SPI_DIRECTION_1LINE)||(hspi->Init.Direction == SPI_DIRECTION_2LINES_RXONLY))) + { + /* Disable SPI peripheral */ + __HAL_SPI_DISABLE(hspi); + } + + /* Reset CRC Calculation */ + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED) + { + __HAL_SPI_RESET_CRC(hspi); + } + + hspi->State = HAL_SPI_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hspi); + + return HAL_TIMEOUT; + } + } + } + + return HAL_OK; +} + +/** + * @brief This function handles the check of the RX transaction complete. + * @param hspi: SPI handle + * @param Timeout : Timeout duration + */ +static HAL_StatusTypeDef SPI_EndRxTransaction(SPI_HandleTypeDef *hspi, uint32_t Timeout) +{ + if((hspi->Init.Mode == SPI_MODE_MASTER)&&((hspi->Init.Direction == SPI_DIRECTION_1LINE)||(hspi->Init.Direction == SPI_DIRECTION_2LINES_RXONLY))) + { + /* Disable SPI peripheral */ + __HAL_SPI_DISABLE(hspi); + } + if(SPI_WaitFlagStateUntilTimeout(hspi, SPI_FLAG_BSY, RESET, Timeout) != HAL_OK) + { + hspi->ErrorCode |= HAL_SPI_ERROR_FLAG; + return HAL_TIMEOUT; + } + if(SPI_WaitFifoStateUntilTimeout(hspi, SPI_FLAG_FRLVL, SPI_FRLVL_EMPTY, Timeout) != HAL_OK) + { + hspi->ErrorCode |= HAL_SPI_ERROR_FLAG; + return HAL_TIMEOUT; + } + + return HAL_OK; +} + +/** + * @brief This function handles the check of the RXTX or TX transaction complete. + * @param hspi: SPI handle + * @param Timeout : Timeout duration + */ +static HAL_StatusTypeDef SPI_EndRxTxTransaction(SPI_HandleTypeDef *hspi, uint32_t Timeout) +{ + /* Procedure to check the transaction complete */ + if(SPI_WaitFifoStateUntilTimeout(hspi, SPI_FLAG_FTLVL, SPI_FTLVL_EMPTY, Timeout) != HAL_OK) + { + hspi->ErrorCode |= HAL_SPI_ERROR_FLAG; + return HAL_TIMEOUT; + } + if(SPI_WaitFlagStateUntilTimeout(hspi, SPI_FLAG_BSY, RESET, Timeout) != HAL_OK) + { + hspi->ErrorCode |= HAL_SPI_ERROR_FLAG; + return HAL_TIMEOUT; + } + if(SPI_WaitFifoStateUntilTimeout(hspi, SPI_FLAG_FRLVL, SPI_FRLVL_EMPTY, Timeout) != HAL_OK) + { + hspi->ErrorCode |= HAL_SPI_ERROR_FLAG; + return HAL_TIMEOUT; + } + return HAL_OK; +} + +/** + * @brief This function handles the close of the RXTX transaction. + * @param hspi: SPI handle + */ +static void SPI_CloseRxTx_ISR(SPI_HandleTypeDef *hspi) +{ + /* Disable ERR interrupt */ + __HAL_SPI_DISABLE_IT(hspi, SPI_IT_ERR); + + /* Check the end of the transaction */ + SPI_EndRxTxTransaction(hspi,SPI_DEFAULT_TIMEOUT); + + /* Check if CRC error occurred */ + if(__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_CRCERR) != RESET) + { + hspi->State = HAL_SPI_STATE_READY; + hspi->ErrorCode|= HAL_SPI_ERROR_CRC; + __HAL_SPI_CLEAR_CRCERRFLAG(hspi); + HAL_SPI_ErrorCallback(hspi); + } + else + { + if(hspi->ErrorCode == HAL_SPI_ERROR_NONE) + { + if(hspi->State == HAL_SPI_STATE_BUSY_RX) + { + hspi->State = HAL_SPI_STATE_READY; + HAL_SPI_RxCpltCallback(hspi); + } + else + { + hspi->State = HAL_SPI_STATE_READY; + HAL_SPI_TxRxCpltCallback(hspi); + } + } + else + { + hspi->State = HAL_SPI_STATE_READY; + HAL_SPI_ErrorCallback(hspi); + } + } +} + +/** + * @brief This function handles the close of the RX transaction. + * @param hspi: SPI handle + */ +static void SPI_CloseRx_ISR(SPI_HandleTypeDef *hspi) +{ + /* Disable RXNE and ERR interrupt */ + __HAL_SPI_DISABLE_IT(hspi, (SPI_IT_RXNE | SPI_IT_ERR)); + + /* Check the end of the transaction */ + SPI_EndRxTransaction(hspi,SPI_DEFAULT_TIMEOUT); + + hspi->State = HAL_SPI_STATE_READY; + + /* Check if CRC error occurred */ + if(__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_CRCERR) != RESET) + { + hspi->ErrorCode|= HAL_SPI_ERROR_CRC; + __HAL_SPI_CLEAR_CRCERRFLAG(hspi); + HAL_SPI_ErrorCallback(hspi); + } + else + { + if(hspi->ErrorCode == HAL_SPI_ERROR_NONE) + { + HAL_SPI_RxCpltCallback(hspi); + } + else + { + HAL_SPI_ErrorCallback(hspi); + } + } +} + +/** + * @brief This function handles the close of the TX transaction. + * @param hspi: SPI handle + */ +static void SPI_CloseTx_ISR(SPI_HandleTypeDef *hspi) +{ + /* Disable TXE and ERR interrupt */ + __HAL_SPI_DISABLE_IT(hspi, (SPI_IT_TXE | SPI_IT_ERR)); + + /* Check the end of the transaction */ + SPI_EndRxTxTransaction(hspi,SPI_DEFAULT_TIMEOUT); + + /* Clear OVERUN flag in 2 Lines communication mode because received is not read */ + if(hspi->Init.Direction == SPI_DIRECTION_2LINES) + { + __HAL_SPI_CLEAR_OVRFLAG(hspi); + } + + hspi->State = HAL_SPI_STATE_READY; + if(hspi->ErrorCode != HAL_SPI_ERROR_NONE) + { + HAL_SPI_ErrorCallback(hspi); + } + else + { + HAL_SPI_TxCpltCallback(hspi); + } +} + +/** + * @brief Tx Transfer completed callbacks + * @param hspi: SPI handle + * @retval None + */ +__weak void HAL_SPI_TxCpltCallback(SPI_HandleTypeDef *hspi) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_SPI_TxCpltCallback could be implenetd in the user file + */ +} + +/** + * @brief Rx Transfer completed callbacks + * @param hspi: SPI handle + * @retval None + */ +__weak void HAL_SPI_RxCpltCallback(SPI_HandleTypeDef *hspi) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_SPI_RxCpltCallback could be implenetd in the user file + */ +} + +/** + * @brief Tx and Rx Transfer completed callbacks + * @param hspi: SPI handle + * @retval None + */ +__weak void HAL_SPI_TxRxCpltCallback(SPI_HandleTypeDef *hspi) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_SPI_TxRxCpltCallback could be implenetd in the user file + */ +} + +/** + * @brief SPI error callbacks + * @param hspi: SPI handle + * @retval None + */ + __weak void HAL_SPI_ErrorCallback(SPI_HandleTypeDef *hspi) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_SPI_ErrorCallback could be implenetd in the user file + */ +} + +/** + * @} + */ + +/** @defgroup HAL_SPI_Group3 Peripheral Control functions + * @brief SPI control functions + * +@verbatim + =============================================================================== + ##### Peripheral Control functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to control the SPI. + (+) HAL_SPI_GetState() API can be helpful to check in run-time the state of the SPI peripheral. + (+) HAL_SPI_Ctl() API can be used to update the spi configuration (only one parameter) + without calling the HAL_SPI_Init() API +@endverbatim + * @{ + */ + +/** + * @brief Return the SPI state + * @param hspi : SPI handle + * @retval HAL state + */ +HAL_SPI_StateTypeDef HAL_SPI_GetState(SPI_HandleTypeDef *hspi) +{ + return hspi->State; +} +/** + * @} + */ + +/** + * @} + */ + + +#endif /* HAL_SPI_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_spi.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_spi.h new file mode 100644 index 0000000000..12c4b59b01 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_spi.h @@ -0,0 +1,639 @@ + /** + ****************************************************************************** + * @file stm32f0xx_hal_spi.h + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief Header file of SPI HAL module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32F0xx_HAL_SPI_H +#define __STM32F0xx_HAL_SPI_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal_def.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @addtogroup SPI + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ + +/** + * @brief SPI Configuration Structure definition + */ +typedef struct +{ + uint32_t Mode; /*!< Specifies the SPI operating mode. + This parameter can be a value of @ref SPI_mode */ + + uint32_t Direction; /*!< Specifies the SPI bidirectional mode state. + This parameter can be a value of @ref SPI_Direction */ + + uint32_t DataSize; /*!< Specifies the SPI data size. + This parameter can be a value of @ref SPI_data_size */ + + uint32_t CLKPolarity; /*!< Specifies the serial clock steady state. + This parameter can be a value of @ref SPI_Clock_Polarity */ + + uint32_t CLKPhase; /*!< Specifies the clock active edge for the bit capture. + This parameter can be a value of @ref SPI_Clock_Phase */ + + uint32_t NSS; /*!< Specifies whether the NSS signal is managed by + hardware (NSS pin) or by software using the SSI bit. + This parameter can be a value of @ref SPI_Slave_Select_management */ + + uint32_t BaudRatePrescaler; /*!< Specifies the Baud Rate prescaler value which will be + used to configure the transmit and receive SCK clock. + This parameter can be a value of @ref SPI_BaudRate_Prescaler + @note The communication clock is derived from the master + clock. The slave clock does not need to be set. */ + + uint32_t FirstBit; /*!< Specifies whether data transfers start from MSB or LSB bit. + This parameter can be a value of @ref SPI_MSB_LSB_transmission */ + + uint32_t TIMode; /*!< Specifies if the TI mode is enabled or not . + This parameter can be a value of @ref SPI_TI_mode */ + + uint32_t CRCCalculation; /*!< Specifies if the CRC calculation is enabled or not. + This parameter can be a value of @ref SPI_CRC_Calculation */ + + uint32_t CRCPolynomial; /*!< Specifies the polynomial used for the CRC calculation. + This parameter must be a number between Min_Data = 0 and Max_Data = 65535 */ + + uint32_t CRCLength; /*!< Specifies the CRC Length used for the CRC calculation. + CRC Length is only used with Data8 and Data16, not other data size + This parameter must 0 or 1 or 2*/ + + uint32_t NSSPMode; /*!< Specifies whether the NSSP signal is enabled or not . + This mode is activated by the NSSP bit in the SPIx_CR2 register and + it takes effect only if the SPI interface is configured as Motorola SPI + master (FRF=0) with capture on the first edge (SPIx_CR1 CPHA = 0, + CPOL setting is ignored).. */ +} SPI_InitTypeDef; + +/** + * @brief HAL State structures definition + */ +typedef enum +{ + HAL_SPI_STATE_RESET = 0x00, /*!< Peripheral not Initialized */ + HAL_SPI_STATE_READY = 0x01, /*!< Peripheral Initialized and ready for use */ + HAL_SPI_STATE_BUSY = 0x02, /*!< an internal process is ongoing */ + HAL_SPI_STATE_BUSY_TX = 0x03, /*!< Data Transmission process is ongoing */ + HAL_SPI_STATE_BUSY_RX = 0x04, /*!< Data Reception process is ongoing */ + HAL_SPI_STATE_BUSY_TX_RX = 0x05, /*!< Data Transmission and Reception process is ongoing */ + HAL_SPI_STATE_TIMEOUT = 0x06, /*!< Timeout state */ + HAL_SPI_STATE_ERROR = 0x07 /*!< Data Transmission and Reception process is ongoing */ + +}HAL_SPI_StateTypeDef; + +/** + * @brief HAL SPI Error Code structure definition + */ +typedef enum +{ + HAL_SPI_ERROR_NONE = 0x00, /*!< No error */ + HAL_SPI_ERROR_MODF = 0x01, /*!< MODF error */ + HAL_SPI_ERROR_CRC = 0x02, /*!< CRC error */ + HAL_SPI_ERROR_OVR = 0x04, /*!< OVR error */ + HAL_SPI_ERROR_FRE = 0x08, /*!< FRE error */ + HAL_SPI_ERROR_DMA = 0x10, /*!< DMA transfer error */ + HAL_SPI_ERROR_FLAG = 0x20, /*!< Error on BSY/TXE/FTLVL/FRLVL Flag */ + HAL_SPI_ERROR_UNKNOW = 0x40, /*!< Unknow Error error */ +}HAL_SPI_ErrorTypeDef; + +/** + * @brief SPI handle Structure definition + */ +typedef struct __SPI_HandleTypeDef +{ + SPI_TypeDef *Instance; /* SPI registers base address */ + + SPI_InitTypeDef Init; /* SPI communication parameters */ + + uint8_t *pTxBuffPtr; /* Pointer to SPI Tx transfer Buffer */ + + uint16_t TxXferSize; /* SPI Tx Transfer size */ + + uint16_t TxXferCount; /* SPI Tx Transfer Counter */ + + uint8_t *pRxBuffPtr; /* Pointer to SPI Rx transfer Buffer */ + + uint16_t RxXferSize; /* SPI Rx Transfer size */ + + uint16_t RxXferCount; /* SPI Rx Transfer Counter */ + + uint32_t CRCSize; /* SPI CRC size used for the transfer */ + + void (*RxISR)(struct __SPI_HandleTypeDef *hspi); /* function pointer on Rx IRQ handler */ + + void (*TxISR)(struct __SPI_HandleTypeDef *hspi); /* function pointer on Tx IRQ handler */ + + DMA_HandleTypeDef *hdmatx; /* SPI Tx DMA Handle parameters */ + + DMA_HandleTypeDef *hdmarx; /* SPI Rx DMA Handle parameters */ + + HAL_LockTypeDef Lock; /* Locking object */ + + HAL_SPI_StateTypeDef State; /* SPI communication state */ + + HAL_SPI_ErrorTypeDef ErrorCode; /* SPI Error code */ + +}SPI_HandleTypeDef; + +/* Exported constants --------------------------------------------------------*/ + +/** @defgroup SPI_Exported_Constants + * @{ + */ + +/** @defgroup SPI_mode + * @{ + */ + +#define SPI_MODE_SLAVE ((uint32_t)0x00000000) +#define SPI_MODE_MASTER (SPI_CR1_MSTR | SPI_CR1_SSI) +#define IS_SPI_MODE(MODE) (((MODE) == SPI_MODE_SLAVE) || \ + ((MODE) == SPI_MODE_MASTER)) +/** + * @} + */ + +/** @defgroup SPI_Direction + * @{ + */ +#define SPI_DIRECTION_2LINES ((uint32_t)0x00000000) +#define SPI_DIRECTION_2LINES_RXONLY SPI_CR1_RXONLY +#define SPI_DIRECTION_1LINE SPI_CR1_BIDIMODE + +#define IS_SPI_DIRECTION(MODE) (((MODE) == SPI_DIRECTION_2LINES) || \ + ((MODE) == SPI_DIRECTION_2LINES_RXONLY) ||\ + ((MODE) == SPI_DIRECTION_1LINE)) + +#define IS_SPI_DIRECTION_2LINES(MODE) ((MODE) == SPI_DIRECTION_2LINES) + +#define IS_SPI_DIRECTION_2LINES_OR_1LINE(MODE) (((MODE) == SPI_DIRECTION_2LINES)|| \ + ((MODE) == SPI_DIRECTION_1LINE)) +/** + * @} + */ + +/** @defgroup SPI_data_size + * @{ + */ + +#define SPI_DATASIZE_4BIT ((uint16_t)0x0300) +#define SPI_DATASIZE_5BIT ((uint16_t)0x0400) +#define SPI_DATASIZE_6BIT ((uint16_t)0x0500) +#define SPI_DATASIZE_7BIT ((uint16_t)0x0600) +#define SPI_DATASIZE_8BIT ((uint16_t)0x0700) +#define SPI_DATASIZE_9BIT ((uint16_t)0x0800) +#define SPI_DATASIZE_10BIT ((uint16_t)0x0900) +#define SPI_DATASIZE_11BIT ((uint16_t)0x0A00) +#define SPI_DATASIZE_12BIT ((uint16_t)0x0B00) +#define SPI_DATASIZE_13BIT ((uint16_t)0x0C00) +#define SPI_DATASIZE_14BIT ((uint16_t)0x0D00) +#define SPI_DATASIZE_15BIT ((uint16_t)0x0E00) +#define SPI_DATASIZE_16BIT ((uint16_t)0x0F00) +#define IS_SPI_DATASIZE(DATASIZE) (((DATASIZE) == SPI_DATASIZE_16BIT) || \ + ((DATASIZE) == SPI_DATASIZE_15BIT) || \ + ((DATASIZE) == SPI_DATASIZE_14BIT) || \ + ((DATASIZE) == SPI_DATASIZE_13BIT) || \ + ((DATASIZE) == SPI_DATASIZE_12BIT) || \ + ((DATASIZE) == SPI_DATASIZE_11BIT) || \ + ((DATASIZE) == SPI_DATASIZE_10BIT) || \ + ((DATASIZE) == SPI_DATASIZE_9BIT) || \ + ((DATASIZE) == SPI_DATASIZE_8BIT) || \ + ((DATASIZE) == SPI_DATASIZE_7BIT) || \ + ((DATASIZE) == SPI_DATASIZE_6BIT) || \ + ((DATASIZE) == SPI_DATASIZE_5BIT) || \ + ((DATASIZE) == SPI_DATASIZE_4BIT)) + +/** + * @} + */ + +/** @defgroup SPI_Clock_Polarity + * @{ + */ + +#define SPI_POLARITY_LOW ((uint32_t)0x00000000) +#define SPI_POLARITY_HIGH SPI_CR1_CPOL +#define IS_SPI_CPOL(CPOL) (((CPOL) == SPI_POLARITY_LOW) || \ + ((CPOL) == SPI_POLARITY_HIGH)) +/** + * @} + */ + +/** @defgroup SPI_Clock_Phase + * @{ + */ + +#define SPI_PHASE_1EDGE ((uint32_t)0x00000000) +#define SPI_PHASE_2EDGE SPI_CR1_CPHA +#define IS_SPI_CPHA(CPHA) (((CPHA) == SPI_PHASE_1EDGE) || \ + ((CPHA) == SPI_PHASE_2EDGE)) +/** + * @} + */ + +/** @defgroup SPI_Slave_Select_management + * @{ + */ + +#define SPI_NSS_SOFT SPI_CR1_SSM +#define SPI_NSS_HARD_INPUT ((uint32_t)0x00000000) +#define SPI_NSS_HARD_OUTPUT ((uint32_t)0x00040000) +#define IS_SPI_NSS(NSS) (((NSS) == SPI_NSS_SOFT) || \ + ((NSS) == SPI_NSS_HARD_INPUT) || \ + ((NSS) == SPI_NSS_HARD_OUTPUT)) + + /** + * @} + */ + + +/** @defgroup SPI_NSS pulse management + * @{ + */ +#define SPI_NSS_PULSE_ENABLED SPI_CR2_NSSP +#define SPI_NSS_PULSE_DISABLED ((uint32_t)0x00000000) + +#define IS_SPI_NSSP(NSSP) (((NSSP) == SPI_NSS_PULSE_ENABLED) || \ + ((NSSP) == SPI_NSS_PULSE_DISABLED)) + +/** + * @} + */ + + +/** @defgroup SPI_BaudRate_Prescaler + * @{ + */ + +#define SPI_BAUDRATEPRESCALER_2 ((uint32_t)0x00000000) +#define SPI_BAUDRATEPRESCALER_4 ((uint32_t)0x00000008) +#define SPI_BAUDRATEPRESCALER_8 ((uint32_t)0x00000010) +#define SPI_BAUDRATEPRESCALER_16 ((uint32_t)0x00000018) +#define SPI_BAUDRATEPRESCALER_32 ((uint32_t)0x00000020) +#define SPI_BAUDRATEPRESCALER_64 ((uint32_t)0x00000028) +#define SPI_BAUDRATEPRESCALER_128 ((uint32_t)0x00000030) +#define SPI_BAUDRATEPRESCALER_256 ((uint32_t)0x00000038) +#define IS_SPI_BAUDRATE_PRESCALER(PRESCALER) (((PRESCALER) == SPI_BAUDRATEPRESCALER_2) || \ + ((PRESCALER) == SPI_BAUDRATEPRESCALER_4) || \ + ((PRESCALER) == SPI_BAUDRATEPRESCALER_8) || \ + ((PRESCALER) == SPI_BAUDRATEPRESCALER_16) || \ + ((PRESCALER) == SPI_BAUDRATEPRESCALER_32) || \ + ((PRESCALER) == SPI_BAUDRATEPRESCALER_64) || \ + ((PRESCALER) == SPI_BAUDRATEPRESCALER_128) || \ + ((PRESCALER) == SPI_BAUDRATEPRESCALER_256)) +/** + * @} + */ + +/** @defgroup SPI_MSB_LSB_transmission + * @{ + */ + +#define SPI_FIRSTBIT_MSB ((uint32_t)0x00000000) +#define SPI_FIRSTBIT_LSB SPI_CR1_LSBFIRST +#define IS_SPI_FIRST_BIT(BIT) (((BIT) == SPI_FIRSTBIT_MSB) || \ + ((BIT) == SPI_FIRSTBIT_LSB)) +/** + * @} + */ + +/** @defgroup SPI_TI_mode + * @{ + */ + +#define SPI_TIMODE_DISABLED ((uint32_t)0x00000000) +#define SPI_TIMODE_ENABLED SPI_CR2_FRF +#define IS_SPI_TIMODE(MODE) (((MODE) == SPI_TIMODE_DISABLED) || \ + ((MODE) == SPI_TIMODE_ENABLED)) +/** + * @} + */ + +/** @defgroup SPI_CRC_Calculation + * @{ + */ + +#define SPI_CRCCALCULATION_DISABLED ((uint32_t)0x00000000) +#define SPI_CRCCALCULATION_ENABLED SPI_CR1_CRCEN +#define IS_SPI_CRC_CALCULATION(CALCULATION) (((CALCULATION) == SPI_CRCCALCULATION_DISABLED) || \ + ((CALCULATION) == SPI_CRCCALCULATION_ENABLED)) +/** + * @} + */ + +/** @defgroup SPI_CRC_length + * @{ + * This parameter can be one of the following values: + * SPI_CRC_LENGTH_DATASIZE: aligned with the data size + * SPI_CRC_LENGTH_8BIT : CRC 8bit + * SPI_CRC_LENGTH_16BIT : CRC 16bit + */ +#define SPI_CRC_LENGTH_DATASIZE 0 +#define SPI_CRC_LENGTH_8BIT 1 +#define SPI_CRC_LENGTH_16BIT 2 +#define IS_SPI_CRC_LENGTH(LENGTH) (((LENGTH) == SPI_CRC_LENGTH_DATASIZE) ||\ + ((LENGTH) == SPI_CRC_LENGTH_8BIT) || \ + ((LENGTH) == SPI_CRC_LENGTH_16BIT)) +/** + * @} + */ + +/** @defgroup SPI_FIFO_reception_threshold + * @{ + * This parameter can be one of the following values: + * SPI_RxFIFOThreshold_HF: RXNE event is generated if the FIFO + * level is greater or equal to 1/2(16-bits). + * SPI_RxFIFOThreshold_QF: RXNE event is generated if the FIFO + * level is greater or equal to 1/4(8 bits). + */ +#define SPI_RXFIFO_THRESHOLD SPI_CR2_FRXTH +#define SPI_RXFIFO_THRESHOLD_QF SPI_CR2_FRXTH +#define SPI_RXFIFO_THRESHOLD_HF ((uint32_t)0x0) + +/** + * @} + */ + +/** @defgroup SPI_Interrupt_configuration_definition + * @brief SPI Interrupt definition + * Elements values convention: 0xXXXXXXXX + * - XXXXXXXX : Interrupt control mask + * @{ + */ +#define SPI_IT_TXE SPI_CR2_TXEIE +#define SPI_IT_RXNE SPI_CR2_RXNEIE +#define SPI_IT_ERR SPI_CR2_ERRIE +#define IS_SPI_IT(IT) (((IT) == SPI_IT_TXE) || \ + ((IT) == SPI_IT_RXNE) || \ + ((IT) == SPI_IT_ERR)) +/** + * @} + */ + + +/** @defgroup SPI_Flag_definition + * @brief Flag definition + * Elements values convention: 0xXXXXYYYY + * - XXXX : Flag register Index + * - YYYY : Flag mask + */ +#define SPI_FLAG_RXNE SPI_SR_RXNE /* SPI status flag: Rx buffer not empty flag */ +#define SPI_FLAG_TXE SPI_SR_TXE /* SPI status flag: Tx buffer empty flag */ +#define SPI_FLAG_BSY SPI_SR_BSY /* SPI status flag: Busy flag */ +#define SPI_FLAG_CRCERR SPI_SR_CRCERR /* SPI Error flag: CRC error flag */ +#define SPI_FLAG_MODF SPI_SR_MODF /* SPI Error flag: Mode fault flag */ +#define SPI_FLAG_OVR SPI_SR_OVR /* SPI Error flag: Overrun flag */ +#define SPI_FLAG_FRE SPI_SR_FRE /* SPI Error flag: TI mode frame format error flag */ +#define SPI_FLAG_FTLVL SPI_SR_FTLVL /* SPI fifo transmission level */ +#define SPI_FLAG_FRLVL SPI_SR_FRLVL /* SPI fifo reception level */ +#define IS_SPI_FLAG(FLAG) (((FLAG) == SPI_FLAG_RXNE) || \ + ((FLAG) == SPI_FLAG_TXE) || \ + ((FLAG) == SPI_FLAG_BSY) || \ + ((FLAG) == SPI_FLAG_CRCERR)|| \ + ((FLAG) == SPI_FLAG_MODF) || \ + ((FLAG) == SPI_FLAG_OVR) || \ + ((FLAG) == SPI_FLAG_FTLVL) || \ + ((FLAG) == SPI_FLAG_FRLVL) || \ + ((FLAG) == SPI_IT_FRE)) + + +/** @defgroup SPI_transmission_fifo_status_level + * @{ + */ + +#define SPI_FTLVL_EMPTY ((uint16_t)0x0000) +#define SPI_FTLVL_QUARTER_FULL ((uint16_t)0x0800) +#define SPI_FTLVL_HALF_FULL ((uint16_t)0x1000) +#define SPI_FTLVL_FULL ((uint16_t)0x1800) + + +/** + * @} + */ + +/** @defgroup SPI_reception_fifo_status_level + * @{ + */ +#define SPI_FRLVL_EMPTY ((uint16_t)0x0000) +#define SPI_FRLVL_QUARTER_FULL ((uint16_t)0x0200) +#define SPI_FRLVL_HALF_FULL ((uint16_t)0x0400) +#define SPI_FRLVL_FULL ((uint16_t)0x0600) + +/** + * @} + */ + +/** + * @} + */ + + +/* Exported macros ------------------------------------------------------------*/ + +/** @brief Reset SPI handle state + * @param __HANDLE__: SPI handle. + * @retval None + */ +#define __HAL_SPI_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_SPI_STATE_RESET) + +/** @brief Enables or disables the specified SPI interrupts. + * @param __HANDLE__: specifies the SPI Handle. + * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. + * @param __INTERRUPT__: specifies the interrupt source to enable or disable. + * This parameter can be one of the following values: + * @arg SPI_IT_TXE: Tx buffer empty interrupt enable + * @arg SPI_IT_RXNE: RX buffer not empty interrupt enable + * @arg SPI_IT_ERR: Error interrupt enable + * @retval None + */ + +#define __HAL_SPI_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR2 |= (__INTERRUPT__)) +#define __HAL_SPI_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR2 &= (uint16_t)(~(__INTERRUPT__))) + +/** @brief Checks if the specified SPI interrupt source is enabled or disabled. + * @param __HANDLE__: specifies the SPI Handle. + * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. + * @param __INTERRUPT__: specifies the SPI interrupt source to check. + * This parameter can be one of the following values: + * @arg SPI_IT_TXE: Tx buffer empty interrupt enable + * @arg SPI_IT_RXNE: RX buffer not empty interrupt enable + * @arg SPI_IT_ERR: Error interrupt enable + * @retval The new state of __IT__ (TRUE or FALSE). + */ +#define __HAL_SPI_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((((__HANDLE__)->Instance->CR2 & (__INTERRUPT__)) == (__INTERRUPT__)) ? SET : RESET) + +/** @brief Checks whether the specified SPI flag is set or not. + * @param __HANDLE__: specifies the SPI Handle. + * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. + * @param __FLAG__: specifies the flag to check. + * This parameter can be one of the following values: + * @arg SPI_FLAG_RXNE: Receive buffer not empty flag + * @arg SPI_FLAG_TXE: Transmit buffer empty flag + * @arg SPI_FLAG_CRCERR: CRC error flag + * @arg SPI_FLAG_MODF: Mode fault flag + * @arg SPI_FLAG_OVR: Overrun flag + * @arg SPI_FLAG_BSY: Busy flag + * @arg SPI_FLAG_FRE: Frame format error flag + * @retval The new state of __FLAG__ (TRUE or FALSE). + */ +#define __HAL_SPI_GET_FLAG(__HANDLE__, __FLAG__) ((((__HANDLE__)->Instance->SR) & (__FLAG__)) == (__FLAG__)) + +/** @brief Clears the SPI CRCERR pending flag. + * @param __HANDLE__: specifies the SPI Handle. + * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. + * @retval None + */ +#define __HAL_SPI_CLEAR_CRCERRFLAG(__HANDLE__) ((__HANDLE__)->Instance->SR &= (uint16_t)(~SPI_FLAG_CRCERR)) + +/** @brief Clears the SPI MODF pending flag. + * @param __HANDLE__: specifies the SPI Handle. + * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. + * + * @retval None + */ +#define __HAL_SPI_CLEAR_MODFFLAG(__HANDLE__) do{(__HANDLE__)->Instance->SR;\ + (__HANDLE__)->Instance->CR1 &= (uint16_t)(~SPI_CR1_SPE);}while(0) + +/** @brief Clears the SPI OVR pending flag. + * @param __HANDLE__: specifies the SPI Handle. + * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. + * + * @retval None + */ +#define __HAL_SPI_CLEAR_OVRFLAG(__HANDLE__) do{(__HANDLE__)->Instance->DR;\ + (__HANDLE__)->Instance->SR;}while(0) + +/** @brief Clears the SPI FRE pending flag. + * @param __HANDLE__: specifies the SPI Handle. + * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. + * + * @retval None + */ +#define __HAL_SPI_CLEAR_FREFLAG(__HANDLE__) ((__HANDLE__)->Instance->SR) + +/** @brief Enables the SPI. + * @param __HANDLE__: specifies the SPI Handle. + * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. + * @retval None + */ +#define __HAL_SPI_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 |= SPI_CR1_SPE) + +/** @brief Disables the SPI. + * @param __HANDLE__: specifies the SPI Handle. + * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. + * @retval None + */ +#define __HAL_SPI_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 &= (uint16_t)(~SPI_CR1_SPE)) + +/** @brief Sets the SPI transmit-only mode. + * @param __HANDLE__: specifies the SPI Handle. + * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. + * @retval None + */ +#define __HAL_SPI_1LINE_TX(__HANDLE__) ((__HANDLE__)->Instance->CR1 |= SPI_CR1_BIDIOE) + +/** @brief Sets the SPI receive-only mode. + * @param __HANDLE__: specifies the SPI Handle. + * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. + * @retval None + */ +#define __HAL_SPI_1LINE_RX(__HANDLE__) ((__HANDLE__)->Instance->CR1 &= (uint16_t)(~SPI_CR1_BIDIOE)) + +/** @brief Resets the CRC calculation of the SPI. + * @param __HANDLE__: specifies the SPI Handle. + * This parameter can be SPI where x: 1, 2, or 3 to select the SPI peripheral. + * @retval None + */ +#define __HAL_SPI_RESET_CRC(__HANDLE__) do{(__HANDLE__)->Instance->CR1 &= (uint16_t)(~SPI_CR1_CRCEN);\ + (__HANDLE__)->Instance->CR1 |= SPI_CR1_CRCEN;}while(0) + + +#define IS_SPI_CRC_POLYNOMIAL(POLYNOMIAL) (((POLYNOMIAL) >= 0x1) && ((POLYNOMIAL) <= 0xFFFF)) + +/* Exported functions --------------------------------------------------------*/ + +/* Initialization and de-initialization functions ****************************/ +HAL_StatusTypeDef HAL_SPI_Init(SPI_HandleTypeDef *hspi); +HAL_StatusTypeDef HAL_SPI_InitExtended(SPI_HandleTypeDef *hspi); +HAL_StatusTypeDef HAL_SPI_DeInit (SPI_HandleTypeDef *hspi); +void HAL_SPI_MspInit(SPI_HandleTypeDef *hspi); +void HAL_SPI_MspDeInit(SPI_HandleTypeDef *hspi); + +/* IO operation functions *****************************************************/ +HAL_StatusTypeDef HAL_SPI_Transmit(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size, uint32_t Timeout); +HAL_StatusTypeDef HAL_SPI_Receive(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size, uint32_t Timeout); +HAL_StatusTypeDef HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size, uint32_t Timeout); +HAL_StatusTypeDef HAL_SPI_Transmit_IT(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size); +HAL_StatusTypeDef HAL_SPI_Receive_IT(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size); +HAL_StatusTypeDef HAL_SPI_TransmitReceive_IT(SPI_HandleTypeDef *hspi, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size); +HAL_StatusTypeDef HAL_SPI_Transmit_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size); +HAL_StatusTypeDef HAL_SPI_Receive_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size); +HAL_StatusTypeDef HAL_SPI_TransmitReceive_DMA(SPI_HandleTypeDef *hspi, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size); +void HAL_SPI_IRQHandler(SPI_HandleTypeDef *hspi); +void HAL_SPI_TxCpltCallback(SPI_HandleTypeDef *hspi); +void HAL_SPI_RxCpltCallback(SPI_HandleTypeDef *hspi); +void HAL_SPI_TxRxCpltCallback(SPI_HandleTypeDef *hspi); +void HAL_SPI_ErrorCallback(SPI_HandleTypeDef *hspi); + +/* Peripheral State and Error functions ***************************************/ +HAL_SPI_StateTypeDef HAL_SPI_GetState(SPI_HandleTypeDef *hspi); + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __STM32F0xx_HAL_SPI_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_tim.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_tim.c new file mode 100644 index 0000000000..ef0953df4d --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_tim.c @@ -0,0 +1,5227 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_tim.c + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief TIM HAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the Timer (TIM) peripheral: + * + Time Base Initialization + * + Time Base Start + * + Time Base Start Interruption + * + Time Base Start DMA + * + Time Output Compare/PWM Initialization + * + Time Output Compare/PWM Channel Configuration + * + Time Output Compare/PWM Start + * + Time Output Compare/PWM Start Interruption + * + Time Output Compare/PWM Start DMA + * + Time Input Capture Initialization + * + Time Input Capture Channel Configuration + * + Time Input Capture Start + * + Time Input Capture Start Interruption + * + Time Input Capture Start DMA + * + Time One Pulse Initialization + * + Time One Pulse Channel Configuration + * + Time One Pulse Start + * + Time Encoder Interface Initialization + * + Time Encoder Interface Start + * + Time Encoder Interface Start Interruption + * + Time Encoder Interface Start DMA + * + Commutation Event configuration with Interruption and DMA + * + Time OCRef clear configuration + * + Time External Clock configuration + @verbatim + ============================================================================== + ##### TIMER Generic features ##### + ============================================================================== + [..] The Timer features include: + (#) 16-bit up, down, up/down auto-reload counter. + (#) 16-bit programmable prescaler allowing dividing (also on the fly) the + counter clock frequency either by any factor between 1 and 65536. + (#) Up to 4 independent channels for: + (++) Input Capture + (++) Output Compare + (++) PWM generation (Edge and Center-aligned Mode) + (++) One-pulse mode output + + ##### How to use this driver ##### + ============================================================================== + [..] + (#) Initialize the TIM low level resources by implementing the following functions + depending from feature used : + (++) Time Base : HAL_TIM_Base_MspInit() + (++) Input Capture : HAL_TIM_IC_MspInit() + (++) Output Compare : HAL_TIM_OC_MspInit() + (++) PWM generation : HAL_TIM_PWM_MspInit() + (++) One-pulse mode output : HAL_TIM_OnePulse_MspInit() + (++) Encoder mode output : HAL_TIM_Encoder_MspInit() + + (#) Initialize the TIM low level resources : + (##) Enable the TIM interface clock using __TIMx_CLK_ENABLE(); + (##) TIM pins configuration + (+++) Enable the clock for the TIM GPIOs using the following function: + __GPIOx_CLK_ENABLE(); + (+++) Configure these TIM pins in Alternate function mode using HAL_GPIO_Init(); + + (#) The external Clock can be configured, if needed (the default clock is the + internal clock from the APBx), using the following function: + HAL_TIM_ConfigClockSource, the clock configuration should be done before + any start function. + + (#) Configure the TIM in the desired functioning mode using one of the + Initialization function of this driver: + (++) HAL_TIM_Base_Init: to use the Timer to generate a simple time base + (++) HAL_TIM_OC_Init and HAL_TIM_OC_ConfigChannel: to use the Timer to generate an + Output Compare signal. + (++) HAL_TIM_PWM_Init and HAL_TIM_PWM_ConfigChannel: to use the Timer to generate a + PWM signal. + (++) HAL_TIM_IC_Init and HAL_TIM_IC_ConfigChannel: to use the Timer to measure an + external signal. + (++) HAL_TIM_OnePulse_Init and HAL_TIM_OnePulse_ConfigChannel: to use the Timer + in One Pulse Mode. + (++) HAL_TIM_Encoder_Init: to use the Timer Encoder Interface. + + (#) Activate the TIM peripheral using one of the start functions depending from the feature used: + (++) Time Base : HAL_TIM_Base_Start(), HAL_TIM_Base_Start_DMA(), HAL_TIM_Base_Start_IT() + (++) Input Capture : HAL_TIM_IC_Start(), HAL_TIM_IC_Start_DMA(), HAL_TIM_IC_Start_IT() + (++) Output Compare : HAL_TIM_OC_Start(), HAL_TIM_OC_Start_DMA(), HAL_TIM_OC_Start_IT() + (++) PWM generation : HAL_TIM_PWM_Start(), HAL_TIM_PWM_Start_DMA(), HAL_TIM_PWM_Start_IT() + (++) One-pulse mode output : HAL_TIM_OnePulse_Start(), HAL_TIM_OnePulse_Start_IT() + (++) Encoder mode output : HAL_TIM_Encoder_Start(), HAL_TIM_Encoder_Start_DMA(), HAL_TIM_Encoder_Start_IT(). + + (#) The DMA Burst is managed with the two following functions: + HAL_TIM_DMABurst_WriteStart() + HAL_TIM_DMABurst_ReadStart() + + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @defgroup TIM + * @brief TIM HAL module driver + * @{ + */ + +#ifdef HAL_TIM_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +static void TIM_OC1_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config); +static void TIM_OC3_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config); +static void TIM_OC4_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config); + +static void TIM_TI1_ConfigInputStage(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICFilter); +static void TIM_TI2_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICSelection, + uint32_t TIM_ICFilter); +static void TIM_TI2_ConfigInputStage(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICFilter); +static void TIM_TI3_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICSelection, + uint32_t TIM_ICFilter); +static void TIM_TI4_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICSelection, + uint32_t TIM_ICFilter); + +static void TIM_ETR_SetConfig(TIM_TypeDef* TIMx, uint32_t TIM_ExtTRGPrescaler, + uint32_t TIM_ExtTRGPolarity, uint32_t ExtTRGFilter); + +static void TIM_ITRx_SetConfig(TIM_TypeDef* TIMx, uint16_t InputTriggerSource); +static void TIM_DMAPeriodElapsedCplt(DMA_HandleTypeDef *hdma); +static void TIM_DMATriggerCplt(DMA_HandleTypeDef *hdma); +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup TIM_Private_Functions + * @{ + */ + +/** @defgroup TIM_Group1 Time Base functions + * @brief Time Base functions + * +@verbatim + ============================================================================== + ##### Time Base functions ##### + ============================================================================== + [..] + This section provides functions allowing to: + (+) Initialize and configure the TIM base. + (+) De-initialize the TIM base. + (+) Start the Time Base. + (+) Stop the Time Base. + (+) Start the Time Base and enable interrupt. + (+) Stop the Time Base and disable interrupt. + (+) Start the Time Base and enable DMA transfer. + (+) Stop the Time Base and disable DMA transfer. + +@endverbatim + * @{ + */ +/** + * @brief Initializes the TIM Time base Unit according to the specified + * parameters in the TIM_HandleTypeDef and create the associated handle. + * @param htim: TIM Base handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_Base_Init(TIM_HandleTypeDef *htim) +{ + /* Check the TIM handle allocation */ + if(htim == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_TIM_INSTANCE(htim->Instance)); + assert_param(IS_TIM_COUNTER_MODE(htim->Init.CounterMode)); + assert_param(IS_TIM_CLOCKDIVISION_DIV(htim->Init.ClockDivision)); + + if(htim->State == HAL_TIM_STATE_RESET) + { + /* Init the low level hardware : GPIO, CLOCK, NVIC */ + HAL_TIM_Base_MspInit(htim); + } + + /* Set the TIM state */ + htim->State= HAL_TIM_STATE_BUSY; + + /* Set the Time Base configuration */ + TIM_Base_SetConfig(htim->Instance, &htim->Init); + + /* Initialize the TIM state*/ + htim->State= HAL_TIM_STATE_READY; + + return HAL_OK; +} + +/** + * @brief DeInitializes the TIM Base peripheral + * @param htim: TIM Base handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_Base_DeInit(TIM_HandleTypeDef *htim) +{ + /* Check the parameters */ + assert_param(IS_TIM_INSTANCE(htim->Instance)); + + htim->State = HAL_TIM_STATE_BUSY; + + /* Disable the TIM Peripheral Clock */ + __HAL_TIM_DISABLE(htim); + + /* DeInit the low level hardware: GPIO, CLOCK, NVIC */ + HAL_TIM_Base_MspDeInit(htim); + + /* Change TIM state */ + htim->State = HAL_TIM_STATE_RESET; + + /* Release Lock */ + __HAL_UNLOCK(htim); + + return HAL_OK; +} + +/** + * @brief Initializes the TIM Base MSP. + * @param htim: TIM handle + * @retval None + */ +__weak void HAL_TIM_Base_MspInit(TIM_HandleTypeDef *htim) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_TIM_Base_MspInit could be implemented in the user file + */ +} + +/** + * @brief DeInitializes TIM Base MSP. + * @param htim: TIM handle + * @retval None + */ +__weak void HAL_TIM_Base_MspDeInit(TIM_HandleTypeDef *htim) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_TIM_Base_MspDeInit could be implemented in the user file + */ +} + + +/** + * @brief Starts the TIM Base generation. + * @param htim : TIM handle + * @retval HAL status +*/ +HAL_StatusTypeDef HAL_TIM_Base_Start(TIM_HandleTypeDef *htim) +{ + /* Check the parameters */ + assert_param(IS_TIM_INSTANCE(htim->Instance)); + + /* Set the TIM state */ + htim->State= HAL_TIM_STATE_BUSY; + + /* Enable the Peripheral */ + __HAL_TIM_ENABLE(htim); + + /* Change the TIM state*/ + htim->State= HAL_TIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the TIM Base generation. + * @param htim : TIM handle + * @retval HAL status +*/ +HAL_StatusTypeDef HAL_TIM_Base_Stop(TIM_HandleTypeDef *htim) +{ + /* Check the parameters */ + assert_param(IS_TIM_INSTANCE(htim->Instance)); + + /* Set the TIM state */ + htim->State= HAL_TIM_STATE_BUSY; + + /* Disable the Peripheral */ + __HAL_TIM_DISABLE(htim); + + /* Change the TIM state*/ + htim->State= HAL_TIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Starts the TIM Base generation in interrupt mode. + * @param htim : TIM handle + * @retval HAL status +*/ +HAL_StatusTypeDef HAL_TIM_Base_Start_IT(TIM_HandleTypeDef *htim) +{ + /* Check the parameters */ + assert_param(IS_TIM_INSTANCE(htim->Instance)); + + /* Enable the TIM Update interrupt */ + __HAL_TIM_ENABLE_IT(htim, TIM_IT_UPDATE); + + /* Enable the Peripheral */ + __HAL_TIM_ENABLE(htim); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the TIM Base generation in interrupt mode. + * @param htim : TIM handle + * @retval HAL status +*/ +HAL_StatusTypeDef HAL_TIM_Base_Stop_IT(TIM_HandleTypeDef *htim) +{ + /* Check the parameters */ + assert_param(IS_TIM_INSTANCE(htim->Instance)); + /* Disable the TIM Update interrupt */ + __HAL_TIM_DISABLE_IT(htim, TIM_IT_UPDATE); + + /* Disable the Peripheral */ + __HAL_TIM_DISABLE(htim); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Starts the TIM Base generation in DMA mode. + * @param htim : TIM handle + * @param pData: The source Buffer address. + * @param Length: The length of data to be transferred from memory to peripheral. + * @retval HAL status +*/ +HAL_StatusTypeDef HAL_TIM_Base_Start_DMA(TIM_HandleTypeDef *htim, uint32_t *pData, uint16_t Length) +{ + /* Check the parameters */ + assert_param(IS_TIM_DMA_INSTANCE(htim->Instance)); + + if((htim->State == HAL_TIM_STATE_BUSY)) + { + return HAL_BUSY; + } + else if((htim->State == HAL_TIM_STATE_READY)) + { + if((pData == 0 ) && (Length > 0)) + { + return HAL_ERROR; + } + else + { + htim->State = HAL_TIM_STATE_BUSY; + } + } + /* Set the DMA Period elapsed callback */ + htim->hdma[TIM_DMA_ID_UPDATE]->XferCpltCallback = TIM_DMAPeriodElapsedCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_UPDATE]->XferErrorCallback = HAL_TIM_DMAError ; + + /* Enable the DMA channel */ + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_UPDATE], (uint32_t)pData, (uint32_t)&htim->Instance->ARR, Length); + + /* Enable the TIM Update DMA request */ + __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_UPDATE); + + /* Enable the Peripheral */ + __HAL_TIM_ENABLE(htim); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the TIM Base generation in DMA mode. + * @param htim : TIM handle + * @retval HAL status +*/ +HAL_StatusTypeDef HAL_TIM_Base_Stop_DMA(TIM_HandleTypeDef *htim) +{ + /* Check the parameters */ + assert_param(IS_TIM_DMA_INSTANCE(htim->Instance)); + + /* Disable the TIM Update DMA request */ + __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_UPDATE); + + /* Disable the Peripheral */ + __HAL_TIM_DISABLE(htim); + + /* Change the htim state */ + htim->State = HAL_TIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @} + */ + +/** @defgroup TIM_Group2 Time Output Compare functions + * @brief Time Output Compare functions + * +@verbatim + ============================================================================== + ##### Time Output Compare functions ##### + ============================================================================== + [..] + This section provides functions allowing to: + (+) Initialize and configure the TIM Output Compare. + (+) De-initialize the TIM Output Compare. + (+) Start the Time Output Compare. + (+) Stop the Time Output Compare. + (+) Start the Time Output Compare and enable interrupt. + (+) Stop the Time Output Compare and disable interrupt. + (+) Start the Time Output Compare and enable DMA transfer. + (+) Stop the Time Output Compare and disable DMA transfer. + +@endverbatim + * @{ + */ +/** + * @brief Initializes the TIM Output Compare according to the specified + * parameters in the TIM_HandleTypeDef and create the associated handle. + * @param htim: TIM Output Compare handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_OC_Init(TIM_HandleTypeDef* htim) +{ + /* Check the TIM handle allocation */ + if(htim == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_TIM_INSTANCE(htim->Instance)); + assert_param(IS_TIM_COUNTER_MODE(htim->Init.CounterMode)); + assert_param(IS_TIM_CLOCKDIVISION_DIV(htim->Init.ClockDivision)); + + if(htim->State == HAL_TIM_STATE_RESET) + { + /* Init the low level hardware : GPIO, CLOCK, NVIC and DMA */ + HAL_TIM_OC_MspInit(htim); + } + + /* Set the TIM state */ + htim->State= HAL_TIM_STATE_BUSY; + + /* Init the base time for the Output Compare */ + TIM_Base_SetConfig(htim->Instance, &htim->Init); + + /* Initialize the TIM state*/ + htim->State= HAL_TIM_STATE_READY; + + return HAL_OK; +} + +/** + * @brief DeInitializes the TIM peripheral + * @param htim: TIM Output Compare handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_OC_DeInit(TIM_HandleTypeDef *htim) +{ + /* Check the parameters */ + assert_param(IS_TIM_INSTANCE(htim->Instance)); + + htim->State = HAL_TIM_STATE_BUSY; + + /* Disable the TIM Peripheral Clock */ + __HAL_TIM_DISABLE(htim); + + /* DeInit the low level hardware: GPIO, CLOCK, NVIC and DMA */ + HAL_TIM_OC_MspDeInit(htim); + + /* Change TIM state */ + htim->State = HAL_TIM_STATE_RESET; + + /* Release Lock */ + __HAL_UNLOCK(htim); + + return HAL_OK; +} + +/** + * @brief Initializes the TIM Output Compare MSP. + * @param htim: TIM handle + * @retval None + */ +__weak void HAL_TIM_OC_MspInit(TIM_HandleTypeDef *htim) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_TIM_OC_MspInit could be implemented in the user file + */ +} + +/** + * @brief DeInitializes TIM Output Compare MSP. + * @param htim: TIM handle + * @retval None + */ +__weak void HAL_TIM_OC_MspDeInit(TIM_HandleTypeDef *htim) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_TIM_OC_MspDeInit could be implemented in the user file + */ +} + +/** + * @brief Starts the TIM Output Compare signal generation. + * @param htim : TIM Output Compare handle + * @param Channel : TIM Channel to be enabled + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @arg TIM_CHANNEL_3: TIM Channel 3 selected + * @arg TIM_CHANNEL_4: TIM Channel 4 selected + * @retval HAL status +*/ +HAL_StatusTypeDef HAL_TIM_OC_Start(TIM_HandleTypeDef *htim, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel)); + + /* Enable the Output compare channel */ + TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_ENABLE); + + if(IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET) + { + /* Enable the main output */ + __HAL_TIM_MOE_ENABLE(htim); + } + + /* Enable the Peripheral */ + __HAL_TIM_ENABLE(htim); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the TIM Output Compare signal generation. + * @param htim : TIM handle + * @param Channel : TIM Channel to be disabled + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @arg TIM_CHANNEL_3: TIM Channel 3 selected + * @arg TIM_CHANNEL_4: TIM Channel 4 selected + * @retval HAL status +*/ +HAL_StatusTypeDef HAL_TIM_OC_Stop(TIM_HandleTypeDef *htim, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel)); + + /* Disable the Output compare channel */ + TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_DISABLE); + + if(IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET) + { + /* Disable the Main Ouput */ + __HAL_TIM_MOE_DISABLE(htim); + } + + /* Disable the Peripheral */ + __HAL_TIM_DISABLE(htim); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Starts the TIM Output Compare signal generation in interrupt mode. + * @param htim : TIM OC handle + * @param Channel : TIM Channel to be enabled + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @arg TIM_CHANNEL_3: TIM Channel 3 selected + * @arg TIM_CHANNEL_4: TIM Channel 4 selected + * @retval HAL status +*/ +HAL_StatusTypeDef HAL_TIM_OC_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel)); + + switch (Channel) + { + case TIM_CHANNEL_1: + { + /* Enable the TIM Capture/Compare 1 interrupt */ + __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC1); + } + break; + + case TIM_CHANNEL_2: + { + /* Enable the TIM Capture/Compare 2 interrupt */ + __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC2); + } + break; + + case TIM_CHANNEL_3: + { + /* Enable the TIM Capture/Compare 3 interrupt */ + __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC3); + } + break; + + case TIM_CHANNEL_4: + { + /* Enable the TIM Capture/Compare 4 interrupt */ + __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC4); + } + break; + + default: + break; + } + + /* Enable the Output compare channel */ + TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_ENABLE); + + if(IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET) + { + /* Enable the main output */ + __HAL_TIM_MOE_ENABLE(htim); + } + + /* Enable the Peripheral */ + __HAL_TIM_ENABLE(htim); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the TIM Output Compare signal generation in interrupt mode. + * @param htim : TIM Output Compare handle + * @param Channel : TIM Channel to be disabled + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @arg TIM_CHANNEL_3: TIM Channel 3 selected + * @arg TIM_CHANNEL_4: TIM Channel 4 selected + * @retval HAL status +*/ +HAL_StatusTypeDef HAL_TIM_OC_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel)); + + switch (Channel) + { + case TIM_CHANNEL_1: + { + /* Disable the TIM Capture/Compare 1 interrupt */ + __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC1); + } + break; + + case TIM_CHANNEL_2: + { + /* Disable the TIM Capture/Compare 2 interrupt */ + __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC2); + } + break; + + case TIM_CHANNEL_3: + { + /* Disable the TIM Capture/Compare 3 interrupt */ + __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC3); + } + break; + + case TIM_CHANNEL_4: + { + /* Disable the TIM Capture/Compare 4 interrupt */ + __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC4); + } + break; + + default: + break; + } + + /* Disable the Output compare channel */ + TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_DISABLE); + + if(IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET) + { + /* Disable the Main Ouput */ + __HAL_TIM_MOE_DISABLE(htim); + } + + /* Disable the Peripheral */ + __HAL_TIM_DISABLE(htim); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Starts the TIM Output Compare signal generation in DMA mode. + * @param htim : TIM Output Compare handle + * @param Channel : TIM Channel to be enabled + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @arg TIM_CHANNEL_3: TIM Channel 3 selected + * @arg TIM_CHANNEL_4: TIM Channel 4 selected + * @param pData: The source Buffer address. + * @param Length: The length of data to be transferred from memory to TIM peripheral + * @retval HAL status +*/ +HAL_StatusTypeDef HAL_TIM_OC_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel, uint32_t *pData, uint16_t Length) +{ + /* Check the parameters */ + assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel)); + + if((htim->State == HAL_TIM_STATE_BUSY)) + { + return HAL_BUSY; + } + else if((htim->State == HAL_TIM_STATE_READY)) + { + if(((uint32_t)pData == 0 ) && (Length > 0)) + { + return HAL_ERROR; + } + else + { + htim->State = HAL_TIM_STATE_BUSY; + } + } + switch (Channel) + { + case TIM_CHANNEL_1: + { + /* Set the DMA Period elapsed callback */ + htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = HAL_TIM_DMADelayPulseCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = HAL_TIM_DMAError ; + + /* Enable the DMA channel */ + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)pData, (uint32_t)&htim->Instance->CCR1, Length); + + /* Enable the TIM Capture/Compare 1 DMA request */ + __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC1); + } + break; + + case TIM_CHANNEL_2: + { + /* Set the DMA Period elapsed callback */ + htim->hdma[TIM_DMA_ID_CC2]->XferCpltCallback = HAL_TIM_DMADelayPulseCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC2]->XferErrorCallback = HAL_TIM_DMAError ; + + /* Enable the DMA channel */ + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)pData, (uint32_t)&htim->Instance->CCR2, Length); + + /* Enable the TIM Capture/Compare 2 DMA request */ + __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC2); + } + break; + + case TIM_CHANNEL_3: + { + /* Set the DMA Period elapsed callback */ + htim->hdma[TIM_DMA_ID_CC3]->XferCpltCallback = HAL_TIM_DMADelayPulseCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC3]->XferErrorCallback = HAL_TIM_DMAError ; + + /* Enable the DMA channel */ + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC3], (uint32_t)pData, (uint32_t)&htim->Instance->CCR3,Length); + + /* Enable the TIM Capture/Compare 3 DMA request */ + __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC3); + } + break; + + case TIM_CHANNEL_4: + { + /* Set the DMA Period elapsed callback */ + htim->hdma[TIM_DMA_ID_CC4]->XferCpltCallback = HAL_TIM_DMADelayPulseCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC4]->XferErrorCallback = HAL_TIM_DMAError ; + + /* Enable the DMA channel */ + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC4], (uint32_t)pData, (uint32_t)&htim->Instance->CCR4, Length); + + /* Enable the TIM Capture/Compare 4 DMA request */ + __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC4); + } + break; + + default: + break; + } + + /* Enable the Output compare channel */ + TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_ENABLE); + + if(IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET) + { + /* Enable the main output */ + __HAL_TIM_MOE_ENABLE(htim); + } + + /* Enable the Peripheral */ + __HAL_TIM_ENABLE(htim); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the TIM Output Compare signal generation in DMA mode. + * @param htim : TIM Output Compare handle + * @param Channel : TIM Channel to be disabled + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @arg TIM_CHANNEL_3: TIM Channel 3 selected + * @arg TIM_CHANNEL_4: TIM Channel 4 selected + * @retval HAL status +*/ +HAL_StatusTypeDef HAL_TIM_OC_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel)); + + switch (Channel) + { + case TIM_CHANNEL_1: + { + /* Disable the TIM Capture/Compare 1 DMA request */ + __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC1); + } + break; + + case TIM_CHANNEL_2: + { + /* Disable the TIM Capture/Compare 2 DMA request */ + __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC2); + } + break; + + case TIM_CHANNEL_3: + { + /* Disable the TIM Capture/Compare 3 DMA request */ + __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC3); + } + break; + + case TIM_CHANNEL_4: + { + /* Disable the TIM Capture/Compare 4 interrupt */ + __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC4); + } + break; + + default: + break; + } + + /* Disable the Output compare channel */ + TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_DISABLE); + + if(IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET) + { + /* Disable the Main Ouput */ + __HAL_TIM_MOE_DISABLE(htim); + } + + /* Disable the Peripheral */ + __HAL_TIM_DISABLE(htim); + + /* Change the htim state */ + htim->State = HAL_TIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @} + */ + +/** @defgroup TIM_Group3 Time PWM functions + * @brief Time PWM functions + * +@verbatim + ============================================================================== + ##### Time PWM functions ##### + ============================================================================== + [..] + This section provides functions allowing to: + (+) Initialize and configure the TIM OPWM. + (+) De-initialize the TIM PWM. + (+) Start the Time PWM. + (+) Stop the Time PWM. + (+) Start the Time PWM and enable interrupt. + (+) Stop the Time PWM and disable interrupt. + (+) Start the Time PWM and enable DMA transfer. + (+) Stop the Time PWM and disable DMA transfer. + +@endverbatim + * @{ + */ +/** + * @brief Initializes the TIM PWM Time Base according to the specified + * parameters in the TIM_HandleTypeDef and create the associated handle. + * @param htim: TIM handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_PWM_Init(TIM_HandleTypeDef *htim) +{ + /* Check the TIM handle allocation */ + if(htim == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_TIM_INSTANCE(htim->Instance)); + assert_param(IS_TIM_COUNTER_MODE(htim->Init.CounterMode)); + assert_param(IS_TIM_CLOCKDIVISION_DIV(htim->Init.ClockDivision)); + + if(htim->State == HAL_TIM_STATE_RESET) + { + /* Init the low level hardware : GPIO, CLOCK, NVIC and DMA */ + HAL_TIM_PWM_MspInit(htim); + } + + /* Set the TIM state */ + htim->State= HAL_TIM_STATE_BUSY; + + /* Init the base time for the PWM */ + TIM_Base_SetConfig(htim->Instance, &htim->Init); + + /* Initialize the TIM state*/ + htim->State= HAL_TIM_STATE_READY; + + return HAL_OK; +} + +/** + * @brief DeInitializes the TIM peripheral + * @param htim: TIM handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_PWM_DeInit(TIM_HandleTypeDef *htim) +{ + /* Check the parameters */ + assert_param(IS_TIM_INSTANCE(htim->Instance)); + + htim->State = HAL_TIM_STATE_BUSY; + + /* Disable the TIM Peripheral Clock */ + __HAL_TIM_DISABLE(htim); + + /* DeInit the low level hardware: GPIO, CLOCK, NVIC and DMA */ + HAL_TIM_PWM_MspDeInit(htim); + + /* Change TIM state */ + htim->State = HAL_TIM_STATE_RESET; + + /* Release Lock */ + __HAL_UNLOCK(htim); + + return HAL_OK; +} + +/** + * @brief Initializes the TIM PWM MSP. + * @param htim: TIM handle + * @retval None + */ +__weak void HAL_TIM_PWM_MspInit(TIM_HandleTypeDef *htim) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_TIM_PWM_MspInit could be implemented in the user file + */ +} + +/** + * @brief DeInitializes TIM PWM MSP. + * @param htim: TIM handle + * @retval None + */ +__weak void HAL_TIM_PWM_MspDeInit(TIM_HandleTypeDef *htim) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_TIM_PWM_MspDeInit could be implemented in the user file + */ +} + +/** + * @brief Starts the PWM signal generation. + * @param htim : TIM handle + * @param Channel : TIM Channels to be enabled + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @arg TIM_CHANNEL_3: TIM Channel 3 selected + * @arg TIM_CHANNEL_4: TIM Channel 4 selected + * @retval HAL status +*/ +HAL_StatusTypeDef HAL_TIM_PWM_Start(TIM_HandleTypeDef *htim, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel)); + + /* Enable the Capture compare channel */ + TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_ENABLE); + + if(IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET) + { + /* Enable the main output */ + __HAL_TIM_MOE_ENABLE(htim); + } + + /* Enable the Peripheral */ + __HAL_TIM_ENABLE(htim); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the PWM signal generation. + * @param htim : TIM handle + * @param Channel : TIM Channels to be disabled + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @arg TIM_CHANNEL_3: TIM Channel 3 selected + * @arg TIM_CHANNEL_4: TIM Channel 4 selected + * @retval HAL status +*/ +HAL_StatusTypeDef HAL_TIM_PWM_Stop(TIM_HandleTypeDef *htim, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel)); + + /* Disable the Capture compare channel */ + TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_DISABLE); + + if(IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET) + { + /* Disable the Main Ouput */ + __HAL_TIM_MOE_DISABLE(htim); + } + + /* Disable the Peripheral */ + __HAL_TIM_DISABLE(htim); + + /* Change the htim state */ + htim->State = HAL_TIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Starts the PWM signal generation in interrupt mode. + * @param htim : TIM handle + * @param Channel : TIM Channel to be disabled + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @arg TIM_CHANNEL_3: TIM Channel 3 selected + * @arg TIM_CHANNEL_4: TIM Channel 4 selected + * @retval HAL status +*/ +HAL_StatusTypeDef HAL_TIM_PWM_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel)); + + switch (Channel) + { + case TIM_CHANNEL_1: + { + /* Enable the TIM Capture/Compare 1 interrupt */ + __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC1); + } + break; + + case TIM_CHANNEL_2: + { + /* Enable the TIM Capture/Compare 2 interrupt */ + __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC2); + } + break; + + case TIM_CHANNEL_3: + { + /* Enable the TIM Capture/Compare 3 interrupt */ + __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC3); + } + break; + + case TIM_CHANNEL_4: + { + /* Enable the TIM Capture/Compare 4 interrupt */ + __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC4); + } + break; + + default: + break; + } + + /* Enable the Capture compare channel */ + TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_ENABLE); + + if(IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET) + { + /* Enable the main output */ + __HAL_TIM_MOE_ENABLE(htim); + } + + /* Enable the Peripheral */ + __HAL_TIM_ENABLE(htim); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the PWM signal generation in interrupt mode. + * @param htim : TIM handle + * @param Channel : TIM Channels to be disabled + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @arg TIM_CHANNEL_3: TIM Channel 3 selected + * @arg TIM_CHANNEL_4: TIM Channel 4 selected + * @retval HAL status +*/ +HAL_StatusTypeDef HAL_TIM_PWM_Stop_IT (TIM_HandleTypeDef *htim, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel)); + + switch (Channel) + { + case TIM_CHANNEL_1: + { + /* Disable the TIM Capture/Compare 1 interrupt */ + __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC1); + } + break; + + case TIM_CHANNEL_2: + { + /* Disable the TIM Capture/Compare 2 interrupt */ + __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC2); + } + break; + + case TIM_CHANNEL_3: + { + /* Disable the TIM Capture/Compare 3 interrupt */ + __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC3); + } + break; + + case TIM_CHANNEL_4: + { + /* Disable the TIM Capture/Compare 4 interrupt */ + __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC4); + } + break; + + default: + break; + } + + /* Disable the Capture compare channel */ + TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_DISABLE); + + if(IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET) + { + /* Disable the Main Ouput */ + __HAL_TIM_MOE_DISABLE(htim); + } + + /* Disable the Peripheral */ + __HAL_TIM_DISABLE(htim); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Starts the TIM PWM signal generation in DMA mode. + * @param htim : TIM handle + * @param Channel : TIM Channels to be enabled + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @arg TIM_CHANNEL_3: TIM Channel 3 selected + * @arg TIM_CHANNEL_4: TIM Channel 4 selected + * @param pData: The source Buffer address. + * @param Length: The length of data to be transferred from memory to TIM peripheral + * @retval HAL status +*/ +HAL_StatusTypeDef HAL_TIM_PWM_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel, uint32_t *pData, uint16_t Length) +{ + /* Check the parameters */ + assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel)); + + if((htim->State == HAL_TIM_STATE_BUSY)) + { + return HAL_BUSY; + } + else if((htim->State == HAL_TIM_STATE_READY)) + { + if(((uint32_t)pData == 0 ) && (Length > 0)) + { + return HAL_ERROR; + } + else + { + htim->State = HAL_TIM_STATE_BUSY; + } + } + switch (Channel) + { + case TIM_CHANNEL_1: + { + /* Set the DMA Period elapsed callback */ + htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = HAL_TIM_DMADelayPulseCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = HAL_TIM_DMAError ; + + /* Enable the DMA channel */ + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)pData, (uint32_t)&htim->Instance->CCR1, Length); + + /* Enable the TIM Capture/Compare 1 DMA request */ + __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC1); + } + break; + + case TIM_CHANNEL_2: + { + /* Set the DMA Period elapsed callback */ + htim->hdma[TIM_DMA_ID_CC2]->XferCpltCallback = HAL_TIM_DMADelayPulseCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC2]->XferErrorCallback = HAL_TIM_DMAError ; + + /* Enable the DMA channel */ + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)pData, (uint32_t)&htim->Instance->CCR2, Length); + + /* Enable the TIM Capture/Compare 2 DMA request */ + __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC2); + } + break; + + case TIM_CHANNEL_3: + { + /* Set the DMA Period elapsed callback */ + htim->hdma[TIM_DMA_ID_CC3]->XferCpltCallback = HAL_TIM_DMADelayPulseCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC3]->XferErrorCallback = HAL_TIM_DMAError ; + + /* Enable the DMA channel */ + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC3], (uint32_t)pData, (uint32_t)&htim->Instance->CCR3,Length); + + /* Enable the TIM Output Capture/Compare 3 request */ + __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC3); + } + break; + + case TIM_CHANNEL_4: + { + /* Set the DMA Period elapsed callback */ + htim->hdma[TIM_DMA_ID_CC4]->XferCpltCallback = HAL_TIM_DMADelayPulseCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC4]->XferErrorCallback = HAL_TIM_DMAError ; + + /* Enable the DMA channel */ + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC4], (uint32_t)pData, (uint32_t)&htim->Instance->CCR4, Length); + + /* Enable the TIM Capture/Compare 4 DMA request */ + __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC4); + } + break; + + default: + break; + } + + /* Enable the Capture compare channel */ + TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_ENABLE); + + if(IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET) + { + /* Enable the main output */ + __HAL_TIM_MOE_ENABLE(htim); + } + + /* Enable the Peripheral */ + __HAL_TIM_ENABLE(htim); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the TIM PWM signal generation in DMA mode. + * @param htim : TIM handle + * @param Channel : TIM Channels to be disabled + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @arg TIM_CHANNEL_3: TIM Channel 3 selected + * @arg TIM_CHANNEL_4: TIM Channel 4 selected + * @retval HAL status +*/ +HAL_StatusTypeDef HAL_TIM_PWM_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel)); + + switch (Channel) + { + case TIM_CHANNEL_1: + { + /* Disable the TIM Capture/Compare 1 DMA request */ + __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC1); + } + break; + + case TIM_CHANNEL_2: + { + /* Disable the TIM Capture/Compare 2 DMA request */ + __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC2); + } + break; + + case TIM_CHANNEL_3: + { + /* Disable the TIM Capture/Compare 3 DMA request */ + __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC3); + } + break; + + case TIM_CHANNEL_4: + { + /* Disable the TIM Capture/Compare 4 interrupt */ + __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC4); + } + break; + + default: + break; + } + + /* Disable the Capture compare channel */ + TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_DISABLE); + + if(IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET) + { + /* Disable the Main Ouput */ + __HAL_TIM_MOE_DISABLE(htim); + } + + /* Disable the Peripheral */ + __HAL_TIM_DISABLE(htim); + + /* Change the htim state */ + htim->State = HAL_TIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @} + */ + +/** @defgroup TIM_Group4 Time Input Capture functions + * @brief Time Input Capture functions + * +@verbatim + ============================================================================== + ##### Time Input Capture functions ##### + ============================================================================== + [..] + This section provides functions allowing to: + (+) Initialize and configure the TIM Input Capture. + (+) De-initialize the TIM Input Capture. + (+) Start the Time Input Capture. + (+) Stop the Time Input Capture. + (+) Start the Time Input Capture and enable interrupt. + (+) Stop the Time Input Capture and disable interrupt. + (+) Start the Time Input Capture and enable DMA transfer. + (+) Stop the Time Input Capture and disable DMA transfer. + +@endverbatim + * @{ + */ +/** + * @brief Initializes the TIM Input Capture Time base according to the specified + * parameters in the TIM_HandleTypeDef and create the associated handle. + * @param htim: TIM Input Capture handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_IC_Init(TIM_HandleTypeDef *htim) +{ + /* Check the TIM handle allocation */ + if(htim == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_TIM_INSTANCE(htim->Instance)); + assert_param(IS_TIM_COUNTER_MODE(htim->Init.CounterMode)); + assert_param(IS_TIM_CLOCKDIVISION_DIV(htim->Init.ClockDivision)); + + if(htim->State == HAL_TIM_STATE_RESET) + { + /* Init the low level hardware : GPIO, CLOCK, NVIC and DMA */ + HAL_TIM_IC_MspInit(htim); + } + + /* Set the TIM state */ + htim->State= HAL_TIM_STATE_BUSY; + + /* Init the base time for the input capture */ + TIM_Base_SetConfig(htim->Instance, &htim->Init); + + /* Initialize the TIM state*/ + htim->State= HAL_TIM_STATE_READY; + + return HAL_OK; +} + +/** + * @brief DeInitializes the TIM peripheral + * @param htim: TIM Input Capture handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_IC_DeInit(TIM_HandleTypeDef *htim) +{ + /* Check the parameters */ + assert_param(IS_TIM_INSTANCE(htim->Instance)); + + htim->State = HAL_TIM_STATE_BUSY; + + /* Disable the TIM Peripheral Clock */ + __HAL_TIM_DISABLE(htim); + + /* DeInit the low level hardware: GPIO, CLOCK, NVIC and DMA */ + HAL_TIM_IC_MspDeInit(htim); + + /* Change TIM state */ + htim->State = HAL_TIM_STATE_RESET; + + /* Release Lock */ + __HAL_UNLOCK(htim); + + return HAL_OK; +} + +/** + * @brief Initializes the TIM INput Capture MSP. + * @param htim: TIM handle + * @retval None + */ +__weak void HAL_TIM_IC_MspInit(TIM_HandleTypeDef *htim) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_TIM_IC_MspInit could be implemented in the user file + */ +} + +/** + * @brief DeInitializes TIM Input Capture MSP. + * @param htim: TIM handle + * @retval None + */ +__weak void HAL_TIM_IC_MspDeInit(TIM_HandleTypeDef *htim) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_TIM_IC_MspDeInit could be implemented in the user file + */ +} + +/** + * @brief Starts the TIM Input Capture measurement. + * @param htim : TIM Input Capture handle + * @param Channel : TIM Channels to be enabled + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @arg TIM_CHANNEL_3: TIM Channel 3 selected + * @arg TIM_CHANNEL_4: TIM Channel 4 selected + * @retval HAL status +*/ +HAL_StatusTypeDef HAL_TIM_IC_Start (TIM_HandleTypeDef *htim, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel)); + + /* Enable the Input Capture channel */ + TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_ENABLE); + + /* Enable the Peripheral */ + __HAL_TIM_ENABLE(htim); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the TIM Input Capture measurement. + * @param htim : TIM handle + * @param Channel : TIM Channels to be disabled + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @arg TIM_CHANNEL_3: TIM Channel 3 selected + * @arg TIM_CHANNEL_4: TIM Channel 4 selected + * @retval HAL status +*/ +HAL_StatusTypeDef HAL_TIM_IC_Stop(TIM_HandleTypeDef *htim, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel)); + + /* Disable the Input Capture channel */ + TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_DISABLE); + + /* Disable the Peripheral */ + __HAL_TIM_DISABLE(htim); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Starts the TIM Input Capture measurement in interrupt mode. + * @param htim : TIM Input Capture handle + * @param Channel : TIM Channels to be enabled + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @arg TIM_CHANNEL_3: TIM Channel 3 selected + * @arg TIM_CHANNEL_4: TIM Channel 4 selected + * @retval HAL status +*/ +HAL_StatusTypeDef HAL_TIM_IC_Start_IT (TIM_HandleTypeDef *htim, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel)); + + switch (Channel) + { + case TIM_CHANNEL_1: + { + /* Enable the TIM Capture/Compare 1 interrupt */ + __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC1); + } + break; + + case TIM_CHANNEL_2: + { + /* Enable the TIM Capture/Compare 2 interrupt */ + __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC2); + } + break; + + case TIM_CHANNEL_3: + { + /* Enable the TIM Capture/Compare 3 interrupt */ + __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC3); + } + break; + + case TIM_CHANNEL_4: + { + /* Enable the TIM Capture/Compare 4 interrupt */ + __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC4); + } + break; + + default: + break; + } + /* Enable the Input Capture channel */ + TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_ENABLE); + + /* Enable the Peripheral */ + __HAL_TIM_ENABLE(htim); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the TIM Input Capture measurement in interrupt mode. + * @param htim : TIM handle + * @param Channel : TIM Channels to be disabled + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @arg TIM_CHANNEL_3: TIM Channel 3 selected + * @arg TIM_CHANNEL_4: TIM Channel 4 selected + * @retval HAL status +*/ +HAL_StatusTypeDef HAL_TIM_IC_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel)); + + switch (Channel) + { + case TIM_CHANNEL_1: + { + /* Disable the TIM Capture/Compare 1 interrupt */ + __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC1); + } + break; + + case TIM_CHANNEL_2: + { + /* Disable the TIM Capture/Compare 2 interrupt */ + __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC2); + } + break; + + case TIM_CHANNEL_3: + { + /* Disable the TIM Capture/Compare 3 interrupt */ + __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC3); + } + break; + + case TIM_CHANNEL_4: + { + /* Disable the TIM Capture/Compare 4 interrupt */ + __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC4); + } + break; + + default: + break; + } + + /* Disable the Input Capture channel */ + TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_DISABLE); + + /* Disable the Peripheral */ + __HAL_TIM_DISABLE(htim); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Starts the TIM Input Capture measurement on in DMA mode. + * @param htim : TIM Input Capture handle + * @param Channel : TIM Channels to be enabled + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @arg TIM_CHANNEL_3: TIM Channel 3 selected + * @arg TIM_CHANNEL_4: TIM Channel 4 selected + * @param pData: The destination Buffer address. + * @param Length: The length of data to be transferred from TIM peripheral to memory. + * @retval HAL status +*/ +HAL_StatusTypeDef HAL_TIM_IC_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel, uint32_t *pData, uint16_t Length) +{ + /* Check the parameters */ + assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel)); + assert_param(IS_TIM_DMA_CC_INSTANCE(htim->Instance)); + + if((htim->State == HAL_TIM_STATE_BUSY)) + { + return HAL_BUSY; + } + else if((htim->State == HAL_TIM_STATE_READY)) + { + if((pData == 0 ) && (Length > 0)) + { + return HAL_ERROR; + } + else + { + htim->State = HAL_TIM_STATE_BUSY; + } + } + + switch (Channel) + { + case TIM_CHANNEL_1: + { + /* Set the DMA Period elapsed callback */ + htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = HAL_TIM_DMACaptureCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = HAL_TIM_DMAError ; + + /* Enable the DMA channel */ + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)&htim->Instance->CCR1, (uint32_t)pData, Length); + + /* Enable the TIM Capture/Compare 1 DMA request */ + __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC1); + } + break; + + case TIM_CHANNEL_2: + { + /* Set the DMA Period elapsed callback */ + htim->hdma[TIM_DMA_ID_CC2]->XferCpltCallback = HAL_TIM_DMACaptureCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC2]->XferErrorCallback = HAL_TIM_DMAError ; + + /* Enable the DMA channel */ + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)&htim->Instance->CCR2, (uint32_t)pData, Length); + + /* Enable the TIM Capture/Compare 2 DMA request */ + __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC2); + } + break; + + case TIM_CHANNEL_3: + { + /* Set the DMA Period elapsed callback */ + htim->hdma[TIM_DMA_ID_CC3]->XferCpltCallback = HAL_TIM_DMACaptureCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC3]->XferErrorCallback = HAL_TIM_DMAError ; + + /* Enable the DMA channel */ + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC3], (uint32_t)&htim->Instance->CCR3, (uint32_t)pData, Length); + + /* Enable the TIM Capture/Compare 3 DMA request */ + __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC3); + } + break; + + case TIM_CHANNEL_4: + { + /* Set the DMA Period elapsed callback */ + htim->hdma[TIM_DMA_ID_CC4]->XferCpltCallback = HAL_TIM_DMACaptureCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC4]->XferErrorCallback = HAL_TIM_DMAError ; + + /* Enable the DMA channel */ + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC4], (uint32_t)&htim->Instance->CCR4, (uint32_t)pData, Length); + + /* Enable the TIM Capture/Compare 4 DMA request */ + __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC4); + } + break; + + default: + break; + } + + /* Enable the Input Capture channel */ + TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_ENABLE); + + /* Enable the Peripheral */ + __HAL_TIM_ENABLE(htim); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the TIM Input Capture measurement on in DMA mode. + * @param htim : TIM Input Capture handle + * @param Channel : TIM Channels to be disabled + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @arg TIM_CHANNEL_3: TIM Channel 3 selected + * @arg TIM_CHANNEL_4: TIM Channel 4 selected + * @retval HAL status +*/ +HAL_StatusTypeDef HAL_TIM_IC_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel)); + assert_param(IS_TIM_DMA_CC_INSTANCE(htim->Instance)); + + switch (Channel) + { + case TIM_CHANNEL_1: + { + /* Disable the TIM Capture/Compare 1 DMA request */ + __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC1); + } + break; + + case TIM_CHANNEL_2: + { + /* Disable the TIM Capture/Compare 2 DMA request */ + __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC2); + } + break; + + case TIM_CHANNEL_3: + { + /* Disable the TIM Capture/Compare 3 DMA request */ + __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC3); + } + break; + + case TIM_CHANNEL_4: + { + /* Disable the TIM Capture/Compare 4 DMA request */ + __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC4); + } + break; + + default: + break; + } + + /* Disable the Input Capture channel */ + TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_DISABLE); + + /* Disable the Peripheral */ + __HAL_TIM_DISABLE(htim); + + /* Change the htim state */ + htim->State = HAL_TIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} +/** + * @} + */ + +/** @defgroup TIM_Group5 Time One Pulse functions + * @brief Time One Pulse functions + * +@verbatim + ============================================================================== + ##### Time One Pulse functions ##### + ============================================================================== + [..] + This section provides functions allowing to: + (+) Initialize and configure the TIM One Pulse. + (+) De-initialize the TIM One Pulse. + (+) Start the Time One Pulse. + (+) Stop the Time One Pulse. + (+) Start the Time One Pulse and enable interrupt. + (+) Stop the Time One Pulse and disable interrupt. + (+) Start the Time One Pulse and enable DMA transfer. + (+) Stop the Time One Pulse and disable DMA transfer. + +@endverbatim + * @{ + */ +/** + * @brief Initializes the TIM One Pulse Time Base according to the specified + * parameters in the TIM_HandleTypeDef and create the associated handle. + * @param htim: TIM OnePulse handle + * @param OnePulseMode: Select the One pulse mode. + * This parameter can be one of the following values: + * @arg TIM_OPMODE_SINGLE: Only one pulse will be generated. + * @arg TIM_OPMODE_REPETITIVE: Repetitive pulses wil be generated. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_OnePulse_Init(TIM_HandleTypeDef *htim, uint32_t OnePulseMode) +{ + /* Check the TIM handle allocation */ + if(htim == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_TIM_INSTANCE(htim->Instance)); + assert_param(IS_TIM_COUNTER_MODE(htim->Init.CounterMode)); + assert_param(IS_TIM_CLOCKDIVISION_DIV(htim->Init.ClockDivision)); + assert_param(IS_TIM_OPM_MODE(OnePulseMode)); + + if(htim->State == HAL_TIM_STATE_RESET) + { + /* Init the low level hardware : GPIO, CLOCK, NVIC and DMA */ + HAL_TIM_OnePulse_MspInit(htim); + } + + /* Set the TIM state */ + htim->State= HAL_TIM_STATE_BUSY; + + /* Configure the Time base in the One Pulse Mode */ + TIM_Base_SetConfig(htim->Instance, &htim->Init); + + /* Reset the OPM Bit */ + htim->Instance->CR1 &= (uint16_t)(~TIM_CR1_OPM); + + /* Configure the OPM Mode */ + htim->Instance->CR1 |= OnePulseMode; + + /* Initialize the TIM state*/ + htim->State= HAL_TIM_STATE_READY; + + return HAL_OK; +} + +/** + * @brief DeInitializes the TIM One Pulse + * @param htim: TIM One Pulse handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_OnePulse_DeInit(TIM_HandleTypeDef *htim) +{ + /* Check the parameters */ + assert_param(IS_TIM_INSTANCE(htim->Instance)); + + htim->State = HAL_TIM_STATE_BUSY; + + /* Disable the TIM Peripheral Clock */ + __HAL_TIM_DISABLE(htim); + + /* DeInit the low level hardware: GPIO, CLOCK, NVIC */ + HAL_TIM_OnePulse_MspDeInit(htim); + + /* Change TIM state */ + htim->State = HAL_TIM_STATE_RESET; + + /* Release Lock */ + __HAL_UNLOCK(htim); + + return HAL_OK; +} + +/** + * @brief Initializes the TIM One Pulse MSP. + * @param htim: TIM handle + * @retval None + */ +__weak void HAL_TIM_OnePulse_MspInit(TIM_HandleTypeDef *htim) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_TIM_OnePulse_MspInit could be implemented in the user file + */ +} + +/** + * @brief DeInitializes TIM One Pulse MSP. + * @param htim: TIM handle + * @retval None + */ +__weak void HAL_TIM_OnePulse_MspDeInit(TIM_HandleTypeDef *htim) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_TIM_OnePulse_MspDeInit could be implemented in the user file + */ +} + +/** + * @brief Starts the TIM One Pulse signal generation. + * @param htim : TIM One Pulse handle + * @param OutputChannel : TIM Channels to be enabled + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @retval HAL status +*/ +HAL_StatusTypeDef HAL_TIM_OnePulse_Start(TIM_HandleTypeDef *htim, uint32_t OutputChannel) +{ + /* Enable the Capture compare and the Input Capture channels + (in the OPM Mode the two possible channels that can be used are TIM_CHANNEL_1 and TIM_CHANNEL_2) + if TIM_CHANNEL_1 is used as output, the TIM_CHANNEL_2 will be used as input and + if TIM_CHANNEL_1 is used as input, the TIM_CHANNEL_2 will be used as output + in all combinations, the TIM_CHANNEL_1 and TIM_CHANNEL_2 should be enabled together + + No need to enable the counter, it's enabled automatically by hardware + (the counter starts in response to a stimulus and generate a pulse */ + + TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_ENABLE); + TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_ENABLE); + + if(IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET) + { + /* Enable the main output */ + __HAL_TIM_MOE_ENABLE(htim); + } + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the TIM One Pulse signal generation. + * @param htim : TIM One Pulse handle + * @param OutputChannel : TIM Channels to be disable + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @retval HAL status +*/ +HAL_StatusTypeDef HAL_TIM_OnePulse_Stop(TIM_HandleTypeDef *htim, uint32_t OutputChannel) +{ + /* Disable the Capture compare and the Input Capture channels + (in the OPM Mode the two possible channels that can be used are TIM_CHANNEL_1 and TIM_CHANNEL_2) + if TIM_CHANNEL_1 is used as output, the TIM_CHANNEL_2 will be used as input and + if TIM_CHANNEL_1 is used as input, the TIM_CHANNEL_2 will be used as output + in all combinations, the TIM_CHANNEL_1 and TIM_CHANNEL_2 should be disabled together */ + + TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_DISABLE); + TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_DISABLE); + + if(IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET) + { + /* Disable the Main Ouput */ + __HAL_TIM_MOE_DISABLE(htim); + } + + /* Disable the Peripheral */ + __HAL_TIM_DISABLE(htim); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Starts the TIM One Pulse signal generation in interrupt mode. + * @param htim : TIM One Pulse handle + * @param OutputChannel : TIM Channels to be enabled + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @retval HAL status +*/ +HAL_StatusTypeDef HAL_TIM_OnePulse_Start_IT(TIM_HandleTypeDef *htim, uint32_t OutputChannel) +{ + /* Enable the Capture compare and the Input Capture channels + (in the OPM Mode the two possible channels that can be used are TIM_CHANNEL_1 and TIM_CHANNEL_2) + if TIM_CHANNEL_1 is used as output, the TIM_CHANNEL_2 will be used as input and + if TIM_CHANNEL_1 is used as input, the TIM_CHANNEL_2 will be used as output + in all combinations, the TIM_CHANNEL_1 and TIM_CHANNEL_2 should be enabled together + + No need to enable the counter, it's enabled automatically by hardware + (the counter starts in response to a stimulus and generate a pulse */ + + /* Enable the TIM Capture/Compare 1 interrupt */ + __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC1); + + /* Enable the TIM Capture/Compare 2 interrupt */ + __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC2); + + TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_ENABLE); + TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_ENABLE); + + if(IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET) + { + /* Enable the main output */ + __HAL_TIM_MOE_ENABLE(htim); + } + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the TIM One Pulse signal generation in interrupt mode. + * @param htim : TIM One Pulse handle + * @param OutputChannel : TIM Channels to be enabled + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @retval HAL status +*/ +HAL_StatusTypeDef HAL_TIM_OnePulse_Stop_IT(TIM_HandleTypeDef *htim, uint32_t OutputChannel) +{ + /* Disable the TIM Capture/Compare 1 interrupt */ + __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC1); + + /* Disable the TIM Capture/Compare 2 interrupt */ + __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC2); + + /* Disable the Capture compare and the Input Capture channels + (in the OPM Mode the two possible channels that can be used are TIM_CHANNEL_1 and TIM_CHANNEL_2) + if TIM_CHANNEL_1 is used as output, the TIM_CHANNEL_2 will be used as input and + if TIM_CHANNEL_1 is used as input, the TIM_CHANNEL_2 will be used as output + in all combinations, the TIM_CHANNEL_1 and TIM_CHANNEL_2 should be disabled together */ + TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_DISABLE); + TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_DISABLE); + + if(IS_TIM_BREAK_INSTANCE(htim->Instance) != RESET) + { + /* Disable the Main Ouput */ + __HAL_TIM_MOE_DISABLE(htim); + } + + /* Disable the Peripheral */ + __HAL_TIM_DISABLE(htim); + + /* Return function status */ + return HAL_OK; +} + +/** + * @} + */ + +/** @defgroup TIM_Group6 Time Encoder functions + * @brief Time Encoder functions + * +@verbatim + ============================================================================== + ##### Time Encoder functions ##### + ============================================================================== + [..] + This section provides functions allowing to: + (+) Initialize and configure the TIM Encoder. + (+) De-initialize the TIM Encoder. + (+) Start the Time Encoder. + (+) Stop the Time Encoder. + (+) Start the Time Encoder and enable interrupt. + (+) Stop the Time Encoder and disable interrupt. + (+) Start the Time Encoder and enable DMA transfer. + (+) Stop the Time Encoder and disable DMA transfer. + +@endverbatim + * @{ + */ +/** + * @brief Initializes the TIM Encoder Interface and create the associated handle. + * @param htim: TIM Encoder Interface handle + * @param sConfig: TIM Encoder Interface configuration structure + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_Encoder_Init(TIM_HandleTypeDef *htim, TIM_Encoder_InitTypeDef* sConfig) +{ + uint32_t tmpsmcr = 0; + uint32_t tmpccmr1 = 0; + uint32_t tmpccer = 0; + + /* Check the TIM handle allocation */ + if(htim == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_TIM_CC2_INSTANCE(htim->Instance)); + assert_param(IS_TIM_ENCODER_MODE(sConfig->EncoderMode)); + assert_param(IS_TIM_IC_SELECTION(sConfig->IC1Selection)); + assert_param(IS_TIM_IC_SELECTION(sConfig->IC2Selection)); + assert_param(IS_TIM_IC_POLARITY(sConfig->IC1Polarity)); + assert_param(IS_TIM_IC_POLARITY(sConfig->IC2Polarity)); + assert_param(IS_TIM_IC_PRESCALER(sConfig->IC1Prescaler)); + assert_param(IS_TIM_IC_PRESCALER(sConfig->IC2Prescaler)); + assert_param(IS_TIM_IC_FILTER(sConfig->IC1Filter)); + assert_param(IS_TIM_IC_FILTER(sConfig->IC2Filter)); + + if(htim->State == HAL_TIM_STATE_RESET) + { + /* Init the low level hardware : GPIO, CLOCK, NVIC and DMA */ + HAL_TIM_Encoder_MspInit(htim); + } + + /* Set the TIM state */ + htim->State= HAL_TIM_STATE_BUSY; + + /* Reset the SMS bits */ + htim->Instance->SMCR &= (uint16_t)(~TIM_SMCR_SMS); + + /* Configure the Time base in the Encoder Mode */ + TIM_Base_SetConfig(htim->Instance, &htim->Init); + + /* Get the TIMx SMCR register value */ + tmpsmcr = htim->Instance->SMCR; + + /* Get the TIMx CCMR1 register value */ + tmpccmr1 = htim->Instance->CCMR1; + + /* Get the TIMx CCER register value */ + tmpccer = htim->Instance->CCER; + + /* Set the encoder Mode */ + tmpsmcr |= sConfig->EncoderMode; + + /* Select the Capture Compare 1 and the Capture Compare 2 as input */ + tmpccmr1 &= (uint16_t)(~(TIM_CCMR1_CC1S | TIM_CCMR1_CC2S)); + tmpccmr1 |= (sConfig->IC1Selection | (sConfig->IC2Selection << 8)); + + /* Set the the Capture Compare 1 and the Capture Compare 2 prescalers and filters */ + tmpccmr1 &= (uint16_t)(~(TIM_CCMR1_IC1PSC | TIM_CCMR1_IC2PSC)); + tmpccmr1 &= (uint16_t)(~(TIM_CCMR1_IC1F | TIM_CCMR1_IC2F)); + tmpccmr1 |= sConfig->IC1Prescaler | (sConfig->IC2Prescaler << 8); + tmpccmr1 |= (sConfig->IC1Filter << 4) | (sConfig->IC2Filter << 12); + + /* Set the TI1 and the TI2 Polarities */ + tmpccer &= (uint16_t)(~(TIM_CCER_CC1P | TIM_CCER_CC2P)); + tmpccer &= (uint16_t)(~(TIM_CCER_CC1NP | TIM_CCER_CC2NP)); + tmpccer |= sConfig->IC1Polarity | (sConfig->IC2Polarity << 4); + + /* Write to TIMx SMCR */ + htim->Instance->SMCR = tmpsmcr; + + /* Write to TIMx CCMR1 */ + htim->Instance->CCMR1 = tmpccmr1; + + /* Write to TIMx CCER */ + htim->Instance->CCER = tmpccer; + + /* Initialize the TIM state*/ + htim->State= HAL_TIM_STATE_READY; + + return HAL_OK; +} + + +/** + * @brief DeInitializes the TIM Encoder interface + * @param htim: TIM Encoder handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_Encoder_DeInit(TIM_HandleTypeDef *htim) +{ + /* Check the parameters */ + assert_param(IS_TIM_INSTANCE(htim->Instance)); + + htim->State = HAL_TIM_STATE_BUSY; + + /* Disable the TIM Peripheral Clock */ + __HAL_TIM_DISABLE(htim); + + /* DeInit the low level hardware: GPIO, CLOCK, NVIC */ + HAL_TIM_Encoder_MspDeInit(htim); + + /* Change TIM state */ + htim->State = HAL_TIM_STATE_RESET; + + /* Release Lock */ + __HAL_UNLOCK(htim); + + return HAL_OK; +} + +/** + * @brief Initializes the TIM Encoder Interface MSP. + * @param htim: TIM handle + * @retval None + */ +__weak void HAL_TIM_Encoder_MspInit(TIM_HandleTypeDef *htim) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_TIM_Encoder_MspInit could be implemented in the user file + */ +} + +/** + * @brief DeInitializes TIM Encoder Interface MSP. + * @param htim: TIM handle + * @retval None + */ +__weak void HAL_TIM_Encoder_MspDeInit(TIM_HandleTypeDef *htim) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_TIM_Encoder_MspDeInit could be implemented in the user file + */ +} + +/** + * @brief Starts the TIM Encoder Interface. + * @param htim : TIM Encoder Interface handle + * @param Channel : TIM Channels to be enabled + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @retval HAL status +*/ +HAL_StatusTypeDef HAL_TIM_Encoder_Start(TIM_HandleTypeDef *htim, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_TIM_CC2_INSTANCE(htim->Instance)); + + /* Enable the encoder interface channels */ + switch (Channel) + { + case TIM_CHANNEL_1: + { + TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_ENABLE); + break; + } + case TIM_CHANNEL_2: + { + TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_ENABLE); + break; + } + default : + { + TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_ENABLE); + TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_ENABLE); + break; + } + } + /* Enable the Peripheral */ + __HAL_TIM_ENABLE(htim); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the TIM Encoder Interface. + * @param htim : TIM Encoder Interface handle + * @param Channel : TIM Channels to be disabled + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @retval HAL status +*/ +HAL_StatusTypeDef HAL_TIM_Encoder_Stop(TIM_HandleTypeDef *htim, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_TIM_CC2_INSTANCE(htim->Instance)); + + /* Disable the Input Capture channels 1 and 2 + (in the EncoderInterface the two possible channels that can be used are TIM_CHANNEL_1 and TIM_CHANNEL_2) */ + switch (Channel) + { + case TIM_CHANNEL_1: + { + TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_DISABLE); + break; + } + case TIM_CHANNEL_2: + { + TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_DISABLE); + break; + } + default : + { + TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_DISABLE); + TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_DISABLE); + break; + } + } + + /* Disable the Peripheral */ + __HAL_TIM_DISABLE(htim); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Starts the TIM Encoder Interface in interrupt mode. + * @param htim : TIM Encoder Interface handle + * @param Channel : TIM Channels to be enabled + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @retval HAL status +*/ +HAL_StatusTypeDef HAL_TIM_Encoder_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_TIM_CC2_INSTANCE(htim->Instance)); + + /* Enable the encoder interface channels */ + /* Enable the capture compare Interrupts 1 and/or 2 */ + switch (Channel) + { + case TIM_CHANNEL_1: + { + TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_ENABLE); + __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC1); + break; + } + case TIM_CHANNEL_2: + { + TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_ENABLE); + __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC2); + break; + } + default : + { + TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_ENABLE); + TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_ENABLE); + __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC1); + __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC2); + break; + } + } + + /* Enable the Peripheral */ + __HAL_TIM_ENABLE(htim); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the TIM Encoder Interface in interrupt mode. + * @param htim : TIM Encoder Interface handle + * @param Channel : TIM Channels to be disabled + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @retval HAL status +*/ +HAL_StatusTypeDef HAL_TIM_Encoder_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_TIM_CC2_INSTANCE(htim->Instance)); + + /* Disable the Input Capture channels 1 and 2 + (in the EncoderInterface the two possible channels that can be used are TIM_CHANNEL_1 and TIM_CHANNEL_2) */ + if(Channel == TIM_CHANNEL_1) + { + TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_DISABLE); + + /* Disable the capture compare Interrupts 1 */ + __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC1); + } + else if(Channel == TIM_CHANNEL_2) + { + TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_DISABLE); + + /* Disable the capture compare Interrupts 2 */ + __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC2); + } + else + { + TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_DISABLE); + TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_DISABLE); + + /* Disable the capture compare Interrupts 1 and 2 */ + __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC1); + __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC2); + } + + /* Disable the Peripheral */ + __HAL_TIM_DISABLE(htim); + + /* Change the htim state */ + htim->State = HAL_TIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Starts the TIM Encoder Interface in DMA mode. + * @param htim : TIM Encoder Interface handle + * @param Channel : TIM Channels to be enabled + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @param pData1: The destination Buffer address for IC1. + * @param pData2: The destination Buffer address for IC2. + * @param Length: The length of data to be transferred from TIM peripheral to memory. + * @retval HAL status +*/ +HAL_StatusTypeDef HAL_TIM_Encoder_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel, uint32_t *pData1, uint32_t *pData2, uint16_t Length) +{ + /* Check the parameters */ + assert_param(IS_TIM_DMA_CC_INSTANCE(htim->Instance)); + + if((htim->State == HAL_TIM_STATE_BUSY)) + { + return HAL_BUSY; + } + else if((htim->State == HAL_TIM_STATE_READY)) + { + if((((pData1 == 0) || (pData2 == 0) )) && (Length > 0)) + { + return HAL_ERROR; + } + else + { + htim->State = HAL_TIM_STATE_BUSY; + } + } + + switch (Channel) + { + case TIM_CHANNEL_1: + { + /* Set the DMA Period elapsed callback */ + htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = HAL_TIM_DMACaptureCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = HAL_TIM_DMAError ; + + /* Enable the DMA channel */ + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)&htim->Instance->CCR1, (uint32_t )pData1, Length); + + /* Enable the TIM Input Capture DMA request */ + __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC1); + + /* Enable the Peripheral */ + __HAL_TIM_ENABLE(htim); + + /* Enable the Capture compare channel */ + TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_ENABLE); + } + break; + + case TIM_CHANNEL_2: + { + /* Set the DMA Period elapsed callback */ + htim->hdma[TIM_DMA_ID_CC2]->XferCpltCallback = HAL_TIM_DMACaptureCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC2]->XferErrorCallback = HAL_TIM_DMAError; + /* Enable the DMA channel */ + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)&htim->Instance->CCR2, (uint32_t)pData2, Length); + + /* Enable the TIM Input Capture DMA request */ + __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC2); + + /* Enable the Peripheral */ + __HAL_TIM_ENABLE(htim); + + /* Enable the Capture compare channel */ + TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_ENABLE); + } + break; + + case TIM_CHANNEL_ALL: + { + /* Set the DMA Period elapsed callback */ + htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = HAL_TIM_DMACaptureCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = HAL_TIM_DMAError ; + + /* Enable the DMA channel */ + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)&htim->Instance->CCR1, (uint32_t)pData1, Length); + + /* Set the DMA Period elapsed callback */ + htim->hdma[TIM_DMA_ID_CC2]->XferCpltCallback = HAL_TIM_DMACaptureCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC2]->XferErrorCallback = HAL_TIM_DMAError ; + + /* Enable the DMA channel */ + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)&htim->Instance->CCR2, (uint32_t)pData2, Length); + + /* Enable the Peripheral */ + __HAL_TIM_ENABLE(htim); + + /* Enable the Capture compare channel */ + TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_ENABLE); + TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_ENABLE); + + /* Enable the TIM Input Capture DMA request */ + __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC1); + /* Enable the TIM Input Capture DMA request */ + __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC2); + } + break; + + default: + break; + } + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the TIM Encoder Interface in DMA mode. + * @param htim : TIM Encoder Interface handle + * @param Channel : TIM Channels to be enabled + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @retval HAL status +*/ +HAL_StatusTypeDef HAL_TIM_Encoder_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_TIM_DMA_CC_INSTANCE(htim->Instance)); + + /* Disable the Input Capture channels 1 and 2 + (in the EncoderInterface the two possible channels that can be used are TIM_CHANNEL_1 and TIM_CHANNEL_2) */ + if(Channel == TIM_CHANNEL_1) + { + TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_DISABLE); + + /* Disable the capture compare DMA Request 1 */ + __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC1); + } + else if(Channel == TIM_CHANNEL_2) + { + TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_DISABLE); + + /* Disable the capture compare DMA Request 2 */ + __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC2); + } + else + { + TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_DISABLE); + TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_DISABLE); + + /* Disable the capture compare DMA Request 1 and 2 */ + __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC1); + __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC2); + } + + /* Disable the Peripheral */ + __HAL_TIM_DISABLE(htim); + + /* Change the htim state */ + htim->State = HAL_TIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @} + */ +/** @defgroup TIM_Group7 TIM IRQ handler management + * @brief IRQ handler management + * +@verbatim + ============================================================================== + ##### IRQ handler management ##### + ============================================================================== + [..] + This section provides Timer IRQ handler function. + +@endverbatim + * @{ + */ +/** + * @brief This function handles TIM interrupts requests. + * @param htim: TIM handle + * @retval None + */ +void HAL_TIM_IRQHandler(TIM_HandleTypeDef *htim) +{ + /* Capture compare 1 event */ + if(__HAL_TIM_GET_FLAG(htim, TIM_FLAG_CC1) != RESET) + { + if(__HAL_TIM_GET_ITSTATUS(htim, TIM_IT_CC1) !=RESET) + { + { + __HAL_TIM_CLEAR_IT(htim, TIM_IT_CC1); + htim->Channel = HAL_TIM_ACTIVE_CHANNEL_1; + + /* Input capture event */ + if((htim->Instance->CCMR1 & TIM_CCMR1_CC1S) != 0x00) + { + HAL_TIM_IC_CaptureCallback(htim); + } + /* Output compare event */ + else + { + HAL_TIM_OC_DelayElapsedCallback(htim); + HAL_TIM_PWM_PulseFinishedCallback(htim); + } + htim->Channel = HAL_TIM_ACTIVE_CHANNEL_CLEARED; + } + } + } + /* Capture compare 2 event */ + if(__HAL_TIM_GET_FLAG(htim, TIM_FLAG_CC2) != RESET) + { + if(__HAL_TIM_GET_ITSTATUS(htim, TIM_IT_CC2) !=RESET) + { + __HAL_TIM_CLEAR_IT(htim, TIM_IT_CC2); + htim->Channel = HAL_TIM_ACTIVE_CHANNEL_2; + /* Input capture event */ + if((htim->Instance->CCMR1 & TIM_CCMR1_CC2S) != 0x00) + { + HAL_TIM_IC_CaptureCallback(htim); + } + /* Output compare event */ + else + { + HAL_TIM_OC_DelayElapsedCallback(htim); + HAL_TIM_PWM_PulseFinishedCallback(htim); + } + htim->Channel = HAL_TIM_ACTIVE_CHANNEL_CLEARED; + } + } + /* Capture compare 3 event */ + if(__HAL_TIM_GET_FLAG(htim, TIM_FLAG_CC3) != RESET) + { + if(__HAL_TIM_GET_ITSTATUS(htim, TIM_IT_CC3) !=RESET) + { + __HAL_TIM_CLEAR_IT(htim, TIM_IT_CC3); + htim->Channel = HAL_TIM_ACTIVE_CHANNEL_3; + /* Input capture event */ + if((htim->Instance->CCMR1 & TIM_CCMR2_CC3S) != 0x00) + { + HAL_TIM_IC_CaptureCallback(htim); + } + /* Output compare event */ + else + { + HAL_TIM_OC_DelayElapsedCallback(htim); + HAL_TIM_PWM_PulseFinishedCallback(htim); + } + htim->Channel = HAL_TIM_ACTIVE_CHANNEL_CLEARED; + } + } + /* Capture compare 4 event */ + if(__HAL_TIM_GET_FLAG(htim, TIM_FLAG_CC4) != RESET) + { + if(__HAL_TIM_GET_ITSTATUS(htim, TIM_IT_CC4) !=RESET) + { + __HAL_TIM_CLEAR_IT(htim, TIM_IT_CC4); + htim->Channel = HAL_TIM_ACTIVE_CHANNEL_4; + /* Input capture event */ + if((htim->Instance->CCMR1 & TIM_CCMR2_CC4S) != 0x00) + { + HAL_TIM_IC_CaptureCallback(htim); + } + /* Output compare event */ + else + { + HAL_TIM_OC_DelayElapsedCallback(htim); + HAL_TIM_PWM_PulseFinishedCallback(htim); + } + htim->Channel = HAL_TIM_ACTIVE_CHANNEL_CLEARED; + } + } + /* TIM Update event */ + if(__HAL_TIM_GET_FLAG(htim, TIM_FLAG_UPDATE) != RESET) + { + if(__HAL_TIM_GET_ITSTATUS(htim, TIM_IT_UPDATE) !=RESET) + { + __HAL_TIM_CLEAR_IT(htim, TIM_IT_UPDATE); + HAL_TIM_PeriodElapsedCallback(htim); + } + } + /* TIM Break input event */ + if(__HAL_TIM_GET_FLAG(htim, TIM_FLAG_BREAK) != RESET) + { + if(__HAL_TIM_GET_ITSTATUS(htim, TIM_IT_BREAK) !=RESET) + { + __HAL_TIM_CLEAR_IT(htim, TIM_IT_BREAK); + HAL_TIMEx_BreakCallback(htim); + } + } + /* TIM Trigger detection event */ + if(__HAL_TIM_GET_FLAG(htim, TIM_FLAG_TRIGGER) != RESET) + { + if(__HAL_TIM_GET_ITSTATUS(htim, TIM_IT_TRIGGER) !=RESET) + { + __HAL_TIM_CLEAR_IT(htim, TIM_IT_TRIGGER); + HAL_TIM_TriggerCallback(htim); + } + } + /* TIM commutation event */ + if(__HAL_TIM_GET_FLAG(htim, TIM_FLAG_COM) != RESET) + { + if(__HAL_TIM_GET_ITSTATUS(htim, TIM_IT_COM) !=RESET) + { + __HAL_TIM_CLEAR_IT(htim, TIM_FLAG_COM); + HAL_TIMEx_CommutationCallback(htim); + } + } +} + +/** + * @} + */ + +/** @defgroup TIM_Group8 Peripheral Control functions + * @brief Peripheral Control functions + * +@verbatim + ============================================================================== + ##### Peripheral Control functions ##### + ============================================================================== + [..] + This section provides functions allowing to: + (+) Configure The Input Output channels for OC, PWM, IC or One Pulse mode. + (+) Configure External Clock source. + (+) Configure Complementary channels, break features and dead time. + (+) Configure Master and the Slave synchronization. + (+) Configure the DMA Burst Mode. + +@endverbatim + * @{ + */ + +/** + * @brief Initializes the TIM Output Compare Channels according to the specified + * parameters in the TIM_OC_InitTypeDef. + * @param htim: TIM Output Compare handle + * @param sConfig: TIM Output Compare configuration structure + * @param Channel : TIM Channels to be enabled + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @arg TIM_CHANNEL_3: TIM Channel 3 selected + * @arg TIM_CHANNEL_4: TIM Channel 4 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_OC_ConfigChannel(TIM_HandleTypeDef *htim, TIM_OC_InitTypeDef* sConfig, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_TIM_CHANNELS(Channel)); + assert_param(IS_TIM_OC_MODE(sConfig->OCMode)); + assert_param(IS_TIM_OC_POLARITY(sConfig->OCPolarity)); + assert_param(IS_TIM_OCN_POLARITY(sConfig->OCNPolarity)); + assert_param(IS_TIM_FAST_STATE(sConfig->OCFastMode)); + assert_param(IS_TIM_OCNIDLE_STATE(sConfig->OCNIdleState)); + assert_param(IS_TIM_OCIDLE_STATE(sConfig->OCIdleState)); + + /* Check input state */ + __HAL_LOCK(htim); + + htim->State = HAL_TIM_STATE_BUSY; + + switch (Channel) + { + case TIM_CHANNEL_1: + { + assert_param(IS_TIM_CC1_INSTANCE(htim->Instance)); + /* Configure the TIM Channel 1 in Output Compare */ + TIM_OC1_SetConfig(htim->Instance, sConfig); + } + break; + + case TIM_CHANNEL_2: + { + assert_param(IS_TIM_CC2_INSTANCE(htim->Instance)); + /* Configure the TIM Channel 2 in Output Compare */ + TIM_OC2_SetConfig(htim->Instance, sConfig); + } + break; + + case TIM_CHANNEL_3: + { + assert_param(IS_TIM_CC3_INSTANCE(htim->Instance)); + /* Configure the TIM Channel 3 in Output Compare */ + TIM_OC3_SetConfig(htim->Instance, sConfig); + } + break; + + case TIM_CHANNEL_4: + { + assert_param(IS_TIM_CC4_INSTANCE(htim->Instance)); + /* Configure the TIM Channel 4 in Output Compare */ + TIM_OC4_SetConfig(htim->Instance, sConfig); + } + break; + + default: + break; + } + htim->State = HAL_TIM_STATE_READY; + + __HAL_UNLOCK(htim); + + return HAL_OK; +} + +/** + * @brief Initializes the TIM Input Capture Channels according to the specified + * parameters in the TIM_IC_InitTypeDef. + * @param htim: TIM IC handle + * @param sConfig: TIM Input Capture configuration structure + * @param Channel : TIM Channels to be enabled + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @arg TIM_CHANNEL_3: TIM Channel 3 selected + * @arg TIM_CHANNEL_4: TIM Channel 4 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_IC_ConfigChannel(TIM_HandleTypeDef *htim, TIM_IC_InitTypeDef* sConfig, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_TIM_CC1_INSTANCE(htim->Instance)); + assert_param(IS_TIM_IC_POLARITY(sConfig->ICPolarity)); + assert_param(IS_TIM_IC_SELECTION(sConfig->ICSelection)); + assert_param(IS_TIM_IC_PRESCALER(sConfig->ICPrescaler)); + assert_param(IS_TIM_IC_FILTER(sConfig->ICFilter)); + + __HAL_LOCK(htim); + + htim->State = HAL_TIM_STATE_BUSY; + + if (Channel == TIM_CHANNEL_1) + { + /* TI1 Configuration */ + TIM_TI1_SetConfig(htim->Instance, + sConfig->ICPolarity, + sConfig->ICSelection, + sConfig->ICFilter); + + /* Reset the IC1PSC Bits */ + htim->Instance->CCMR1 &= (uint16_t)(~TIM_CCMR1_IC1PSC); + + /* Set the IC1PSC value */ + htim->Instance->CCMR1 |= sConfig->ICPrescaler; + } + else if (Channel == TIM_CHANNEL_2) + { + /* TI2 Configuration */ + assert_param(IS_TIM_CC2_INSTANCE(htim->Instance)); + + TIM_TI2_SetConfig(htim->Instance, + sConfig->ICPolarity, + sConfig->ICSelection, + sConfig->ICFilter); + + /* Reset the IC2PSC Bits */ + htim->Instance->CCMR1 &= (uint16_t)(~TIM_CCMR1_IC2PSC); + + /* Set the IC2PSC value */ + htim->Instance->CCMR1 |= (sConfig->ICPrescaler << 8); + } + else if (Channel == TIM_CHANNEL_3) + { + /* TI3 Configuration */ + assert_param(IS_TIM_CC3_INSTANCE(htim->Instance)); + + TIM_TI3_SetConfig(htim->Instance, + sConfig->ICPolarity, + sConfig->ICSelection, + sConfig->ICFilter); + + /* Reset the IC3PSC Bits */ + htim->Instance->CCMR2 &= (uint16_t)(~TIM_CCMR2_IC3PSC); + + /* Set the IC3PSC value */ + htim->Instance->CCMR2 |= sConfig->ICPrescaler; + } + else + { + /* TI4 Configuration */ + assert_param(IS_TIM_CC4_INSTANCE(htim->Instance)); + + TIM_TI4_SetConfig(htim->Instance, + sConfig->ICPolarity, + sConfig->ICSelection, + sConfig->ICFilter); + + /* Reset the IC4PSC Bits */ + htim->Instance->CCMR2 &= (uint16_t)(~TIM_CCMR2_IC4PSC); + + /* Set the IC4PSC value */ + htim->Instance->CCMR2 |= (sConfig->ICPrescaler << 8); + } + + htim->State = HAL_TIM_STATE_READY; + + __HAL_UNLOCK(htim); + + return HAL_OK; +} + +/** + * @brief Initializes the TIM PWM channels according to the specified + * parameters in the TIM_OC_InitTypeDef. + * @param htim: TIM handle + * @param sConfig: TIM PWM configuration structure + * @param Channel : TIM Channels to be enabled + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @arg TIM_CHANNEL_3: TIM Channel 3 selected + * @arg TIM_CHANNEL_4: TIM Channel 4 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_PWM_ConfigChannel(TIM_HandleTypeDef *htim, TIM_OC_InitTypeDef* sConfig, uint32_t Channel) +{ + __HAL_LOCK(htim); + + /* Check the parameters */ + assert_param(IS_TIM_CHANNELS(Channel)); + assert_param(IS_TIM_PWM_MODE(sConfig->OCMode)); + assert_param(IS_TIM_OC_POLARITY(sConfig->OCPolarity)); + assert_param(IS_TIM_OCN_POLARITY(sConfig->OCNPolarity)); + assert_param(IS_TIM_OCNIDLE_STATE(sConfig->OCNIdleState)); + assert_param(IS_TIM_OCIDLE_STATE(sConfig->OCIdleState)); + + htim->State = HAL_TIM_STATE_BUSY; + + switch (Channel) + { + case TIM_CHANNEL_1: + { + assert_param(IS_TIM_CC1_INSTANCE(htim->Instance)); + /* Configure the Channel 1 in PWM mode */ + TIM_OC1_SetConfig(htim->Instance, sConfig); + + /* Set the Preload enable bit for channel1 */ + htim->Instance->CCMR1 |= TIM_CCMR1_OC1PE; + + /* Configure the Output Fast mode */ + htim->Instance->CCMR1 &= (uint16_t)(~TIM_CCMR1_OC1FE); + htim->Instance->CCMR1 |= sConfig->OCFastMode; + } + break; + + case TIM_CHANNEL_2: + { + assert_param(IS_TIM_CC2_INSTANCE(htim->Instance)); + /* Configure the Channel 2 in PWM mode */ + TIM_OC2_SetConfig(htim->Instance, sConfig); + + /* Set the Preload enable bit for channel2 */ + htim->Instance->CCMR1 |= TIM_CCMR1_OC2PE; + + /* Configure the Output Fast mode */ + htim->Instance->CCMR1 &= (uint16_t)(~TIM_CCMR1_OC2FE); + htim->Instance->CCMR1 |= sConfig->OCFastMode << 8; + } + break; + + case TIM_CHANNEL_3: + { + assert_param(IS_TIM_CC3_INSTANCE(htim->Instance)); + /* Configure the Channel 3 in PWM mode */ + TIM_OC3_SetConfig(htim->Instance, sConfig); + + /* Set the Preload enable bit for channel3 */ + htim->Instance->CCMR2 |= TIM_CCMR2_OC3PE; + + /* Configure the Output Fast mode */ + htim->Instance->CCMR2 &= (uint16_t)(~TIM_CCMR2_OC3FE); + htim->Instance->CCMR2 |= sConfig->OCFastMode; + } + break; + + case TIM_CHANNEL_4: + { + assert_param(IS_TIM_CC4_INSTANCE(htim->Instance)); + /* Configure the Channel 4 in PWM mode */ + TIM_OC4_SetConfig(htim->Instance, sConfig); + + /* Set the Preload enable bit for channel4 */ + htim->Instance->CCMR2 |= TIM_CCMR2_OC4PE; + + /* Configure the Output Fast mode */ + htim->Instance->CCMR2 &= (uint16_t)(~TIM_CCMR2_OC4FE); + htim->Instance->CCMR2 |= sConfig->OCFastMode << 8; + } + break; + + default: + break; + } + + htim->State = HAL_TIM_STATE_READY; + + __HAL_UNLOCK(htim); + + return HAL_OK; +} + +/** + * @brief Initializes the TIM One Pulse Channels according to the specified + * parameters in the TIM_OnePulse_InitTypeDef. + * @param htim: TIM One Pulse handle + * @param sConfig: TIM One Pulse configuration structure + * @param OutputChannel : TIM Channels to be enabled + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @param InputChannel : TIM Channels to be enabled + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_OnePulse_ConfigChannel(TIM_HandleTypeDef *htim, TIM_OnePulse_InitTypeDef* sConfig, uint32_t OutputChannel, uint32_t InputChannel) +{ + TIM_OC_InitTypeDef temp1; + + /* Check the parameters */ + assert_param(IS_TIM_OPM_CHANNELS(OutputChannel)); + assert_param(IS_TIM_OPM_CHANNELS(InputChannel)); + + if(OutputChannel != InputChannel) + { + __HAL_LOCK(htim); + + htim->State = HAL_TIM_STATE_BUSY; + + /* Extract the Ouput compare configuration from sConfig structure */ + temp1.OCMode = sConfig->OCMode; + temp1.Pulse = sConfig->Pulse; + temp1.OCPolarity = sConfig->OCPolarity; + temp1.OCNPolarity = sConfig->OCNPolarity; + temp1.OCIdleState = sConfig->OCIdleState; + temp1.OCNIdleState = sConfig->OCNIdleState; + + switch (OutputChannel) + { + case TIM_CHANNEL_1: + { + assert_param(IS_TIM_CC1_INSTANCE(htim->Instance)); + + TIM_OC1_SetConfig(htim->Instance, &temp1); + } + break; + case TIM_CHANNEL_2: + { + assert_param(IS_TIM_CC2_INSTANCE(htim->Instance)); + + TIM_OC2_SetConfig(htim->Instance, &temp1); + } + break; + default: + break; + } + switch (InputChannel) + { + case TIM_CHANNEL_1: + { + assert_param(IS_TIM_CC1_INSTANCE(htim->Instance)); + + TIM_TI1_SetConfig(htim->Instance, sConfig->ICPolarity, + sConfig->ICSelection, sConfig->ICFilter); + + /* Reset the IC1PSC Bits */ + htim->Instance->CCMR1 &= (uint16_t)(~TIM_CCMR1_IC1PSC); + + /* Select the Trigger source */ + htim->Instance->SMCR &= (uint16_t)(~TIM_SMCR_TS); + htim->Instance->SMCR |= TIM_TS_TI1FP1; + + /* Select the Slave Mode */ + htim->Instance->SMCR &= (uint16_t)(~TIM_SMCR_SMS); + htim->Instance->SMCR |= TIM_SLAVEMODE_TRIGGER; + } + break; + case TIM_CHANNEL_2: + { + assert_param(IS_TIM_CC2_INSTANCE(htim->Instance)); + + TIM_TI2_SetConfig(htim->Instance, sConfig->ICPolarity, + sConfig->ICSelection, sConfig->ICFilter); + + /* Reset the IC2PSC Bits */ + htim->Instance->CCMR1 &= (uint16_t)(~TIM_CCMR1_IC2PSC); + + /* Select the Trigger source */ + htim->Instance->SMCR &= (uint16_t)(~TIM_SMCR_TS); + htim->Instance->SMCR |= TIM_TS_TI2FP2; + + /* Select the Slave Mode */ + htim->Instance->SMCR &= (uint16_t)(~TIM_SMCR_SMS); + htim->Instance->SMCR |= TIM_SLAVEMODE_TRIGGER; + } + break; + + default: + break; + } + + htim->State = HAL_TIM_STATE_READY; + + __HAL_UNLOCK(htim); + + return HAL_OK; +} + else + { + return HAL_ERROR; + } +} + +/** + * @brief Configure the DMA Burst to transfer Data from the memory to the TIM peripheral + * @param htim: TIM handle + * @param BurstBaseAddress: TIM Base address from when the DMA will starts the Data write + * This parameters can be on of the following values: + * @arg TIM_DMABase_CR1 + * @arg TIM_DMABase_CR2 + * @arg TIM_DMABase_SMCR + * @arg TIM_DMABase_DIER + * @arg TIM_DMABase_SR + * @arg TIM_DMABase_EGR + * @arg TIM_DMABase_CCMR1 + * @arg TIM_DMABase_CCMR2 + * @arg TIM_DMABase_CCER + * @arg TIM_DMABase_CNT + * @arg TIM_DMABase_PSC + * @arg TIM_DMABase_ARR + * @arg TIM_DMABase_RCR + * @arg TIM_DMABase_CCR1 + * @arg TIM_DMABase_CCR2 + * @arg TIM_DMABase_CCR3 + * @arg TIM_DMABase_CCR4 + * @arg TIM_DMABase_BDTR + * @arg TIM_DMABase_DCR + * @param BurstRequestSrc: TIM DMA Request sources + * This parameters can be on of the following values: + * @arg TIM_DMA_UPDATE: TIM update Interrupt source + * @arg TIM_DMA_CC1: TIM Capture Compare 1 DMA source + * @arg TIM_DMA_CC2: TIM Capture Compare 2 DMA source + * @arg TIM_DMA_CC3: TIM Capture Compare 3 DMA source + * @arg TIM_DMA_CC4: TIM Capture Compare 4 DMA source + * @arg TIM_DMA_COM: TIM Commutation DMA source + * @arg TIM_DMA_TRIGGER: TIM Trigger DMA source + * @param BurstBuffer: The Buffer address. + * @param BurstLength: DMA Burst length. This parameter can be one value + * between: TIM_DMABurstLength_1Transfer and TIM_DMABurstLength_18Transfers. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_DMABurst_WriteStart(TIM_HandleTypeDef *htim, uint32_t BurstBaseAddress, uint32_t BurstRequestSrc, + uint32_t* BurstBuffer, uint32_t BurstLength) +{ + /* Check the parameters */ + assert_param(IS_TIM_DMABURST_INSTANCE(htim->Instance)); + assert_param(IS_TIM_DMA_BASE(BurstBaseAddress)); + assert_param(IS_TIM_DMA_SOURCE(BurstRequestSrc)); + assert_param(IS_TIM_DMA_LENGTH(BurstLength)); + + if((htim->State == HAL_TIM_STATE_BUSY)) + { + return HAL_BUSY; + } + else if((htim->State == HAL_TIM_STATE_READY)) + { + if((BurstBuffer == 0 ) && (BurstLength > 0)) + { + return HAL_ERROR; + } + else + { + htim->State = HAL_TIM_STATE_BUSY; + } + } + switch(BurstRequestSrc) + { + case TIM_DMA_UPDATE: + { + /* Set the DMA Period elapsed callback */ + htim->hdma[TIM_DMA_ID_UPDATE]->XferCpltCallback = TIM_DMAPeriodElapsedCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_UPDATE]->XferErrorCallback = HAL_TIM_DMAError ; + + /* Enable the DMA channel */ + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_UPDATE], (uint32_t)BurstBuffer, (uint32_t)&htim->Instance->DMAR, ((BurstLength) >> 8) + 1); + } + break; + case TIM_DMA_CC1: + { + /* Set the DMA Period elapsed callback */ + htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = HAL_TIM_DMADelayPulseCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = HAL_TIM_DMAError ; + + /* Enable the DMA channel */ + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)BurstBuffer, (uint32_t)&htim->Instance->DMAR, ((BurstLength) >> 8) + 1); + } + break; + case TIM_DMA_CC2: + { + /* Set the DMA Period elapsed callback */ + htim->hdma[TIM_DMA_ID_CC2]->XferCpltCallback = HAL_TIM_DMADelayPulseCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC2]->XferErrorCallback = HAL_TIM_DMAError ; + + /* Enable the DMA channel */ + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)BurstBuffer, (uint32_t)&htim->Instance->DMAR, ((BurstLength) >> 8) + 1); + } + break; + case TIM_DMA_CC3: + { + /* Set the DMA Period elapsed callback */ + htim->hdma[TIM_DMA_ID_CC3]->XferCpltCallback = HAL_TIM_DMADelayPulseCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC3]->XferErrorCallback = HAL_TIM_DMAError ; + + /* Enable the DMA channel */ + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC3], (uint32_t)BurstBuffer, (uint32_t)&htim->Instance->DMAR, ((BurstLength) >> 8) + 1); + } + break; + case TIM_DMA_CC4: + { + /* Set the DMA Period elapsed callback */ + htim->hdma[TIM_DMA_ID_CC4]->XferCpltCallback = HAL_TIM_DMADelayPulseCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC4]->XferErrorCallback = HAL_TIM_DMAError ; + + /* Enable the DMA channel */ + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC4], (uint32_t)BurstBuffer, (uint32_t)&htim->Instance->DMAR, ((BurstLength) >> 8) + 1); + } + break; + case TIM_DMA_COM: + { + /* Set the DMA Period elapsed callback */ + htim->hdma[TIM_DMA_ID_COMMUTATION]->XferCpltCallback = HAL_TIMEx_DMACommutationCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_COMMUTATION]->XferErrorCallback = HAL_TIM_DMAError ; + + /* Enable the DMA channel */ + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_COMMUTATION], (uint32_t)BurstBuffer, (uint32_t)&htim->Instance->DMAR, ((BurstLength) >> 8) + 1); + } + break; + case TIM_DMA_TRIGGER: + { + /* Set the DMA Period elapsed callback */ + htim->hdma[TIM_DMA_ID_TRIGGER]->XferCpltCallback = TIM_DMATriggerCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_TRIGGER]->XferErrorCallback = HAL_TIM_DMAError ; + + /* Enable the DMA channel */ + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_TRIGGER], (uint32_t)BurstBuffer, (uint32_t)&htim->Instance->DMAR, ((BurstLength) >> 8) + 1); + } + break; + default: + break; + } + /* configure the DMA Burst Mode */ + htim->Instance->DCR = BurstBaseAddress | BurstLength; + + /* Enable the TIM DMA Request */ + __HAL_TIM_ENABLE_DMA(htim, BurstRequestSrc); + + htim->State = HAL_TIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the TIM DMA Burst mode + * @param htim: TIM handle + * @param BurstRequestSrc: TIM DMA Request sources to disable + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_DMABurst_WriteStop(TIM_HandleTypeDef *htim, uint32_t BurstRequestSrc) +{ + /* Check the parameters */ + assert_param(IS_TIM_DMA_SOURCE(BurstRequestSrc)); + + /* Abort the DMA transfer (at least disable the DMA channel) */ + switch(BurstRequestSrc) + { + case TIM_DMA_UPDATE: + { + HAL_DMA_Abort(htim->hdma[TIM_DMA_ID_UPDATE]); + } + break; + case TIM_DMA_CC1: + { + HAL_DMA_Abort(htim->hdma[TIM_DMA_ID_CC1]); + } + break; + case TIM_DMA_CC2: + { + HAL_DMA_Abort(htim->hdma[TIM_DMA_ID_CC2]); + } + break; + case TIM_DMA_CC3: + { + HAL_DMA_Abort(htim->hdma[TIM_DMA_ID_CC3]); + } + break; + case TIM_DMA_CC4: + { + HAL_DMA_Abort(htim->hdma[TIM_DMA_ID_CC4]); + } + break; + case TIM_DMA_COM: + { + HAL_DMA_Abort(htim->hdma[TIM_DMA_ID_COMMUTATION]); + } + break; + case TIM_DMA_TRIGGER: + { + HAL_DMA_Abort(htim->hdma[TIM_DMA_ID_TRIGGER]); + } + break; + default: + break; + } + + /* Disable the TIM Update DMA request */ + __HAL_TIM_DISABLE_DMA(htim, BurstRequestSrc); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Configure the DMA Burst to transfer Data from the TIM peripheral to the memory + * @param htim: TIM handle + * @param BurstBaseAddress: TIM Base address from when the DMA will starts the Data read + * This parameters can be on of the following values: + * @arg TIM_DMABase_CR1 + * @arg TIM_DMABase_CR2 + * @arg TIM_DMABase_SMCR + * @arg TIM_DMABase_DIER + * @arg TIM_DMABase_SR + * @arg TIM_DMABase_EGR + * @arg TIM_DMABase_CCMR1 + * @arg TIM_DMABase_CCMR2 + * @arg TIM_DMABase_CCER + * @arg TIM_DMABase_CNT + * @arg TIM_DMABase_PSC + * @arg TIM_DMABase_ARR + * @arg TIM_DMABase_RCR + * @arg TIM_DMABase_CCR1 + * @arg TIM_DMABase_CCR2 + * @arg TIM_DMABase_CCR3 + * @arg TIM_DMABase_CCR4 + * @arg TIM_DMABase_BDTR + * @arg TIM_DMABase_DCR + * @param BurstRequestSrc: TIM DMA Request sources + * This parameters can be on of the following values: + * @arg TIM_DMA_UPDATE: TIM update Interrupt source + * @arg TIM_DMA_CC1: TIM Capture Compare 1 DMA source + * @arg TIM_DMA_CC2: TIM Capture Compare 2 DMA source + * @arg TIM_DMA_CC3: TIM Capture Compare 3 DMA source + * @arg TIM_DMA_CC4: TIM Capture Compare 4 DMA source + * @arg TIM_DMA_COM: TIM Commutation DMA source + * @arg TIM_DMA_TRIGGER: TIM Trigger DMA source + * @param BurstBuffer: The Buffer address. + * @param BurstLength: DMA Burst length. This parameter can be one value + * between: TIM_DMABurstLength_1Transfer and TIM_DMABurstLength_18Transfers. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_DMABurst_ReadStart(TIM_HandleTypeDef *htim, uint32_t BurstBaseAddress, uint32_t BurstRequestSrc, + uint32_t *BurstBuffer, uint32_t BurstLength) +{ + /* Check the parameters */ + assert_param(IS_TIM_DMABURST_INSTANCE(htim->Instance)); + assert_param(IS_TIM_DMA_BASE(BurstBaseAddress)); + assert_param(IS_TIM_DMA_SOURCE(BurstRequestSrc)); + assert_param(IS_TIM_DMA_LENGTH(BurstLength)); + + if((htim->State == HAL_TIM_STATE_BUSY)) + { + return HAL_BUSY; + } + else if((htim->State == HAL_TIM_STATE_READY)) + { + if((BurstBuffer == 0 ) && (BurstLength > 0)) + { + return HAL_ERROR; + } + else + { + htim->State = HAL_TIM_STATE_BUSY; + } + } + switch(BurstRequestSrc) + { + case TIM_DMA_UPDATE: + { + /* Set the DMA Period elapsed callback */ + htim->hdma[TIM_DMA_ID_UPDATE]->XferCpltCallback = TIM_DMAPeriodElapsedCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_UPDATE]->XferErrorCallback = HAL_TIM_DMAError ; + + /* Enable the DMA channel */ + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_UPDATE], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, ((BurstLength) >> 8) + 1); + } + break; + case TIM_DMA_CC1: + { + /* Set the DMA Period elapsed callback */ + htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = HAL_TIM_DMACaptureCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = HAL_TIM_DMAError ; + + /* Enable the DMA channel */ + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, ((BurstLength) >> 8) + 1); + } + break; + case TIM_DMA_CC2: + { + /* Set the DMA Period elapsed callback */ + htim->hdma[TIM_DMA_ID_CC2]->XferCpltCallback = HAL_TIM_DMACaptureCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC2]->XferErrorCallback = HAL_TIM_DMAError ; + + /* Enable the DMA channel */ + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, ((BurstLength) >> 8) + 1); + } + break; + case TIM_DMA_CC3: + { + /* Set the DMA Period elapsed callback */ + htim->hdma[TIM_DMA_ID_CC3]->XferCpltCallback = HAL_TIM_DMACaptureCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC3]->XferErrorCallback = HAL_TIM_DMAError ; + + /* Enable the DMA channel */ + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC3], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, ((BurstLength) >> 8) + 1); + } + break; + case TIM_DMA_CC4: + { + /* Set the DMA Period elapsed callback */ + htim->hdma[TIM_DMA_ID_CC4]->XferCpltCallback = HAL_TIM_DMACaptureCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC4]->XferErrorCallback = HAL_TIM_DMAError ; + + /* Enable the DMA channel */ + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC4], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, ((BurstLength) >> 8) + 1); + } + break; + case TIM_DMA_COM: + { + /* Set the DMA Period elapsed callback */ + htim->hdma[TIM_DMA_ID_COMMUTATION]->XferCpltCallback = HAL_TIMEx_DMACommutationCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_COMMUTATION]->XferErrorCallback = HAL_TIM_DMAError ; + + /* Enable the DMA channel */ + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_COMMUTATION], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, ((BurstLength) >> 8) + 1); + } + break; + case TIM_DMA_TRIGGER: + { + /* Set the DMA Period elapsed callback */ + htim->hdma[TIM_DMA_ID_TRIGGER]->XferCpltCallback = TIM_DMATriggerCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_TRIGGER]->XferErrorCallback = HAL_TIM_DMAError ; + + /* Enable the DMA channel */ + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_TRIGGER], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, ((BurstLength) >> 8) + 1); + } + break; + default: + break; + } + + /* configure the DMA Burst Mode */ + htim->Instance->DCR = BurstBaseAddress | BurstLength; + + /* Enable the TIM DMA Request */ + __HAL_TIM_ENABLE_DMA(htim, BurstRequestSrc); + + htim->State = HAL_TIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stop the DMA burst reading + * @param htim: TIM handle + * @param BurstRequestSrc: TIM DMA Request sources to disable. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_DMABurst_ReadStop(TIM_HandleTypeDef *htim, uint32_t BurstRequestSrc) +{ + /* Check the parameters */ + assert_param(IS_TIM_DMA_SOURCE(BurstRequestSrc)); + + /* Abort the DMA transfer (at least disable the DMA channel) */ + switch(BurstRequestSrc) + { + case TIM_DMA_UPDATE: + { + HAL_DMA_Abort(htim->hdma[TIM_DMA_ID_UPDATE]); + } + break; + case TIM_DMA_CC1: + { + HAL_DMA_Abort(htim->hdma[TIM_DMA_ID_CC1]); + } + break; + case TIM_DMA_CC2: + { + HAL_DMA_Abort(htim->hdma[TIM_DMA_ID_CC2]); + } + break; + case TIM_DMA_CC3: + { + HAL_DMA_Abort(htim->hdma[TIM_DMA_ID_CC3]); + } + break; + case TIM_DMA_CC4: + { + HAL_DMA_Abort(htim->hdma[TIM_DMA_ID_CC4]); + } + break; + case TIM_DMA_COM: + { + HAL_DMA_Abort(htim->hdma[TIM_DMA_ID_COMMUTATION]); + } + break; + case TIM_DMA_TRIGGER: + { + HAL_DMA_Abort(htim->hdma[TIM_DMA_ID_TRIGGER]); + } + break; + default: + break; + } + + /* Disable the TIM Update DMA request */ + __HAL_TIM_DISABLE_DMA(htim, BurstRequestSrc); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Generate a software event + * @param htim: TIM handle + * @param EventSource: specifies the event source. + * This parameter can be one of the following values: + * @arg TIM_EventSource_Update: Timer update Event source + * @arg TIM_EventSource_CC1: Timer Capture Compare 1 Event source + * @arg TIM_EventSource_CC2: Timer Capture Compare 2 Event source + * @arg TIM_EventSource_CC3: Timer Capture Compare 3 Event source + * @arg TIM_EventSource_CC4: Timer Capture Compare 4 Event source + * @arg TIM_EventSource_COM: Timer COM event source + * @arg TIM_EventSource_Trigger: Timer Trigger Event source + * @arg TIM_EventSource_Break: Timer Break event source + * @note TBC can only generate an update event. + * @note TIM_EventSource_COM and TIM_EventSource_Break are used only with TBC. + * @retval HAL status + */ + +HAL_StatusTypeDef HAL_TIM_GenerateEvent(TIM_HandleTypeDef *htim, uint32_t EventSource) +{ + /* Check the parameters */ + assert_param(IS_TIM_INSTANCE(htim->Instance)); + assert_param(IS_TIM_EVENT_SOURCE(EventSource)); + + /* Process Locked */ + __HAL_LOCK(htim); + + /* Change the TIM state */ + htim->State = HAL_TIM_STATE_BUSY; + + /* Set the event sources */ + htim->Instance->EGR = EventSource; + + /* Change the TIM state */ + htim->State = HAL_TIM_STATE_READY; + + __HAL_UNLOCK(htim); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Configures the OCRef clear feature + * @param htim: TIM handle + * @param sClearInputConfig: pointer to a TIM_ClearInputConfigTypeDef structure that + * contains the OCREF clear feature and parameters for the TIM peripheral. + * @param Channel: specifies the TIM Channel + * This parameter can be one of the following values: + * @arg TIM_Channel_1: TIM Channel 1 + * @arg TIM_Channel_2: TIM Channel 2 + * @arg TIM_Channel_3: TIM Channel 3 + * @arg TIM_Channel_4: TIM Channel 4 + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_ConfigOCrefClear(TIM_HandleTypeDef *htim, TIM_ClearInputConfigTypeDef * sClearInputConfig, uint32_t Channel) +{ + uint32_t tmpsmcr = 0; + + /* Check the parameters */ + assert_param(IS_TIM_OCXREF_CLEAR_INSTANCE(htim->Instance)); + assert_param(IS_TIM_CLEARINPUT_SOURCE(sClearInputConfig->ClearInputSource)); + assert_param(IS_TIM_CLEARINPUT_POLARITY(sClearInputConfig->ClearInputPolarity)); + assert_param(IS_TIM_CLEARINPUT_PRESCALER(sClearInputConfig->ClearInputPrescaler)); + assert_param(IS_TIM_CLEARINPUT_FILTER(sClearInputConfig->ClearInputFilter)); + + /* Process Locked */ + __HAL_LOCK(htim); + + htim->State = HAL_TIM_STATE_BUSY; + + switch (sClearInputConfig->ClearInputSource) + { + case TIM_CLEARINPUTSOURCE_NONE: + { + /* Clear the OCREF clear selection bit */ + tmpsmcr &= (uint16_t)(~TIM_SMCR_OCCS); + + /* Clear the ETR Bits */ + tmpsmcr &= (uint16_t)(~(TIM_SMCR_ETF | TIM_SMCR_ETPS | TIM_SMCR_ECE | TIM_SMCR_ETP)); + + /* Set TIMx_SMCR */ + htim->Instance->SMCR = tmpsmcr; + } + break; + + case TIM_CLEARINPUTSOURCE_ETR: + { + TIM_ETR_SetConfig(htim->Instance, + sClearInputConfig->ClearInputPrescaler, + sClearInputConfig->ClearInputPolarity, + sClearInputConfig->ClearInputFilter); + + /* Set the OCREF clear selection bit */ + htim->Instance->SMCR |= TIM_SMCR_OCCS; + } + break; + } + + switch (Channel) + { + case TIM_CHANNEL_1: + { + if(sClearInputConfig->ClearInputState != RESET) + { + /* Enable the Ocref clear feature for Channel 1 */ + htim->Instance->CCMR1 |= TIM_CCMR1_OC1CE; + } + else + { + /* Disable the Ocref clear feature for Channel 1 */ + htim->Instance->CCMR1 &= (uint16_t)(~TIM_CCMR1_OC1CE); + } + } + break; + case TIM_CHANNEL_2: + { + assert_param(IS_TIM_CC2_INSTANCE(htim->Instance)); + if(sClearInputConfig->ClearInputState != RESET) + { + /* Enable the Ocref clear feature for Channel 1 */ + htim->Instance->CCMR1 |= TIM_CCMR1_OC2CE; + } + else + { + /* Disable the Ocref clear feature for Channel 1 */ + htim->Instance->CCMR1 &= (uint16_t)(~TIM_CCMR1_OC2CE); + } + } + break; + case TIM_CHANNEL_3: + { + assert_param(IS_TIM_CC3_INSTANCE(htim->Instance)); + if(sClearInputConfig->ClearInputState != RESET) + { + /* Enable the Ocref clear feature for Channel 1 */ + htim->Instance->CCMR2 |= TIM_CCMR2_OC3CE; + } + else + { + /* Disable the Ocref clear feature for Channel 1 */ + htim->Instance->CCMR2 &= (uint16_t)(~TIM_CCMR2_OC3CE); + } + } + break; + case TIM_CHANNEL_4: + { + assert_param(IS_TIM_CC4_INSTANCE(htim->Instance)); + if(sClearInputConfig->ClearInputState != RESET) + { + /* Enable the Ocref clear feature for Channel 1 */ + htim->Instance->CCMR2 |= TIM_CCMR2_OC4CE; + } + else + { + /* Disable the Ocref clear feature for Channel 1 */ + htim->Instance->CCMR2 &= (uint16_t)(~TIM_CCMR2_OC4CE); + } + } + break; + default: + break; + } + + htim->State = HAL_TIM_STATE_READY; + + __HAL_UNLOCK(htim); + + return HAL_OK; +} + +/** + * @brief Configures the clock source to be used + * @param htim: TIM handle + * @param sClockSourceConfig: pointer to a TIM_ClockConfigTypeDef structure that + * contains the clock source information for the TIM peripheral. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_ConfigClockSource(TIM_HandleTypeDef *htim, TIM_ClockConfigTypeDef * sClockSourceConfig) +{ + uint32_t tmpsmcr = 0; + + /* Process Locked */ + __HAL_LOCK(htim); + + htim->State = HAL_TIM_STATE_BUSY; + + /* Check the parameters */ + assert_param(IS_TIM_CLOCKSOURCE(sClockSourceConfig->ClockSource)); + assert_param(IS_TIM_CLOCKPOLARITY(sClockSourceConfig->ClockPolarity)); + assert_param(IS_TIM_CLOCKPRESCALER(sClockSourceConfig->ClockPrescaler)); + assert_param(IS_TIM_CLOCKFILTER(sClockSourceConfig->ClockFilter)); + + /* Reset the SMS, TS, ECE, ETPS and ETRF bits */ + tmpsmcr = htim->Instance->SMCR; + tmpsmcr &= (uint16_t)(~(TIM_SMCR_SMS | TIM_SMCR_TS)); + tmpsmcr &= (uint16_t)(~(TIM_SMCR_ETF | TIM_SMCR_ETPS | TIM_SMCR_ECE | TIM_SMCR_ETP)); + htim->Instance->SMCR = tmpsmcr; + + switch (sClockSourceConfig->ClockSource) + { + case TIM_CLOCKSOURCE_INTERNAL: + { + assert_param(IS_TIM_INSTANCE(htim->Instance)); + /* Disable slave mode to clock the prescaler directly with the internal clock */ + htim->Instance->SMCR &= (uint16_t)(~TIM_SMCR_SMS); + } + break; + + case TIM_CLOCKSOURCE_ETRMODE1: + { + /* Check whether or not the timer instance supports external trigger input mode 1 (ETRF)*/ + assert_param(IS_TIM_CLOCKSOURCE_ETRMODE1_INSTANCE(htim->Instance)); + + /* Configure the ETR Clock source */ + TIM_ETR_SetConfig(htim->Instance, + sClockSourceConfig->ClockPrescaler, + sClockSourceConfig->ClockPolarity, + sClockSourceConfig->ClockFilter); + /* Get the TIMx SMCR register value */ + tmpsmcr = htim->Instance->SMCR; + /* Reset the SMS and TS Bits */ + tmpsmcr &= (uint16_t)(~(TIM_SMCR_SMS | TIM_SMCR_TS)); + /* Select the External clock mode1 and the ETRF trigger */ + tmpsmcr |= (TIM_SLAVEMODE_EXTERNAL1 | TIM_CLOCKSOURCE_ETRMODE1); + /* Write to TIMx SMCR */ + htim->Instance->SMCR = tmpsmcr; + } + break; + + case TIM_CLOCKSOURCE_ETRMODE2: + { + /* Check whether or not the timer instance supports external trigger input mode 2 (ETRF)*/ + assert_param(IS_TIM_CLOCKSOURCE_ETRMODE2_INSTANCE(htim->Instance)); + + /* Configure the ETR Clock source */ + TIM_ETR_SetConfig(htim->Instance, + sClockSourceConfig->ClockPrescaler, + sClockSourceConfig->ClockPolarity, + sClockSourceConfig->ClockFilter); + /* Enable the External clock mode2 */ + htim->Instance->SMCR |= TIM_SMCR_ECE; + } + break; + + case TIM_CLOCKSOURCE_TI1: + { + /* Check whether or not the timer instance supports external clock mode 1 */ + assert_param(IS_TIM_CLOCKSOURCE_TIX_INSTANCE(htim->Instance)); + + TIM_TI1_ConfigInputStage(htim->Instance, + sClockSourceConfig->ClockPolarity, + sClockSourceConfig->ClockFilter); + TIM_ITRx_SetConfig(htim->Instance, TIM_CLOCKSOURCE_TI1); + } + break; + case TIM_CLOCKSOURCE_TI2: + { + /* Check whether or not the timer instance supports external clock mode 1 (ETRF)*/ + assert_param(IS_TIM_CLOCKSOURCE_TIX_INSTANCE(htim->Instance)); + + TIM_TI2_ConfigInputStage(htim->Instance, + sClockSourceConfig->ClockPolarity, + sClockSourceConfig->ClockFilter); + TIM_ITRx_SetConfig(htim->Instance, TIM_CLOCKSOURCE_TI2); + } + break; + case TIM_CLOCKSOURCE_TI1ED: + { + /* Check whether or not the timer instance supports external clock mode 1 */ + assert_param(IS_TIM_CLOCKSOURCE_TIX_INSTANCE(htim->Instance)); + + TIM_TI1_ConfigInputStage(htim->Instance, + sClockSourceConfig->ClockPolarity, + sClockSourceConfig->ClockFilter); + TIM_ITRx_SetConfig(htim->Instance, TIM_CLOCKSOURCE_TI1ED); + } + break; + case TIM_CLOCKSOURCE_ITR0: + { + /* Check whether or not the timer instance supports external clock mode 1 */ + assert_param(IS_TIM_CLOCKSOURCE_ITRX_INSTANCE(htim->Instance)); + + TIM_ITRx_SetConfig(htim->Instance, TIM_CLOCKSOURCE_ITR0); + } + break; + case TIM_CLOCKSOURCE_ITR1: + { + /* Check whether or not the timer instance supports external clock mode 1 */ + assert_param(IS_TIM_CLOCKSOURCE_ITRX_INSTANCE(htim->Instance)); + + TIM_ITRx_SetConfig(htim->Instance, TIM_CLOCKSOURCE_ITR1); + } + break; + case TIM_CLOCKSOURCE_ITR2: + { + /* Check whether or not the timer instance supports external clock mode 1 */ + assert_param(IS_TIM_CLOCKSOURCE_ITRX_INSTANCE(htim->Instance)); + + TIM_ITRx_SetConfig(htim->Instance, TIM_CLOCKSOURCE_ITR2); + } + break; + case TIM_CLOCKSOURCE_ITR3: + { + /* Check whether or not the timer instance supports external clock mode 1 */ + assert_param(IS_TIM_CLOCKSOURCE_ITRX_INSTANCE(htim->Instance)); + + TIM_ITRx_SetConfig(htim->Instance, TIM_CLOCKSOURCE_ITR3); + } + break; + + default: + break; + } + htim->State = HAL_TIM_STATE_READY; + + __HAL_UNLOCK(htim); + + return HAL_OK; +} + +/** + * @brief Selects the signal connected to the TI1 input: direct from CH1_input + * or a XOR combination between CH1_input, CH2_input & CH3_input + * @param htim: TIM handle. + * @param TI1_Selection: Indicate whether or not channel 1 is connected to the + * output of a XOR gate. + * This parameter can be one of the following values: + * @arg TIM_TI1SELECTION_CH1: The TIMx_CH1 pin is connected to TI1 input + * @arg TIM_TI1SELECTION_XORCOMBINATION: The TIMx_CH1, CH2 and CH3 + * pins are connected to the TI1 input (XOR combination) + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_ConfigTI1Input(TIM_HandleTypeDef *htim, uint32_t TI1_Selection) +{ + uint32_t tmpcr2 = 0; + + /* Check the parameters */ + assert_param(IS_TIM_XOR_INSTANCE(htim->Instance)); + assert_param(IS_TIM_TI1SELECTION(TI1_Selection)); + + /* Get the TIMx CR2 register value */ + tmpcr2 = htim->Instance->CR2; + + /* Reset the TI1 selection */ + tmpcr2 &= (uint16_t)(~TIM_CR2_TI1S); + + /* Set the the TI1 selection */ + tmpcr2 |= TI1_Selection; + + /* Write to TIMxCR2 */ + htim->Instance->CR2 = tmpcr2; + + return HAL_OK; +} + +/** + * @brief Configures the TIM in Slave mode + * @param htim: TIM handle. + * @param sSlaveConfig: pointer to a TIM_SlaveConfigTypeDef structure that + * contains the selected trigger (internal trigger input, filtered + * timer input or external trigger input) and the ) and the Slave + * mode (Disable, Reset, Gated, Trigger, External clock mode 1). + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_SlaveConfigSynchronization(TIM_HandleTypeDef *htim, TIM_SlaveConfigTypeDef * sSlaveConfig) +{ + uint32_t tmpsmcr = 0; + uint32_t tmpccmr1 = 0; + uint32_t tmpccer = 0; + + /* Check the parameters */ + assert_param(IS_TIM_SLAVE_INSTANCE(htim->Instance)); + assert_param(IS_TIM_SLAVE_MODE(sSlaveConfig->SlaveMode)); + assert_param(IS_TIM_TRIGGER_SELECTION(sSlaveConfig->InputTrigger)); + + __HAL_LOCK(htim); + + htim->State = HAL_TIM_STATE_BUSY; + + /* Get the TIMx SMCR register value */ + tmpsmcr = htim->Instance->SMCR; + + /* Reset the Trigger Selection Bits */ + tmpsmcr &= (uint16_t)(~TIM_SMCR_TS); + /* Set the Input Trigger source */ + tmpsmcr |= sSlaveConfig->InputTrigger; + + /* Reset the slave mode Bits */ + tmpsmcr &= (uint16_t)(~TIM_SMCR_SMS); + /* Set the slave mode */ + tmpsmcr |= sSlaveConfig->SlaveMode; + + /* Write to TIMx SMCR */ + htim->Instance->SMCR = tmpsmcr; + + /* Configure the trigger prescaler, filter, and polarity */ + switch (sSlaveConfig->InputTrigger) + { + case TIM_TS_ETRF: + { + /* Check the parameters */ + assert_param(IS_TIM_CLOCKSOURCE_ETRMODE1_INSTANCE(htim->Instance)); + assert_param(IS_TIM_TRIGGERPRESCALER(sSlaveConfig->TriggerPrescaler)); + assert_param(IS_TIM_TRIGGERPOLARITY(sSlaveConfig->TriggerPolarity)); + assert_param(IS_TIM_TRIGGERFILTER(sSlaveConfig->TriggerFilter)); + /* Configure the ETR Trigger source */ + TIM_ETR_SetConfig(htim->Instance, + sSlaveConfig->TriggerPrescaler, + sSlaveConfig->TriggerPolarity, + sSlaveConfig->TriggerFilter); + } + break; + + case TIM_TS_TI1F_ED: + { + /* Check the parameters */ + assert_param(IS_TIM_CC1_INSTANCE(htim->Instance)); + assert_param(IS_TIM_TRIGGERPOLARITY(sSlaveConfig->TriggerPolarity)); + assert_param(IS_TIM_TRIGGERFILTER(sSlaveConfig->TriggerFilter)); + + /* Disable the Channel 1: Reset the CC1E Bit */ + tmpccer = htim->Instance->CCER; + htim->Instance->CCER &= (uint16_t)(~TIM_CCER_CC1E); + tmpccmr1 = htim->Instance->CCMR1; + + /* Set the filter */ + tmpccmr1 &= (uint16_t)(~TIM_CCMR1_IC1F); + tmpccmr1 |= ((sSlaveConfig->TriggerFilter) << 4); + + /* Write to TIMx CCMR1 and CCER registers */ + htim->Instance->CCMR1 = tmpccmr1; + htim->Instance->CCER = tmpccer; + + } + break; + + case TIM_TS_TI1FP1: + { + /* Check the parameters */ + assert_param(IS_TIM_CC1_INSTANCE(htim->Instance)); + assert_param(IS_TIM_TRIGGERPOLARITY(sSlaveConfig->TriggerPolarity)); + assert_param(IS_TIM_TRIGGERFILTER(sSlaveConfig->TriggerFilter)); + + /* Configure TI1 Filter and Polarity */ + TIM_TI1_ConfigInputStage(htim->Instance, + sSlaveConfig->TriggerPolarity, + sSlaveConfig->TriggerFilter); + } + break; + + case TIM_TS_TI2FP2: + { + /* Check the parameters */ + assert_param(IS_TIM_CC2_INSTANCE(htim->Instance)); + assert_param(IS_TIM_TRIGGERPOLARITY(sSlaveConfig->TriggerPolarity)); + assert_param(IS_TIM_TRIGGERFILTER(sSlaveConfig->TriggerFilter)); + + /* Configure TI2 Filter and Polarity */ + TIM_TI2_ConfigInputStage(htim->Instance, + sSlaveConfig->TriggerPolarity, + sSlaveConfig->TriggerFilter); + } + break; + + case TIM_TS_ITR0: + { + /* Check the parameter */ + assert_param(IS_TIM_CC2_INSTANCE(htim->Instance)); + } + break; + + case TIM_TS_ITR1: + { + /* Check the parameter */ + assert_param(IS_TIM_CC2_INSTANCE(htim->Instance)); + } + break; + + case TIM_TS_ITR2: + { + /* Check the parameter */ + assert_param(IS_TIM_CC2_INSTANCE(htim->Instance)); + } + break; + + case TIM_TS_ITR3: + { + /* Check the parameter */ + assert_param(IS_TIM_CC2_INSTANCE(htim->Instance)); + } + break; + + default: + break; + } + + htim->State = HAL_TIM_STATE_READY; + + __HAL_UNLOCK(htim); + + return HAL_OK; +} + +/** + * @brief Read the captured value from Capture Compare unit + * @param htim: TIM handle. + * @param Channel : TIM Channels to be enabled + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @arg TIM_CHANNEL_3: TIM Channel 3 selected + * @arg TIM_CHANNEL_4: TIM Channel 4 selected + * @retval Captured value + */ +uint32_t HAL_TIM_ReadCapturedValue(TIM_HandleTypeDef *htim, uint32_t Channel) +{ + uint32_t tmpreg = 0; + + __HAL_LOCK(htim); + + switch (Channel) + { + case TIM_CHANNEL_1: + { + /* Check the parameters */ + assert_param(IS_TIM_CC1_INSTANCE(htim->Instance)); + + /* Return the capture 1 value */ + tmpreg = htim->Instance->CCR1; + + break; + } + case TIM_CHANNEL_2: + { + /* Check the parameters */ + assert_param(IS_TIM_CC2_INSTANCE(htim->Instance)); + + /* Return the capture 2 value */ + tmpreg = htim->Instance->CCR2; + + break; + } + + case TIM_CHANNEL_3: + { + /* Check the parameters */ + assert_param(IS_TIM_CC3_INSTANCE(htim->Instance)); + + /* Return the capture 3 value */ + tmpreg = htim->Instance->CCR3; + + break; + } + + case TIM_CHANNEL_4: + { + /* Check the parameters */ + assert_param(IS_TIM_CC4_INSTANCE(htim->Instance)); + + /* Return the capture 4 value */ + tmpreg = htim->Instance->CCR4; + + break; + } + + default: + break; + } + + __HAL_UNLOCK(htim); + return tmpreg; +} + +/** + * @} + */ + +/** @defgroup TIM_Group9 TIM Callbacks functions + * @brief TIM Callbacks functions + * +@verbatim + ============================================================================== + ##### TIM Callbacks functions ##### + ============================================================================== + [..] + This section provides TIM callback functions: + (+) Timer Period elapsed callback + (+) Timer Output Compare callback + (+) Timer Input capture callback + (+) Timer Trigger callback + (+) Timer Error callback + +@endverbatim + * @{ + */ + +/** + * @brief Period elapsed callback in non blocking mode + * @param htim : TIM handle + * @retval None + */ +__weak void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the __HAL_TIM_PeriodElapsedCallback could be implemented in the user file + */ + +} +/** + * @brief Output Compare callback in non blocking mode + * @param htim : TIM OC handle + * @retval None + */ +__weak void HAL_TIM_OC_DelayElapsedCallback(TIM_HandleTypeDef *htim) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the __HAL_TIM_OC_DelayElapsedCallback could be implemented in the user file + */ +} +/** + * @brief Input Capture callback in non blocking mode + * @param htim : TIM IC handle + * @retval None + */ +__weak void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef *htim) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the __HAL_TIM_IC_CaptureCallback could be implemented in the user file + */ +} + +/** + * @brief PWM Pulse finished callback in non blocking mode + * @param htim : TIM handle + * @retval None + */ +__weak void HAL_TIM_PWM_PulseFinishedCallback(TIM_HandleTypeDef *htim) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the __HAL_TIM_PWM_PulseFinishedCallback could be implemented in the user file + */ +} + +/** + * @brief Hall Trigger detection callback in non blocking mode + * @param htim : TIM handle + * @retval None + */ +__weak void HAL_TIM_TriggerCallback(TIM_HandleTypeDef *htim) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_TIM_TriggerCallback could be implemented in the user file + */ +} + +/** + * @brief Timer error callback in non blocking mode + * @param htim : TIM handle + * @retval None + */ +__weak void HAL_TIM_ErrorCallback(TIM_HandleTypeDef *htim) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_TIM_ErrorCallback could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup TIM_Group10 Peripheral State functions + * @brief Peripheral State functions + * +@verbatim + ============================================================================== + ##### Peripheral State functions ##### + ============================================================================== + [..] + This subsection permit to get in run-time the status of the peripheral + and the data flow. + +@endverbatim + * @{ + */ + +/** + * @brief Return the TIM Base state + * @param htim: TIM Base handle + * @retval HAL state + */ +HAL_TIM_StateTypeDef HAL_TIM_Base_GetState(TIM_HandleTypeDef *htim) +{ + return htim->State; +} + +/** + * @brief Return the TIM OC state + * @param htim: TIM Ouput Compare handle + * @retval HAL state + */ +HAL_TIM_StateTypeDef HAL_TIM_OC_GetState(TIM_HandleTypeDef *htim) +{ + return htim->State; +} + +/** + * @brief Return the TIM PWM state + * @param htim: TIM handle + * @retval HAL state + */ +HAL_TIM_StateTypeDef HAL_TIM_PWM_GetState(TIM_HandleTypeDef *htim) +{ + return htim->State; +} + +/** + * @brief Return the TIM Input Capture state + * @param htim: TIM IC handle + * @retval HAL state + */ +HAL_TIM_StateTypeDef HAL_TIM_IC_GetState(TIM_HandleTypeDef *htim) +{ + return htim->State; +} + +/** + * @brief Return the TIM One Pulse Mode state + * @param htim: TIM OPM handle + * @retval HAL state + */ +HAL_TIM_StateTypeDef HAL_TIM_OnePulse_GetState(TIM_HandleTypeDef *htim) +{ + return htim->State; +} + +/** + * @brief Return the TIM Encoder Mode state + * @param htim: TIM Encoder handle + * @retval HAL state + */ +HAL_TIM_StateTypeDef HAL_TIM_Encoder_GetState(TIM_HandleTypeDef *htim) +{ + return htim->State; +} + +/** + * @} + */ + +/** + * @brief TIM DMA error callback + * @param hdma : pointer to DMA handle. + * @retval None + */ +void HAL_TIM_DMAError(DMA_HandleTypeDef *hdma) +{ + TIM_HandleTypeDef* htim = ( TIM_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + + htim->State= HAL_TIM_STATE_READY; + + HAL_TIM_ErrorCallback(htim); +} + +/** + * @brief TIM DMA Delay Pulse complete callback. + * @param hdma : pointer to DMA handle. + * @retval None + */ +void HAL_TIM_DMADelayPulseCplt(DMA_HandleTypeDef *hdma) +{ + TIM_HandleTypeDef* htim = ( TIM_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + + htim->State= HAL_TIM_STATE_READY; + + if (hdma == htim->hdma[TIM_DMA_ID_CC1]) + { + htim->Channel = HAL_TIM_ACTIVE_CHANNEL_1; + } + else if (hdma == htim->hdma[TIM_DMA_ID_CC2]) + { + htim->Channel = HAL_TIM_ACTIVE_CHANNEL_2; + } + else if (hdma == htim->hdma[TIM_DMA_ID_CC3]) + { + htim->Channel = HAL_TIM_ACTIVE_CHANNEL_3; + } + else if (hdma == htim->hdma[TIM_DMA_ID_CC4]) + { + htim->Channel = HAL_TIM_ACTIVE_CHANNEL_4; + } + + HAL_TIM_PWM_PulseFinishedCallback(htim); + + htim->Channel = HAL_TIM_ACTIVE_CHANNEL_CLEARED; +} +/** + * @brief TIM DMA Capture complete callback. + * @param hdma : pointer to DMA handle. + * @retval None + */ +void HAL_TIM_DMACaptureCplt(DMA_HandleTypeDef *hdma) +{ + TIM_HandleTypeDef* htim = ( TIM_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + + htim->State= HAL_TIM_STATE_READY; + + if (hdma == htim->hdma[TIM_DMA_ID_CC1]) + { + htim->Channel = HAL_TIM_ACTIVE_CHANNEL_1; + } + else if (hdma == htim->hdma[TIM_DMA_ID_CC2]) + { + htim->Channel = HAL_TIM_ACTIVE_CHANNEL_2; + } + else if (hdma == htim->hdma[TIM_DMA_ID_CC3]) + { + htim->Channel = HAL_TIM_ACTIVE_CHANNEL_3; + } + else if (hdma == htim->hdma[TIM_DMA_ID_CC4]) + { + htim->Channel = HAL_TIM_ACTIVE_CHANNEL_4; + } + + HAL_TIM_IC_CaptureCallback(htim); + + htim->Channel = HAL_TIM_ACTIVE_CHANNEL_CLEARED; +} + +/** + * @brief TIM DMA Period Elapse complete callback. + * @param hdma : pointer to DMA handle. + * @retval None + */ +static void TIM_DMAPeriodElapsedCplt(DMA_HandleTypeDef *hdma) +{ + TIM_HandleTypeDef* htim = ( TIM_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + + htim->State= HAL_TIM_STATE_READY; + + HAL_TIM_PeriodElapsedCallback(htim); +} + +/** + * @brief TIM DMA Trigger callback. + * @param hdma : pointer to DMA handle. + * @retval None + */ +static void TIM_DMATriggerCplt(DMA_HandleTypeDef *hdma) +{ + TIM_HandleTypeDef* htim = ( TIM_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + + htim->State= HAL_TIM_STATE_READY; + + HAL_TIM_TriggerCallback(htim); +} + +/** + * @brief Time Base configuration + * @param TIMx: TIM periheral + * @param Structure: TIM Base configuration structure + * @retval None + */ +void TIM_Base_SetConfig(TIM_TypeDef *TIMx, TIM_Base_InitTypeDef *Structure) +{ + uint32_t tmpcr1 = 0; + tmpcr1 = TIMx->CR1; + + /* Set TIM Time Base Unit parameters ---------------------------------------*/ + if (IS_TIM_COUNTER_MODE_SELECT_INSTANCE(TIMx)) + { + /* Select the Counter Mode */ + tmpcr1 &= (uint16_t)(~(TIM_CR1_DIR | TIM_CR1_CMS)); + tmpcr1 |= Structure->CounterMode; + } + + if(IS_TIM_CLOCK_DIVISION_INSTANCE(TIMx)) + { + /* Set the clock division */ + tmpcr1 &= (uint16_t)(~TIM_CR1_CKD); + tmpcr1 |= (uint32_t)Structure->ClockDivision; + } + + TIMx->CR1 = tmpcr1; + + /* Set the Autoreload value */ + TIMx->ARR = (uint32_t)Structure->Period ; + + /* Set the Prescaler value */ + TIMx->PSC = (uint32_t)Structure->Prescaler; + + if (IS_TIM_REPETITION_COUNTER_INSTANCE(TIMx)) + { + /* Set the Repetition Counter value */ + TIMx->RCR = Structure->RepetitionCounter; + } + + /* Generate an update event to reload the Prescaler + and the repetition counter(only for TIM1 and TIM8) value immediatly */ + TIMx->EGR = TIM_EGR_UG; +} + +/** + * @brief Time Ouput Compare 1 configuration + * @param TIMx to select the TIM peripheral + * @param OC_Config: The ouput configuration structure + * @retval None + */ +static void TIM_OC1_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config) +{ + uint32_t tmpccmrx = 0; + uint32_t tmpccer = 0; + uint32_t tmpcr2 = 0; + + /* Disable the Channel 1: Reset the CC1E Bit */ + TIMx->CCER &= (uint16_t)(~TIM_CCER_CC1E); + + /* Get the TIMx CCER register value */ + tmpccer = TIMx->CCER; + /* Get the TIMx CR2 register value */ + tmpcr2 = TIMx->CR2; + + /* Get the TIMx CCMR1 register value */ + tmpccmrx = TIMx->CCMR1; + + /* Reset the Output Compare Mode Bits */ + tmpccmrx &= (uint16_t)(~TIM_CCMR1_OC1M); + tmpccmrx &= (uint16_t)(~TIM_CCMR1_CC1S); + /* Select the Output Compare Mode */ + tmpccmrx |= OC_Config->OCMode; + + /* Reset the Output Polarity level */ + tmpccer &= (uint16_t)(~TIM_CCER_CC1P); + /* Set the Output Compare Polarity */ + tmpccer |= OC_Config->OCPolarity; + + if(IS_TIM_CCXN_INSTANCE(TIMx, TIM_CHANNEL_1)) + { + /* Check parameters */ + assert_param(IS_TIM_OCN_POLARITY(OC_Config->OCNPolarity)); + + /* Reset the Output N Polarity level */ + tmpccer &= (uint16_t)(~TIM_CCER_CC1NP); + /* Set the Output N Polarity */ + tmpccer |= OC_Config->OCNPolarity; + /* Reset the Output N State */ + tmpccer &= (uint16_t)(~TIM_CCER_CC1NE); + } + + if(IS_TIM_BREAK_INSTANCE(TIMx)) + { + /* Check parameters */ + assert_param(IS_TIM_OCNIDLE_STATE(OC_Config->OCNIdleState)); + assert_param(IS_TIM_OCIDLE_STATE(OC_Config->OCIdleState)); + + /* Reset the Output Compare and Output Compare N IDLE State */ + tmpcr2 &= (uint16_t)(~TIM_CR2_OIS1); + tmpcr2 &= (uint16_t)(~TIM_CR2_OIS1N); + /* Set the Output Idle state */ + tmpcr2 |= OC_Config->OCIdleState; + /* Set the Output N Idle state */ + tmpcr2 |= OC_Config->OCNIdleState; + } + /* Write to TIMx CR2 */ + TIMx->CR2 = tmpcr2; + + /* Write to TIMx CCMR1 */ + TIMx->CCMR1 = tmpccmrx; + + /* Set the Capture Compare Register value */ + TIMx->CCR1 = OC_Config->Pulse; + + /* Write to TIMx CCER */ + TIMx->CCER = tmpccer; +} + +/** + * @brief Time Ouput Compare 2 configuration + * @param TIMx to select the TIM peripheral + * @param OC_Config: The ouput configuration structure + * @retval None + */ +void TIM_OC2_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config) +{ + uint32_t tmpccmrx = 0; + uint32_t tmpccer = 0; + uint32_t tmpcr2 = 0; + + /* Disable the Channel 2: Reset the CC2E Bit */ + TIMx->CCER &= (uint16_t)(~TIM_CCER_CC2E); + + /* Get the TIMx CCER register value */ + tmpccer = TIMx->CCER; + /* Get the TIMx CR2 register value */ + tmpcr2 = TIMx->CR2; + + /* Get the TIMx CCMR1 register value */ + tmpccmrx = TIMx->CCMR1; + + /* Reset the Output Compare mode and Capture/Compare selection Bits */ + tmpccmrx &= (uint16_t)(~TIM_CCMR1_OC2M); + tmpccmrx &= (uint16_t)(~TIM_CCMR1_CC2S); + + /* Select the Output Compare Mode */ + tmpccmrx |= (OC_Config->OCMode << 8); + + /* Reset the Output Polarity level */ + tmpccer &= (uint16_t)(~TIM_CCER_CC2P); + /* Set the Output Compare Polarity */ + tmpccer |= (OC_Config->OCPolarity << 4); + + if(IS_TIM_CCXN_INSTANCE(TIMx, TIM_CHANNEL_2)) + { + assert_param(IS_TIM_OCN_POLARITY(OC_Config->OCNPolarity)); + assert_param(IS_TIM_OCNIDLE_STATE(OC_Config->OCNIdleState)); + assert_param(IS_TIM_OCIDLE_STATE(OC_Config->OCIdleState)); + + /* Reset the Output N Polarity level */ + tmpccer &= (uint16_t)(~TIM_CCER_CC2NP); + /* Set the Output N Polarity */ + tmpccer |= (OC_Config->OCNPolarity << 4); + /* Reset the Output N State */ + tmpccer &= (uint16_t)(~TIM_CCER_CC2NE); + + } + + if(IS_TIM_BREAK_INSTANCE(TIMx)) + { + /* Check parameters */ + assert_param(IS_TIM_OCNIDLE_STATE(OC_Config->OCNIdleState)); + assert_param(IS_TIM_OCIDLE_STATE(OC_Config->OCIdleState)); + + /* Reset the Output Compare and Output Compare N IDLE State */ + tmpcr2 &= (uint16_t)(~TIM_CR2_OIS2); + tmpcr2 &= (uint16_t)(~TIM_CR2_OIS2N); + /* Set the Output Idle state */ + tmpcr2 |= (OC_Config->OCIdleState << 2); + /* Set the Output N Idle state */ + tmpcr2 |= (OC_Config->OCNIdleState << 2); + } + + /* Write to TIMx CR2 */ + TIMx->CR2 = tmpcr2; + + /* Write to TIMx CCMR1 */ + TIMx->CCMR1 = tmpccmrx; + + /* Set the Capture Compare Register value */ + TIMx->CCR2 = OC_Config->Pulse; + + /* Write to TIMx CCER */ + TIMx->CCER = tmpccer; +} + +/** + * @brief Time Ouput Compare 3 configuration + * @param TIMx to select the TIM peripheral + * @param OC_Config: The ouput configuration structure + * @retval None + */ +static void TIM_OC3_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config) +{ + uint32_t tmpccmrx = 0; + uint32_t tmpccer = 0; + uint32_t tmpcr2 = 0; + + /* Disable the Channel 3: Reset the CC2E Bit */ + TIMx->CCER &= (uint16_t)(~TIM_CCER_CC3E); + + /* Get the TIMx CCER register value */ + tmpccer = TIMx->CCER; + /* Get the TIMx CR2 register value */ + tmpcr2 = TIMx->CR2; + + /* Get the TIMx CCMR2 register value */ + tmpccmrx = TIMx->CCMR2; + + /* Reset the Output Compare mode and Capture/Compare selection Bits */ + tmpccmrx &= (uint16_t)(~TIM_CCMR2_OC3M); + tmpccmrx &= (uint16_t)(~TIM_CCMR2_CC3S); + /* Select the Output Compare Mode */ + tmpccmrx |= OC_Config->OCMode; + + /* Reset the Output Polarity level */ + tmpccer &= (uint16_t)(~TIM_CCER_CC3P); + /* Set the Output Compare Polarity */ + tmpccer |= (OC_Config->OCPolarity << 8); + + if(IS_TIM_CCXN_INSTANCE(TIMx, TIM_CHANNEL_3)) + { + assert_param(IS_TIM_OCN_POLARITY(OC_Config->OCNPolarity)); + assert_param(IS_TIM_OCNIDLE_STATE(OC_Config->OCNIdleState)); + assert_param(IS_TIM_OCIDLE_STATE(OC_Config->OCIdleState)); + + /* Reset the Output N Polarity level */ + tmpccer &= (uint16_t)(~TIM_CCER_CC3NP); + /* Set the Output N Polarity */ + tmpccer |= (OC_Config->OCNPolarity << 8); + /* Reset the Output N State */ + tmpccer &= (uint16_t)(~TIM_CCER_CC3NE); + } + + if(IS_TIM_BREAK_INSTANCE(TIMx)) + { + /* Check parameters */ + assert_param(IS_TIM_OCNIDLE_STATE(OC_Config->OCNIdleState)); + assert_param(IS_TIM_OCIDLE_STATE(OC_Config->OCIdleState)); + + /* Reset the Output Compare and Output Compare N IDLE State */ + tmpcr2 &= (uint16_t)(~TIM_CR2_OIS3); + tmpcr2 &= (uint16_t)(~TIM_CR2_OIS3N); + /* Set the Output Idle state */ + tmpcr2 |= (OC_Config->OCIdleState << 4); + /* Set the Output N Idle state */ + tmpcr2 |= (OC_Config->OCNIdleState << 4); + } + + /* Write to TIMx CR2 */ + TIMx->CR2 = tmpcr2; + + /* Write to TIMx CCMR2 */ + TIMx->CCMR2 = tmpccmrx; + + /* Set the Capture Compare Register value */ + TIMx->CCR3 = OC_Config->Pulse; + + /* Write to TIMx CCER */ + TIMx->CCER = tmpccer; +} + +/** + * @brief Time Ouput Compare 4 configuration + * @param TIMx to select the TIM peripheral + * @param OC_Config: The ouput configuration structure + * @retval None + */ +static void TIM_OC4_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config) +{ + uint32_t tmpccmrx = 0; + uint32_t tmpccer = 0; + uint32_t tmpcr2 = 0; + + /* Disable the Channel 4: Reset the CC4E Bit */ + TIMx->CCER &= (uint16_t)(~TIM_CCER_CC4E); + + /* Get the TIMx CCER register value */ + tmpccer = TIMx->CCER; + /* Get the TIMx CR2 register value */ + tmpcr2 = TIMx->CR2; + + /* Get the TIMx CCMR2 register value */ + tmpccmrx = TIMx->CCMR2; + + /* Reset the Output Compare mode and Capture/Compare selection Bits */ + tmpccmrx &= (uint16_t)(~TIM_CCMR2_OC4M); + tmpccmrx &= (uint16_t)(~TIM_CCMR2_CC4S); + + /* Select the Output Compare Mode */ + tmpccmrx |= (OC_Config->OCMode << 8); + + /* Reset the Output Polarity level */ + tmpccer &= (uint16_t)(~TIM_CCER_CC4P); + /* Set the Output Compare Polarity */ + tmpccer |= (OC_Config->OCPolarity << 12); + + if(IS_TIM_BREAK_INSTANCE(TIMx)) + { + assert_param(IS_TIM_OCIDLE_STATE(OC_Config->OCIdleState)); + + /* Reset the Output Compare IDLE State */ + tmpcr2 &= (uint16_t)(~TIM_CR2_OIS4); + /* Set the Output Idle state */ + tmpcr2 |= (OC_Config->OCIdleState << 6); + } + + /* Write to TIMx CR2 */ + TIMx->CR2 = tmpcr2; + + /* Write to TIMx CCMR2 */ + TIMx->CCMR2 = tmpccmrx; + + /* Set the Capture Compare Register value */ + TIMx->CCR4 = OC_Config->Pulse; + + /* Write to TIMx CCER */ + TIMx->CCER = tmpccer; +} + +/** + * @brief Configure the TI1 as Input. + * @param TIMx to select the TIM peripheral. + * @param TIM_ICPolarity : The Input Polarity. + * This parameter can be one of the following values: + * @arg TIM_ICPolarity_Rising + * @arg TIM_ICPolarity_Falling + * @arg TIM_ICPolarity_BothEdge + * @param TIM_ICSelection: specifies the input to be used. + * This parameter can be one of the following values: + * @arg TIM_ICSelection_DirectTI: TIM Input 1 is selected to be connected to IC1. + * @arg TIM_ICSelection_IndirectTI: TIM Input 1 is selected to be connected to IC2. + * @arg TIM_ICSelection_TRC: TIM Input 1 is selected to be connected to TRC. + * @param TIM_ICFilter: Specifies the Input Capture Filter. + * This parameter must be a value between 0x00 and 0x0F. + * @retval None + */ +void TIM_TI1_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICSelection, + uint32_t TIM_ICFilter) +{ + uint32_t tmpccmr1 = 0; + uint32_t tmpccer = 0; + + /* Disable the Channel 1: Reset the CC1E Bit */ + TIMx->CCER &= (uint16_t)(~TIM_CCER_CC1E); + tmpccmr1 = TIMx->CCMR1; + tmpccer = TIMx->CCER; + + /* Select the Input */ + if(IS_TIM_CC2_INSTANCE(TIMx) != RESET) + { + tmpccmr1 &= (uint16_t)(~TIM_CCMR1_CC1S); + tmpccmr1 |= TIM_ICSelection; + } + else + { + tmpccmr1 |= TIM_CCMR1_CC1S_0; + } + + /* Set the filter */ + tmpccmr1 &= (uint16_t)(~TIM_CCMR1_IC1F); + tmpccmr1 |= (TIM_ICFilter << 4); + + /* Select the Polarity and set the CC1E Bit */ + tmpccer &= (uint16_t)(~(TIM_CCER_CC1P | TIM_CCER_CC1NP)); + tmpccer |= TIM_ICPolarity; + + /* Write to TIMx CCMR1 and CCER registers */ + TIMx->CCMR1 = tmpccmr1; + TIMx->CCER = tmpccer; +} + +/** + * @brief Configure the Polarity and Filter for TI1. + * @param TIMx to select the TIM peripheral. + * @param TIM_ICPolarity : The Input Polarity. + * This parameter can be one of the following values: + * @arg TIM_ICPolarity_Rising + * @arg TIM_ICPolarity_Falling + * @arg TIM_ICPolarity_BothEdge + * @param TIM_ICFilter: Specifies the Input Capture Filter. + * This parameter must be a value between 0x00 and 0x0F. + * @retval None + */ +static void TIM_TI1_ConfigInputStage(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICFilter) +{ + uint32_t tmpccmr1 = 0; + uint32_t tmpccer = 0; + + /* Disable the Channel 1: Reset the CC1E Bit */ + tmpccer = TIMx->CCER; + TIMx->CCER &= (uint16_t)(~TIM_CCER_CC1E); + tmpccmr1 = TIMx->CCMR1; + + /* Set the filter */ + tmpccmr1 &= (uint16_t)(~TIM_CCMR1_IC1F); + tmpccmr1 |= (TIM_ICFilter << 4); + + /* Select the Polarity and set the CC1E Bit */ + tmpccer &= (uint16_t)(~(TIM_CCER_CC1P | TIM_CCER_CC1NP)); + tmpccer |= TIM_ICPolarity; + + /* Write to TIMx CCMR1 and CCER registers */ + TIMx->CCMR1 = tmpccmr1; + TIMx->CCER = tmpccer; +} + +/** + * @brief Configure the TI2 as Input. + * @param TIMx to select the TIM peripheral + * @param TIM_ICPolarity : The Input Polarity. + * This parameter can be one of the following values: + * @arg TIM_ICPolarity_Rising + * @arg TIM_ICPolarity_Falling + * @arg TIM_ICPolarity_BothEdge + * @param TIM_ICSelection: specifies the input to be used. + * This parameter can be one of the following values: + * @arg TIM_ICSelection_DirectTI: TIM Input 2 is selected to be connected to IC2. + * @arg TIM_ICSelection_IndirectTI: TIM Input 2 is selected to be connected to IC1. + * @arg TIM_ICSelection_TRC: TIM Input 2 is selected to be connected to TRC. + * @param TIM_ICFilter: Specifies the Input Capture Filter. + * This parameter must be a value between 0x00 and 0x0F. + * @retval None + */ +static void TIM_TI2_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICSelection, + uint32_t TIM_ICFilter) +{ + uint32_t tmpccmr1 = 0; + uint32_t tmpccer = 0; + + /* Disable the Channel 2: Reset the CC2E Bit */ + TIMx->CCER &= (uint16_t)(~TIM_CCER_CC2E); + tmpccmr1 = TIMx->CCMR1; + tmpccer = TIMx->CCER; + + /* Select the Input */ + tmpccmr1 &= (uint16_t)(~TIM_CCMR1_CC2S); + tmpccmr1 |= (TIM_ICSelection << 8); + + /* Set the filter */ + tmpccmr1 &= (uint16_t)(~TIM_CCMR1_IC2F); + tmpccmr1 |= (TIM_ICFilter << 12); + + /* Select the Polarity and set the CC2E Bit */ + tmpccer &= (uint16_t)(~(TIM_CCER_CC2P | TIM_CCER_CC2NP)); + tmpccer |= (TIM_ICPolarity << 4); + + /* Write to TIMx CCMR1 and CCER registers */ + TIMx->CCMR1 = tmpccmr1 ; + TIMx->CCER = tmpccer; +} + +/** + * @brief Configure the Polarity and Filter for TI2. + * @param TIMx to select the TIM peripheral. + * @param TIM_ICPolarity : The Input Polarity. + * This parameter can be one of the following values: + * @arg TIM_ICPolarity_Rising + * @arg TIM_ICPolarity_Falling + * @arg TIM_ICPolarity_BothEdge + * @param TIM_ICFilter: Specifies the Input Capture Filter. + * This parameter must be a value between 0x00 and 0x0F. + * @retval None + */ +static void TIM_TI2_ConfigInputStage(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICFilter) +{ + uint32_t tmpccmr1 = 0; + uint32_t tmpccer = 0; + + /* Disable the Channel 2: Reset the CC2E Bit */ + TIMx->CCER &= (uint16_t)(~TIM_CCER_CC2E); + tmpccmr1 = TIMx->CCMR1; + tmpccer = TIMx->CCER; + + /* Set the filter */ + tmpccmr1 &= (uint16_t)(~TIM_CCMR1_IC2F); + tmpccmr1 |= (TIM_ICFilter << 12); + + /* Select the Polarity and set the CC2E Bit */ + tmpccer &= (uint16_t)(~(TIM_CCER_CC2P | TIM_CCER_CC2NP)); + tmpccer |= (TIM_ICPolarity << 4); + + /* Write to TIMx CCMR1 and CCER registers */ + TIMx->CCMR1 = tmpccmr1 ; + TIMx->CCER = tmpccer; +} + +/** + * @brief Configure the TI3 as Input. + * @param TIMx to select the TIM peripheral + * @param TIM_ICPolarity : The Input Polarity. + * This parameter can be one of the following values: + * @arg TIM_ICPolarity_Rising + * @arg TIM_ICPolarity_Falling + * @arg TIM_ICPolarity_BothEdge + * @param TIM_ICSelection: specifies the input to be used. + * This parameter can be one of the following values: + * @arg TIM_ICSelection_DirectTI: TIM Input 3 is selected to be connected to IC3. + * @arg TIM_ICSelection_IndirectTI: TIM Input 3 is selected to be connected to IC4. + * @arg TIM_ICSelection_TRC: TIM Input 3 is selected to be connected to TRC. + * @param TIM_ICFilter: Specifies the Input Capture Filter. + * This parameter must be a value between 0x00 and 0x0F. + * @retval None + */ +static void TIM_TI3_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICSelection, + uint32_t TIM_ICFilter) +{ + uint32_t tmpccmr2 = 0; + uint32_t tmpccer = 0; + + /* Disable the Channel 3: Reset the CC3E Bit */ + TIMx->CCER &= (uint16_t)(~TIM_CCER_CC3E); + tmpccmr2 = TIMx->CCMR2; + tmpccer = TIMx->CCER; + + /* Select the Input */ + tmpccmr2 &= (uint16_t)(~TIM_CCMR2_CC3S); + tmpccmr2 |= TIM_ICSelection; + + /* Set the filter */ + tmpccmr2 &= (uint16_t)(~TIM_CCMR2_IC3F); + tmpccmr2 |= (TIM_ICFilter << 4); + + /* Select the Polarity and set the CC3E Bit */ + tmpccer &= (uint16_t)(~(TIM_CCER_CC3P | TIM_CCER_CC3NP)); + tmpccer |= (TIM_ICPolarity << 8); + + /* Write to TIMx CCMR2 and CCER registers */ + TIMx->CCMR2 = tmpccmr2; + TIMx->CCER = tmpccer; +} + +/** + * @brief Configure the TI4 as Input. + * @param TIMx to select the TIM peripheral + * @param TIM_ICPolarity : The Input Polarity. + * This parameter can be one of the following values: + * @arg TIM_ICPolarity_Rising + * @arg TIM_ICPolarity_Falling + * @arg TIM_ICPolarity_BothEdge + * @param TIM_ICSelection: specifies the input to be used. + * This parameter can be one of the following values: + * @arg TIM_ICSelection_DirectTI: TIM Input 4 is selected to be connected to IC4. + * @arg TIM_ICSelection_IndirectTI: TIM Input 4 is selected to be connected to IC3. + * @arg TIM_ICSelection_TRC: TIM Input 4 is selected to be connected to TRC. + * @param TIM_ICFilter: Specifies the Input Capture Filter. + * This parameter must be a value between 0x00 and 0x0F. + * @retval None + */ +static void TIM_TI4_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICSelection, + uint32_t TIM_ICFilter) +{ + uint32_t tmpccmr2 = 0; + uint32_t tmpccer = 0; + + /* Disable the Channel 4: Reset the CC4E Bit */ + TIMx->CCER &= (uint16_t)(~TIM_CCER_CC4E); + tmpccmr2 = TIMx->CCMR2; + tmpccer = TIMx->CCER; + + /* Select the Input */ + tmpccmr2 &= (uint16_t)(~TIM_CCMR2_CC4S); + tmpccmr2 |= (TIM_ICSelection << 8); + + /* Set the filter */ + tmpccmr2 &= (uint16_t)(~TIM_CCMR2_IC4F); + tmpccmr2 |= (TIM_ICFilter << 12); + + /* Select the Polarity and set the CC4E Bit */ + tmpccer &= (uint16_t)(~(TIM_CCER_CC4P | TIM_CCER_CC4NP)); + tmpccer |= (TIM_ICPolarity << 12); + + /* Write to TIMx CCMR2 and CCER registers */ + TIMx->CCMR2 = tmpccmr2; + TIMx->CCER = tmpccer ; +} + +/** + * @brief Selects the Input Trigger source + * @param TIMx to select the TIM peripheral + * @param InputTriggerSource: The Input Trigger source. + * This parameter can be one of the following values: + * @arg TIM_TS_ITR0: Internal Trigger 0 + * @arg TIM_TS_ITR1: Internal Trigger 1 + * @arg TIM_TS_ITR2: Internal Trigger 2 + * @arg TIM_TS_ITR3: Internal Trigger 3 + * @arg TIM_TS_TI1F_ED: TI1 Edge Detector + * @arg TIM_TS_TI1FP1: Filtered Timer Input 1 + * @arg TIM_TS_TI2FP2: Filtered Timer Input 2 + * @arg TIM_TS_ETRF: External Trigger input + * @retval None + */ +static void TIM_ITRx_SetConfig(TIM_TypeDef *TIMx, uint16_t InputTriggerSource) +{ + uint32_t tmpsmcr = 0; + + /* Get the TIMx SMCR register value */ + tmpsmcr = TIMx->SMCR; + /* Reset the TS Bits */ + tmpsmcr &= (uint16_t)(~TIM_SMCR_TS); + /* Set the Input Trigger source and the slave mode*/ + tmpsmcr |= InputTriggerSource | TIM_SLAVEMODE_EXTERNAL1; + /* Write to TIMx SMCR */ + TIMx->SMCR = tmpsmcr; +} +/** + * @brief Configures the TIMx External Trigger (ETR). + * @param TIMx to select the TIM peripheral + * @param TIM_ExtTRGPrescaler: The external Trigger Prescaler. + * This parameter can be one of the following values: + * @arg TIM_ExtTRGPSC_DIV1: ETRP Prescaler OFF. + * @arg TIM_ExtTRGPSC_DIV2: ETRP frequency divided by 2. + * @arg TIM_ExtTRGPSC_DIV4: ETRP frequency divided by 4. + * @arg TIM_ExtTRGPSC_DIV8: ETRP frequency divided by 8. + * @param TIM_ExtTRGPolarity: The external Trigger Polarity. + * This parameter can be one of the following values: + * @arg TIM_ExtTRGPolarity_Inverted: active low or falling edge active. + * @arg TIM_ExtTRGPolarity_NonInverted: active high or rising edge active. + * @param ExtTRGFilter: External Trigger Filter. + * This parameter must be a value between 0x00 and 0x0F + * @retval None + */ +static void TIM_ETR_SetConfig(TIM_TypeDef* TIMx, uint32_t TIM_ExtTRGPrescaler, + uint32_t TIM_ExtTRGPolarity, uint32_t ExtTRGFilter) +{ + uint32_t tmpsmcr = 0; + + tmpsmcr = TIMx->SMCR; + + /* Reset the ETR Bits */ + tmpsmcr &= (uint32_t)(~(TIM_SMCR_ETF | TIM_SMCR_ETPS | TIM_SMCR_ECE | TIM_SMCR_ETP)); + + /* Set the Prescaler, the Filter value and the Polarity */ + tmpsmcr |= (uint32_t)(TIM_ExtTRGPrescaler | (TIM_ExtTRGPolarity | (ExtTRGFilter << 8))); + + /* Write to TIMx SMCR */ + TIMx->SMCR = tmpsmcr; +} + +/** + * @brief Enables or disables the TIM Capture Compare Channel x. + * @param TIMx to select the TIM peripheral + * @param Channel: specifies the TIM Channel + * This parameter can be one of the following values: + * @arg TIM_Channel_1: TIM Channel 1 + * @arg TIM_Channel_2: TIM Channel 2 + * @arg TIM_Channel_3: TIM Channel 3 + * @arg TIM_Channel_4: TIM Channel 4 + * @param ChannelState: specifies the TIM Channel CCxE bit new state. + * This parameter can be: TIM_CCx_ENABLE or TIM_CCx_Disable. + * @retval None + */ +void TIM_CCxChannelCmd(TIM_TypeDef* TIMx, uint32_t Channel, uint32_t ChannelState) +{ + uint32_t tmp = 0; + + /* Check the parameters */ + assert_param(IS_TIM_CC1_INSTANCE(TIMx)); + assert_param(IS_TIM_CHANNELS(Channel)); + + tmp = (uint16_t)(TIM_CCER_CC1E << Channel); + + /* Reset the CCxE Bit */ + TIMx->CCER &= ~tmp; + + /* Set or reset the CCxE Bit */ + TIMx->CCER |= (uint32_t)(ChannelState << Channel); +} + + +/** + * @} + */ + +#endif /* HAL_TIM_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_tim.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_tim.h new file mode 100644 index 0000000000..0cf1877943 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_tim.h @@ -0,0 +1,1519 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_tim.h + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief Header file of TIM HAL module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32F0xx_HAL_TIM_H +#define __STM32F0xx_HAL_TIM_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal_def.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @addtogroup TIM + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ + +/** + * @brief TIM Time base Configuration Structure definition + */ +typedef struct +{ + uint32_t Prescaler; /*!< Specifies the prescaler value used to divide the TIM clock. + This parameter can be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF */ + + uint32_t CounterMode; /*!< Specifies the counter mode. + This parameter can be a value of @ref TIM_Counter_Mode */ + + uint32_t Period; /*!< Specifies the period value to be loaded into the active + Auto-Reload Register at the next update event. + This parameter can be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF. */ + + uint32_t ClockDivision; /*!< Specifies the clock division. + This parameter can be a value of @ref TIM_ClockDivision */ + + uint32_t RepetitionCounter; /*!< Specifies the repetition counter value. Each time the RCR downcounter + reaches zero, an update event is generated and counting restarts + from the RCR value (N). + This means in PWM mode that (N+1) corresponds to: + - the number of PWM periods in edge-aligned mode + - the number of half PWM period in center-aligned mode + This parameter must be a number between Min_Data = 0x00 and Max_Data = 0xFF. + @note This parameter is valid only for TIM1 and TIM8. */ +} TIM_Base_InitTypeDef; + +/** + * @brief TIM Output Compare Configuration Structure definition + */ +typedef struct +{ + uint32_t OCMode; /*!< Specifies the TIM mode. + This parameter can be a value of @ref TIM_Output_Compare_and_PWM_modes */ + + uint32_t Pulse; /*!< Specifies the pulse value to be loaded into the Capture Compare Register. + This parameter can be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF */ + + uint32_t OCPolarity; /*!< Specifies the output polarity. + This parameter can be a value of @ref TIM_Output_Compare_Polarity */ + + uint32_t OCNPolarity; /*!< Specifies the complementary output polarity. + This parameter can be a value of @ref TIM_Output_Compare_N_Polarity + @note This parameter is valid only for TIM1 and TIM8. */ + + uint32_t OCFastMode; /*!< Specifies the Fast mode state. + This parameter can be a value of @ref TIM_Output_Fast_State + @note This parameter is valid only in PWM1 and PWM2 mode. */ + + + uint32_t OCIdleState; /*!< Specifies the TIM Output Compare pin state during Idle state. + This parameter can be a value of @ref TIM_Output_Compare_Idle_State + @note This parameter is valid only for TIM1 and TIM8. */ + + uint32_t OCNIdleState; /*!< Specifies the TIM Output Compare pin state during Idle state. + This parameter can be a value of @ref TIM_Output_Compare_N_Idle_State + @note This parameter is valid only for TIM1 and TIM8. */ +} TIM_OC_InitTypeDef; + +/** + * @brief TIM One Pulse Mode Configuration Structure definition + */ +typedef struct +{ + uint32_t OCMode; /*!< Specifies the TIM mode. + This parameter can be a value of @ref TIM_Output_Compare_and_PWM_modes */ + + uint32_t Pulse; /*!< Specifies the pulse value to be loaded into the Capture Compare Register. + This parameter can be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF */ + + uint32_t OCPolarity; /*!< Specifies the output polarity. + This parameter can be a value of @ref TIM_Output_Compare_Polarity */ + + uint32_t OCNPolarity; /*!< Specifies the complementary output polarity. + This parameter can be a value of @ref TIM_Output_Compare_N_Polarity + @note This parameter is valid only for TIM1 and TIM8. */ + + uint32_t OCIdleState; /*!< Specifies the TIM Output Compare pin state during Idle state. + This parameter can be a value of @ref TIM_Output_Compare_Idle_State + @note This parameter is valid only for TIM1 and TIM8. */ + + uint32_t OCNIdleState; /*!< Specifies the TIM Output Compare pin state during Idle state. + This parameter can be a value of @ref TIM_Output_Compare_N_Idle_State + @note This parameter is valid only for TIM1 and TIM8. */ + + uint32_t ICPolarity; /*!< Specifies the active edge of the input signal. + This parameter can be a value of @ref TIM_Input_Capture_Polarity */ + + uint32_t ICSelection; /*!< Specifies the input. + This parameter can be a value of @ref TIM_Input_Capture_Selection */ + + uint32_t ICFilter; /*!< Specifies the input capture filter. + This parameter can be a number between Min_Data = 0x0 and Max_Data = 0xF */ +} TIM_OnePulse_InitTypeDef; + + +/** + * @brief TIM Input Capture Configuration Structure definition + */ +typedef struct +{ + uint32_t ICPolarity; /*!< Specifies the active edge of the input signal. + This parameter can be a value of @ref TIM_Input_Capture_Polarity */ + + uint32_t ICSelection; /*!< Specifies the input. + This parameter can be a value of @ref TIM_Input_Capture_Selection */ + + uint32_t ICPrescaler; /*!< Specifies the Input Capture Prescaler. + This parameter can be a value of @ref TIM_Input_Capture_Prescaler */ + + uint32_t ICFilter; /*!< Specifies the input capture filter. + This parameter can be a number between Min_Data = 0x0 and Max_Data = 0xF */ +} TIM_IC_InitTypeDef; + +/** + * @brief TIM Encoder Configuration Structure definition + */ +typedef struct +{ + uint32_t EncoderMode; /*!< Specifies the active edge of the input signal. + This parameter can be a value of @ref TIM_Encoder_Mode */ + + uint32_t IC1Polarity; /*!< Specifies the active edge of the input signal. + This parameter can be a value of @ref TIM_Input_Capture_Polarity */ + + uint32_t IC1Selection; /*!< Specifies the input. + This parameter can be a value of @ref TIM_Input_Capture_Selection */ + + uint32_t IC1Prescaler; /*!< Specifies the Input Capture Prescaler. + This parameter can be a value of @ref TIM_Input_Capture_Prescaler */ + + uint32_t IC1Filter; /*!< Specifies the input capture filter. + This parameter can be a number between Min_Data = 0x0 and Max_Data = 0xF */ + + uint32_t IC2Polarity; /*!< Specifies the active edge of the input signal. + This parameter can be a value of @ref TIM_Input_Capture_Polarity */ + + uint32_t IC2Selection; /*!< Specifies the input. + This parameter can be a value of @ref TIM_Input_Capture_Selection */ + + uint32_t IC2Prescaler; /*!< Specifies the Input Capture Prescaler. + This parameter can be a value of @ref TIM_Input_Capture_Prescaler */ + + uint32_t IC2Filter; /*!< Specifies the input capture filter. + This parameter can be a number between Min_Data = 0x0 and Max_Data = 0xF */ +} TIM_Encoder_InitTypeDef; + + +/** + * @brief Clock Configuration Handle Structure definition + */ +typedef struct +{ + uint32_t ClockSource; /*!< TIM clock sources + This parameter can be a value of @ref TIM_Clock_Source */ + uint32_t ClockPolarity; /*!< TIM clock polarity + This parameter can be a value of @ref TIM_Clock_Polarity */ + uint32_t ClockPrescaler; /*!< TIM clock prescaler + This parameter can be a value of @ref TIM_Clock_Prescaler */ + uint32_t ClockFilter; /*!< TIM clock filter + This parameter can be a value of @ref TIM_Clock_Filter */ +}TIM_ClockConfigTypeDef; + +/** + * @brief Clear Input Configuration Handle Structure definition + */ +typedef struct +{ + uint32_t ClearInputState; /*!< TIM clear Input state + This parameter can be ENABLE or DISABLE */ + uint32_t ClearInputSource; /*!< TIM clear Input sources + This parameter can be a value of @ref TIM_ClearInput_Source */ + uint32_t ClearInputPolarity; /*!< TIM Clear Input polarity + This parameter can be a value of @ref TIM_ClearInput_Polarity */ + uint32_t ClearInputPrescaler; /*!< TIM Clear Input prescaler + This parameter can be a value of @ref TIM_ClearInput_Prescaler */ + uint32_t ClearInputFilter; /*!< TIM Clear Input filter + This parameter can be a value of @ref TIM_ClearInput_Filter */ +}TIM_ClearInputConfigTypeDef; + +/** + * @brief TIM Slave configuration Structure definition + */ +typedef struct { + uint32_t SlaveMode; /*!< Slave mode selection + This parameter can be a value of @ref TIM_Slave_Mode */ + uint32_t InputTrigger; /*!< Input Trigger source + This parameter can be a value of @ref TIM_Trigger_Selection */ + uint32_t TriggerPolarity; /*!< Input Trigger polarity + This parameter can be a value of @ref TIM_Trigger_Polarity */ + uint32_t TriggerPrescaler; /*!< Input trigger prescaler + This parameter can be a value of @ref TIM_Trigger_Prescaler */ + uint32_t TriggerFilter; /*!< Input trigger filter + This parameter can be a value of @ref TIM_Trigger_Filter */ + +}TIM_SlaveConfigTypeDef; + +/** + * @brief HAL State structures definition + */ +typedef enum +{ + HAL_TIM_STATE_RESET = 0x00, /*!< Peripheral not yet initialized or disabled */ + HAL_TIM_STATE_READY = 0x01, /*!< Peripheral Initialized and ready for use */ + HAL_TIM_STATE_BUSY = 0x02, /*!< An internal process is ongoing */ + HAL_TIM_STATE_TIMEOUT = 0x03, /*!< Timeout state */ + HAL_TIM_STATE_ERROR = 0x04 /*!< Reception process is ongoing */ +}HAL_TIM_StateTypeDef; + +/** + * @brief HAL Active channel structures definition + */ +typedef enum +{ + HAL_TIM_ACTIVE_CHANNEL_1 = 0x01, /*!< The active channel is 1 */ + HAL_TIM_ACTIVE_CHANNEL_2 = 0x02, /*!< The active channel is 2 */ + HAL_TIM_ACTIVE_CHANNEL_3 = 0x04, /*!< The active channel is 3 */ + HAL_TIM_ACTIVE_CHANNEL_4 = 0x08, /*!< The active channel is 4 */ + HAL_TIM_ACTIVE_CHANNEL_CLEARED = 0x00 /*!< All active channels cleared */ +}HAL_TIM_ActiveChannel; + +/** + * @brief TIM Time Base Handle Structure definition + */ +typedef struct +{ + TIM_TypeDef *Instance; /*!< Register base address */ + TIM_Base_InitTypeDef Init; /*!< TIM Time Base required parameters */ + HAL_TIM_ActiveChannel Channel; /*!< Active channel */ + DMA_HandleTypeDef *hdma[7]; /*!< DMA Handlers array + This array is accessed by a @ref DMA_Handle_index */ + HAL_LockTypeDef Lock; /*!< Locking object */ + __IO HAL_TIM_StateTypeDef State; /*!< TIM operation state */ +}TIM_HandleTypeDef; + +/* Exported constants --------------------------------------------------------*/ +/** @defgroup TIM_Exported_Constants + * @{ + */ + +/** @defgroup TIM_Input_Channel_Polarity + * @{ + */ +#define TIM_INPUTCHANNELPOLARITY_RISING ((uint32_t)0x00000000) /*!< Polarity for TIx source */ +#define TIM_INPUTCHANNELPOLARITY_FALLING (TIM_CCER_CC1P) /*!< Polarity for TIx source */ +#define TIM_INPUTCHANNELPOLARITY_BOTHEDGE (TIM_CCER_CC1P | TIM_CCER_CC1NP) /*!< Polarity for TIx source */ +/** + * @} + */ + +/** @defgroup TIM_ETR_Polarity + * @{ + */ +#define TIM_ETRPOLARITY_INVERTED (TIM_SMCR_ETP) /*!< Polarity for ETR source */ +#define TIM_ETRPOLARITY_NONINVERTED ((uint32_t)0x0000) /*!< Polarity for ETR source */ +/** + * @} + */ + +/** @defgroup TIM_ETR_Prescaler + * @{ + */ +#define TIM_ETRPRESCALER_DIV1 ((uint32_t)0x0000) /*!< No prescaler is used */ +#define TIM_ETRPRESCALER_DIV2 (TIM_SMCR_ETPS_0) /*!< ETR input source is divided by 2 */ +#define TIM_ETRPRESCALER_DIV4 (TIM_SMCR_ETPS_1) /*!< ETR input source is divided by 4 */ +#define TIM_ETRPRESCALER_DIV8 (TIM_SMCR_ETPS) /*!< ETR input source is divided by 8 */ +/** + * @} + */ + +/** @defgroup TIM_Counter_Mode + * @{ + */ +#define TIM_COUNTERMODE_UP ((uint32_t)0x0000) +#define TIM_COUNTERMODE_DOWN TIM_CR1_DIR +#define TIM_COUNTERMODE_CENTERALIGNED1 TIM_CR1_CMS_0 +#define TIM_COUNTERMODE_CENTERALIGNED2 TIM_CR1_CMS_1 +#define TIM_COUNTERMODE_CENTERALIGNED3 TIM_CR1_CMS + +#define IS_TIM_COUNTER_MODE(MODE) (((MODE) == TIM_COUNTERMODE_UP) || \ + ((MODE) == TIM_COUNTERMODE_DOWN) || \ + ((MODE) == TIM_COUNTERMODE_CENTERALIGNED1) || \ + ((MODE) == TIM_COUNTERMODE_CENTERALIGNED2) || \ + ((MODE) == TIM_COUNTERMODE_CENTERALIGNED3)) +/** + * @} + */ + +/** @defgroup TIM_ClockDivision + * @{ + */ +#define TIM_CLOCKDIVISION_DIV1 ((uint32_t)0x0000) +#define TIM_CLOCKDIVISION_DIV2 (TIM_CR1_CKD_0) +#define TIM_CLOCKDIVISION_DIV4 (TIM_CR1_CKD_1) + +#define IS_TIM_CLOCKDIVISION_DIV(DIV) (((DIV) == TIM_CLOCKDIVISION_DIV1) || \ + ((DIV) == TIM_CLOCKDIVISION_DIV2) || \ + ((DIV) == TIM_CLOCKDIVISION_DIV4)) +/** + * @} + */ + +/** @defgroup TIM_Output_Compare_and_PWM_modes + * @{ + */ +#define TIM_OCMODE_TIMING ((uint32_t)0x0000) +#define TIM_OCMODE_ACTIVE (TIM_CCMR1_OC1M_0) +#define TIM_OCMODE_INACTIVE (TIM_CCMR1_OC1M_1) +#define TIM_OCMODE_TOGGLE (TIM_CCMR1_OC1M_0 | TIM_CCMR1_OC1M_1) +#define TIM_OCMODE_PWM1 (TIM_CCMR1_OC1M_1 | TIM_CCMR1_OC1M_2) +#define TIM_OCMODE_PWM2 (TIM_CCMR1_OC1M) +#define TIM_OCMODE_FORCED_ACTIVE (TIM_CCMR1_OC1M_0 | TIM_CCMR1_OC1M_2) +#define TIM_OCMODE_FORCED_INACTIVE (TIM_CCMR1_OC1M_2) + +#define IS_TIM_PWM_MODE(MODE) (((MODE) == TIM_OCMODE_PWM1) || \ + ((MODE) == TIM_OCMODE_PWM2)) + +#define IS_TIM_OC_MODE(MODE) (((MODE) == TIM_OCMODE_TIMING) || \ + ((MODE) == TIM_OCMODE_ACTIVE) || \ + ((MODE) == TIM_OCMODE_INACTIVE) || \ + ((MODE) == TIM_OCMODE_TOGGLE) || \ + ((MODE) == TIM_OCMODE_FORCED_ACTIVE) || \ + ((MODE) == TIM_OCMODE_FORCED_INACTIVE)) +/** + * @} + */ + +/** @defgroup TIM_Output_Compare_State + * @{ + */ +#define TIM_OUTPUTSTATE_DISABLE ((uint32_t)0x0000) +#define TIM_OUTPUTSTATE_ENABLE (TIM_CCER_CC1E) + +#define IS_TIM_OUTPUT_STATE(STATE) (((STATE) == TIM_OUTPUTSTATE_DISABLE) || \ + ((STATE) == TIM_OUTPUTSTATE_ENABLE)) +/** + * @} + */ + +/** @defgroup TIM_Output_Fast_State + * @{ + */ +#define TIM_OCFAST_DISABLE ((uint32_t)0x0000) +#define TIM_OCFAST_ENABLE (TIM_CCMR1_OC1FE) + +#define IS_TIM_FAST_STATE(STATE) (((STATE) == TIM_OCFAST_DISABLE) || \ + ((STATE) == TIM_OCFAST_ENABLE)) +/** + * @} + */ + +/** @defgroup TIM_Output_Compare_N_State + * @{ + */ +#define TIM_OUTPUTNSTATE_DISABLE ((uint32_t)0x0000) +#define TIM_OUTPUTNSTATE_ENABLE (TIM_CCER_CC1NE) + +#define IS_TIM_OUTPUTN_STATE(STATE) (((STATE) == TIM_OUTPUTNSTATE_DISABLE) || \ + ((STATE) == TIM_OUTPUTNSTATE_ENABLE)) +/** + * @} + */ + +/** @defgroup TIM_Output_Compare_Polarity + * @{ + */ +#define TIM_OCPOLARITY_HIGH ((uint32_t)0x0000) +#define TIM_OCPOLARITY_LOW (TIM_CCER_CC1P) + +#define IS_TIM_OC_POLARITY(POLARITY) (((POLARITY) == TIM_OCPOLARITY_HIGH) || \ + ((POLARITY) == TIM_OCPOLARITY_LOW)) +/** + * @} + */ + +/** @defgroup TIM_Output_Compare_N_Polarity + * @{ + */ +#define TIM_OCNPOLARITY_HIGH ((uint32_t)0x0000) +#define TIM_OCNPOLARITY_LOW (TIM_CCER_CC1NP) + +#define IS_TIM_OCN_POLARITY(POLARITY) (((POLARITY) == TIM_OCNPOLARITY_HIGH) || \ + ((POLARITY) == TIM_OCNPOLARITY_LOW)) +/** + * @} + */ + +/** @defgroup TIM_Output_Compare_Idle_State + * @{ + */ +#define TIM_OCIDLESTATE_SET (TIM_CR2_OIS1) +#define TIM_OCIDLESTATE_RESET ((uint32_t)0x0000) +#define IS_TIM_OCIDLE_STATE(STATE) (((STATE) == TIM_OCIDLESTATE_SET) || \ + ((STATE) == TIM_OCIDLESTATE_RESET)) +/** + * @} + */ + +/** @defgroup TIM_Output_Compare_N_Idle_State + * @{ + */ +#define TIM_OCNIDLESTATE_SET (TIM_CR2_OIS1N) +#define TIM_OCNIDLESTATE_RESET ((uint32_t)0x0000) + +#define IS_TIM_OCNIDLE_STATE(STATE) (((STATE) == TIM_OCNIDLESTATE_SET) || \ + ((STATE) == TIM_OCNIDLESTATE_RESET)) +/** + * @} + */ + +/** @defgroup TIM_Channel + * @{ + */ +#define TIM_CHANNEL_1 ((uint32_t)0x0000) +#define TIM_CHANNEL_2 ((uint32_t)0x0004) +#define TIM_CHANNEL_3 ((uint32_t)0x0008) +#define TIM_CHANNEL_4 ((uint32_t)0x000C) +#define TIM_CHANNEL_ALL ((uint32_t)0x0018) + +#define IS_TIM_CHANNELS(CHANNEL) (((CHANNEL) == TIM_CHANNEL_1) || \ + ((CHANNEL) == TIM_CHANNEL_2) || \ + ((CHANNEL) == TIM_CHANNEL_3) || \ + ((CHANNEL) == TIM_CHANNEL_4) || \ + ((CHANNEL) == TIM_CHANNEL_ALL)) + +#define IS_TIM_PWMI_CHANNELS(CHANNEL) (((CHANNEL) == TIM_CHANNEL_1) || \ + ((CHANNEL) == TIM_CHANNEL_2)) + +#define IS_TIM_OPM_CHANNELS(CHANNEL) (((CHANNEL) == TIM_CHANNEL_1) || \ + ((CHANNEL) == TIM_CHANNEL_2)) + +#define IS_TIM_COMPLEMENTARY_CHANNELS(CHANNEL) (((CHANNEL) == TIM_CHANNEL_1) || \ + ((CHANNEL) == TIM_CHANNEL_2) || \ + ((CHANNEL) == TIM_CHANNEL_3)) +/** + * @} + */ + +/** @defgroup TIM_Input_Capture_Polarity + * @{ + */ +#define TIM_ICPOLARITY_RISING TIM_INPUTCHANNELPOLARITY_RISING +#define TIM_ICPOLARITY_FALLING TIM_INPUTCHANNELPOLARITY_FALLING +#define TIM_ICPOLARITY_BOTHEDGE TIM_INPUTCHANNELPOLARITY_BOTHEDGE + +#define IS_TIM_IC_POLARITY(POLARITY) (((POLARITY) == TIM_ICPOLARITY_RISING) || \ + ((POLARITY) == TIM_ICPOLARITY_FALLING) || \ + ((POLARITY) == TIM_ICPOLARITY_BOTHEDGE)) +/** + * @} + */ + +/** @defgroup TIM_Input_Capture_Selection + * @{ + */ +#define TIM_ICSELECTION_DIRECTTI (TIM_CCMR1_CC1S_0) /*!< TIM Input 1, 2, 3 or 4 is selected to be + connected to IC1, IC2, IC3 or IC4, respectively */ +#define TIM_ICSELECTION_INDIRECTTI (TIM_CCMR1_CC1S_1) /*!< TIM Input 1, 2, 3 or 4 is selected to be + connected to IC2, IC1, IC4 or IC3, respectively */ +#define TIM_ICSELECTION_TRC (TIM_CCMR1_CC1S) /*!< TIM Input 1, 2, 3 or 4 is selected to be connected to TRC */ + +#define IS_TIM_IC_SELECTION(SELECTION) (((SELECTION) == TIM_ICSELECTION_DIRECTTI) || \ + ((SELECTION) == TIM_ICSELECTION_INDIRECTTI) || \ + ((SELECTION) == TIM_ICSELECTION_TRC)) +/** + * @} + */ + +/** @defgroup TIM_Input_Capture_Prescaler + * @{ + */ +#define TIM_ICPSC_DIV1 ((uint32_t)0x0000) /*!< Capture performed each time an edge is detected on the capture input */ +#define TIM_ICPSC_DIV2 (TIM_CCMR1_IC1PSC_0) /*!< Capture performed once every 2 events */ +#define TIM_ICPSC_DIV4 (TIM_CCMR1_IC1PSC_1) /*!< Capture performed once every 4 events */ +#define TIM_ICPSC_DIV8 (TIM_CCMR1_IC1PSC) /*!< Capture performed once every 8 events */ + +#define IS_TIM_IC_PRESCALER(PRESCALER) (((PRESCALER) == TIM_ICPSC_DIV1) || \ + ((PRESCALER) == TIM_ICPSC_DIV2) || \ + ((PRESCALER) == TIM_ICPSC_DIV4) || \ + ((PRESCALER) == TIM_ICPSC_DIV8)) +/** + * @} + */ + +/** @defgroup TIM_One_Pulse_Mode + * @{ + */ +#define TIM_OPMODE_SINGLE (TIM_CR1_OPM) +#define TIM_OPMODE_REPETITIVE ((uint32_t)0x0000) + +#define IS_TIM_OPM_MODE(MODE) (((MODE) == TIM_OPMODE_SINGLE) || \ + ((MODE) == TIM_OPMODE_REPETITIVE)) +/** + * @} + */ + +/** @defgroup TIM_Encoder_Mode + * @{ + */ +#define TIM_ENCODERMODE_TI1 (TIM_SMCR_SMS_0) +#define TIM_ENCODERMODE_TI2 (TIM_SMCR_SMS_1) +#define TIM_ENCODERMODE_TI12 (TIM_SMCR_SMS_1 | TIM_SMCR_SMS_0) + +#define IS_TIM_ENCODER_MODE(MODE) (((MODE) == TIM_ENCODERMODE_TI1) || \ + ((MODE) == TIM_ENCODERMODE_TI2) || \ + ((MODE) == TIM_ENCODERMODE_TI12)) +/** + * @} + */ + +/** @defgroup TIM_Interrupt_definition + * @{ + */ +#define TIM_IT_UPDATE (TIM_DIER_UIE) +#define TIM_IT_CC1 (TIM_DIER_CC1IE) +#define TIM_IT_CC2 (TIM_DIER_CC2IE) +#define TIM_IT_CC3 (TIM_DIER_CC3IE) +#define TIM_IT_CC4 (TIM_DIER_CC4IE) +#define TIM_IT_COM (TIM_DIER_COMIE) +#define TIM_IT_TRIGGER (TIM_DIER_TIE) +#define TIM_IT_BREAK (TIM_DIER_BIE) + +#define IS_TIM_IT(IT) ((((IT) & 0xFFFFFF00) == 0x00000000) && ((IT) != 0x00000000)) + +#define IS_TIM_GET_IT(IT) (((IT) == TIM_IT_UPDATE) || \ + ((IT) == TIM_IT_CC1) || \ + ((IT) == TIM_IT_CC2) || \ + ((IT) == TIM_IT_CC3) || \ + ((IT) == TIM_IT_CC4) || \ + ((IT) == TIM_IT_COM) || \ + ((IT) == TIM_IT_TRIGGER) || \ + ((IT) == TIM_IT_BREAK)) +/** + * @} + */ + +#define TIM_COMMUTATION_TRGI (TIM_CR2_CCUS) +#define TIM_COMMUTATION_SOFTWARE ((uint32_t)0x0000) + +/** @defgroup TIM_DMA_sources + * @{ + */ +#define TIM_DMA_UPDATE (TIM_DIER_UDE) +#define TIM_DMA_CC1 (TIM_DIER_CC1DE) +#define TIM_DMA_CC2 (TIM_DIER_CC2DE) +#define TIM_DMA_CC3 (TIM_DIER_CC3DE) +#define TIM_DMA_CC4 (TIM_DIER_CC4DE) +#define TIM_DMA_COM (TIM_DIER_COMDE) +#define TIM_DMA_TRIGGER (TIM_DIER_TDE) + +#define IS_TIM_DMA_SOURCE(SOURCE) ((((SOURCE) & 0xFFFF80FF) == 0x00000000) && ((SOURCE) != 0x00000000)) +/** + * @} + */ + +/** @defgroup TIM_Event_Source + * @{ + */ +#define TIM_EventSource_Update TIM_EGR_UG +#define TIM_EventSource_CC1 TIM_EGR_CC1G +#define TIM_EventSource_CC2 TIM_EGR_CC2G +#define TIM_EventSource_CC3 TIM_EGR_CC3G +#define TIM_EventSource_CC4 TIM_EGR_CC4G +#define TIM_EventSource_COM TIM_EGR_COMG +#define TIM_EventSource_Trigger TIM_EGR_TG +#define TIM_EventSource_Break TIM_EGR_BG + +#define IS_TIM_EVENT_SOURCE(SOURCE) ((((SOURCE) & 0xFFFFFF00) == 0x00000000) && ((SOURCE) != 0x00000000)) +/** + * @} + */ + +/** @defgroup TIM_Flag_definition + * @{ + */ +#define TIM_FLAG_UPDATE (TIM_SR_UIF) +#define TIM_FLAG_CC1 (TIM_SR_CC1IF) +#define TIM_FLAG_CC2 (TIM_SR_CC2IF) +#define TIM_FLAG_CC3 (TIM_SR_CC3IF) +#define TIM_FLAG_CC4 (TIM_SR_CC4IF) +#define TIM_FLAG_COM (TIM_SR_COMIF) +#define TIM_FLAG_TRIGGER (TIM_SR_TIF) +#define TIM_FLAG_BREAK (TIM_SR_BIF) +#define TIM_FLAG_CC1OF (TIM_SR_CC1OF) +#define TIM_FLAG_CC2OF (TIM_SR_CC2OF) +#define TIM_FLAG_CC3OF (TIM_SR_CC3OF) +#define TIM_FLAG_CC4OF (TIM_SR_CC4OF) + +#define IS_TIM_FLAG(FLAG) (((FLAG) == TIM_FLAG_UPDATE) || \ + ((FLAG) == TIM_FLAG_CC1) || \ + ((FLAG) == TIM_FLAG_CC2) || \ + ((FLAG) == TIM_FLAG_CC3) || \ + ((FLAG) == TIM_FLAG_CC4) || \ + ((FLAG) == TIM_FLAG_COM) || \ + ((FLAG) == TIM_FLAG_TRIGGER) || \ + ((FLAG) == TIM_FLAG_BREAK) || \ + ((FLAG) == TIM_FLAG_CC1OF) || \ + ((FLAG) == TIM_FLAG_CC2OF) || \ + ((FLAG) == TIM_FLAG_CC3OF) || \ + ((FLAG) == TIM_FLAG_CC4OF)) +/** + * @} + */ + +/** @defgroup TIM_Clock_Source + * @{ + */ +#define TIM_CLOCKSOURCE_ETRMODE2 (TIM_SMCR_ETPS_1) +#define TIM_CLOCKSOURCE_INTERNAL (TIM_SMCR_ETPS_0) +#define TIM_CLOCKSOURCE_ITR0 ((uint32_t)0x0000) +#define TIM_CLOCKSOURCE_ITR1 (TIM_SMCR_TS_0) +#define TIM_CLOCKSOURCE_ITR2 (TIM_SMCR_TS_1) +#define TIM_CLOCKSOURCE_ITR3 (TIM_SMCR_TS_0 | TIM_SMCR_TS_1) +#define TIM_CLOCKSOURCE_TI1ED (TIM_SMCR_TS_2) +#define TIM_CLOCKSOURCE_TI1 (TIM_SMCR_TS_0 | TIM_SMCR_TS_2) +#define TIM_CLOCKSOURCE_TI2 (TIM_SMCR_TS_1 | TIM_SMCR_TS_2) +#define TIM_CLOCKSOURCE_ETRMODE1 (TIM_SMCR_TS) + +#define IS_TIM_CLOCKSOURCE(CLOCK) (((CLOCK) == TIM_CLOCKSOURCE_INTERNAL) || \ + ((CLOCK) == TIM_CLOCKSOURCE_ETRMODE2) || \ + ((CLOCK) == TIM_CLOCKSOURCE_ITR0) || \ + ((CLOCK) == TIM_CLOCKSOURCE_ITR1) || \ + ((CLOCK) == TIM_CLOCKSOURCE_ITR2) || \ + ((CLOCK) == TIM_CLOCKSOURCE_ITR3) || \ + ((CLOCK) == TIM_CLOCKSOURCE_TI1ED) || \ + ((CLOCK) == TIM_CLOCKSOURCE_TI1) || \ + ((CLOCK) == TIM_CLOCKSOURCE_TI2) || \ + ((CLOCK) == TIM_CLOCKSOURCE_ETRMODE1)) +/** + * @} + */ + +/** @defgroup TIM_Clock_Polarity + * @{ + */ +#define TIM_CLOCKPOLARITY_INVERTED TIM_ETRPOLARITY_INVERTED /*!< Polarity for ETRx clock sources */ +#define TIM_CLOCKPOLARITY_NONINVERTED TIM_ETRPOLARITY_NONINVERTED /*!< Polarity for ETRx clock sources */ +#define TIM_CLOCKPOLARITY_RISING TIM_INPUTCHANNELPOLARITY_RISING /*!< Polarity for TIx clock sources */ +#define TIM_CLOCKPOLARITY_FALLING TIM_INPUTCHANNELPOLARITY_FALLING /*!< Polarity for TIx clock sources */ +#define TIM_CLOCKPOLARITY_BOTHEDGE TIM_INPUTCHANNELPOLARITY_BOTHEDGE /*!< Polarity for TIx clock sources */ + +#define IS_TIM_CLOCKPOLARITY(POLARITY) (((POLARITY) == TIM_CLOCKPOLARITY_INVERTED) || \ + ((POLARITY) == TIM_CLOCKPOLARITY_NONINVERTED) || \ + ((POLARITY) == TIM_CLOCKPOLARITY_RISING) || \ + ((POLARITY) == TIM_CLOCKPOLARITY_FALLING) || \ + ((POLARITY) == TIM_CLOCKPOLARITY_BOTHEDGE)) +/** + * @} + */ + +/** @defgroup TIM_Clock_Prescaler + * @{ + */ +#define TIM_CLOCKPRESCALER_DIV1 TIM_ETRPRESCALER_DIV1 /*!< No prescaler is used */ +#define TIM_CLOCKPRESCALER_DIV2 TIM_ETRPRESCALER_DIV2 /*!< Prescaler for External ETR Clock: Capture performed once every 2 events. */ +#define TIM_CLOCKPRESCALER_DIV4 TIM_ETRPRESCALER_DIV4 /*!< Prescaler for External ETR Clock: Capture performed once every 4 events. */ +#define TIM_CLOCKPRESCALER_DIV8 TIM_ETRPRESCALER_DIV8 /*!< Prescaler for External ETR Clock: Capture performed once every 8 events. */ + +#define IS_TIM_CLOCKPRESCALER(PRESCALER) (((PRESCALER) == TIM_CLOCKPRESCALER_DIV1) || \ + ((PRESCALER) == TIM_CLOCKPRESCALER_DIV2) || \ + ((PRESCALER) == TIM_CLOCKPRESCALER_DIV4) || \ + ((PRESCALER) == TIM_CLOCKPRESCALER_DIV8)) +/** + * @} + */ + +/** @defgroup TIM_Clock_Filter + * @{ + */ +#define IS_TIM_CLOCKFILTER(ICFILTER) ((ICFILTER) <= 0xF) +/** + * @} + */ + +/** @defgroup TIM_ClearInput_Source + * @{ + */ +#define TIM_CLEARINPUTSOURCE_ETR ((uint32_t)0x0001) +#define TIM_CLEARINPUTSOURCE_NONE ((uint32_t)0x0000) + +#define IS_TIM_CLEARINPUT_SOURCE(SOURCE) (((SOURCE) == TIM_CLEARINPUTSOURCE_NONE) || \ + ((SOURCE) == TIM_CLEARINPUTSOURCE_ETR)) +/** + * @} + */ + +/** @defgroup TIM_ClearInput_Polarity + * @{ + */ +#define TIM_CLEARINPUTPOLARITY_INVERTED TIM_ETRPOLARITY_INVERTED /*!< Polarity for ETRx pin */ +#define TIM_CLEARINPUTPOLARITY_NONINVERTED TIM_ETRPOLARITY_NONINVERTED /*!< Polarity for ETRx pin */ + + +#define IS_TIM_CLEARINPUT_POLARITY(POLARITY) (((POLARITY) == TIM_CLEARINPUTPOLARITY_INVERTED) || \ + ((POLARITY) == TIM_CLEARINPUTPOLARITY_NONINVERTED)) +/** + * @} + */ + +/** @defgroup TIM_ClearInput_Prescaler + * @{ + */ +#define TIM_CLEARINPUTPRESCALER_DIV1 TIM_ETRPRESCALER_DIV1 /*!< No prescaler is used */ +#define TIM_CLEARINPUTPRESCALER_DIV2 TIM_ETRPRESCALER_DIV2 /*!< Prescaler for External ETR pin: Capture performed once every 2 events. */ +#define TIM_CLEARINPUTPRESCALER_DIV4 TIM_ETRPRESCALER_DIV4 /*!< Prescaler for External ETR pin: Capture performed once every 4 events. */ +#define TIM_CLEARINPUTPRESCALER_DIV8 TIM_ETRPRESCALER_DIV8 /*!< Prescaler for External ETR pin: Capture performed once every 8 events. */ + +#define IS_TIM_CLEARINPUT_PRESCALER(PRESCALER) (((PRESCALER) == TIM_CLEARINPUTPRESCALER_DIV1) || \ + ((PRESCALER) == TIM_CLEARINPUTPRESCALER_DIV2) || \ + ((PRESCALER) == TIM_CLEARINPUTPRESCALER_DIV4) || \ + ((PRESCALER) == TIM_CLEARINPUTPRESCALER_DIV8)) +/** + * @} + */ + +/** @defgroup TIM_ClearInput_Filter + * @{ + */ +#define IS_TIM_CLEARINPUT_FILTER(ICFILTER) ((ICFILTER) <= 0xF) +/** + * @} + */ + +/** @defgroup TIM_OSSR_Off_State_Selection_for_Run_mode_state + * @{ + */ +#define TIM_OSSR_ENABLE (TIM_BDTR_OSSR) +#define TIM_OSSR_DISABLE ((uint32_t)0x0000) + +#define IS_TIM_OSSR_STATE(STATE) (((STATE) == TIM_OSSR_ENABLE) || \ + ((STATE) == TIM_OSSR_DISABLE)) +/** + * @} + */ + +/** @defgroup TIM_OSSI_Off_State_Selection_for_Idle_mode_state + * @{ + */ +#define TIM_OSSI_ENABLE (TIM_BDTR_OSSI) +#define TIM_OSSI_DISABLE ((uint32_t)0x0000) + +#define IS_TIM_OSSI_STATE(STATE) (((STATE) == TIM_OSSI_ENABLE) || \ + ((STATE) == TIM_OSSI_DISABLE)) +/** + * @} + */ + +/** @defgroup TIM_Lock_level + * @{ + */ +#define TIM_LOCKLEVEL_OFF ((uint32_t)0x0000) +#define TIM_LOCKLEVEL_1 (TIM_BDTR_LOCK_0) +#define TIM_LOCKLEVEL_2 (TIM_BDTR_LOCK_1) +#define TIM_LOCKLEVEL_3 (TIM_BDTR_LOCK) + +#define IS_TIM_LOCK_LEVEL(LEVEL) (((LEVEL) == TIM_LOCKLEVEL_OFF) || \ + ((LEVEL) == TIM_LOCKLEVEL_1) || \ + ((LEVEL) == TIM_LOCKLEVEL_2) || \ + ((LEVEL) == TIM_LOCKLEVEL_3)) +/** + * @} + */ + +/** @defgroup TIM_Break_Input_enable_disable + * @{ + */ +#define TIM_BREAK_ENABLE (TIM_BDTR_BKE) +#define TIM_BREAK_DISABLE ((uint32_t)0x0000) + +#define IS_TIM_BREAK_STATE(STATE) (((STATE) == TIM_BREAK_ENABLE) || \ + ((STATE) == TIM_BREAK_DISABLE)) +/** + * @} + */ + +/** @defgroup TIM_Break_Polarity + * @{ + */ +#define TIM_BREAKPOLARITY_LOW ((uint32_t)0x0000) +#define TIM_BREAKPOLARITY_HIGH (TIM_BDTR_BKP) + +#define IS_TIM_BREAK_POLARITY(POLARITY) (((POLARITY) == TIM_BREAKPOLARITY_LOW) || \ + ((POLARITY) == TIM_BREAKPOLARITY_HIGH)) +/** + * @} + */ + +/** @defgroup TIM_AOE_Bit_Set_Reset + * @{ + */ +#define TIM_AUTOMATICOUTPUT_ENABLE (TIM_BDTR_AOE) +#define TIM_AUTOMATICOUTPUT_DISABLE ((uint32_t)0x0000) + +#define IS_TIM_AUTOMATIC_OUTPUT_STATE(STATE) (((STATE) == TIM_AUTOMATICOUTPUT_ENABLE) || \ + ((STATE) == TIM_AUTOMATICOUTPUT_DISABLE)) +/** + * @} + */ + +/** @defgroup TIM_Master_Mode_Selection + * @{ + */ +#define TIM_TRGO_RESET ((uint32_t)0x0000) +#define TIM_TRGO_ENABLE (TIM_CR2_MMS_0) +#define TIM_TRGO_UPDATE (TIM_CR2_MMS_1) +#define TIM_TRGO_OC1 ((TIM_CR2_MMS_1 | TIM_CR2_MMS_0)) +#define TIM_TRGO_OC1REF (TIM_CR2_MMS_2) +#define TIM_TRGO_OC2REF ((TIM_CR2_MMS_2 | TIM_CR2_MMS_0)) +#define TIM_TRGO_OC3REF ((TIM_CR2_MMS_2 | TIM_CR2_MMS_1)) +#define TIM_TRGO_OC4REF ((TIM_CR2_MMS_2 | TIM_CR2_MMS_1 | TIM_CR2_MMS_0)) + +#define IS_TIM_TRGO_SOURCE(SOURCE) (((SOURCE) == TIM_TRGO_RESET) || \ + ((SOURCE) == TIM_TRGO_ENABLE) || \ + ((SOURCE) == TIM_TRGO_UPDATE) || \ + ((SOURCE) == TIM_TRGO_OC1) || \ + ((SOURCE) == TIM_TRGO_OC1REF) || \ + ((SOURCE) == TIM_TRGO_OC2REF) || \ + ((SOURCE) == TIM_TRGO_OC3REF) || \ + ((SOURCE) == TIM_TRGO_OC4REF)) +/** + * @} + */ + +/** @defgroup TIM_Slave_Mode + * @{ + */ +#define TIM_SLAVEMODE_DISABLE ((uint32_t)0x0000) +#define TIM_SLAVEMODE_RESET ((uint32_t)0x0004) +#define TIM_SLAVEMODE_GATED ((uint32_t)0x0005) +#define TIM_SLAVEMODE_TRIGGER ((uint32_t)0x0006) +#define TIM_SLAVEMODE_EXTERNAL1 ((uint32_t)0x0007) + +#define IS_TIM_SLAVE_MODE(MODE) (((MODE) == TIM_SLAVEMODE_DISABLE) || \ + ((MODE) == TIM_SLAVEMODE_GATED) || \ + ((MODE) == TIM_SLAVEMODE_RESET) || \ + ((MODE) == TIM_SLAVEMODE_TRIGGER) || \ + ((MODE) == TIM_SLAVEMODE_EXTERNAL1)) +/** + * @} + */ + +/** @defgroup TIM_Master_Slave_Mode + * @{ + */ +#define TIM_MASTERSLAVEMODE_ENABLE ((uint32_t)0x0080) +#define TIM_MASTERSLAVEMODE_DISABLE ((uint32_t)0x0000) + +#define IS_TIM_MSM_STATE(STATE) (((STATE) == TIM_MASTERSLAVEMODE_ENABLE) || \ + ((STATE) == TIM_MASTERSLAVEMODE_DISABLE)) +/** + * @} + */ + +/** @defgroup TIM_Trigger_Selection + * @{ + */ +#define TIM_TS_ITR0 ((uint32_t)0x0000) +#define TIM_TS_ITR1 ((uint32_t)0x0010) +#define TIM_TS_ITR2 ((uint32_t)0x0020) +#define TIM_TS_ITR3 ((uint32_t)0x0030) +#define TIM_TS_TI1F_ED ((uint32_t)0x0040) +#define TIM_TS_TI1FP1 ((uint32_t)0x0050) +#define TIM_TS_TI2FP2 ((uint32_t)0x0060) +#define TIM_TS_ETRF ((uint32_t)0x0070) +#define TIM_TS_NONE ((uint32_t)0xFFFF) + +#define IS_TIM_TRIGGER_SELECTION(SELECTION) (((SELECTION) == TIM_TS_ITR0) || \ + ((SELECTION) == TIM_TS_ITR1) || \ + ((SELECTION) == TIM_TS_ITR2) || \ + ((SELECTION) == TIM_TS_ITR3) || \ + ((SELECTION) == TIM_TS_TI1F_ED) || \ + ((SELECTION) == TIM_TS_TI1FP1) || \ + ((SELECTION) == TIM_TS_TI2FP2) || \ + ((SELECTION) == TIM_TS_ETRF)) + +#define IS_TIM_INTERNAL_TRIGGER_SELECTION(SELECTION) (((SELECTION) == TIM_TS_ITR0) || \ + ((SELECTION) == TIM_TS_ITR1) || \ + ((SELECTION) == TIM_TS_ITR2) || \ + ((SELECTION) == TIM_TS_ITR3)) + +#define IS_TIM_INTERNAL_TRIGGEREVENT_SELECTION(SELECTION) (((SELECTION) == TIM_TS_ITR0) || \ + ((SELECTION) == TIM_TS_ITR1) || \ + ((SELECTION) == TIM_TS_ITR2) || \ + ((SELECTION) == TIM_TS_ITR3) || \ + ((SELECTION) == TIM_TS_NONE)) +/** + * @} + */ + +/** @defgroup TIM_Trigger_Polarity + * @{ + */ +#define TIM_TRIGGERPOLARITY_INVERTED TIM_ETRPOLARITY_INVERTED /*!< Polarity for ETRx trigger sources */ +#define TIM_TRIGGERPOLARITY_NONINVERTED TIM_ETRPOLARITY_NONINVERTED /*!< Polarity for ETRx trigger sources */ +#define TIM_TRIGGERPOLARITY_RISING TIM_INPUTCHANNELPOLARITY_RISING /*!< Polarity for TIxFPx or TI1_ED trigger sources */ +#define TIM_TRIGGERPOLARITY_FALLING TIM_INPUTCHANNELPOLARITY_FALLING /*!< Polarity for TIxFPx or TI1_ED trigger sources */ +#define TIM_TRIGGERPOLARITY_BOTHEDGE TIM_INPUTCHANNELPOLARITY_BOTHEDGE /*!< Polarity for TIxFPx or TI1_ED trigger sources */ + +#define IS_TIM_TRIGGERPOLARITY(POLARITY) (((POLARITY) == TIM_TRIGGERPOLARITY_INVERTED ) || \ + ((POLARITY) == TIM_TRIGGERPOLARITY_NONINVERTED) || \ + ((POLARITY) == TIM_TRIGGERPOLARITY_RISING ) || \ + ((POLARITY) == TIM_TRIGGERPOLARITY_FALLING ) || \ + ((POLARITY) == TIM_TRIGGERPOLARITY_BOTHEDGE )) +/** + * @} + */ + +/** @defgroup TIM_Trigger_Prescaler + * @{ + */ +#define TIM_TRIGGERPRESCALER_DIV1 TIM_ETRPRESCALER_DIV1 /*!< No prescaler is used */ +#define TIM_TRIGGERPRESCALER_DIV2 TIM_ETRPRESCALER_DIV2 /*!< Prescaler for External ETR Trigger: Capture performed once every 2 events. */ +#define TIM_TRIGGERPRESCALER_DIV4 TIM_ETRPRESCALER_DIV4 /*!< Prescaler for External ETR Trigger: Capture performed once every 4 events. */ +#define TIM_TRIGGERPRESCALER_DIV8 TIM_ETRPRESCALER_DIV8 /*!< Prescaler for External ETR Trigger: Capture performed once every 8 events. */ + +#define IS_TIM_TRIGGERPRESCALER(PRESCALER) (((PRESCALER) == TIM_TRIGGERPRESCALER_DIV1) || \ + ((PRESCALER) == TIM_TRIGGERPRESCALER_DIV2) || \ + ((PRESCALER) == TIM_TRIGGERPRESCALER_DIV4) || \ + ((PRESCALER) == TIM_TRIGGERPRESCALER_DIV8)) +/** + * @} + */ + +/** @defgroup TIM_Trigger_Filter + * @{ + */ +#define IS_TIM_TRIGGERFILTER(ICFILTER) ((ICFILTER) <= 0xF) +/** + * @} + */ + +/** @defgroup TIM_TI1_Selection + * @{ + */ +#define TIM_TI1SELECTION_CH1 ((uint32_t)0x0000) +#define TIM_TI1SELECTION_XORCOMBINATION (TIM_CR2_TI1S) + +#define IS_TIM_TI1SELECTION(TI1SELECTION) (((TI1SELECTION) == TIM_TI1SELECTION_CH1) || \ + ((TI1SELECTION) == TIM_TI1SELECTION_XORCOMBINATION)) +/** + * @} + */ + +/** @defgroup TIM_DMA_Base_address + * @{ + */ +#define TIM_DMABase_CR1 (0x00000000) +#define TIM_DMABase_CR2 (0x00000001) +#define TIM_DMABase_SMCR (0x00000002) +#define TIM_DMABase_DIER (0x00000003) +#define TIM_DMABase_SR (0x00000004) +#define TIM_DMABase_EGR (0x00000005) +#define TIM_DMABase_CCMR1 (0x00000006) +#define TIM_DMABase_CCMR2 (0x00000007) +#define TIM_DMABase_CCER (0x00000008) +#define TIM_DMABase_CNT (0x00000009) +#define TIM_DMABase_PSC (0x0000000A) +#define TIM_DMABase_ARR (0x0000000B) +#define TIM_DMABase_RCR (0x0000000C) +#define TIM_DMABase_CCR1 (0x0000000D) +#define TIM_DMABase_CCR2 (0x0000000E) +#define TIM_DMABase_CCR3 (0x0000000F) +#define TIM_DMABase_CCR4 (0x00000010) +#define TIM_DMABase_BDTR (0x00000011) +#define TIM_DMABase_DCR (0x00000012) +#define TIM_DMABase_OR (0x00000013) + +#define IS_TIM_DMA_BASE(BASE) (((BASE) == TIM_DMABase_CR1) || \ + ((BASE) == TIM_DMABase_CR2) || \ + ((BASE) == TIM_DMABase_SMCR) || \ + ((BASE) == TIM_DMABase_DIER) || \ + ((BASE) == TIM_DMABase_SR) || \ + ((BASE) == TIM_DMABase_EGR) || \ + ((BASE) == TIM_DMABase_CCMR1) || \ + ((BASE) == TIM_DMABase_CCMR2) || \ + ((BASE) == TIM_DMABase_CCER) || \ + ((BASE) == TIM_DMABase_CNT) || \ + ((BASE) == TIM_DMABase_PSC) || \ + ((BASE) == TIM_DMABase_ARR) || \ + ((BASE) == TIM_DMABase_RCR) || \ + ((BASE) == TIM_DMABase_CCR1) || \ + ((BASE) == TIM_DMABase_CCR2) || \ + ((BASE) == TIM_DMABase_CCR3) || \ + ((BASE) == TIM_DMABase_CCR4) || \ + ((BASE) == TIM_DMABase_BDTR) || \ + ((BASE) == TIM_DMABase_DCR) || \ + ((BASE) == TIM_DMABase_OR)) +/** + * @} + */ + +/** @defgroup TIM_DMA_Burst_Length + * @{ + */ +#define TIM_DMABurstLength_1Transfer (0x00000000) +#define TIM_DMABurstLength_2Transfers (0x00000100) +#define TIM_DMABurstLength_3Transfers (0x00000200) +#define TIM_DMABurstLength_4Transfers (0x00000300) +#define TIM_DMABurstLength_5Transfers (0x00000400) +#define TIM_DMABurstLength_6Transfers (0x00000500) +#define TIM_DMABurstLength_7Transfers (0x00000600) +#define TIM_DMABurstLength_8Transfers (0x00000700) +#define TIM_DMABurstLength_9Transfers (0x00000800) +#define TIM_DMABurstLength_10Transfers (0x00000900) +#define TIM_DMABurstLength_11Transfers (0x00000A00) +#define TIM_DMABurstLength_12Transfers (0x00000B00) +#define TIM_DMABurstLength_13Transfers (0x00000C00) +#define TIM_DMABurstLength_14Transfers (0x00000D00) +#define TIM_DMABurstLength_15Transfers (0x00000E00) +#define TIM_DMABurstLength_16Transfers (0x00000F00) +#define TIM_DMABurstLength_17Transfers (0x00001000) +#define TIM_DMABurstLength_18Transfers (0x00001100) + +#define IS_TIM_DMA_LENGTH(LENGTH) (((LENGTH) == TIM_DMABurstLength_1Transfer) || \ + ((LENGTH) == TIM_DMABurstLength_2Transfers) || \ + ((LENGTH) == TIM_DMABurstLength_3Transfers) || \ + ((LENGTH) == TIM_DMABurstLength_4Transfers) || \ + ((LENGTH) == TIM_DMABurstLength_5Transfers) || \ + ((LENGTH) == TIM_DMABurstLength_6Transfers) || \ + ((LENGTH) == TIM_DMABurstLength_7Transfers) || \ + ((LENGTH) == TIM_DMABurstLength_8Transfers) || \ + ((LENGTH) == TIM_DMABurstLength_9Transfers) || \ + ((LENGTH) == TIM_DMABurstLength_10Transfers) || \ + ((LENGTH) == TIM_DMABurstLength_11Transfers) || \ + ((LENGTH) == TIM_DMABurstLength_12Transfers) || \ + ((LENGTH) == TIM_DMABurstLength_13Transfers) || \ + ((LENGTH) == TIM_DMABurstLength_14Transfers) || \ + ((LENGTH) == TIM_DMABurstLength_15Transfers) || \ + ((LENGTH) == TIM_DMABurstLength_16Transfers) || \ + ((LENGTH) == TIM_DMABurstLength_17Transfers) || \ + ((LENGTH) == TIM_DMABurstLength_18Transfers)) +/** + * @} + */ + +/** @defgroup TIM_Input_Capture_Filer_Value + * @{ + */ +#define IS_TIM_IC_FILTER(ICFILTER) ((ICFILTER) <= 0xF) +/** + * @} + */ + +/** @defgroup DMA_Handle_index + * @{ + */ +#define TIM_DMA_ID_UPDATE ((uint16_t) 0x0) /*!< Index of the DMA handle used for Update DMA requests */ +#define TIM_DMA_ID_CC1 ((uint16_t) 0x1) /*!< Index of the DMA handle used for Capture/Compare 1 DMA requests */ +#define TIM_DMA_ID_CC2 ((uint16_t) 0x2) /*!< Index of the DMA handle used for Capture/Compare 2 DMA requests */ +#define TIM_DMA_ID_CC3 ((uint16_t) 0x3) /*!< Index of the DMA handle used for Capture/Compare 3 DMA requests */ +#define TIM_DMA_ID_CC4 ((uint16_t) 0x4) /*!< Index of the DMA handle used for Capture/Compare 4 DMA requests */ +#define TIM_DMA_ID_COMMUTATION ((uint16_t) 0x5) /*!< Index of the DMA handle used for Commutation DMA requests */ +#define TIM_DMA_ID_TRIGGER ((uint16_t) 0x6) /*!< Index of the DMA handle used for Trigger DMA requests */ +/** + * @} + */ + +/** @defgroup Channel_CC_State + * @{ + */ +#define TIM_CCx_ENABLE ((uint32_t)0x0001) +#define TIM_CCx_DISABLE ((uint32_t)0x0000) +#define TIM_CCxN_ENABLE ((uint32_t)0x0004) +#define TIM_CCxN_DISABLE ((uint32_t)0x0000) +/** + * @} + */ + +/** + * @} + */ + +/* Exported macros -----------------------------------------------------------*/ +/** @defgroup TIM_Exported_Macros + * @{ + */ + +/** @brief Reset TIM handle state + * @param __HANDLE__: TIM handle. + * @retval None + */ +#define __HAL_TIM_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_TIM_STATE_RESET) + +/** + * @brief Enable the TIM peripheral. + * @param __HANDLE__: TIM handle + * @retval None + */ +#define __HAL_TIM_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1|=(TIM_CR1_CEN)) + +/** + * @brief Enable the TIM main Output. + * @param __HANDLE__: TIM handle + * @retval None + */ +#define __HAL_TIM_MOE_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->BDTR|=(TIM_BDTR_MOE)) + +/* The counter of a timer instance is disabled only if all the CCx and CCxN + channels have been disabled */ +#define CCER_CCxE_MASK ((uint32_t)(TIM_CCER_CC1E | TIM_CCER_CC2E | TIM_CCER_CC3E | TIM_CCER_CC4E)) +#define CCER_CCxNE_MASK ((uint32_t)(TIM_CCER_CC1NE | TIM_CCER_CC2NE | TIM_CCER_CC3NE)) + +/** + * @brief Disable the TIM peripheral. + * @param __HANDLE__: TIM handle + * @retval None + */ +#define __HAL_TIM_DISABLE(__HANDLE__) \ + do { \ + if (((__HANDLE__)->Instance->CCER & CCER_CCxE_MASK) == 0) \ + { \ + if(((__HANDLE__)->Instance->CCER & CCER_CCxNE_MASK) == 0) \ + { \ + (__HANDLE__)->Instance->CR1 &= (uint16_t)(~TIM_CR1_CEN); \ + } \ + } \ + } while(0) +/* The Main Output Enable of a timer instance is disabled only if all the CCx and CCxN + channels have been disabled */ +/** + * @brief Disable the TIM main Output. + * @param __HANDLE__: TIM handle + * @retval None + */ +#define __HAL_TIM_MOE_DISABLE(__HANDLE__) \ + do { \ + if (((__HANDLE__)->Instance->CCER & CCER_CCxE_MASK) == 0) \ + { \ + if(((__HANDLE__)->Instance->CCER & CCER_CCxNE_MASK) == 0) \ + { \ + (__HANDLE__)->Instance->BDTR &= (uint16_t)(~TIM_BDTR_MOE); \ + } \ + } \ + } while(0) + +#define __HAL_TIM_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->DIER |= (__INTERRUPT__)) +#define __HAL_TIM_ENABLE_DMA(__HANDLE__, __DMA__) ((__HANDLE__)->Instance->DIER |= (__DMA__)) +#define __HAL_TIM_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->DIER &= (uint16_t)~(__INTERRUPT__)) +#define __HAL_TIM_DISABLE_DMA(__HANDLE__, __DMA__) ((__HANDLE__)->Instance->DIER &= (uint16_t)~(__DMA__)) +#define __HAL_TIM_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->SR &(__FLAG__)) == (__FLAG__)) +#define __HAL_TIM_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->SR &= (uint16_t)~(__FLAG__)) + +#define __HAL_TIM_GET_ITSTATUS(__HANDLE__, __INTERRUPT__) ((((__HANDLE__)->Instance->DIER & (__INTERRUPT__)) == (__INTERRUPT__)) ? SET : RESET) +#define __HAL_TIM_CLEAR_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->SR &= (uint16_t)~(__INTERRUPT__)) + +#define __HAL_TIM_DIRECTION_STATUS(__HANDLE__) (((__HANDLE__)->Instance->CR1 & (TIM_CR1_DIR)) == (TIM_CR1_DIR)) +#define __HAL_TIM_PRESCALER (__HANDLE__, __PRESC__) ((__HANDLE__)->Instance->PSC |= (__PRESC__)) + +#define __HAL_TIM_SetICPrescalerValue(__HANDLE__, __CHANNEL__, __ICPSC__) \ +(((__CHANNEL__) == TIM_CHANNEL_1) ? ((__HANDLE__)->Instance->CCMR1 |= (__ICPSC__)) :\ + ((__CHANNEL__) == TIM_CHANNEL_2) ? ((__HANDLE__)->Instance->CCMR1 |= ((__ICPSC__) << 8)) :\ + ((__CHANNEL__) == TIM_CHANNEL_3) ? ((__HANDLE__)->Instance->CCMR2 |= (__ICPSC__)) :\ + ((__HANDLE__)->Instance->CCMR2 |= ((__ICPSC__) << 8))) + +#define __HAL_TIM_ResetICPrescalerValue(__HANDLE__, __CHANNEL__) \ +(((__CHANNEL__) == TIM_CHANNEL_1) ? ((__HANDLE__)->Instance->CCMR1 &= (uint16_t)~TIM_CCMR1_IC1PSC) :\ + ((__CHANNEL__) == TIM_CHANNEL_2) ? ((__HANDLE__)->Instance->CCMR1 &= (uint16_t)~TIM_CCMR1_IC2PSC) :\ + ((__CHANNEL__) == TIM_CHANNEL_3) ? ((__HANDLE__)->Instance->CCMR2 &= (uint16_t)~TIM_CCMR2_IC3PSC) :\ + ((__HANDLE__)->Instance->CCMR2 &= (uint16_t)~TIM_CCMR2_IC4PSC)) + +/** + * @brief Sets the TIM Capture Compare Register value on runtime without + * calling another time ConfigChannel function. + * @param __HANDLE__: TIM handle. + * @param __CHANNEL__ : TIM Channels to be configured. + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @arg TIM_CHANNEL_3: TIM Channel 3 selected + * @arg TIM_CHANNEL_4: TIM Channel 4 selected + * @param __COMPARE__: specifies the Capture Compare register new value. + * @retval None + */ +#define __HAL_TIM_SetCompare(__HANDLE__, __CHANNEL__, __COMPARE__) \ +(*(__IO uint32_t *)(&((__HANDLE__)->Instance->CCR1) + ((__CHANNEL__) >> 2)) = (__COMPARE__)) + +/** + * @brief Gets the TIM Capture Compare Register value on runtime + * @param __HANDLE__: TIM handle. + * @param __CHANNEL__ : TIM Channel associated with the capture compare register + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: get capture/compare 1 register value + * @arg TIM_CHANNEL_2: get capture/compare 2 register value + * @arg TIM_CHANNEL_3: get capture/compare 3 register value + * @arg TIM_CHANNEL_4: get capture/compare 4 register value + * @retval None + */ +#define __HAL_TIM_GetCompare(__HANDLE__, __CHANNEL__) \ + (*(__IO uint32_t *)(&((__HANDLE__)->Instance->CCR1) + ((__CHANNEL__) >> 2))) + +/** + * @brief Sets the TIM Counter Register value on runtime. + * @param __HANDLE__: TIM handle. + * @param __COUNTER__: specifies the Counter register new value. + * @retval None + */ +#define __HAL_TIM_SetCounter(__HANDLE__, __COUNTER__) ((__HANDLE__)->Instance->CNT = (__COUNTER__)) + +/** + * @brief Gets the TIM Counter Register value on runtime. + * @param __HANDLE__: TIM handle. + * @retval None + */ +#define __HAL_TIM_GetCounter(__HANDLE__) \ + ((__HANDLE__)->Instance->CNT) + +/** + * @brief Sets the TIM Autoreload Register value on runtime without calling + * another time any Init function. + * @param __HANDLE__: TIM handle. + * @param __AUTORELOAD__: specifies the Counter register new value. + * @retval None + */ +#define __HAL_TIM_SetAutoreload(__HANDLE__, __AUTORELOAD__) \ + do{ \ + (__HANDLE__)->Instance->ARR = (__AUTORELOAD__); \ + (__HANDLE__)->Init.Period = (__AUTORELOAD__); \ + } while(0) + +/** + * @brief Gets the TIM Autoreload Register value on runtime + * @param __HANDLE__: TIM handle. + * @retval None + */ +#define __HAL_TIM_GetAutoreload(__HANDLE__) \ + ((__HANDLE__)->Instance->ARR) + +/** + * @brief Sets the TIM Clock Division value on runtime without calling + * another time any Init function. + * @param __HANDLE__: TIM handle. + * @param __CKD__: specifies the clock division value. + * This parameter can be one of the following value: + * @arg TIM_CLOCKDIVISION_DIV1 + * @arg TIM_CLOCKDIVISION_DIV2 + * @arg TIM_CLOCKDIVISION_DIV4 + * @retval None + */ +#define __HAL_TIM_SetClockDivision(__HANDLE__, __CKD__) \ + do{ \ + (__HANDLE__)->Instance->CR1 &= (uint16_t)(~TIM_CR1_CKD); \ + (__HANDLE__)->Instance->CR1 |= (__CKD__); \ + (__HANDLE__)->Init.ClockDivision = (__CKD__); \ + } while(0) + +/** + * @brief Gets the TIM Clock Division value on runtime + * @param __HANDLE__: TIM handle. + * @retval None + */ +#define __HAL_TIM_GetClockDivision(__HANDLE__) \ + ((__HANDLE__)->Instance->CR1 & TIM_CR1_CKD) + +/** + * @brief Sets the TIM Input Capture prescaler on runtime without calling + * another time HAL_TIM_IC_ConfigChannel() function. + * @param __HANDLE__: TIM handle. + * @param __CHANNEL__ : TIM Channels to be configured. + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @arg TIM_CHANNEL_3: TIM Channel 3 selected + * @arg TIM_CHANNEL_4: TIM Channel 4 selected + * @param __ICPSC__: specifies the Input Capture4 prescaler new value. + * This parameter can be one of the following values: + * @arg TIM_ICPSC_DIV1: no prescaler + * @arg TIM_ICPSC_DIV2: capture is done once every 2 events + * @arg TIM_ICPSC_DIV4: capture is done once every 4 events + * @arg TIM_ICPSC_DIV8: capture is done once every 8 events + * @retval None + */ +#define __HAL_TIM_SetICPrescaler(__HANDLE__, __CHANNEL__, __ICPSC__) \ + do{ \ + __HAL_TIM_ResetICPrescalerValue((__HANDLE__), (__CHANNEL__)); \ + __HAL_TIM_SetICPrescalerValue((__HANDLE__), (__CHANNEL__), (__ICPSC__)); \ + } while(0) + +/** + * @brief Gets the TIM Input Capture prescaler on runtime + * @param __HANDLE__: TIM handle. + * @param __CHANNEL__ : TIM Channels to be configured. + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: get input capture 1 prescaler value + * @arg TIM_CHANNEL_2: get input capture 2 prescaler value + * @arg TIM_CHANNEL_3: get input capture 3 prescaler value + * @arg TIM_CHANNEL_4: get input capture 4 prescaler value + * @retval None + */ +#define __HAL_TIM_GetICPrescaler(__HANDLE__, __CHANNEL__) \ + (((__CHANNEL__) == TIM_CHANNEL_1) ? ((__HANDLE__)->Instance->CCMR1 & TIM_CCMR1_IC1PSC) :\ + ((__CHANNEL__) == TIM_CHANNEL_2) ? (((__HANDLE__)->Instance->CCMR1 & TIM_CCMR1_IC2PSC) >> 8) :\ + ((__CHANNEL__) == TIM_CHANNEL_3) ? ((__HANDLE__)->Instance->CCMR2 & TIM_CCMR2_IC3PSC) :\ + (((__HANDLE__)->Instance->CCMR2 & TIM_CCMR2_IC4PSC)) >> 8) + +/** + * @} + */ + +/* Include TIM HAL Extension module */ +#include "stm32f0xx_hal_tim_ex.h" + +/* Exported functions --------------------------------------------------------*/ + +/* Time Base functions ********************************************************/ +HAL_StatusTypeDef HAL_TIM_Base_Init(TIM_HandleTypeDef *htim); +HAL_StatusTypeDef HAL_TIM_Base_DeInit(TIM_HandleTypeDef *htim); +void HAL_TIM_Base_MspInit(TIM_HandleTypeDef *htim); +void HAL_TIM_Base_MspDeInit(TIM_HandleTypeDef *htim); +/* Blocking mode: Polling */ +HAL_StatusTypeDef HAL_TIM_Base_Start(TIM_HandleTypeDef *htim); +HAL_StatusTypeDef HAL_TIM_Base_Stop(TIM_HandleTypeDef *htim); +/* Non-Blocking mode: Interrupt */ +HAL_StatusTypeDef HAL_TIM_Base_Start_IT(TIM_HandleTypeDef *htim); +HAL_StatusTypeDef HAL_TIM_Base_Stop_IT(TIM_HandleTypeDef *htim); +/* Non-Blocking mode: DMA */ +HAL_StatusTypeDef HAL_TIM_Base_Start_DMA(TIM_HandleTypeDef *htim, uint32_t *pData, uint16_t Length); +HAL_StatusTypeDef HAL_TIM_Base_Stop_DMA(TIM_HandleTypeDef *htim); + +/* Timer Output Compare functions **********************************************/ +HAL_StatusTypeDef HAL_TIM_OC_Init(TIM_HandleTypeDef *htim); +HAL_StatusTypeDef HAL_TIM_OC_DeInit(TIM_HandleTypeDef *htim); +void HAL_TIM_OC_MspInit(TIM_HandleTypeDef *htim); +void HAL_TIM_OC_MspDeInit(TIM_HandleTypeDef *htim); +/* Blocking mode: Polling */ +HAL_StatusTypeDef HAL_TIM_OC_Start(TIM_HandleTypeDef *htim, uint32_t Channel); +HAL_StatusTypeDef HAL_TIM_OC_Stop(TIM_HandleTypeDef *htim, uint32_t Channel); +/* Non-Blocking mode: Interrupt */ +HAL_StatusTypeDef HAL_TIM_OC_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel); +HAL_StatusTypeDef HAL_TIM_OC_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channel); +/* Non-Blocking mode: DMA */ +HAL_StatusTypeDef HAL_TIM_OC_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel, uint32_t *pData, uint16_t Length); +HAL_StatusTypeDef HAL_TIM_OC_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel); + +/* Timer PWM functions *********************************************************/ +HAL_StatusTypeDef HAL_TIM_PWM_Init(TIM_HandleTypeDef *htim); +HAL_StatusTypeDef HAL_TIM_PWM_DeInit(TIM_HandleTypeDef *htim); +void HAL_TIM_PWM_MspInit(TIM_HandleTypeDef *htim); +void HAL_TIM_PWM_MspDeInit(TIM_HandleTypeDef *htim); +/* Blocking mode: Polling */ +HAL_StatusTypeDef HAL_TIM_PWM_Start(TIM_HandleTypeDef *htim, uint32_t Channel); +HAL_StatusTypeDef HAL_TIM_PWM_Stop(TIM_HandleTypeDef *htim, uint32_t Channel); +/* Non-Blocking mode: Interrupt */ +HAL_StatusTypeDef HAL_TIM_PWM_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel); +HAL_StatusTypeDef HAL_TIM_PWM_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channel); +/* Non-Blocking mode: DMA */ +HAL_StatusTypeDef HAL_TIM_PWM_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel, uint32_t *pData, uint16_t Length); +HAL_StatusTypeDef HAL_TIM_PWM_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel); + +/* Timer Input Capture functions ***********************************************/ +HAL_StatusTypeDef HAL_TIM_IC_Init(TIM_HandleTypeDef *htim); +HAL_StatusTypeDef HAL_TIM_IC_DeInit(TIM_HandleTypeDef *htim); +void HAL_TIM_IC_MspInit(TIM_HandleTypeDef *htim); +void HAL_TIM_IC_MspDeInit(TIM_HandleTypeDef *htim); +/* Blocking mode: Polling */ +HAL_StatusTypeDef HAL_TIM_IC_Start(TIM_HandleTypeDef *htim, uint32_t Channel); +HAL_StatusTypeDef HAL_TIM_IC_Stop(TIM_HandleTypeDef *htim, uint32_t Channel); +/* Non-Blocking mode: Interrupt */ +HAL_StatusTypeDef HAL_TIM_IC_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel); +HAL_StatusTypeDef HAL_TIM_IC_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channel); +/* Non-Blocking mode: DMA */ +HAL_StatusTypeDef HAL_TIM_IC_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel, uint32_t *pData, uint16_t Length); +HAL_StatusTypeDef HAL_TIM_IC_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel); + +/* Timer One Pulse functions ***************************************************/ +HAL_StatusTypeDef HAL_TIM_OnePulse_Init(TIM_HandleTypeDef *htim, uint32_t OnePulseMode); +HAL_StatusTypeDef HAL_TIM_OnePulse_DeInit(TIM_HandleTypeDef *htim); +void HAL_TIM_OnePulse_MspInit(TIM_HandleTypeDef *htim); +void HAL_TIM_OnePulse_MspDeInit(TIM_HandleTypeDef *htim); +/* Blocking mode: Polling */ +HAL_StatusTypeDef HAL_TIM_OnePulse_Start(TIM_HandleTypeDef *htim, uint32_t OutputChannel); +HAL_StatusTypeDef HAL_TIM_OnePulse_Stop(TIM_HandleTypeDef *htim, uint32_t OutputChannel); +/* Non-Blocking mode: Interrupt */ +HAL_StatusTypeDef HAL_TIM_OnePulse_Start_IT(TIM_HandleTypeDef *htim, uint32_t OutputChannel); +HAL_StatusTypeDef HAL_TIM_OnePulse_Stop_IT(TIM_HandleTypeDef *htim, uint32_t OutputChannel); + +/* Timer Encoder functions *****************************************************/ +HAL_StatusTypeDef HAL_TIM_Encoder_Init(TIM_HandleTypeDef *htim, TIM_Encoder_InitTypeDef* sConfig); +HAL_StatusTypeDef HAL_TIM_Encoder_DeInit(TIM_HandleTypeDef *htim); + + + + + + + +void HAL_TIM_Encoder_MspInit(TIM_HandleTypeDef *htim); +void HAL_TIM_Encoder_MspDeInit(TIM_HandleTypeDef *htim); + /* Blocking mode: Polling */ +HAL_StatusTypeDef HAL_TIM_Encoder_Start(TIM_HandleTypeDef *htim, uint32_t Channel); +HAL_StatusTypeDef HAL_TIM_Encoder_Stop(TIM_HandleTypeDef *htim, uint32_t Channel); +/* Non-Blocking mode: Interrupt */ +HAL_StatusTypeDef HAL_TIM_Encoder_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel); +HAL_StatusTypeDef HAL_TIM_Encoder_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channel); +/* Non-Blocking mode: DMA */ +HAL_StatusTypeDef HAL_TIM_Encoder_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel, uint32_t *pData1, uint32_t *pData2, uint16_t Length); +HAL_StatusTypeDef HAL_TIM_Encoder_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel); + +/* Interrupt Handler functions **********************************************/ +void HAL_TIM_IRQHandler(TIM_HandleTypeDef *htim); + +/* Control functions *********************************************************/ +HAL_StatusTypeDef HAL_TIM_OC_ConfigChannel(TIM_HandleTypeDef *htim, TIM_OC_InitTypeDef* sConfig, uint32_t Channel); +HAL_StatusTypeDef HAL_TIM_PWM_ConfigChannel(TIM_HandleTypeDef *htim, TIM_OC_InitTypeDef* sConfig, uint32_t Channel); +HAL_StatusTypeDef HAL_TIM_IC_ConfigChannel(TIM_HandleTypeDef *htim, TIM_IC_InitTypeDef* sConfig, uint32_t Channel); +HAL_StatusTypeDef HAL_TIM_OnePulse_ConfigChannel(TIM_HandleTypeDef *htim, TIM_OnePulse_InitTypeDef* sConfig, uint32_t OutputChannel, uint32_t InputChannel); +HAL_StatusTypeDef HAL_TIM_ConfigOCrefClear(TIM_HandleTypeDef *htim, TIM_ClearInputConfigTypeDef * sClearInputConfig, uint32_t Channel); +HAL_StatusTypeDef HAL_TIM_ConfigClockSource(TIM_HandleTypeDef *htim, TIM_ClockConfigTypeDef * sClockSourceConfig); +HAL_StatusTypeDef HAL_TIM_ConfigTI1Input(TIM_HandleTypeDef *htim, uint32_t TI1_Selection); +HAL_StatusTypeDef HAL_TIM_SlaveConfigSynchronization(TIM_HandleTypeDef *htim, TIM_SlaveConfigTypeDef * sSlaveConfig); +HAL_StatusTypeDef HAL_TIM_DMABurst_WriteStart(TIM_HandleTypeDef *htim, uint32_t BurstBaseAddress, uint32_t BurstRequestSrc, \ + uint32_t *BurstBuffer, uint32_t BurstLength); +HAL_StatusTypeDef HAL_TIM_DMABurst_WriteStop(TIM_HandleTypeDef *htim, uint32_t BurstRequestSrc); +HAL_StatusTypeDef HAL_TIM_DMABurst_ReadStart(TIM_HandleTypeDef *htim, uint32_t BurstBaseAddress, uint32_t BurstRequestSrc, \ + uint32_t *BurstBuffer, uint32_t BurstLength); +HAL_StatusTypeDef HAL_TIM_DMABurst_ReadStop(TIM_HandleTypeDef *htim, uint32_t BurstRequestSrc); +HAL_StatusTypeDef HAL_TIM_GenerateEvent(TIM_HandleTypeDef *htim, uint32_t EventSource); +uint32_t HAL_TIM_ReadCapturedValue(TIM_HandleTypeDef *htim, uint32_t Channel); + +/* Callback in non blocking modes (Interrupt and DMA) *************************/ +void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim); +void HAL_TIM_OC_DelayElapsedCallback(TIM_HandleTypeDef *htim); +void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef *htim); +void HAL_TIM_PWM_PulseFinishedCallback(TIM_HandleTypeDef *htim); +void HAL_TIM_TriggerCallback(TIM_HandleTypeDef *htim); +void HAL_TIM_ErrorCallback(TIM_HandleTypeDef *htim); + +/* Peripheral State functions **************************************************/ +HAL_TIM_StateTypeDef HAL_TIM_Base_GetState(TIM_HandleTypeDef *htim); +HAL_TIM_StateTypeDef HAL_TIM_OC_GetState(TIM_HandleTypeDef *htim); +HAL_TIM_StateTypeDef HAL_TIM_PWM_GetState(TIM_HandleTypeDef *htim); +HAL_TIM_StateTypeDef HAL_TIM_IC_GetState(TIM_HandleTypeDef *htim); +HAL_TIM_StateTypeDef HAL_TIM_OnePulse_GetState(TIM_HandleTypeDef *htim); +HAL_TIM_StateTypeDef HAL_TIM_Encoder_GetState(TIM_HandleTypeDef *htim); + +void TIM_Base_SetConfig(TIM_TypeDef *TIMx, TIM_Base_InitTypeDef *Structure); +void TIM_TI1_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICSelection, uint32_t TIM_ICFilter); +void TIM_OC2_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config); +void HAL_TIM_DMADelayPulseCplt(DMA_HandleTypeDef *hdma); +void HAL_TIM_DMAError(DMA_HandleTypeDef *hdma); +void HAL_TIM_DMACaptureCplt(DMA_HandleTypeDef *hdma); +void TIM_CCxChannelCmd(TIM_TypeDef* TIMx, uint32_t Channel, uint32_t ChannelState); + + + + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __STM32F0xx_HAL_TIM_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_tim_ex.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_tim_ex.c new file mode 100644 index 0000000000..f3a6e667c7 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_tim_ex.c @@ -0,0 +1,1801 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_tim_ex.c + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief TIM HAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the Timer extension peripheral: + * + Time Hall Sensor Interface Initialization + * + Time Hall Sensor Interface Start + * + Time Complementary signal bread and dead time configuration + * + Time Master and Slave synchronization configuration + * + Timer remapping capabilities configuration + @verbatim + ============================================================================== + ##### TIMER Extended features ##### + ============================================================================== + [..] + The Timer Extension features include: + (#) Complementary outputs with programmable dead-time for : + (++) Output Compare + (++) PWM generation (Edge and Center-aligned Mode) + (++) One-pulse mode output + (#) Synchronization circuit to control the timer with external signals and to + interconnect several timers together. + (#) Break input to put the timer output signals in reset state or in a known state. + (#) Supports incremental (quadrature) encoder and hall-sensor circuitry for + positioning purposes + + ##### How to use this driver ##### + ============================================================================== + [..] + (#) Initialize the TIM low level resources by implementing the following functions + depending from feature used : + (++) Complementary Output Compare : HAL_TIM_OC_MspInit() + (++) Complementary PWM generation : HAL_TIM_PWM_MspInit() + (++) Complementary One-pulse mode output : HAL_TIM_OnePulse_MspInit() + (++) Hall Sensor output : HAL_TIM_HallSensor_MspInit() + + (#) Initialize the TIM low level resources : + (##) Enable the TIM interface clock using __TIMx_CLK_ENABLE(); + (##) TIM pins configuration + (+++) Enable the clock for the TIM GPIOs using the following function: + __GPIOx_CLK_ENABLE(); + (+++) Configure these TIM pins in Alternate function mode using HAL_GPIO_Init(); + + (#) The external Clock can be configured, if needed (the default clock is the + internal clock from the APBx), using the following function: + HAL_TIM_ConfigClockSource, the clock configuration should be done before + any start function. + + (#) Configure the TIM in the desired functioning mode using one of the + initialization function of this driver: + (++) HAL_TIMEx_HallSensor_Init and HAL_TIMEx_ConfigCommutationEvent: to use the + Timer Hall Sensor Interface and the commutation event with the corresponding + Interrupt and DMA request if needed (Note that One Timer is used to interface + with the Hall sensor Interface and another Timer should be used to use + the commutation event). + + (#) Activate the TIM peripheral using one of the start functions: + (++) Complementary Output Compare : HAL_TIMEx_OCN_Start(), HAL_TIMEx_OCN_Start_DMA(), HAL_TIMEx_OC_Start_IT() + (++) Complementary PWM generation : HAL_TIMEx_PWMN_Start(), HAL_TIMEx_PWMN_Start_DMA(), HAL_TIMEx_PWMN_Start_IT() + (++) Complementary One-pulse mode output : HAL_TIMEx_OnePulseN_Start(), HAL_TIMEx_OnePulseN_Start_IT() + (++) Hall Sensor output : HAL_TIMEx_HallSensor_Start(), HAL_TIMEx_HallSensor_Start_DMA(), HAL_TIMEx_HallSensor_Start_IT(). + + + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** +*/ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @defgroup TIMEx + * @brief TIM HAL module driver + * @{ + */ + +#ifdef HAL_TIM_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +static void TIM_CCxNChannelCmd(TIM_TypeDef* TIMx, uint32_t Channel, uint32_t ChannelNState); + +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup TIMEx_Private_Functions + * @{ + */ + +/** @defgroup TIMEx_Group1 Timer Hall Sensor functions + * @brief Timer Hall Sensor functions + * +@verbatim + ============================================================================== + ##### Timer Hall Sensor functions ##### + ============================================================================== + [..] + This section provides functions allowing to: + (+) Initialize and configure TIM HAL Sensor. + (+) De-initialize TIM HAL Sensor. + (+) Start the Hall Sensor Interface. + (+) Stop the Hall Sensor Interface. + (+) Start the Hall Sensor Interface and enable interrupts. + (+) Stop the Hall Sensor Interface and disable interrupts. + (+) Start the Hall Sensor Interface and enable DMA transfers. + (+) Stop the Hall Sensor Interface and disable DMA transfers. + +@endverbatim + * @{ + */ +/** + * @brief Initializes the TIM Hall Sensor Interface and create the associated handle. + * @param htim: TIM Encoder Interface handle + * @param sConfig: TIM Hall Sensor configuration structure + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIMEx_HallSensor_Init(TIM_HandleTypeDef *htim, TIM_HallSensor_InitTypeDef* sConfig) +{ + TIM_OC_InitTypeDef OC_Config; + + /* Check the TIM handle allocation */ + if(htim == NULL) + { + return HAL_ERROR; + } + + assert_param(IS_TIM_XOR_INSTANCE(htim->Instance)); + assert_param(IS_TIM_COUNTER_MODE(htim->Init.CounterMode)); + assert_param(IS_TIM_CLOCKDIVISION_DIV(htim->Init.ClockDivision)); + assert_param(IS_TIM_IC_POLARITY(sConfig->IC1Polarity)); + assert_param(IS_TIM_IC_PRESCALER(sConfig->IC1Prescaler)); + assert_param(IS_TIM_IC_FILTER(sConfig->IC1Filter)); + + /* Set the TIM state */ + htim->State= HAL_TIM_STATE_BUSY; + + /* Init the low level hardware : GPIO, CLOCK, NVIC and DMA */ + HAL_TIMEx_HallSensor_MspInit(htim); + + /* Configure the Time base in the Encoder Mode */ + TIM_Base_SetConfig(htim->Instance, &htim->Init); + + /* Configure the Channel 1 as Input Channel to interface with the three Outputs of the Hall sensor */ + TIM_TI1_SetConfig(htim->Instance, sConfig->IC1Polarity, TIM_ICSELECTION_TRC, sConfig->IC1Filter); + + /* Reset the IC1PSC Bits */ + htim->Instance->CCMR1 &= (uint16_t)(~TIM_CCMR1_IC1PSC); + /* Set the IC1PSC value */ + htim->Instance->CCMR1 |= sConfig->IC1Prescaler; + + /* Enable the Hall sensor interface (XOR function of the three inputs) */ + htim->Instance->CR2 |= TIM_CR2_TI1S; + + /* Select the TIM_TS_TI1F_ED signal as Input trigger for the TIM */ + htim->Instance->SMCR &= (uint16_t)(~TIM_SMCR_TS); + htim->Instance->SMCR |= TIM_TS_TI1F_ED; + + /* Use the TIM_TS_TI1F_ED signal to reset the TIM counter each edge detection */ + htim->Instance->SMCR &= (uint16_t)(~TIM_SMCR_SMS); + htim->Instance->SMCR |= TIM_SLAVEMODE_RESET; + + /* Program channel 2 in PWM 2 mode with the desired Commutation_Delay*/ + OC_Config.OCFastMode = TIM_OCFAST_DISABLE; + OC_Config.OCIdleState = TIM_OCIDLESTATE_RESET; + OC_Config.OCMode = TIM_OCMODE_PWM2; + OC_Config.OCNIdleState = TIM_OCNIDLESTATE_RESET; + OC_Config.OCNPolarity = TIM_OCNPOLARITY_HIGH; + OC_Config.OCPolarity = TIM_OCPOLARITY_HIGH; + OC_Config.Pulse = sConfig->Commutation_Delay; + + TIM_OC2_SetConfig(htim->Instance, &OC_Config); + + /* Select OC2REF as trigger output on TRGO: write the MMS bits in the TIMx_CR2 + register to 101 */ + htim->Instance->CR2 &= (uint16_t)(~TIM_CR2_MMS); + htim->Instance->CR2 |= TIM_TRGO_OC2REF; + + /* Initialize the TIM state*/ + htim->State= HAL_TIM_STATE_READY; + + return HAL_OK; +} + +/** + * @brief DeInitializes the TIM Hall Sensor interface + * @param htim: TIM Hall Sensor handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIMEx_HallSensor_DeInit(TIM_HandleTypeDef *htim) +{ + /* Check the parameters */ + assert_param(IS_TIM_INSTANCE(htim->Instance)); + + htim->State = HAL_TIM_STATE_BUSY; + + /* Disable the TIM Peripheral Clock */ + __HAL_TIM_DISABLE(htim); + + /* DeInit the low level hardware: GPIO, CLOCK, NVIC */ + HAL_TIMEx_HallSensor_MspDeInit(htim); + + /* Change TIM state */ + htim->State = HAL_TIM_STATE_RESET; + + /* Release Lock */ + __HAL_UNLOCK(htim); + + return HAL_OK; +} + +/** + * @brief Initializes the TIM Hall Sensor MSP. + * @param htim: TIM handle + * @retval None + */ +__weak void HAL_TIMEx_HallSensor_MspInit(TIM_HandleTypeDef *htim) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_TIMEx_HallSensor_MspInit could be implemented in the user file + */ +} + +/** + * @brief DeInitializes TIM Hall Sensor MSP. + * @param htim: TIM handle + * @retval None + */ +__weak void HAL_TIMEx_HallSensor_MspDeInit(TIM_HandleTypeDef *htim) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_TIMEx_HallSensor_MspDeInit could be implemented in the user file + */ +} + +/** + * @brief Starts the TIM Hall Sensor Interface. + * @param htim : TIM Hall Sensor handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIMEx_HallSensor_Start(TIM_HandleTypeDef *htim) +{ + /* Check the parameters */ + assert_param(IS_TIM_XOR_INSTANCE(htim->Instance)); + + /* Enable the Input Capture channels 1 + (in the Hall Sensor Interface the Three possible channels that can be used are TIM_CHANNEL_1, TIM_CHANNEL_2 and TIM_CHANNEL_3) */ + TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_ENABLE); + + /* Enable the Peripheral */ + __HAL_TIM_ENABLE(htim); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the TIM Hall sensor Interface. + * @param htim : TIM Hall Sensor handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIMEx_HallSensor_Stop(TIM_HandleTypeDef *htim) +{ + /* Check the parameters */ + assert_param(IS_TIM_XOR_INSTANCE(htim->Instance)); + + /* Disable the Input Capture channels 1, 2 and 3 + (in the Hall Sensor Interface the Three possible channels that can be used are TIM_CHANNEL_1, TIM_CHANNEL_2 and TIM_CHANNEL_3) */ + TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_DISABLE); + + /* Disable the Peripheral */ + __HAL_TIM_DISABLE(htim); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Starts the TIM Hall Sensor Interface in interrupt mode. + * @param htim : TIM Hall Sensor handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIMEx_HallSensor_Start_IT(TIM_HandleTypeDef *htim) +{ + /* Check the parameters */ + assert_param(IS_TIM_XOR_INSTANCE(htim->Instance)); + + /* Enable the capture compare Interrupts 1 event */ + __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC1); + + /* Enable the Input Capture channels 1 + (in the Hall Sensor Interface the Three possible channels that can be used are TIM_CHANNEL_1, TIM_CHANNEL_2 and TIM_CHANNEL_3) */ + TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_ENABLE); + + /* Enable the Peripheral */ + __HAL_TIM_ENABLE(htim); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the TIM Hall Sensor Interface in interrupt mode. + * @param htim : TIM handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIMEx_HallSensor_Stop_IT(TIM_HandleTypeDef *htim) +{ + /* Check the parameters */ + assert_param(IS_TIM_XOR_INSTANCE(htim->Instance)); + + /* Disable the Input Capture channels 1 + (in the Hall Sensor Interface the Three possible channels that can be used are TIM_CHANNEL_1, TIM_CHANNEL_2 and TIM_CHANNEL_3) */ + TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_DISABLE); + + /* Disable the capture compare Interrupts event */ + __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC1); + + /* Disable the Peripheral */ + __HAL_TIM_DISABLE(htim); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Starts the TIM Hall Sensor Interface in DMA mode. + * @param htim : TIM Hall Sensor handle + * @param pData: The destination Buffer address. + * @param Length: The length of data to be transferred from TIM peripheral to memory. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIMEx_HallSensor_Start_DMA(TIM_HandleTypeDef *htim, uint32_t *pData, uint16_t Length) +{ + /* Check the parameters */ + assert_param(IS_TIM_XOR_INSTANCE(htim->Instance)); + + if((htim->State == HAL_TIM_STATE_BUSY)) + { + return HAL_BUSY; + } + else if((htim->State == HAL_TIM_STATE_READY)) + { + if(((uint32_t)pData == 0 ) && (Length > 0)) + { + return HAL_ERROR; + } + else + { + htim->State = HAL_TIM_STATE_BUSY; + } + } + /* Enable the Input Capture channels 1 + (in the Hall Sensor Interface the Three possible channels that can be used are TIM_CHANNEL_1, TIM_CHANNEL_2 and TIM_CHANNEL_3) */ + TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_ENABLE); + + /* Set the DMA Input Capture 1 Callback */ + htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = HAL_TIM_DMACaptureCplt; + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = HAL_TIM_DMAError ; + + /* Enable the DMA channel for Capture 1*/ + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)&htim->Instance->CCR1, (uint32_t)pData, Length); + + /* Enable the capture compare 1 Interrupt */ + __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC1); + + /* Enable the Peripheral */ + __HAL_TIM_ENABLE(htim); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the TIM Hall Sensor Interface in DMA mode. + * @param htim : TIM handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIMEx_HallSensor_Stop_DMA(TIM_HandleTypeDef *htim) +{ + /* Check the parameters */ + assert_param(IS_TIM_XOR_INSTANCE(htim->Instance)); + + /* Disable the Input Capture channels 1 + (in the Hall Sensor Interface the Three possible channels that can be used are TIM_CHANNEL_1, TIM_CHANNEL_2 and TIM_CHANNEL_3) */ + TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_DISABLE); + + + /* Disable the capture compare Interrupts 1 event */ + __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC1); + + /* Disable the Peripheral */ + __HAL_TIM_DISABLE(htim); + + /* Return function status */ + return HAL_OK; +} + +/** + * @} + */ + +/** @defgroup TIMEx_Group2 Timer Complementary Output Compare functions + * @brief Timer Complementary Output Compare functions + * +@verbatim + ============================================================================== + ##### Timer Complementary Output Compare functions ##### + ============================================================================== + [..] + This section provides functions allowing to: + (+) Start the Complementary Output Compare/PWM. + (+) Stop the Complementary Output Compare/PWM. + (+) Start the Complementary Output Compare/PWM and enable interrupts. + (+) Stop the Complementary Output Compare/PWM and disable interrupts. + (+) Start the Complementary Output Compare/PWM and enable DMA transfers. + (+) Stop the Complementary Output Compare/PWM and disable DMA transfers. + +@endverbatim + * @{ + */ + +/** + * @brief Starts the TIM Output Compare signal generation on the complementary + * output. + * @param htim : TIM Output Compare handle + * @param Channel : TIM Channel to be enabled + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @arg TIM_CHANNEL_3: TIM Channel 3 selected + * @arg TIM_CHANNEL_4: TIM Channel 4 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIMEx_OCN_Start(TIM_HandleTypeDef *htim, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, Channel)); + + /* Enable the Capture compare channel N */ + TIM_CCxNChannelCmd(htim->Instance, Channel, TIM_CCxN_ENABLE); + + /* Enable the Main Ouput */ + __HAL_TIM_MOE_ENABLE(htim); + + /* Enable the Peripheral */ + __HAL_TIM_ENABLE(htim); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the TIM Output Compare signal generation on the complementary + * output. + * @param htim : TIM handle + * @param Channel : TIM Channel to be disabled + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @arg TIM_CHANNEL_3: TIM Channel 3 selected + * @arg TIM_CHANNEL_4: TIM Channel 4 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIMEx_OCN_Stop(TIM_HandleTypeDef *htim, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, Channel)); + + /* Disable the Capture compare channel N */ + TIM_CCxNChannelCmd(htim->Instance, Channel, TIM_CCxN_DISABLE); + + /* Disable the Main Ouput */ + __HAL_TIM_MOE_DISABLE(htim); + + /* Disable the Peripheral */ + __HAL_TIM_DISABLE(htim); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Starts the TIM Output Compare signal generation in interrupt mode + * on the complementary output. + * @param htim : TIM OC handle + * @param Channel : TIM Channel to be enabled + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @arg TIM_CHANNEL_3: TIM Channel 3 selected + * @arg TIM_CHANNEL_4: TIM Channel 4 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIMEx_OCN_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, Channel)); + + switch (Channel) + { + case TIM_CHANNEL_1: + { + /* Enable the TIM Output Compare interrupt */ + __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC1); + } + break; + + case TIM_CHANNEL_2: + { + /* Enable the TIM Output Compare interrupt */ + __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC2); + } + break; + + case TIM_CHANNEL_3: + { + /* Enable the TIM Output Compare interrupt */ + __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC3); + } + break; + + case TIM_CHANNEL_4: + { + /* Enable the TIM Output Compare interrupt */ + __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC4); + } + break; + + default: + break; + } + + /* Enable the Capture compare channel N */ + TIM_CCxNChannelCmd(htim->Instance, Channel, TIM_CCxN_ENABLE); + + /* Enable the Main Ouput */ + __HAL_TIM_MOE_ENABLE(htim); + + /* Enable the Peripheral */ + __HAL_TIM_ENABLE(htim); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the TIM Output Compare signal generation in interrupt mode + * on the complementary output. + * @param htim : TIM Output Compare handle + * @param Channel : TIM Channel to be disabled + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @arg TIM_CHANNEL_3: TIM Channel 3 selected + * @arg TIM_CHANNEL_4: TIM Channel 4 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIMEx_OCN_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, Channel)); + + switch (Channel) + { + case TIM_CHANNEL_1: + { + /* Disable the TIM Output Compare interrupt */ + __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC1); + } + break; + + case TIM_CHANNEL_2: + { + /* Disable the TIM Output Compare interrupt */ + __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC2); + } + break; + + case TIM_CHANNEL_3: + { + /* Disable the TIM Output Compare interrupt */ + __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC3); + } + break; + + case TIM_CHANNEL_4: + { + /* Disable the TIM Output Compare interrupt */ + __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC4); + } + break; + + default: + break; + } + + /* Disable the Capture compare channel N */ + TIM_CCxNChannelCmd(htim->Instance, Channel, TIM_CCxN_DISABLE); + + /* Disable the Main Ouput */ + __HAL_TIM_MOE_DISABLE(htim); + + /* Disable the Peripheral */ + __HAL_TIM_DISABLE(htim); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Starts the TIM Output Compare signal generation in DMA mode + * on the complementary output. + * @param htim : TIM Output Compare handle + * @param Channel : TIM Channel to be enabled + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @arg TIM_CHANNEL_3: TIM Channel 3 selected + * @arg TIM_CHANNEL_4: TIM Channel 4 selected + * @param pData: The source Buffer address. + * @param Length: The length of data to be transferred from memory to TIM peripheral + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIMEx_OCN_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel, uint32_t *pData, uint16_t Length) +{ + /* Check the parameters */ + assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, Channel)); + + if((htim->State == HAL_TIM_STATE_BUSY)) + { + return HAL_BUSY; + } + else if((htim->State == HAL_TIM_STATE_READY)) + { + if(((uint32_t)pData == 0 ) && (Length > 0)) + { + return HAL_ERROR; + } + else + { + htim->State = HAL_TIM_STATE_BUSY; + } + } + switch (Channel) + { + case TIM_CHANNEL_1: + { + /* Set the DMA Period elapsed callback */ + htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = HAL_TIM_DMADelayPulseCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = HAL_TIM_DMAError ; + + /* Enable the DMA channel */ + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)pData, (uint32_t)&htim->Instance->CCR1, Length); + + /* Enable the TIM Output Compare DMA request */ + __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC1); + } + break; + + case TIM_CHANNEL_2: + { + /* Set the DMA Period elapsed callback */ + htim->hdma[TIM_DMA_ID_CC2]->XferCpltCallback = HAL_TIM_DMADelayPulseCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC2]->XferErrorCallback = HAL_TIM_DMAError ; + + /* Enable the DMA channel */ + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)pData, (uint32_t)&htim->Instance->CCR2, Length); + + /* Enable the TIM Output Compare DMA request */ + __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC2); + } + break; + + case TIM_CHANNEL_3: +{ + /* Set the DMA Period elapsed callback */ + htim->hdma[TIM_DMA_ID_CC3]->XferCpltCallback = HAL_TIM_DMADelayPulseCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC3]->XferErrorCallback = HAL_TIM_DMAError ; + + /* Enable the DMA channel */ + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC3], (uint32_t)pData, (uint32_t)&htim->Instance->CCR3,Length); + + /* Enable the TIM Output Compare DMA request */ + __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC3); + } + break; + + case TIM_CHANNEL_4: + { + /* Set the DMA Period elapsed callback */ + htim->hdma[TIM_DMA_ID_CC4]->XferCpltCallback = HAL_TIM_DMADelayPulseCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC4]->XferErrorCallback = HAL_TIM_DMAError ; + + /* Enable the DMA channel */ + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC4], (uint32_t)pData, (uint32_t)&htim->Instance->CCR4, Length); + + /* Enable the TIM Output Compare DMA request */ + __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC4); + } + break; + + default: + break; + } + + /* Enable the Capture compare channel N */ + TIM_CCxNChannelCmd(htim->Instance, Channel, TIM_CCxN_ENABLE); + + /* Enable the Main Ouput */ + __HAL_TIM_MOE_ENABLE(htim); + + /* Enable the Peripheral */ + __HAL_TIM_ENABLE(htim); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the TIM Output Compare signal generation in DMA mode + * on the complementary output. + * @param htim : TIM Output Compare handle + * @param Channel : TIM Channel to be disabled + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @arg TIM_CHANNEL_3: TIM Channel 3 selected + * @arg TIM_CHANNEL_4: TIM Channel 4 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIMEx_OCN_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, Channel)); + + switch (Channel) + { + case TIM_CHANNEL_1: + { + /* Disable the TIM Output Compare DMA request */ + __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC1); + } + break; + + case TIM_CHANNEL_2: + { + /* Disable the TIM Output Compare DMA request */ + __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC2); + } + break; + + case TIM_CHANNEL_3: + { + /* Disable the TIM Output Compare DMA request */ + __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC3); + } + break; + + case TIM_CHANNEL_4: + { + /* Disable the TIM Output Compare interrupt */ + __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC4); + } + break; + + default: + break; + } + + /* Disable the Capture compare channel N */ + TIM_CCxNChannelCmd(htim->Instance, Channel, TIM_CCxN_DISABLE); + + /* Disable the Main Ouput */ + __HAL_TIM_MOE_DISABLE(htim); + + /* Disable the Peripheral */ + __HAL_TIM_DISABLE(htim); + + /* Change the htim state */ + htim->State = HAL_TIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @} + */ + +/** @defgroup TIMEx_Group3 Timer Complementary PWM functions + * @brief Timer Complementary PWM functions + * +@verbatim + ============================================================================== + ##### Timer Complementary PWM functions ##### + ============================================================================== + [..] + This section provides functions allowing to: + (+) Start the Complementary PWM. + (+) Stop the Complementary PWM. + (+) Start the Complementary PWM and enable interrupts. + (+) Stop the Complementary PWM and disable interrupts. + (+) Start the Complementary PWM and enable DMA transfers. + (+) Stop the Complementary PWM and disable DMA transfers. + (+) Start the Complementary Input Capture measurement. + (+) Stop the Complementary Input Capture. + (+) Start the Complementary Input Capture and enable interrupts. + (+) Stop the Complementary Input Capture and disable interrupts. + (+) Start the Complementary Input Capture and enable DMA transfers. + (+) Stop the Complementary Input Capture and disable DMA transfers. + (+) Start the Complementary One Pulse generation. + (+) Stop the Complementary One Pulse. + (+) Start the Complementary One Pulse and enable interrupts. + (+) Stop the Complementary One Pulse and disable interrupts. + +@endverbatim + * @{ + */ + +/** + * @brief Starts the PWM signal generation on the complementary output. + * @param htim : TIM handle + * @param Channel : TIM Channel to be enabled + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @arg TIM_CHANNEL_3: TIM Channel 3 selected + * @arg TIM_CHANNEL_4: TIM Channel 4 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIMEx_PWMN_Start(TIM_HandleTypeDef *htim, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, Channel)); + + /* Enable the complementary PWM output */ + TIM_CCxNChannelCmd(htim->Instance, Channel, TIM_CCxN_ENABLE); + + /* Enable the Main Ouput */ + __HAL_TIM_MOE_ENABLE(htim); + + /* Enable the Peripheral */ + __HAL_TIM_ENABLE(htim); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the PWM signal generation on the complementary output. + * @param htim : TIM handle + * @param Channel : TIM Channel to be disabled + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @arg TIM_CHANNEL_3: TIM Channel 3 selected + * @arg TIM_CHANNEL_4: TIM Channel 4 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIMEx_PWMN_Stop(TIM_HandleTypeDef *htim, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, Channel)); + + /* Disable the complementary PWM output */ + TIM_CCxNChannelCmd(htim->Instance, Channel, TIM_CCxN_DISABLE); + + /* Disable the Main Ouput */ + __HAL_TIM_MOE_DISABLE(htim); + + /* Disable the Peripheral */ + __HAL_TIM_DISABLE(htim); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Starts the PWM signal generation in interrupt mode on the + * complementary output. + * @param htim : TIM handle + * @param Channel : TIM Channel to be disabled + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @arg TIM_CHANNEL_3: TIM Channel 3 selected + * @arg TIM_CHANNEL_4: TIM Channel 4 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIMEx_PWMN_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, Channel)); + + switch (Channel) + { + case TIM_CHANNEL_1: + { + /* Enable the TIM Capture/Compare 1 interrupt */ + __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC1); + } + break; + + case TIM_CHANNEL_2: + { + /* Enable the TIM Capture/Compare 2 interrupt */ + __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC2); + } + break; + + case TIM_CHANNEL_3: + { + /* Enable the TIM Capture/Compare 3 interrupt */ + __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC3); + } + break; + + case TIM_CHANNEL_4: + { + /* Enable the TIM Capture/Compare 4 interrupt */ + __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC4); + } + break; + + default: + break; + } + + /* Enable the TIM Break interrupt */ + __HAL_TIM_ENABLE_IT(htim, TIM_IT_BREAK); + + /* Enable the complementary PWM output */ + TIM_CCxNChannelCmd(htim->Instance, Channel, TIM_CCxN_ENABLE); + + /* Enable the Main Ouput */ + __HAL_TIM_MOE_ENABLE(htim); + + /* Enable the Peripheral */ + __HAL_TIM_ENABLE(htim); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the PWM signal generation in interrupt mode on the + * complementary output. + * @param htim : TIM handle + * @param Channel : TIM Channel to be disabled + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @arg TIM_CHANNEL_3: TIM Channel 3 selected + * @arg TIM_CHANNEL_4: TIM Channel 4 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIMEx_PWMN_Stop_IT (TIM_HandleTypeDef *htim, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, Channel)); + + switch (Channel) + { + case TIM_CHANNEL_1: + { + /* Disable the TIM Capture/Compare 1 interrupt */ + __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC1); + } + break; + + case TIM_CHANNEL_2: + { + /* Disable the TIM Capture/Compare 2 interrupt */ + __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC2); + } + break; + + case TIM_CHANNEL_3: + { + /* Disable the TIM Capture/Compare 3 interrupt */ + __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC3); + } + break; + + case TIM_CHANNEL_4: + { + /* Disable the TIM Capture/Compare 3 interrupt */ + __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC4); + } + break; + + default: + break; + } + + /* Disable the TIM Break interrupt */ + __HAL_TIM_DISABLE_IT(htim, TIM_IT_BREAK); + + /* Disable the complementary PWM output */ + TIM_CCxNChannelCmd(htim->Instance, Channel, TIM_CCxN_DISABLE); + + /* Disable the Main Ouput */ + __HAL_TIM_MOE_DISABLE(htim); + + /* Disable the Peripheral */ + __HAL_TIM_DISABLE(htim); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Starts the TIM PWM signal generation in DMA mode on the + * complementary output + * @param htim : TIM handle + * @param Channel : TIM Channel to be enabled + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @arg TIM_CHANNEL_3: TIM Channel 3 selected + * @arg TIM_CHANNEL_4: TIM Channel 4 selected + * @param pData: The source Buffer address. + * @param Length: The length of data to be transferred from memory to TIM peripheral + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIMEx_PWMN_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel, uint32_t *pData, uint16_t Length) +{ + /* Check the parameters */ + assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, Channel)); + + if((htim->State == HAL_TIM_STATE_BUSY)) + { + return HAL_BUSY; + } + else if((htim->State == HAL_TIM_STATE_READY)) + { + if(((uint32_t)pData == 0 ) && (Length > 0)) + { + return HAL_ERROR; + } + else + { + htim->State = HAL_TIM_STATE_BUSY; + } + } + switch (Channel) + { + case TIM_CHANNEL_1: + { + /* Set the DMA Period elapsed callback */ + htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = HAL_TIM_DMADelayPulseCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = HAL_TIM_DMAError ; + + /* Enable the DMA channel */ + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)pData, (uint32_t)&htim->Instance->CCR1, Length); + + /* Enable the TIM Capture/Compare 1 DMA request */ + __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC1); + } + break; + + case TIM_CHANNEL_2: + { + /* Set the DMA Period elapsed callback */ + htim->hdma[TIM_DMA_ID_CC2]->XferCpltCallback = HAL_TIM_DMADelayPulseCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC2]->XferErrorCallback = HAL_TIM_DMAError ; + + /* Enable the DMA channel */ + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)pData, (uint32_t)&htim->Instance->CCR2, Length); + + /* Enable the TIM Capture/Compare 2 DMA request */ + __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC2); + } + break; + + case TIM_CHANNEL_3: + { + /* Set the DMA Period elapsed callback */ + htim->hdma[TIM_DMA_ID_CC3]->XferCpltCallback = HAL_TIM_DMADelayPulseCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC3]->XferErrorCallback = HAL_TIM_DMAError ; + + /* Enable the DMA channel */ + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC3], (uint32_t)pData, (uint32_t)&htim->Instance->CCR3,Length); + + /* Enable the TIM Capture/Compare 3 DMA request */ + __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC3); + } + break; + + case TIM_CHANNEL_4: + { + /* Set the DMA Period elapsed callback */ + htim->hdma[TIM_DMA_ID_CC4]->XferCpltCallback = HAL_TIM_DMADelayPulseCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC4]->XferErrorCallback = HAL_TIM_DMAError ; + + /* Enable the DMA channel */ + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC4], (uint32_t)pData, (uint32_t)&htim->Instance->CCR4, Length); + + /* Enable the TIM Capture/Compare 4 DMA request */ + __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC4); + } + break; + + default: + break; + } + + /* Enable the complementary PWM output */ + TIM_CCxNChannelCmd(htim->Instance, Channel, TIM_CCxN_ENABLE); + + /* Enable the Main Ouput */ + __HAL_TIM_MOE_ENABLE(htim); + + /* Enable the Peripheral */ + __HAL_TIM_ENABLE(htim); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the TIM PWM signal generation in DMA mode on the complementary + * output + * @param htim : TIM handle + * @param Channel : TIM Channel to be disabled + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @arg TIM_CHANNEL_3: TIM Channel 3 selected + * @arg TIM_CHANNEL_4: TIM Channel 4 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIMEx_PWMN_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, Channel)); + + switch (Channel) + { + case TIM_CHANNEL_1: + { + /* Disable the TIM Capture/Compare 1 DMA request */ + __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC1); + } + break; + + case TIM_CHANNEL_2: + { + /* Disable the TIM Capture/Compare 2 DMA request */ + __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC2); + } + break; + + case TIM_CHANNEL_3: + { + /* Disable the TIM Capture/Compare 3 DMA request */ + __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC3); + } + break; + + case TIM_CHANNEL_4: + { + /* Disable the TIM Capture/Compare 4 DMA request */ + __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC4); + } + break; + + default: + break; + } + + /* Disable the complementary PWM output */ + TIM_CCxNChannelCmd(htim->Instance, Channel, TIM_CCxN_DISABLE); + + /* Disable the Main Ouput */ + __HAL_TIM_MOE_DISABLE(htim); + + /* Disable the Peripheral */ + __HAL_TIM_DISABLE(htim); + + /* Change the htim state */ + htim->State = HAL_TIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @} + */ + +/** @defgroup TIMEx_Group4 Timer Complementary One Pulse functions + * @brief Timer Complementary One Pulse functions + * +@verbatim + ============================================================================== + ##### Timer Complementary One Pulse functions ##### + ============================================================================== + [..] + This section provides functions allowing to: + (+) Start the Complementary One Pulse generation. + (+) Stop the Complementary One Pulse. + (+) Start the Complementary One Pulse and enable interrupts. + (+) Stop the Complementary One Pulse and disable interrupts. + +@endverbatim + * @{ + */ + +/** + * @brief Starts the TIM One Pulse signal generation on the complemetary + * output. + * @param htim : TIM One Pulse handle + * @param OutputChannel : TIM Channel to be enabled + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIMEx_OnePulseN_Start(TIM_HandleTypeDef *htim, uint32_t OutputChannel) + { + /* Check the parameters */ + assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, OutputChannel)); + + /* Enable the complementary One Pulse output */ + TIM_CCxNChannelCmd(htim->Instance, OutputChannel, TIM_CCxN_ENABLE); + + /* Enable the Main Ouput */ + __HAL_TIM_MOE_ENABLE(htim); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the TIM One Pulse signal generation on the complementary + * output. + * @param htim : TIM One Pulse handle + * @param OutputChannel : TIM Channel to be disabled + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIMEx_OnePulseN_Stop(TIM_HandleTypeDef *htim, uint32_t OutputChannel) +{ + + /* Check the parameters */ + assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, OutputChannel)); + + /* Disable the complementary One Pulse output */ + TIM_CCxNChannelCmd(htim->Instance, OutputChannel, TIM_CCxN_DISABLE); + + /* Disable the Main Ouput */ + __HAL_TIM_MOE_DISABLE(htim); + + /* Disable the Peripheral */ + __HAL_TIM_DISABLE(htim); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Starts the TIM One Pulse signal generation in interrupt mode on the + * complementary channel. + * @param htim : TIM One Pulse handle + * @param OutputChannel : TIM Channel to be enabled + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIMEx_OnePulseN_Start_IT(TIM_HandleTypeDef *htim, uint32_t OutputChannel) +{ + /* Check the parameters */ + assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, OutputChannel)); + + /* Enable the TIM Capture/Compare 1 interrupt */ + __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC1); + + /* Enable the TIM Capture/Compare 2 interrupt */ + __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC2); + + /* Enable the complementary One Pulse output */ + TIM_CCxNChannelCmd(htim->Instance, OutputChannel, TIM_CCxN_ENABLE); + + /* Enable the Main Ouput */ + __HAL_TIM_MOE_ENABLE(htim); + + /* Return function status */ + return HAL_OK; + } + +/** + * @brief Stops the TIM One Pulse signal generation in interrupt mode on the + * complementary channel. + * @param htim : TIM One Pulse handle + * @param OutputChannel : TIM Channel to be disabled + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIMEx_OnePulseN_Stop_IT(TIM_HandleTypeDef *htim, uint32_t OutputChannel) +{ + /* Check the parameters */ + assert_param(IS_TIM_CCXN_INSTANCE(htim->Instance, OutputChannel)); + + /* Disable the TIM Capture/Compare 1 interrupt */ + __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC1); + + /* Disable the TIM Capture/Compare 2 interrupt */ + __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC2); + + /* Disable the complementary One Pulse output */ + TIM_CCxNChannelCmd(htim->Instance, OutputChannel, TIM_CCxN_DISABLE); + + /* Disable the Main Ouput */ + __HAL_TIM_MOE_DISABLE(htim); + + /* Disable the Peripheral */ + __HAL_TIM_DISABLE(htim); + + /* Return function status */ + return HAL_OK; +} + + + +/** + * @} + */ +/** @defgroup TIMEx_Group5 Peripheral Control functions + * @brief Peripheral Control functions + * +@verbatim + ============================================================================== + ##### Peripheral Control functions ##### + ============================================================================== + [..] + This section provides functions allowing to: + (+) Configure the commutation event in case of use of the Hall sensor interface. + (+) Configure Complementary channels, break features and dead time. + (+) Configure Master synchronization. + (+) Configure timer remapping capabilities. + +@endverbatim + * @{ + */ +/** + * @brief Configure the TIM commutation event sequence. + * @note: this function is mandatory to use the commutation event in order to + * update the configuration at each commutation detection on the TRGI input of the Timer, + * the typical use of this feature is with the use of another Timer(interface Timer) + * configured in Hall sensor interface, this interface Timer will generate the + * commutation at its TRGO output (connected to Timer used in this function) each time + * the TI1 of the Interface Timer detect a commutation at its input TI1. + * @param htim: TIM handle + * @param InputTrigger : the Internal trigger corresponding to the Timer Interfacing with the Hall sensor + * This parameter can be one of the following values: + * @arg TIM_TS_ITR0: Internal trigger 0 selected + * @arg TIM_TS_ITR1: Internal trigger 1 selected + * @arg TIM_TS_ITR2: Internal trigger 2 selected + * @arg TIM_TS_ITR3: Internal trigger 3 selected + * @arg TIM_TS_NONE: No trigger is needed + * @param CommutationSource : the Commutation Event source + * This parameter can be one of the following values: + * @arg TIM_COMMUTATION_TRGI: Commutation source is the TRGI of the Interface Timer + * @arg TIM_COMMUTATION_SOFTWARE: Commutation source is set by software using the COMG bit + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIMEx_ConfigCommutationEvent(TIM_HandleTypeDef *htim, uint32_t InputTrigger, uint32_t CommutationSource) +{ + /* Check the parameters */ + assert_param(IS_TIM_COMMUTATION_EVENT_INSTANCE(htim->Instance)); + assert_param(IS_TIM_INTERNAL_TRIGGEREVENT_SELECTION(InputTrigger)); + + __HAL_LOCK(htim); + + if ((InputTrigger == TIM_TS_ITR0) || (InputTrigger == TIM_TS_ITR1) || + (InputTrigger == TIM_TS_ITR2) || (InputTrigger == TIM_TS_ITR3)) + { + /* Select the Input trigger */ + htim->Instance->SMCR &= (uint16_t)(~TIM_SMCR_TS); + htim->Instance->SMCR |= InputTrigger; + } + + /* Select the Capture Compare preload feature */ + htim->Instance->CR2 |= TIM_CR2_CCPC; + /* Select the Commutation event source */ + htim->Instance->CR2 &= (uint16_t)(~TIM_CR2_CCUS); + htim->Instance->CR2 |= CommutationSource; + + __HAL_UNLOCK(htim); + + return HAL_OK; +} + +/** + * @brief Configure the TIM commutation event sequence with interrupt. + * @note: this function is mandatory to use the commutation event in order to + * update the configuration at each commutation detection on the TRGI input of the Timer, + * the typical use of this feature is with the use of another Timer(interface Timer) + * configured in Hall sensor interface, this interface Timer will generate the + * commutation at its TRGO output (connected to Timer used in this function) each time + * the TI1 of the Interface Timer detect a commutation at its input TI1. + * @param htim: TIM handle + * @param InputTrigger : the Internal trigger corresponding to the Timer Interfacing with the Hall sensor + * This parameter can be one of the following values: + * @arg TIM_TS_ITR0: Internal trigger 0 selected + * @arg TIM_TS_ITR1: Internal trigger 1 selected + * @arg TIM_TS_ITR2: Internal trigger 2 selected + * @arg TIM_TS_ITR3: Internal trigger 3 selected + * @arg TIM_TS_NONE: No trigger is needed + * @param CommutationSource : the Commutation Event source + * This parameter can be one of the following values: + * @arg TIM_COMMUTATION_TRGI: Commutation source is the TRGI of the Interface Timer + * @arg TIM_COMMUTATION_SOFTWARE: Commutation source is set by software using the COMG bit + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIMEx_ConfigCommutationEvent_IT(TIM_HandleTypeDef *htim, uint32_t InputTrigger, uint32_t CommutationSource) +{ + /* Check the parameters */ + assert_param(IS_TIM_COMMUTATION_EVENT_INSTANCE(htim->Instance)); + assert_param(IS_TIM_INTERNAL_TRIGGEREVENT_SELECTION(InputTrigger)); + + __HAL_LOCK(htim); + + if ((InputTrigger == TIM_TS_ITR0) || (InputTrigger == TIM_TS_ITR1) || + (InputTrigger == TIM_TS_ITR2) || (InputTrigger == TIM_TS_ITR3)) + { + /* Select the Input trigger */ + htim->Instance->SMCR &= (uint16_t)(~TIM_SMCR_TS); + htim->Instance->SMCR |= InputTrigger; + } + + /* Select the Capture Compare preload feature */ + htim->Instance->CR2 |= TIM_CR2_CCPC; + /* Select the Commutation event source */ + htim->Instance->CR2 &= (uint16_t)(~TIM_CR2_CCUS); + htim->Instance->CR2 |= CommutationSource; + + /* Enable the Commutation Interrupt Request */ + __HAL_TIM_ENABLE_IT(htim, TIM_IT_COM); + + __HAL_UNLOCK(htim); + + return HAL_OK; +} + +/** + * @brief Configure the TIM commutation event sequence with DMA. + * @note: this function is mandatory to use the commutation event in order to + * update the configuration at each commutation detection on the TRGI input of the Timer, + * the typical use of this feature is with the use of another Timer(interface Timer) + * configured in Hall sensor interface, this interface Timer will generate the + * commutation at its TRGO output (connected to Timer used in this function) each time + * the TI1 of the Interface Timer detect a commutation at its input TI1. + * @note: The user should configure the DMA in his own software, in This function only the COMDE bit is set + * @param htim: TIM handle + * @param InputTrigger : the Internal trigger corresponding to the Timer Interfacing with the Hall sensor + * This parameter can be one of the following values: + * @arg TIM_TS_ITR0: Internal trigger 0 selected + * @arg TIM_TS_ITR1: Internal trigger 1 selected + * @arg TIM_TS_ITR2: Internal trigger 2 selected + * @arg TIM_TS_ITR3: Internal trigger 3 selected + * @arg TIM_TS_NONE: No trigger is needed + * @param CommutationSource : the Commutation Event source + * This parameter can be one of the following values: + * @arg TIM_COMMUTATION_TRGI: Commutation source is the TRGI of the Interface Timer + * @arg TIM_COMMUTATION_SOFTWARE: Commutation source is set by software using the COMG bit + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIMEx_ConfigCommutationEvent_DMA(TIM_HandleTypeDef *htim, uint32_t InputTrigger, uint32_t CommutationSource) +{ + /* Check the parameters */ + assert_param(IS_TIM_COMMUTATION_EVENT_INSTANCE(htim->Instance)); + assert_param(IS_TIM_INTERNAL_TRIGGEREVENT_SELECTION(InputTrigger)); + + __HAL_LOCK(htim); + + if ((InputTrigger == TIM_TS_ITR0) || (InputTrigger == TIM_TS_ITR1) || + (InputTrigger == TIM_TS_ITR2) || (InputTrigger == TIM_TS_ITR3)) + { + /* Select the Input trigger */ + htim->Instance->SMCR &= (uint16_t)(~TIM_SMCR_TS); + htim->Instance->SMCR |= InputTrigger; + } + + /* Select the Capture Compare preload feature */ + htim->Instance->CR2 |= TIM_CR2_CCPC; + /* Select the Commutation event source */ + htim->Instance->CR2 &= (uint16_t)(~TIM_CR2_CCUS); + htim->Instance->CR2 |= CommutationSource; + + /* Enable the Commutation DMA Request */ + /* Set the DMA Commutation Callback */ + htim->hdma[TIM_DMA_ID_COMMUTATION]->XferCpltCallback = HAL_TIMEx_DMACommutationCplt; + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_COMMUTATION]->XferErrorCallback = HAL_TIM_DMAError; + + /* Enable the Commutation DMA Request */ + __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_COM); + + __HAL_UNLOCK(htim); + + return HAL_OK; +} + +/** + * @brief Configures the TIM in master mode. + * @param htim: TIM handle. + * @param sMasterConfig: pointer to a TIM_MasterConfigTypeDef structure that + * contains the selected trigger output (TRGO) and the Master/Slave + * mode. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIMEx_MasterConfigSynchronization(TIM_HandleTypeDef *htim, TIM_MasterConfigTypeDef * sMasterConfig) +{ + /* Check the parameters */ + assert_param(IS_TIM_MASTER_INSTANCE(htim->Instance)); + assert_param(IS_TIM_TRGO_SOURCE(sMasterConfig->MasterOutputTrigger)); + assert_param(IS_TIM_MSM_STATE(sMasterConfig->MasterSlaveMode)); + + __HAL_LOCK(htim); + + htim->State = HAL_TIM_STATE_BUSY; + + /* Reset the MMS Bits */ + htim->Instance->CR2 &= (uint16_t)(~TIM_CR2_MMS); + /* Select the TRGO source */ + htim->Instance->CR2 |= sMasterConfig->MasterOutputTrigger; + + /* Reset the MSM Bit */ + htim->Instance->SMCR &= (uint16_t)(~TIM_SMCR_MSM); + /* Set or Reset the MSM Bit */ + htim->Instance->SMCR |= sMasterConfig->MasterSlaveMode; + + htim->State = HAL_TIM_STATE_READY; + + __HAL_UNLOCK(htim); + + return HAL_OK; +} + +/** + * @brief Configures the Break feature, dead time, Lock level, OSSI/OSSR State + * and the AOE(automatic output enable). + * @param htim: TIM handle + * @param sBreakDeadTimeConfig: pointer to a TIM_ConfigBreakDeadConfigTypeDef structure that + * contains the BDTR Register configuration information for the TIM peripheral. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIMEx_ConfigBreakDeadTime(TIM_HandleTypeDef *htim, + TIM_BreakDeadTimeConfigTypeDef *sBreakDeadTimeConfig) +{ + /* Check the parameters */ + assert_param(IS_TIM_BREAK_INSTANCE(htim->Instance)); + assert_param(IS_TIM_OSSR_STATE(sBreakDeadTimeConfig->OffStateRunMode)); + assert_param(IS_TIM_OSSI_STATE(sBreakDeadTimeConfig->OffStateIDLEMode)); + assert_param(IS_TIM_LOCK_LEVEL(sBreakDeadTimeConfig->LockLevel)); + assert_param(IS_TIM_BREAK_STATE(sBreakDeadTimeConfig->BreakState)); + assert_param(IS_TIM_BREAK_POLARITY(sBreakDeadTimeConfig->BreakPolarity)); + assert_param(IS_TIM_AUTOMATIC_OUTPUT_STATE(sBreakDeadTimeConfig->AutomaticOutput)); + + /* Process Locked */ + __HAL_LOCK(htim); + + htim->State = HAL_TIM_STATE_BUSY; + + /* Set the Lock level, the Break enable Bit and the Polarity, the OSSR State, + the OSSI State, the dead time value and the Automatic Output Enable Bit */ + htim->Instance->BDTR = (uint32_t)sBreakDeadTimeConfig->OffStateRunMode | + sBreakDeadTimeConfig->OffStateIDLEMode | + sBreakDeadTimeConfig->LockLevel | + sBreakDeadTimeConfig->DeadTime | + sBreakDeadTimeConfig->BreakState | + sBreakDeadTimeConfig->BreakPolarity | + sBreakDeadTimeConfig->AutomaticOutput; + + + htim->State = HAL_TIM_STATE_READY; + + __HAL_UNLOCK(htim); + + return HAL_OK; +} + +/** + * @brief Configures the TIM14 Remapping input capabilities. + * @param htim: TIM handle. + * @param Remap: specifies the TIM remapping source. + * This parameter can be one of the following values: + * @arg TIM_TIM14_GPIO: TIM14 TI1 is connected to GPIO + * @arg TIM_TIM14_RTC: TIM14 TI1 is connected to RTC_clock + * @arg TIM_TIM14_HSE: TIM14 TI1 is connected to HSE/32 + * @arg TIM_TIM14_MCO: TIM14 TI1 is connected to MCO + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIMEx_RemapConfig(TIM_HandleTypeDef *htim, uint32_t Remap) +{ + __HAL_LOCK(htim); + + /* Check parameters */ + assert_param(IS_TIM_REMAP_INSTANCE(htim->Instance)); + assert_param(IS_TIM_REMAP(Remap)); + + /* Set the Timer remapping configuration */ + htim->Instance->OR = Remap; + + htim->State = HAL_TIM_STATE_READY; + + __HAL_UNLOCK(htim); + + return HAL_OK; +} + +/** + * @} + */ + +/** @defgroup TIMEx_Group6 Extension Callbacks functions + * @brief Extension Callbacks functions + * +@verbatim + ============================================================================== + ##### Extension Callbacks functions ##### + ============================================================================== + [..] + This section provides Extension TIM callback functions: + (+) Timer Commutation callback + (+) Timer Break callback + +@endverbatim + * @{ + */ + +/** + * @brief Hall commutation changed callback in non blocking mode + * @param htim : TIM handle + * @retval None + */ +__weak void HAL_TIMEx_CommutationCallback(TIM_HandleTypeDef *htim) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_TIMEx_CommutationCallback could be implemented in the user file + */ +} + +/** + * @brief Hall Break detection callback in non blocking mode + * @param htim : TIM handle + * @retval None + */ +__weak void HAL_TIMEx_BreakCallback(TIM_HandleTypeDef *htim) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_TIMEx_BreakCallback could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup TIMEx_Group7 Extension Peripheral State functions + * @brief Extension Peripheral State functions + * +@verbatim + ============================================================================== + ##### Extension Peripheral State functions ##### + ============================================================================== + [..] + This subsection permit to get in run-time the status of the peripheral + and the data flow. + +@endverbatim + * @{ + */ + +/** + * @brief Return the TIM Hall Sensor interface state + * @param htim: TIM Hall Sensor handle + * @retval HAL state + */ +HAL_TIM_StateTypeDef HAL_TIMEx_HallSensor_GetState(TIM_HandleTypeDef *htim) +{ + return htim->State; +} + +/** + * @} + */ + +/** + * @brief TIM DMA Commutation callback. + * @param hdma : pointer to DMA handle. + * @retval None + */ +void HAL_TIMEx_DMACommutationCplt(DMA_HandleTypeDef *hdma) +{ + TIM_HandleTypeDef* htim = ( TIM_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + + htim->State= HAL_TIM_STATE_READY; + + HAL_TIMEx_CommutationCallback(htim); +} + +/** + * @brief Enables or disables the TIM Capture Compare Channel xN. + * @param TIMx to select the TIM peripheral + * @param Channel: specifies the TIM Channel + * This parameter can be one of the following values: + * @arg TIM_Channel_1: TIM Channel 1 + * @arg TIM_Channel_2: TIM Channel 2 + * @arg TIM_Channel_3: TIM Channel 3 + * @param ChannelNState: specifies the TIM Channel CCxNE bit new state. + * This parameter can be: TIM_CCxN_ENABLE or TIM_CCxN_Disable. + * @retval None + */ +static void TIM_CCxNChannelCmd(TIM_TypeDef* TIMx, uint32_t Channel, uint32_t ChannelNState) +{ + uint32_t tmp = 0; + + tmp = (uint16_t)(TIM_CCER_CC1NE << Channel); + + /* Reset the CCxNE Bit */ + TIMx->CCER &= (uint16_t)(~tmp); + + /* Set or reset the CCxNE Bit */ + TIMx->CCER |= (uint16_t)(ChannelNState << Channel); +} + +/** + * @} + */ + +#endif /* HAL_TIM_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_tim_ex.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_tim_ex.h new file mode 100644 index 0000000000..cfaf43b2cb --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_tim_ex.h @@ -0,0 +1,222 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_tim_ex.h + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief Header file of TIM HAL Extension module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32F0xx_HAL_TIM_EX_H +#define __STM32F0xx_HAL_TIM_EX_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal_def.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @addtogroup TIMEx + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ + +/** + * @brief TIM Hall sensor Configuration Structure definition + */ + +typedef struct +{ + + uint32_t IC1Polarity; /*!< Specifies the active edge of the input signal. + This parameter can be a value of @ref TIM_Input_Capture_Polarity */ + + uint32_t IC1Prescaler; /*!< Specifies the Input Capture Prescaler. + This parameter can be a value of @ref TIM_Input_Capture_Prescaler */ + + uint32_t IC1Filter; /*!< Specifies the input capture filter. + This parameter can be a number between Min_Data = 0x0 and Max_Data = 0xF */ + uint32_t Commutation_Delay; /*!< Specifies the pulse value to be loaded into the Capture Compare Register. + This parameter can be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF */ +} TIM_HallSensor_InitTypeDef; + +/** + * @brief TIM Master configuration Structure definition + */ +typedef struct { + uint32_t MasterOutputTrigger; /*!< Trigger output (TRGO) selection + This parameter can be a value of @ref TIM_Master_Mode_Selection */ + uint32_t MasterSlaveMode; /*!< Master/slave mode selection + This parameter can be a value of @ref TIM_Master_Slave_Mode */ +}TIM_MasterConfigTypeDef; + +/** + * @brief TIM Break and Dead time configuration Structure definition + */ +typedef struct +{ + uint32_t OffStateRunMode; /*!< TIM off state in run mode + This parameter can be a value of @ref TIM_OSSR_Off_State_Selection_for_Run_mode_state */ + uint32_t OffStateIDLEMode; /*!< TIM off state in IDLE mode + This parameter can be a value of @ref TIM_OSSI_Off_State_Selection_for_Idle_mode_state */ + uint32_t LockLevel; /*!< TIM Lock level + This parameter can be a value of @ref TIM_Lock_level */ + uint32_t DeadTime; /*!< TIM dead Time + This parameter can be a number between Min_Data = 0x00 and Max_Data = 0xFF */ + uint32_t BreakState; /*!< TIM Break State + This parameter can be a value of @ref TIM_Break_Input_enable_disable */ + uint32_t BreakPolarity; /*!< TIM Break input polarity + This parameter can be a value of @ref TIM_Break_Polarity */ + uint32_t AutomaticOutput; /*!< TIM Automatic Output Enable state + This parameter can be a value of @ref TIM_AOE_Bit_Set_Reset */ +} TIM_BreakDeadTimeConfigTypeDef; + +/* Exported constants --------------------------------------------------------*/ +/** @defgroup TIMEx_Exported_Constants + * @{ + */ + +/** @defgroup TIMEx_Remap + * @{ + */ + +#define TIM_TIM14_GPIO (0x00000000) /* !< TIM14 TI1 is connected to GPIO */ +#define TIM_TIM14_RTC (0x00000001) /* !< TIM14 TI1 is connected to RTC_clock */ +#define TIM_TIM14_HSE (0x00000002) /* !< TIM14 TI1 is connected to HSE/32 */ +#define TIM_TIM14_MCO (0x00000003) /* !< TIM14 TI1 is connected to MCO */ + +#define IS_TIM_REMAP(TIM_REMAP) (((TIM_REMAP) == TIM_TIM14_GPIO) ||\ + ((TIM_REMAP) == TIM_TIM14_RTC) ||\ + ((TIM_REMAP) == TIM_TIM14_HSE) ||\ + ((TIM_REMAP) == TIM_TIM14_MCO)) + +/** + * @} + */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ + +/* Exported functions --------------------------------------------------------*/ + +/* Timer Hall Sensor functions **********************************************/ +HAL_StatusTypeDef HAL_TIMEx_HallSensor_Init(TIM_HandleTypeDef *htim, TIM_HallSensor_InitTypeDef* sConfig); +HAL_StatusTypeDef HAL_TIMEx_HallSensor_DeInit(TIM_HandleTypeDef *htim); + +void HAL_TIMEx_HallSensor_MspInit(TIM_HandleTypeDef *htim); +void HAL_TIMEx_HallSensor_MspDeInit(TIM_HandleTypeDef *htim); + + /* Blocking mode: Polling */ +HAL_StatusTypeDef HAL_TIMEx_HallSensor_Start(TIM_HandleTypeDef *htim); +HAL_StatusTypeDef HAL_TIMEx_HallSensor_Stop(TIM_HandleTypeDef *htim); +/* Non-Blocking mode: Interrupt */ +HAL_StatusTypeDef HAL_TIMEx_HallSensor_Start_IT(TIM_HandleTypeDef *htim); +HAL_StatusTypeDef HAL_TIMEx_HallSensor_Stop_IT(TIM_HandleTypeDef *htim); +/* Non-Blocking mode: DMA */ +HAL_StatusTypeDef HAL_TIMEx_HallSensor_Start_DMA(TIM_HandleTypeDef *htim, uint32_t *pData, uint16_t Length); +HAL_StatusTypeDef HAL_TIMEx_HallSensor_Stop_DMA(TIM_HandleTypeDef *htim); + +/* Timer Complementary Output Compare functions *****************************/ +/* Blocking mode: Polling */ +HAL_StatusTypeDef HAL_TIMEx_OCN_Start(TIM_HandleTypeDef *htim, uint32_t Channel); +HAL_StatusTypeDef HAL_TIMEx_OCN_Stop(TIM_HandleTypeDef *htim, uint32_t Channel); + +/* Non-Blocking mode: Interrupt */ +HAL_StatusTypeDef HAL_TIMEx_OCN_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel); +HAL_StatusTypeDef HAL_TIMEx_OCN_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channel); + +/* Non-Blocking mode: DMA */ +HAL_StatusTypeDef HAL_TIMEx_OCN_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel, uint32_t *pData, uint16_t Length); +HAL_StatusTypeDef HAL_TIMEx_OCN_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel); + +/* Timer Complementary PWM functions ****************************************/ +/* Blocking mode: Polling */ +HAL_StatusTypeDef HAL_TIMEx_PWMN_Start(TIM_HandleTypeDef *htim, uint32_t Channel); +HAL_StatusTypeDef HAL_TIMEx_PWMN_Stop(TIM_HandleTypeDef *htim, uint32_t Channel); + +/* Non-Blocking mode: Interrupt */ +HAL_StatusTypeDef HAL_TIMEx_PWMN_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel); +HAL_StatusTypeDef HAL_TIMEx_PWMN_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channel); +/* Non-Blocking mode: DMA */ +HAL_StatusTypeDef HAL_TIMEx_PWMN_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel, uint32_t *pData, uint16_t Length); +HAL_StatusTypeDef HAL_TIMEx_PWMN_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel); + +/* Timer Complementary One Pulse functions **********************************/ +/* Blocking mode: Polling */ +HAL_StatusTypeDef HAL_TIMEx_OnePulseN_Start(TIM_HandleTypeDef *htim, uint32_t OutputChannel); +HAL_StatusTypeDef HAL_TIMEx_OnePulseN_Stop(TIM_HandleTypeDef *htim, uint32_t OutputChannel); + +/* Non-Blocking mode: Interrupt */ +HAL_StatusTypeDef HAL_TIMEx_OnePulseN_Start_IT(TIM_HandleTypeDef *htim, uint32_t OutputChannel); +HAL_StatusTypeDef HAL_TIMEx_OnePulseN_Stop_IT(TIM_HandleTypeDef *htim, uint32_t OutputChannel); + +/* Extnsion Control functions ************************************************/ +HAL_StatusTypeDef HAL_TIMEx_ConfigCommutationEvent(TIM_HandleTypeDef *htim, uint32_t InputTrigger, uint32_t CommutationSource); +HAL_StatusTypeDef HAL_TIMEx_ConfigCommutationEvent_IT(TIM_HandleTypeDef *htim, uint32_t InputTrigger, uint32_t CommutationSource); +HAL_StatusTypeDef HAL_TIMEx_ConfigCommutationEvent_DMA(TIM_HandleTypeDef *htim, uint32_t InputTrigger, uint32_t CommutationSource); +HAL_StatusTypeDef HAL_TIMEx_MasterConfigSynchronization(TIM_HandleTypeDef *htim, TIM_MasterConfigTypeDef * sMasterConfig); +HAL_StatusTypeDef HAL_TIMEx_ConfigBreakDeadTime(TIM_HandleTypeDef *htim, TIM_BreakDeadTimeConfigTypeDef *sBreakDeadTimeConfig); +HAL_StatusTypeDef HAL_TIMEx_RemapConfig(TIM_HandleTypeDef *htim, uint32_t Remap); + +/* Extension Callback *********************************************************/ +void HAL_TIMEx_CommutationCallback(TIM_HandleTypeDef *htim); +void HAL_TIMEx_BreakCallback(TIM_HandleTypeDef *htim); +void HAL_TIMEx_DMACommutationCplt(DMA_HandleTypeDef *hdma); + +/* Extension Peripheral State functions **************************************/ +HAL_TIM_StateTypeDef HAL_TIMEx_HallSensor_GetState(TIM_HandleTypeDef *htim); + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + + +#endif /* __STM32F0xx_HAL_TIM_EX_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_tsc.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_tsc.c new file mode 100644 index 0000000000..b74b9a3d0e --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_tsc.c @@ -0,0 +1,774 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_tsc.c + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief This file provides firmware functions to manage the following + * functionalities of the Touch Sensing Controller (TSC) peripheral: + * + Initialization and DeInitialization + * + Channel IOs, Shield IOs and Sampling IOs configuration + * + Start and Stop an acquisition + * + Read acquisition result + * + Interrupts and flags management + * + @verbatim +================================================================================ + ##### TSC specific features ##### +================================================================================ + [..] + (#) Proven and robust surface charge transfer acquisition principle + + (#) Supports up to 3 capacitive sensing channels per group + + (#) Capacitive sensing channels can be acquired in parallel offering a very good + response time + + (#) Spread spectrum feature to improve system robustness in noisy environments + + (#) Full hardware management of the charge transfer acquisition sequence + + (#) Programmable charge transfer frequency + + (#) Programmable sampling capacitor I/O pin + + (#) Programmable channel I/O pin + + (#) Programmable max count value to avoid long acquisition when a channel is faulty + + (#) Dedicated end of acquisition and max count error flags with interrupt capability + + (#) One sampling capacitor for up to 3 capacitive sensing channels to reduce the system + components + + (#) Compatible with proximity, touchkey, linear and rotary touch sensor implementation + + + ##### How to use this driver ##### +================================================================================ + [..] + (#) Enable the TSC interface clock using __TSC_CLK_ENABLE() macro. + + (#) GPIO pins configuration + (++) Enable the clock for the TSC GPIOs using __GPIOx_CLK_ENABLE() macro. + (++) Configure the TSC pins used as sampling IOs in alternate function output Open-Drain mode, + and TSC pins used as channel/shield IOs in alternate function output Push-Pull mode + using HAL_GPIO_Init() function. + (++) Configure the alternate function on all the TSC pins using HAL_xxxx() function. + + (#) Interrupts configuration + (++) Configure the NVIC (if the interrupt model is used) using HAL_xxx() function. + + (#) TSC configuration + (++) Configure all TSC parameters and used TSC IOs using HAL_TSC_Init() function. + + *** Acquisition sequence *** + =================================== + [..] + (+) Discharge all IOs using HAL_TSC_IODischarge() function. + (+) Wait a certain time allowing a good discharge of all capacitors. This delay depends + of the sampling capacitor and electrodes design. + (+) Select the channel IOs to be acquired using HAL_TSC_IOConfig() function. + (+) Launch the acquisition using either HAL_TSC_Start() or HAL_TSC_Start_IT() function. + If the synchronized mode is selected, the acquisition will start as soon as the signal + is received on the synchro pin. + (+) Wait the end of acquisition using either HAL_TSC_PollForAcquisition() or + HAL_TSC_GetState() function or using WFI instruction for example. + (+) Check the group acquisition status using HAL_TSC_GroupGetStatus() function. + (+) Read the acquisition value using HAL_TSC_GroupGetValue() function. + + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @defgroup TSC + * @brief HAL TSC module driver + * @{ + */ + +#ifdef HAL_TSC_MODULE_ENABLED + +#if defined(STM32F051x8) || defined(STM32F071xB) || \ + defined(STM32F042x6) || defined(STM32F048xx) || defined(STM32F072xB) || \ + defined(STM32F058xx) || defined(STM32F078xx) + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +static uint32_t TSC_extract_groups(uint32_t iomask); +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup TSC_Private_Functions + * @{ + */ + +/** @defgroup TSC_Group1 Initialization/de-initialization functions + * @brief Initialization and Configuration functions + * +@verbatim + =============================================================================== + ##### Initialization and de-initialization functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Initialize and configure the TSC. + (+) De-initialize the TSC. +@endverbatim + * @{ + */ + +/** + * @brief Initializes the TSC peripheral according to the specified parameters + * in the TSC_InitTypeDef structure. + * @param htsc: TSC handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TSC_Init(TSC_HandleTypeDef* htsc) +{ + /* Check TSC handle allocation */ + if (htsc == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_TSC_ALL_INSTANCE(htsc->Instance)); + assert_param(IS_TSC_CTPH(htsc->Init.CTPulseHighLength)); + assert_param(IS_TSC_CTPL(htsc->Init.CTPulseLowLength)); + assert_param(IS_TSC_SS(htsc->Init.SpreadSpectrum)); + assert_param(IS_TSC_SSD(htsc->Init.SpreadSpectrumDeviation)); + assert_param(IS_TSC_SS_PRESC(htsc->Init.SpreadSpectrumPrescaler)); + assert_param(IS_TSC_PG_PRESC(htsc->Init.PulseGeneratorPrescaler)); + assert_param(IS_TSC_MCV(htsc->Init.MaxCountValue)); + assert_param(IS_TSC_IODEF(htsc->Init.IODefaultMode)); + assert_param(IS_TSC_SYNC_POL(htsc->Init.SynchroPinPolarity)); + assert_param(IS_TSC_ACQ_MODE(htsc->Init.AcquisitionMode)); + assert_param(IS_TSC_MCE_IT(htsc->Init.MaxCountInterrupt)); + + /* Initialize the TSC state */ + htsc->State = HAL_TSC_STATE_BUSY; + + /* Init the low level hardware : GPIO, CLOCK, CORTEX */ + HAL_TSC_MspInit(htsc); + + /*--------------------------------------------------------------------------*/ + /* Set TSC parameters */ + + /* Enable TSC */ + htsc->Instance->CR = TSC_CR_TSCE; + + /* Set all functions */ + htsc->Instance->CR |= (htsc->Init.CTPulseHighLength | + htsc->Init.CTPulseLowLength | + (uint32_t)(htsc->Init.SpreadSpectrumDeviation << 17) | + htsc->Init.SpreadSpectrumPrescaler | + htsc->Init.PulseGeneratorPrescaler | + htsc->Init.MaxCountValue | + htsc->Init.IODefaultMode | + htsc->Init.SynchroPinPolarity | + htsc->Init.AcquisitionMode); + + /* Spread spectrum */ + if (htsc->Init.SpreadSpectrum == ENABLE) + { + htsc->Instance->CR |= TSC_CR_SSE; + } + + /* Disable Schmitt trigger hysteresis on all used TSC IOs */ + htsc->Instance->IOHCR = (uint32_t)(~(htsc->Init.ChannelIOs | htsc->Init.ShieldIOs | htsc->Init.SamplingIOs)); + + /* Set channel and shield IOs */ + htsc->Instance->IOCCR = (htsc->Init.ChannelIOs | htsc->Init.ShieldIOs); + + /* Set sampling IOs */ + htsc->Instance->IOSCR = htsc->Init.SamplingIOs; + + /* Set the groups to be acquired */ + htsc->Instance->IOGCSR = TSC_extract_groups(htsc->Init.ChannelIOs); + + /* Clear interrupts */ + htsc->Instance->IER &= (uint32_t)(~(TSC_IT_EOA | TSC_IT_MCE)); + + /* Clear flags */ + htsc->Instance->ICR |= (TSC_FLAG_EOA | TSC_FLAG_MCE); + + /*--------------------------------------------------------------------------*/ + + /* Initialize the TSC state */ + htsc->State = HAL_TSC_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Deinitializes the TSC peripheral registers to their default reset values. + * @param htsc: TSC handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TSC_DeInit(TSC_HandleTypeDef* htsc) +{ + /* Check TSC handle allocation */ + if (htsc == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_TSC_ALL_INSTANCE(htsc->Instance)); + + /* Change TSC state */ + htsc->State = HAL_TSC_STATE_BUSY; + + /* DeInit the low level hardware */ + HAL_TSC_MspDeInit(htsc); + + /* Change TSC state */ + htsc->State = HAL_TSC_STATE_RESET; + + /* Process unlocked */ + __HAL_UNLOCK(htsc); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Initializes the TSC MSP. + * @param htsc: pointer to a TSC_HandleTypeDef structure that contains + * the configuration information for the specified TSC. + * @retval None + */ +__weak void HAL_TSC_MspInit(TSC_HandleTypeDef* htsc) +{ + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_TSC_MspInit could be implemented in the user file. + */ +} + +/** + * @brief DeInitializes the TSC MSP. + * @param htsc: pointer to a TSC_HandleTypeDef structure that contains + * the configuration information for the specified TSC. + * @retval None + */ +__weak void HAL_TSC_MspDeInit(TSC_HandleTypeDef* htsc) +{ + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_TSC_MspDeInit could be implemented in the user file. + */ +} + +/** + * @} + */ + +/** @defgroup HAL_TSC_Group2 IO operation functions + * @brief IO operation functions + * +@verbatim + =============================================================================== + ##### I/O Operation functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Start acquisition in polling mode. + (+) Start acquisition in interrupt mode. + (+) Stop conversion in polling mode. + (+) Stop conversion in interrupt mode. + (+) Get group acquisition status. + (+) Get group acquisition value. +@endverbatim + * @{ + */ + +/** + * @brief Starts the acquisition. + * @param htsc: pointer to a TSC_HandleTypeDef structure that contains + * the configuration information for the specified TSC. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TSC_Start(TSC_HandleTypeDef* htsc) +{ + /* Check the parameters */ + assert_param(IS_TSC_ALL_INSTANCE(htsc->Instance)); + + /* Process locked */ + __HAL_LOCK(htsc); + + /* Change TSC state */ + htsc->State = HAL_TSC_STATE_BUSY; + + /* Clear interrupts */ + __HAL_TSC_DISABLE_IT(htsc, (TSC_IT_EOA | TSC_IT_MCE)); + + /* Clear flags */ + __HAL_TSC_CLEAR_FLAG(htsc, (TSC_FLAG_EOA | TSC_FLAG_MCE)); + + /* Stop discharging the IOs */ + __HAL_TSC_SET_IODEF_INFLOAT(htsc); + + /* Launch the acquisition */ + __HAL_TSC_START_ACQ(htsc); + + /* Process unlocked */ + __HAL_UNLOCK(htsc); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Enables the interrupt and starts the acquisition + * @param htsc: pointer to a TSC_HandleTypeDef structure that contains + * the configuration information for the specified TSC. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_TSC_Start_IT(TSC_HandleTypeDef* htsc) +{ + /* Check the parameters */ + assert_param(IS_TSC_ALL_INSTANCE(htsc->Instance)); + assert_param(IS_TSC_MCE_IT(htsc->Init.MaxCountInterrupt)); + + /* Process locked */ + __HAL_LOCK(htsc); + + /* Change TSC state */ + htsc->State = HAL_TSC_STATE_BUSY; + + /* Enable end of acquisition interrupt */ + __HAL_TSC_ENABLE_IT(htsc, TSC_IT_EOA); + + /* Enable max count error interrupt (optional) */ + if (htsc->Init.MaxCountInterrupt == ENABLE) + { + __HAL_TSC_ENABLE_IT(htsc, TSC_IT_MCE); + } + else + { + __HAL_TSC_DISABLE_IT(htsc, TSC_IT_MCE); + } + + /* Clear flags */ + __HAL_TSC_CLEAR_FLAG(htsc, (TSC_FLAG_EOA | TSC_FLAG_MCE)); + + /* Stop discharging the IOs */ + __HAL_TSC_SET_IODEF_INFLOAT(htsc); + + /* Launch the acquisition */ + __HAL_TSC_START_ACQ(htsc); + + /* Process unlocked */ + __HAL_UNLOCK(htsc); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the acquisition previously launched in polling mode + * @param htsc: pointer to a TSC_HandleTypeDef structure that contains + * the configuration information for the specified TSC. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TSC_Stop(TSC_HandleTypeDef* htsc) +{ + /* Check the parameters */ + assert_param(IS_TSC_ALL_INSTANCE(htsc->Instance)); + + /* Process locked */ + __HAL_LOCK(htsc); + + /* Stop the acquisition */ + __HAL_TSC_STOP_ACQ(htsc); + + /* Clear flags */ + __HAL_TSC_CLEAR_FLAG(htsc, (TSC_FLAG_EOA | TSC_FLAG_MCE)); + + /* Change TSC state */ + htsc->State = HAL_TSC_STATE_READY; + + /* Process unlocked */ + __HAL_UNLOCK(htsc); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the acquisition previously launched in interrupt mode + * @param htsc: pointer to a TSC_HandleTypeDef structure that contains + * the configuration information for the specified TSC. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TSC_Stop_IT(TSC_HandleTypeDef* htsc) +{ + /* Check the parameters */ + assert_param(IS_TSC_ALL_INSTANCE(htsc->Instance)); + + /* Process locked */ + __HAL_LOCK(htsc); + + /* Stop the acquisition */ + __HAL_TSC_STOP_ACQ(htsc); + + /* Disable interrupts */ + __HAL_TSC_DISABLE_IT(htsc, (TSC_IT_EOA | TSC_IT_MCE)); + + /* Clear flags */ + __HAL_TSC_CLEAR_FLAG(htsc, (TSC_FLAG_EOA | TSC_FLAG_MCE)); + + /* Change TSC state */ + htsc->State = HAL_TSC_STATE_READY; + + /* Process unlocked */ + __HAL_UNLOCK(htsc); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Gets the acquisition status for a group + * @param htsc: pointer to a TSC_HandleTypeDef structure that contains + * the configuration information for the specified TSC. + * @param gx_index: Index of the group + * @retval Group status + */ +TSC_GroupStatusTypeDef HAL_TSC_GroupGetStatus(TSC_HandleTypeDef* htsc, uint32_t gx_index) +{ + /* Check the parameters */ + assert_param(IS_TSC_ALL_INSTANCE(htsc->Instance)); + assert_param(IS_GROUP_INDEX(gx_index)); + + /* Return the group status */ + return(__HAL_TSC_GET_GROUP_STATUS(htsc, gx_index)); +} + +/** + * @brief Gets the acquisition measure for a group + * @param htsc: pointer to a TSC_HandleTypeDef structure that contains + * the configuration information for the specified TSC. + * @param gx_index: Index of the group + * @retval Acquisition measure + */ +uint32_t HAL_TSC_GroupGetValue(TSC_HandleTypeDef* htsc, uint32_t gx_index) +{ + /* Check the parameters */ + assert_param(IS_TSC_ALL_INSTANCE(htsc->Instance)); + assert_param(IS_GROUP_INDEX(gx_index)); + + /* Return the group acquisition counter */ + return htsc->Instance->IOGXCR[gx_index]; +} + +/** + * @} + */ + +/** @defgroup HAL_TSC_Group3 Peripheral Control functions + * @brief Peripheral Control functions + * +@verbatim + =============================================================================== + ##### Peripheral Control functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Configure TSC IOs + (+) Discharge TSC IOs +@endverbatim + * @{ + */ + +/** + * @brief Configures TSC IOs + * @param htsc: pointer to a TSC_HandleTypeDef structure that contains + * the configuration information for the specified TSC. + * @param config: pointer to the configuration structure. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TSC_IOConfig(TSC_HandleTypeDef* htsc, TSC_IOConfigTypeDef* config) +{ + /* Check the parameters */ + assert_param(IS_TSC_ALL_INSTANCE(htsc->Instance)); + + /* Process locked */ + __HAL_LOCK(htsc); + + /* Stop acquisition */ + __HAL_TSC_STOP_ACQ(htsc); + + /* Disable Schmitt trigger hysteresis on all used TSC IOs */ + htsc->Instance->IOHCR = (uint32_t)(~(config->ChannelIOs | config->ShieldIOs | config->SamplingIOs)); + + /* Set channel and shield IOs */ + htsc->Instance->IOCCR = (config->ChannelIOs | config->ShieldIOs); + + /* Set sampling IOs */ + htsc->Instance->IOSCR = config->SamplingIOs; + + /* Set groups to be acquired */ + htsc->Instance->IOGCSR = TSC_extract_groups(config->ChannelIOs); + + /* Process unlocked */ + __HAL_UNLOCK(htsc); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Discharge TSC IOs + * @param htsc: pointer to a TSC_HandleTypeDef structure that contains + * the configuration information for the specified TSC. + * @param choice: enable or disable + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TSC_IODischarge(TSC_HandleTypeDef* htsc, uint32_t choice) +{ + /* Check the parameters */ + assert_param(IS_TSC_ALL_INSTANCE(htsc->Instance)); + + /* Process locked */ + __HAL_LOCK(htsc); + + if (choice == ENABLE) + { + __HAL_TSC_SET_IODEF_OUTPPLOW(htsc); + } + else + { + __HAL_TSC_SET_IODEF_INFLOAT(htsc); + } + + /* Process unlocked */ + __HAL_UNLOCK(htsc); + + /* Return the group acquisition counter */ + return HAL_OK; +} + +/** + * @} + */ + +/** @defgroup HAL_TSC_Group4 State functions + * @brief State functions + * +@verbatim + =============================================================================== + ##### State functions ##### + =============================================================================== + [..] + This subsection provides functions allowing to + (+) Get TSC state. + (+) Poll for acquisition completed. + (+) Handles TSC interrupt request. + +@endverbatim + * @{ + */ + +/** + * @brief Return the TSC state + * @param htsc: pointer to a TSC_HandleTypeDef structure that contains + * the configuration information for the specified TSC. + * @retval HAL state + */ +HAL_TSC_StateTypeDef HAL_TSC_GetState(TSC_HandleTypeDef* htsc) +{ + /* Check the parameters */ + assert_param(IS_TSC_ALL_INSTANCE(htsc->Instance)); + + if (htsc->State == HAL_TSC_STATE_BUSY) + { + /* Check end of acquisition flag */ + if (__HAL_TSC_GET_FLAG(htsc, TSC_FLAG_EOA) != RESET) + { + /* Check max count error flag */ + if (__HAL_TSC_GET_FLAG(htsc, TSC_FLAG_MCE) != RESET) + { + /* Change TSC state */ + htsc->State = HAL_TSC_STATE_ERROR; + } + else + { + /* Change TSC state */ + htsc->State = HAL_TSC_STATE_READY; + } + } + } + + /* Return TSC state */ + return htsc->State; +} + +/** + * @brief Start acquisition and wait until completion + * @note There is no need of a timeout parameter as the max count error is already + * managed by the TSC peripheral. + * @param htsc: pointer to a TSC_HandleTypeDef structure that contains + * the configuration information for the specified TSC. + * @retval HAL state + */ +HAL_StatusTypeDef HAL_TSC_PollForAcquisition(TSC_HandleTypeDef* htsc) +{ + /* Check the parameters */ + assert_param(IS_TSC_ALL_INSTANCE(htsc->Instance)); + + /* Process locked */ + __HAL_LOCK(htsc); + + /* Check end of acquisition */ + while (HAL_TSC_GetState(htsc) == HAL_TSC_STATE_BUSY) + { + /* The timeout (max count error) is managed by the TSC peripheral itself. */ + } + + /* Process unlocked */ + __HAL_UNLOCK(htsc); + + return HAL_OK; +} + +/** + * @brief Handles TSC interrupt request + * @param htsc: pointer to a TSC_HandleTypeDef structure that contains + * the configuration information for the specified TSC. + * @retval None + */ +void HAL_TSC_IRQHandler(TSC_HandleTypeDef* htsc) +{ + /* Check the parameters */ + assert_param(IS_TSC_ALL_INSTANCE(htsc->Instance)); + + /* Check if the end of acquisition occured */ + if (__HAL_TSC_GET_FLAG(htsc, TSC_FLAG_EOA) != RESET) + { + /* Clear EOA flag */ + __HAL_TSC_CLEAR_FLAG(htsc, TSC_FLAG_EOA); + } + + /* Check if max count error occured */ + if (__HAL_TSC_GET_FLAG(htsc, TSC_FLAG_MCE) != RESET) + { + /* Clear MCE flag */ + __HAL_TSC_CLEAR_FLAG(htsc, TSC_FLAG_MCE); + /* Change TSC state */ + htsc->State = HAL_TSC_STATE_ERROR; + /* Conversion completed callback */ + HAL_TSC_ErrorCallback(htsc); + } + else + { + /* Change TSC state */ + htsc->State = HAL_TSC_STATE_READY; + /* Conversion completed callback */ + HAL_TSC_ConvCpltCallback(htsc); + } +} + +/** + * @} + */ + +/** + * @brief Acquisition completed callback in non blocking mode + * @param htsc: pointer to a TSC_HandleTypeDef structure that contains + * the configuration information for the specified TSC. + * @retval None + */ +__weak void HAL_TSC_ConvCpltCallback(TSC_HandleTypeDef* htsc) +{ + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_TSC_ConvCpltCallback could be implemented in the user file. + */ +} + +/** + * @brief Error callback in non blocking mode + * @param htsc: pointer to a TSC_HandleTypeDef structure that contains + * the configuration information for the specified TSC. + * @retval None + */ +__weak void HAL_TSC_ErrorCallback(TSC_HandleTypeDef* htsc) +{ + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_TSC_ErrorCallback could be implemented in the user file. + */ +} + +/** + * @brief Utility function used to set the acquired groups mask + * @param iomask: Channels IOs mask + * @retval Acquired groups mask + */ +static uint32_t TSC_extract_groups(uint32_t iomask) +{ + uint32_t groups = 0; + uint32_t idx; + + for (idx = 0; idx < TSC_NB_OF_GROUPS; idx++) + { + if ((iomask & ((uint32_t)0x0F << (idx * 4))) != RESET) + { + groups |= ((uint32_t)1 << idx); + } + } + + return groups; +} + +/** + * @} + */ + +#endif /* defined(STM32F051x8) || defined(STM32F071xB) || */ + /* defined(STM32F042x6) || defined(STM32F048xx) || defined(STM32F072xB) || */ + /* defined(STM32F058xx) || defined(STM32F078xx) */ + +#endif /* HAL_TSC_MODULE_ENABLED */ + +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_tsc.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_tsc.h new file mode 100644 index 0000000000..644c7d8d3d --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_tsc.h @@ -0,0 +1,592 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_tsc.h + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief This file contains all the functions prototypes for the TSC firmware + * library. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32F0xx_TSC_H +#define __STM32F0xx_TSC_H + +#ifdef __cplusplus + extern "C" { +#endif + +#if defined(STM32F051x8) || defined(STM32F071xB) || \ + defined(STM32F042x6) || defined(STM32F048xx) || defined(STM32F072xB) || \ + defined(STM32F058xx) || defined(STM32F078xx) + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal_def.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @addtogroup TSC + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ + +/** + * @brief TSC state structure definition + */ +typedef enum +{ + HAL_TSC_STATE_RESET = 0x00, /*!< TSC registers have their reset value */ + HAL_TSC_STATE_READY = 0x01, /*!< TSC registers are initialized or acquisition is completed with success */ + HAL_TSC_STATE_BUSY = 0x02, /*!< TSC initialization or acquisition is on-going */ + HAL_TSC_STATE_ERROR = 0x03 /*!< Acquisition is completed with max count error */ +} HAL_TSC_StateTypeDef; + +/** + * @brief TSC group status structure definition + */ +typedef enum +{ + TSC_GROUP_ONGOING = 0x00, /*!< Acquisition on group is on-going or not started */ + TSC_GROUP_COMPLETED = 0x01 /*!< Acquisition on group is completed with success (no max count error) */ +} TSC_GroupStatusTypeDef; + +/** + * @brief TSC init structure definition + */ +typedef struct +{ + uint32_t CTPulseHighLength; /*!< Charge-transfer high pulse length */ + uint32_t CTPulseLowLength; /*!< Charge-transfer low pulse length */ + uint32_t SpreadSpectrum; /*!< Spread spectrum activation */ + uint32_t SpreadSpectrumDeviation; /*!< Spread spectrum deviation */ + uint32_t SpreadSpectrumPrescaler; /*!< Spread spectrum prescaler */ + uint32_t PulseGeneratorPrescaler; /*!< Pulse generator prescaler */ + uint32_t MaxCountValue; /*!< Max count value */ + uint32_t IODefaultMode; /*!< IO default mode */ + uint32_t SynchroPinPolarity; /*!< Synchro pin polarity */ + uint32_t AcquisitionMode; /*!< Acquisition mode */ + uint32_t MaxCountInterrupt; /*!< Max count interrupt activation */ + uint32_t ChannelIOs; /*!< Channel IOs mask */ + uint32_t ShieldIOs; /*!< Shield IOs mask */ + uint32_t SamplingIOs; /*!< Sampling IOs mask */ +} TSC_InitTypeDef; + +/** + * @brief TSC IOs configuration structure definition + */ +typedef struct +{ + uint32_t ChannelIOs; /*!< Channel IOs mask */ + uint32_t ShieldIOs; /*!< Shield IOs mask */ + uint32_t SamplingIOs; /*!< Sampling IOs mask */ +} TSC_IOConfigTypeDef; + +/** + * @brief TSC handle Structure definition + */ +typedef struct +{ + TSC_TypeDef *Instance; /*!< Register base address */ + TSC_InitTypeDef Init; /*!< Initialization parameters */ + __IO HAL_TSC_StateTypeDef State; /*!< Peripheral state */ + HAL_LockTypeDef Lock; /*!< Lock feature */ +} TSC_HandleTypeDef; + +/* Exported constants --------------------------------------------------------*/ + +/** @defgroup TSC_Exported_Constants + * @{ + */ + +#define TSC_CTPH_1CYCLE ((uint32_t)((uint32_t) 0 << 28)) +#define TSC_CTPH_2CYCLES ((uint32_t)((uint32_t) 1 << 28)) +#define TSC_CTPH_3CYCLES ((uint32_t)((uint32_t) 2 << 28)) +#define TSC_CTPH_4CYCLES ((uint32_t)((uint32_t) 3 << 28)) +#define TSC_CTPH_5CYCLES ((uint32_t)((uint32_t) 4 << 28)) +#define TSC_CTPH_6CYCLES ((uint32_t)((uint32_t) 5 << 28)) +#define TSC_CTPH_7CYCLES ((uint32_t)((uint32_t) 6 << 28)) +#define TSC_CTPH_8CYCLES ((uint32_t)((uint32_t) 7 << 28)) +#define TSC_CTPH_9CYCLES ((uint32_t)((uint32_t) 8 << 28)) +#define TSC_CTPH_10CYCLES ((uint32_t)((uint32_t) 9 << 28)) +#define TSC_CTPH_11CYCLES ((uint32_t)((uint32_t)10 << 28)) +#define TSC_CTPH_12CYCLES ((uint32_t)((uint32_t)11 << 28)) +#define TSC_CTPH_13CYCLES ((uint32_t)((uint32_t)12 << 28)) +#define TSC_CTPH_14CYCLES ((uint32_t)((uint32_t)13 << 28)) +#define TSC_CTPH_15CYCLES ((uint32_t)((uint32_t)14 << 28)) +#define TSC_CTPH_16CYCLES ((uint32_t)((uint32_t)15 << 28)) +#define IS_TSC_CTPH(VAL) (((VAL) == TSC_CTPH_1CYCLE) || \ + ((VAL) == TSC_CTPH_2CYCLES) || \ + ((VAL) == TSC_CTPH_3CYCLES) || \ + ((VAL) == TSC_CTPH_4CYCLES) || \ + ((VAL) == TSC_CTPH_5CYCLES) || \ + ((VAL) == TSC_CTPH_6CYCLES) || \ + ((VAL) == TSC_CTPH_7CYCLES) || \ + ((VAL) == TSC_CTPH_8CYCLES) || \ + ((VAL) == TSC_CTPH_9CYCLES) || \ + ((VAL) == TSC_CTPH_10CYCLES) || \ + ((VAL) == TSC_CTPH_11CYCLES) || \ + ((VAL) == TSC_CTPH_12CYCLES) || \ + ((VAL) == TSC_CTPH_13CYCLES) || \ + ((VAL) == TSC_CTPH_14CYCLES) || \ + ((VAL) == TSC_CTPH_15CYCLES) || \ + ((VAL) == TSC_CTPH_16CYCLES)) + +#define TSC_CTPL_1CYCLE ((uint32_t)((uint32_t) 0 << 24)) +#define TSC_CTPL_2CYCLES ((uint32_t)((uint32_t) 1 << 24)) +#define TSC_CTPL_3CYCLES ((uint32_t)((uint32_t) 2 << 24)) +#define TSC_CTPL_4CYCLES ((uint32_t)((uint32_t) 3 << 24)) +#define TSC_CTPL_5CYCLES ((uint32_t)((uint32_t) 4 << 24)) +#define TSC_CTPL_6CYCLES ((uint32_t)((uint32_t) 5 << 24)) +#define TSC_CTPL_7CYCLES ((uint32_t)((uint32_t) 6 << 24)) +#define TSC_CTPL_8CYCLES ((uint32_t)((uint32_t) 7 << 24)) +#define TSC_CTPL_9CYCLES ((uint32_t)((uint32_t) 8 << 24)) +#define TSC_CTPL_10CYCLES ((uint32_t)((uint32_t) 9 << 24)) +#define TSC_CTPL_11CYCLES ((uint32_t)((uint32_t)10 << 24)) +#define TSC_CTPL_12CYCLES ((uint32_t)((uint32_t)11 << 24)) +#define TSC_CTPL_13CYCLES ((uint32_t)((uint32_t)12 << 24)) +#define TSC_CTPL_14CYCLES ((uint32_t)((uint32_t)13 << 24)) +#define TSC_CTPL_15CYCLES ((uint32_t)((uint32_t)14 << 24)) +#define TSC_CTPL_16CYCLES ((uint32_t)((uint32_t)15 << 24)) +#define IS_TSC_CTPL(VAL) (((VAL) == TSC_CTPL_1CYCLE) || \ + ((VAL) == TSC_CTPL_2CYCLES) || \ + ((VAL) == TSC_CTPL_3CYCLES) || \ + ((VAL) == TSC_CTPL_4CYCLES) || \ + ((VAL) == TSC_CTPL_5CYCLES) || \ + ((VAL) == TSC_CTPL_6CYCLES) || \ + ((VAL) == TSC_CTPL_7CYCLES) || \ + ((VAL) == TSC_CTPL_8CYCLES) || \ + ((VAL) == TSC_CTPL_9CYCLES) || \ + ((VAL) == TSC_CTPL_10CYCLES) || \ + ((VAL) == TSC_CTPL_11CYCLES) || \ + ((VAL) == TSC_CTPL_12CYCLES) || \ + ((VAL) == TSC_CTPL_13CYCLES) || \ + ((VAL) == TSC_CTPL_14CYCLES) || \ + ((VAL) == TSC_CTPL_15CYCLES) || \ + ((VAL) == TSC_CTPL_16CYCLES)) + +#define IS_TSC_SS(VAL) (((VAL) == DISABLE) || ((VAL) == ENABLE)) + +#define IS_TSC_SSD(VAL) (((VAL) == 0) || (((VAL) > 0) && ((VAL) < 128))) + +#define TSC_SS_PRESC_DIV1 ((uint32_t)0) +#define TSC_SS_PRESC_DIV2 (TSC_CR_SSPSC) +#define IS_TSC_SS_PRESC(VAL) (((VAL) == TSC_SS_PRESC_DIV1) || ((VAL) == TSC_SS_PRESC_DIV2)) + +#define TSC_PG_PRESC_DIV1 ((uint32_t)(0 << 12)) +#define TSC_PG_PRESC_DIV2 ((uint32_t)(1 << 12)) +#define TSC_PG_PRESC_DIV4 ((uint32_t)(2 << 12)) +#define TSC_PG_PRESC_DIV8 ((uint32_t)(3 << 12)) +#define TSC_PG_PRESC_DIV16 ((uint32_t)(4 << 12)) +#define TSC_PG_PRESC_DIV32 ((uint32_t)(5 << 12)) +#define TSC_PG_PRESC_DIV64 ((uint32_t)(6 << 12)) +#define TSC_PG_PRESC_DIV128 ((uint32_t)(7 << 12)) +#define IS_TSC_PG_PRESC(VAL) (((VAL) == TSC_PG_PRESC_DIV1) || \ + ((VAL) == TSC_PG_PRESC_DIV2) || \ + ((VAL) == TSC_PG_PRESC_DIV4) || \ + ((VAL) == TSC_PG_PRESC_DIV8) || \ + ((VAL) == TSC_PG_PRESC_DIV16) || \ + ((VAL) == TSC_PG_PRESC_DIV32) || \ + ((VAL) == TSC_PG_PRESC_DIV64) || \ + ((VAL) == TSC_PG_PRESC_DIV128)) + +#define TSC_MCV_255 ((uint32_t)(0 << 5)) +#define TSC_MCV_511 ((uint32_t)(1 << 5)) +#define TSC_MCV_1023 ((uint32_t)(2 << 5)) +#define TSC_MCV_2047 ((uint32_t)(3 << 5)) +#define TSC_MCV_4095 ((uint32_t)(4 << 5)) +#define TSC_MCV_8191 ((uint32_t)(5 << 5)) +#define TSC_MCV_16383 ((uint32_t)(6 << 5)) +#define IS_TSC_MCV(VAL) (((VAL) == TSC_MCV_255) || \ + ((VAL) == TSC_MCV_511) || \ + ((VAL) == TSC_MCV_1023) || \ + ((VAL) == TSC_MCV_2047) || \ + ((VAL) == TSC_MCV_4095) || \ + ((VAL) == TSC_MCV_8191) || \ + ((VAL) == TSC_MCV_16383)) + +#define TSC_IODEF_OUT_PP_LOW ((uint32_t)0) +#define TSC_IODEF_IN_FLOAT (TSC_CR_IODEF) +#define IS_TSC_IODEF(VAL) (((VAL) == TSC_IODEF_OUT_PP_LOW) || ((VAL) == TSC_IODEF_IN_FLOAT)) + +#define TSC_SYNC_POL_FALL ((uint32_t)0) +#define TSC_SYNC_POL_RISE_HIGH (TSC_CR_SYNCPOL) +#define IS_TSC_SYNC_POL(VAL) (((VAL) == TSC_SYNC_POL_FALL) || ((VAL) == TSC_SYNC_POL_RISE_HIGH)) + +#define TSC_ACQ_MODE_NORMAL ((uint32_t)0) +#define TSC_ACQ_MODE_SYNCHRO (TSC_CR_SYNCPOL) +#define IS_TSC_ACQ_MODE(VAL) (((VAL) == TSC_ACQ_MODE_NORMAL) || ((VAL) == TSC_ACQ_MODE_SYNCHRO)) + +#define TSC_IOMODE_UNUSED ((uint32_t)0) +#define TSC_IOMODE_CHANNEL ((uint32_t)1) +#define TSC_IOMODE_SHIELD ((uint32_t)2) +#define TSC_IOMODE_SAMPLING ((uint32_t)3) +#define IS_TSC_IOMODE(VAL) (((VAL) == TSC_IOMODE_UNUSED) || \ + ((VAL) == TSC_IOMODE_CHANNEL) || \ + ((VAL) == TSC_IOMODE_SHIELD) || \ + ((VAL) == TSC_IOMODE_SAMPLING)) + +/** @defgroup TSC_interrupts_definition + * @{ + */ +#define TSC_IT_EOA ((uint32_t)TSC_IER_EOAIE) +#define TSC_IT_MCE ((uint32_t)TSC_IER_MCEIE) +#define IS_TSC_MCE_IT(VAL) (((VAL) == DISABLE) || ((VAL) == ENABLE)) +/** + * @} + */ + +/** @defgroup TSC_flags_definition + * @{ + */ +#define TSC_FLAG_EOA ((uint32_t)TSC_ISR_EOAF) +#define TSC_FLAG_MCE ((uint32_t)TSC_ISR_MCEF) +/** + * @} + */ + +#define TSC_NB_OF_GROUPS (8) + +#define TSC_GROUP1 ((uint32_t)0x00000001) +#define TSC_GROUP2 ((uint32_t)0x00000002) +#define TSC_GROUP3 ((uint32_t)0x00000004) +#define TSC_GROUP4 ((uint32_t)0x00000008) +#define TSC_GROUP5 ((uint32_t)0x00000010) +#define TSC_GROUP6 ((uint32_t)0x00000020) +#define TSC_GROUP7 ((uint32_t)0x00000040) +#define TSC_GROUP8 ((uint32_t)0x00000080) +#define TSC_ALL_GROUPS ((uint32_t)0x000000FF) + +#define TSC_GROUP1_IDX ((uint32_t)0) +#define TSC_GROUP2_IDX ((uint32_t)1) +#define TSC_GROUP3_IDX ((uint32_t)2) +#define TSC_GROUP4_IDX ((uint32_t)3) +#define TSC_GROUP5_IDX ((uint32_t)4) +#define TSC_GROUP6_IDX ((uint32_t)5) +#define TSC_GROUP7_IDX ((uint32_t)6) +#define TSC_GROUP8_IDX ((uint32_t)7) +#define IS_GROUP_INDEX(VAL) (((VAL) == 0) || (((VAL) > 0) && ((VAL) < TSC_NB_OF_GROUPS))) + +#define TSC_GROUP1_IO1 ((uint32_t)0x00000001) +#define TSC_GROUP1_IO2 ((uint32_t)0x00000002) +#define TSC_GROUP1_IO3 ((uint32_t)0x00000004) +#define TSC_GROUP1_IO4 ((uint32_t)0x00000008) +#define TSC_GROUP1_ALL_IOS ((uint32_t)0x0000000F) + +#define TSC_GROUP2_IO1 ((uint32_t)0x00000010) +#define TSC_GROUP2_IO2 ((uint32_t)0x00000020) +#define TSC_GROUP2_IO3 ((uint32_t)0x00000040) +#define TSC_GROUP2_IO4 ((uint32_t)0x00000080) +#define TSC_GROUP2_ALL_IOS ((uint32_t)0x000000F0) + +#define TSC_GROUP3_IO1 ((uint32_t)0x00000100) +#define TSC_GROUP3_IO2 ((uint32_t)0x00000200) +#define TSC_GROUP3_IO3 ((uint32_t)0x00000400) +#define TSC_GROUP3_IO4 ((uint32_t)0x00000800) +#define TSC_GROUP3_ALL_IOS ((uint32_t)0x00000F00) + +#define TSC_GROUP4_IO1 ((uint32_t)0x00001000) +#define TSC_GROUP4_IO2 ((uint32_t)0x00002000) +#define TSC_GROUP4_IO3 ((uint32_t)0x00004000) +#define TSC_GROUP4_IO4 ((uint32_t)0x00008000) +#define TSC_GROUP4_ALL_IOS ((uint32_t)0x0000F000) + +#define TSC_GROUP5_IO1 ((uint32_t)0x00010000) +#define TSC_GROUP5_IO2 ((uint32_t)0x00020000) +#define TSC_GROUP5_IO3 ((uint32_t)0x00040000) +#define TSC_GROUP5_IO4 ((uint32_t)0x00080000) +#define TSC_GROUP5_ALL_IOS ((uint32_t)0x000F0000) + +#define TSC_GROUP6_IO1 ((uint32_t)0x00100000) +#define TSC_GROUP6_IO2 ((uint32_t)0x00200000) +#define TSC_GROUP6_IO3 ((uint32_t)0x00400000) +#define TSC_GROUP6_IO4 ((uint32_t)0x00800000) +#define TSC_GROUP6_ALL_IOS ((uint32_t)0x00F00000) + +#define TSC_GROUP7_IO1 ((uint32_t)0x01000000) +#define TSC_GROUP7_IO2 ((uint32_t)0x02000000) +#define TSC_GROUP7_IO3 ((uint32_t)0x04000000) +#define TSC_GROUP7_IO4 ((uint32_t)0x08000000) +#define TSC_GROUP7_ALL_IOS ((uint32_t)0x0F000000) + +#define TSC_GROUP8_IO1 ((uint32_t)0x10000000) +#define TSC_GROUP8_IO2 ((uint32_t)0x20000000) +#define TSC_GROUP8_IO3 ((uint32_t)0x40000000) +#define TSC_GROUP8_IO4 ((uint32_t)0x80000000) +#define TSC_GROUP8_ALL_IOS ((uint32_t)0xF0000000) + +#define TSC_ALL_GROUPS_ALL_IOS ((uint32_t)0xFFFFFFFF) + +/** + * @} + */ + +/* Exported macros -----------------------------------------------------------*/ + +/** @brief Reset TSC handle state + * @param __HANDLE__: TSC handle. + * @retval None + */ +#define __HAL_TSC_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_TSC_STATE_RESET) + +/** + * @brief Enable the TSC peripheral. + * @param __HANDLE__: TSC handle + * @retval None + */ +#define __HAL_TSC_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= TSC_CR_TSCE) + +/** + * @brief Disable the TSC peripheral. + * @param __HANDLE__: TSC handle + * @retval None + */ +#define __HAL_TSC_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= (uint32_t)(~TSC_CR_TSCE)) + +/** + * @brief Start acquisition + * @param __HANDLE__: TSC handle + * @retval None + */ +#define __HAL_TSC_START_ACQ(__HANDLE__) ((__HANDLE__)->Instance->CR |= TSC_CR_START) + +/** + * @brief Stop acquisition + * @param __HANDLE__: TSC handle + * @retval None + */ +#define __HAL_TSC_STOP_ACQ(__HANDLE__) ((__HANDLE__)->Instance->CR &= (uint32_t)(~TSC_CR_START)) + +/** + * @brief Set IO default mode to output push-pull low + * @param __HANDLE__: TSC handle + * @retval None + */ +#define __HAL_TSC_SET_IODEF_OUTPPLOW(__HANDLE__) ((__HANDLE__)->Instance->CR &= (uint32_t)(~TSC_CR_IODEF)) + +/** + * @brief Set IO default mode to input floating + * @param __HANDLE__: TSC handle + * @retval None + */ +#define __HAL_TSC_SET_IODEF_INFLOAT(__HANDLE__) ((__HANDLE__)->Instance->CR |= TSC_CR_IODEF) + +/** + * @brief Set synchronization polarity to falling edge + * @param __HANDLE__: TSC handle + * @retval None + */ +#define __HAL_TSC_SET_SYNC_POL_FALL(__HANDLE__) ((__HANDLE__)->Instance->CR &= (uint32_t)(~TSC_CR_SYNCPOL)) + +/** + * @brief Set synchronization polarity to rising edge and high level + * @param __HANDLE__: TSC handle + * @retval None + */ +#define __HAL_TSC_SET_SYNC_POL_RISE_HIGH(__HANDLE__) ((__HANDLE__)->Instance->CR |= TSC_CR_SYNCPOL) + +/** + * @brief Enable TSC interrupt. + * @param __HANDLE__: TSC handle + * @param __INTERRUPT__: TSC interrupt + * @retval None + */ +#define __HAL_TSC_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->IER |= (__INTERRUPT__)) + +/** + * @brief Disable TSC interrupt. + * @param __HANDLE__: TSC handle + * @param __INTERRUPT__: TSC interrupt + * @retval None + */ +#define __HAL_TSC_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->IER &= (uint32_t)(~(__INTERRUPT__))) + +/** @brief Check if the specified TSC interrupt source is enabled or disabled. + * @param __HANDLE__: TSC Handle + * @param __INTERRUPT__: TSC interrupt + * @retval SET or RESET + */ +#define __HAL_TSC_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((((__HANDLE__)->Instance->IER & (__INTERRUPT__)) == (__INTERRUPT__)) ? SET : RESET) + +/** + * @brief Get the selected TSC's flag status. + * @param __HANDLE__: TSC handle + * @param __FLAG__: TSC flag + * @retval SET or RESET + */ +#define __HAL_TSC_GET_FLAG(__HANDLE__, __FLAG__) ((((__HANDLE__)->Instance->ISR & (__FLAG__)) == (__FLAG__)) ? SET : RESET) + +/** + * @brief Clear the TSC's pending flag. + * @param __HANDLE__: TSC handle + * @param __FLAG__: TSC flag + * @retval None + */ +#define __HAL_TSC_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->ICR |= (__FLAG__)) + +/** + * @brief Enable schmitt trigger hysteresis on a group of IOs + * @param __HANDLE__: TSC handle + * @param __GX_IOY_MASK__: IOs mask + * @retval None + */ +#define __HAL_TSC_ENABLE_HYSTERESIS(__HANDLE__, __GX_IOY_MASK__) ((__HANDLE__)->Instance->IOHCR |= (__GX_IOY_MASK__)) + +/** + * @brief Disable schmitt trigger hysteresis on a group of IOs + * @param __HANDLE__: TSC handle + * @param __GX_IOY_MASK__: IOs mask + * @retval None + */ +#define __HAL_TSC_DISABLE_HYSTERESIS(__HANDLE__, __GX_IOY_MASK__) ((__HANDLE__)->Instance->IOHCR &= (uint32_t)(~(__GX_IOY_MASK__))) + +/** + * @brief Open analog switch on a group of IOs + * @param __HANDLE__: TSC handle + * @param __GX_IOY_MASK__: IOs mask + * @retval None + */ +#define __HAL_TSC_OPEN_ANALOG_SWITCH(__HANDLE__, __GX_IOY_MASK__) ((__HANDLE__)->Instance->IOASCR &= (uint32_t)(~(__GX_IOY_MASK__))) + +/** + * @brief Close analog switch on a group of IOs + * @param __HANDLE__: TSC handle + * @param __GX_IOY_MASK__: IOs mask + * @retval None + */ +#define __HAL_TSC_CLOSE_ANALOG_SWITCH(__HANDLE__, __GX_IOY_MASK__) ((__HANDLE__)->Instance->IOASCR |= (__GX_IOY_MASK__)) + +/** + * @brief Enable a group of IOs in channel mode + * @param __HANDLE__: TSC handle + * @param __GX_IOY_MASK__: IOs mask + * @retval None + */ +#define __HAL_TSC_ENABLE_CHANNEL(__HANDLE__, __GX_IOY_MASK__) ((__HANDLE__)->Instance->IOCCR |= (__GX_IOY_MASK__)) + +/** + * @brief Disable a group of channel IOs + * @param __HANDLE__: TSC handle + * @param __GX_IOY_MASK__: IOs mask + * @retval None + */ +#define __HAL_TSC_DISABLE_CHANNEL(__HANDLE__, __GX_IOY_MASK__) ((__HANDLE__)->Instance->IOCCR &= (uint32_t)(~(__GX_IOY_MASK__))) + +/** + * @brief Enable a group of IOs in sampling mode + * @param __HANDLE__: TSC handle + * @param __GX_IOY_MASK__: IOs mask + * @retval None + */ +#define __HAL_TSC_ENABLE_SAMPLING(__HANDLE__, __GX_IOY_MASK__) ((__HANDLE__)->Instance->IOSCR |= (__GX_IOY_MASK__)) + +/** + * @brief Disable a group of sampling IOs + * @param __HANDLE__: TSC handle + * @param __GX_IOY_MASK__: IOs mask + * @retval None + */ +#define __HAL_TSC_DISABLE_SAMPLING(__HANDLE__, __GX_IOY_MASK__) ((__HANDLE__)->Instance->IOSCR &= (uint32_t)(~(__GX_IOY_MASK__))) + +/** + * @brief Enable acquisition groups + * @param __HANDLE__: TSC handle + * @param __GX_MASK__: Groups mask + * @retval None + */ +#define __HAL_TSC_ENABLE_GROUP(__HANDLE__, __GX_MASK__) ((__HANDLE__)->Instance->IOGCSR |= (__GX_MASK__)) + +/** + * @brief Disable acquisition groups + * @param __HANDLE__: TSC handle + * @param __GX_MASK__: Groups mask + * @retval None + */ +#define __HAL_TSC_DISABLE_GROUP(__HANDLE__, __GX_MASK__) ((__HANDLE__)->Instance->IOGCSR &= (uint32_t)(~(__GX_MASK__))) + +/** @brief Gets acquisition group status + * @param __HANDLE__: TSC Handle + * @param __GX_INDEX__: Group index + * @retval SET or RESET + */ +#define __HAL_TSC_GET_GROUP_STATUS(__HANDLE__, __GX_INDEX__) \ +((((__HANDLE__)->Instance->IOGCSR & (uint32_t)((uint32_t)1 << ((__GX_INDEX__) + (uint32_t)16))) == (uint32_t)((uint32_t)1 << ((__GX_INDEX__) + (uint32_t)16))) ? TSC_GROUP_COMPLETED : TSC_GROUP_ONGOING) + +/* Exported functions --------------------------------------------------------*/ + +/* Initialization and de-initialization functions *****************************/ +HAL_StatusTypeDef HAL_TSC_Init(TSC_HandleTypeDef* htsc); +HAL_StatusTypeDef HAL_TSC_DeInit(TSC_HandleTypeDef *htsc); +void HAL_TSC_MspInit(TSC_HandleTypeDef* htsc); +void HAL_TSC_MspDeInit(TSC_HandleTypeDef* htsc); + +/* IO operation functions *****************************************************/ +HAL_StatusTypeDef HAL_TSC_Start(TSC_HandleTypeDef* htsc); +HAL_StatusTypeDef HAL_TSC_Start_IT(TSC_HandleTypeDef* htsc); +HAL_StatusTypeDef HAL_TSC_Stop(TSC_HandleTypeDef* htsc); +HAL_StatusTypeDef HAL_TSC_Stop_IT(TSC_HandleTypeDef* htsc); +TSC_GroupStatusTypeDef HAL_TSC_GroupGetStatus(TSC_HandleTypeDef* htsc, uint32_t gx_index); +uint32_t HAL_TSC_GroupGetValue(TSC_HandleTypeDef* htsc, uint32_t gx_index); + +/* Peripheral Control functions ***********************************************/ +HAL_StatusTypeDef HAL_TSC_IOConfig(TSC_HandleTypeDef* htsc, TSC_IOConfigTypeDef* config); +HAL_StatusTypeDef HAL_TSC_IODischarge(TSC_HandleTypeDef* htsc, uint32_t choice); + +/* Peripheral State and Error functions ***************************************/ +HAL_TSC_StateTypeDef HAL_TSC_GetState(TSC_HandleTypeDef* htsc); +HAL_StatusTypeDef HAL_TSC_PollForAcquisition(TSC_HandleTypeDef* htsc); +void HAL_TSC_IRQHandler(TSC_HandleTypeDef* htsc); + +/* Callback functions *********************************************************/ +void HAL_TSC_ConvCpltCallback(TSC_HandleTypeDef* htsc); +void HAL_TSC_ErrorCallback(TSC_HandleTypeDef* htsc); + +#endif /* defined(STM32F051x8) || defined(STM32F071xB) || */ + /* defined(STM32F042x6) || defined(STM32F048xx) || defined(STM32F072xB) || */ + /* defined(STM32F058xx) || defined(STM32F078xx) */ + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /*__STM32F0xx_TSC_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_uart.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_uart.c new file mode 100644 index 0000000000..e26011f7f8 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_uart.c @@ -0,0 +1,1747 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_uart.c + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief UART HAL module driver. + * + * This file provides firmware functions to manage the following + * functionalities of the UART peripheral: + * + Initialization/de-initialization function + * + I/O operation function + * + Peripheral Control function + * + Peripheral State function + * + @verbatim + =============================================================================== + ##### How to use this driver ##### +================================================================================ + [..] + The UART HAL driver can be used as follows: + + (#) Declare a UART_HandleTypeDef handle structure. + (#) Initialize the UART low level resources by implementing the HAL_UART_MspInit ()API: + (##) Enable the USARTx interface clock. + (##) UART pins configuration: + (+) Enable the clock for the UART GPIOs. + (+) Configure these UART pins as alternate function pull-up. + (##) NVIC configuration if you need to use interrupt process (HAL_UART_Transmit_IT() + and HAL_UART_Receive_IT() APIs): + (+) Configure the USARTx interrupt priority. + (+) Enable the NVIC USART IRQ handle. + (@) The specific UART interrupts (Transmission complete interrupt, + RXNE interrupt and Error Interrupts) will be managed using the macros + __HAL_UART_ENABLE_IT() and __HAL_UART_DISABLE_IT() inside the transmit and receive process. + (##) DMA Configuration if you need to use DMA process (HAL_UART_Transmit_DMA() + and HAL_UART_Receive_DMA() APIs): + (+) Declare a DMA handle structure for the Tx/Rx stream. + (+) Enable the DMAx interface clock. + (+) Configure the declared DMA handle structure with the required Tx/Rx parameters. + (+) Configure the DMA Tx/Rx Stream. + (+) Associate the initilalized DMA handle to the UART DMA Tx/Rx handle. + (+) Configure the priority and enable the NVIC for the transfer complete interrupt on the DMA Tx/Rx Stream. + + (#) Program the Baud Rate, Word Length , Stop Bit, Parity, Hardware + flow control and Mode(Receiver/Transmitter) in the huart Init structure. + + (#) If required, program UART advanced features (TX/RX pins swap, auto Baud rate detection,...) + in the huart AdvancedInit structure. + + (#) For the UART asynchronous mode, initialize the UART registers by calling + the HAL_UART_Init() API. + + (#) For the UART Half duplex mode, initialize the UART registers by calling + the HAL_HalfDuplex_Init() API. + + (#) For the UART Multiprocessor mode, initialize the UART registers + by calling the HAL_MultiProcessor_Init() API. + + (#) For the UART RS485 Driver Enabled mode, initialize the UART registers + by calling the HAL_RS485Ex_Init() API. + + (@) These API's(HAL_UART_Init(), HAL_HalfDuplex_Init(), HAL_MultiProcessor_Init(), + also configure also the low level Hardware GPIO, CLOCK, CORTEX...etc) by + calling the customized HAL_UART_MspInit() API. + + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @defgroup UART + * @brief HAL UART module driver + * @{ + */ +#ifdef HAL_UART_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +#define HAL_UART_TXDMA_TIMEOUTVALUE 22000 +#define UART_CR1_FIELDS ((uint32_t)(USART_CR1_M | USART_CR1_PCE | USART_CR1_PS | \ + USART_CR1_TE | USART_CR1_RE | USART_CR1_OVER8)) +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +static void UART_DMATransmitCplt(DMA_HandleTypeDef *hdma); +static void UART_DMAReceiveCplt(DMA_HandleTypeDef *hdma); +static void UART_DMARxHalfCplt(DMA_HandleTypeDef *hdma); +static void UART_DMATxHalfCplt(DMA_HandleTypeDef *hdma); +static void UART_DMAError(DMA_HandleTypeDef *hdma); +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup UART_Private_Functions + * @{ + */ + +/** @defgroup HAL_UART_Group1 Initialization/de-initialization functions + * @brief Initialization and Configuration functions + * +@verbatim +=============================================================================== + ##### Initialization and Configuration functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to initialize the USARTx or the UARTy + in asynchronous mode. + (+) For the asynchronous mode only these parameters can be configured: + (++) Baud Rate + (++) Word Length + (++) Stop Bit + (++) Parity: If the parity is enabled, then the MSB bit of the data written + in the data register is transmitted but is changed by the parity bit. + Depending on the frame length defined by the M bit (8-bits or 9-bits), + the possible UART frame formats are as listed in the following table: + |-----------|-----------|---------------------------------------| + | M1M0 bits | PCE bit | UART frame | + |-----------------------|---------------------------------------| + | 00 | 0 | | SB | 8-bit data | STB | | + |-----------|-----------|---------------------------------------| + | 00 | 1 | | SB | 7-bit data | PB | STB | | + |-----------|-----------|---------------------------------------| + | 01 | 0 | | SB | 9-bit data | STB | | + |-----------|-----------|---------------------------------------| + | 01 | 1 | | SB | 8-bit data | PB | STB | | + +---------------------------------------------------------------+ + | 10 | 0 | | SB | 7-bit data | STB | | + |-----------|-----------|---------------------------------------| + | 10 | 1 | | SB | 6-bit data | PB | STB | | + +---------------------------------------------------------------+ + (++) Hardware flow control + (++) Receiver/transmitter modes + (++) Over Sampling Method + (++) One-Bit Sampling Method + (+) For the asynchronous mode, the following advanced features can be configured as well: + (++) TX and/or RX pin level inversion + (++) data logical level inversion + (++) RX and TX pins swap + (++) RX overrun detection disabling + (++) DMA disabling on RX error + (++) MSB first on communication line + (++) auto Baud rate detection + [..] + The HAL_UART_Init(), HAL_HalfDuplex_Init() and HAL_MultiProcessor_Init() + API follow respectively the UART asynchronous, UART Half duplex and multiprocessor + configuration procedures (details for the procedures are available in reference manual). + +@endverbatim + * @{ + */ + +/** + * @brief Initializes the UART mode according to the specified + * parameters in the UART_InitTypeDef and creates the associated handle . + * @param huart: uart handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_UART_Init(UART_HandleTypeDef *huart) +{ + /* Check the UART handle allocation */ + if(huart == NULL) + { + return HAL_ERROR; + } + + if(huart->Init.HwFlowCtl != UART_HWCONTROL_NONE) + { + /* Check the parameters */ + assert_param(IS_UART_HWFLOW_INSTANCE(huart->Instance)); + } + else + { + /* Check the parameters */ + assert_param(IS_UART_INSTANCE(huart->Instance)); + } + + if(huart->State == HAL_UART_STATE_RESET) + { + /* Init the low level hardware : GPIO, CLOCK */ + HAL_UART_MspInit(huart); + } + + huart->State = HAL_UART_STATE_BUSY; + + /* Disable the Peripheral */ + __HAL_UART_DISABLE(huart); + + /* Set the UART Communication parameters */ + if (UART_SetConfig(huart) == HAL_ERROR) + { + return HAL_ERROR; + } + + if (huart->AdvancedInit.AdvFeatureInit != UART_ADVFEATURE_NO_INIT) + { + UART_AdvFeatureConfig(huart); + } + + /* In asynchronous mode, the following bits must be kept cleared: + - LINEN and CLKEN bits in the USART_CR2 register, + - SCEN, HDSEL and IREN bits in the USART_CR3 register.*/ + huart->Instance->CR2 &= ~(USART_CR2_LINEN | USART_CR2_CLKEN); + huart->Instance->CR3 &= ~(USART_CR3_SCEN | USART_CR3_HDSEL | USART_CR3_IREN); + + /* Enable the Peripheral */ + __HAL_UART_ENABLE(huart); + + /* TEACK and/or REACK to check before moving huart->State to Ready */ + return (UART_CheckIdleState(huart)); +} + +/** + * @brief Initializes the half-duplex mode according to the specified + * parameters in the UART_InitTypeDef and creates the associated handle . + * @param huart: uart handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_HalfDuplex_Init(UART_HandleTypeDef *huart) +{ + /* Check the UART handle allocation */ + if(huart == NULL) + { + return HAL_ERROR; + } + + if(huart->State == HAL_UART_STATE_RESET) + { + /* Init the low level hardware : GPIO, CLOCK */ + HAL_UART_MspInit(huart); + } + + huart->State = HAL_UART_STATE_BUSY; + + /* Disable the Peripheral */ + __HAL_UART_DISABLE(huart); + + /* Set the UART Communication parameters */ + if (UART_SetConfig(huart) == HAL_ERROR) + { + return HAL_ERROR; + } + + if (huart->AdvancedInit.AdvFeatureInit != UART_ADVFEATURE_NO_INIT) + { + UART_AdvFeatureConfig(huart); + } + + /* In half-duplex mode, the following bits must be kept cleared: + - LINEN and CLKEN bits in the USART_CR2 register, + - SCEN and IREN bits in the USART_CR3 register.*/ + huart->Instance->CR2 &= ~(USART_CR2_LINEN | USART_CR2_CLKEN); + huart->Instance->CR3 &= ~(USART_CR3_IREN | USART_CR3_SCEN); + + /* Enable the Half-Duplex mode by setting the HDSEL bit in the CR3 register */ + huart->Instance->CR3 |= USART_CR3_HDSEL; + + /* Enable the Peripheral */ + __HAL_UART_ENABLE(huart); + + /* TEACK and/or REACK to check before moving huart->State to Ready */ + return (UART_CheckIdleState(huart)); +} + + +/** + * @brief Initializes the multiprocessor mode according to the specified + * parameters in the UART_InitTypeDef and creates the associated handle. + * @param huart: UART handle + * @param Address: UART node address (4-, 6-, 7- or 8-bit long) + * @param WakeUpMethod: specifies the UART wakeup method. + * This parameter can be one of the following values: + * @arg UART_WAKEUPMETHOD_IDLELINE: WakeUp by an idle line detection + * @arg UART_WAKEUPMETHOD_ADDRESSMARK: WakeUp by an address mark + * @note If the user resorts to idle line detection wake up, the Address parameter + * is useless and ignored by the initialization function. + * @note If the user resorts to address mark wake up, the address length detection + * is configured by default to 4 bits only. For the UART to be able to + * manage 6-, 7- or 8-bit long addresses detection, the API + * HAL_MultiProcessorEx_AddressLength_Set() must be called after + * HAL_MultiProcessor_Init(). + * @retval HAL status + */ +HAL_StatusTypeDef HAL_MultiProcessor_Init(UART_HandleTypeDef *huart, uint8_t Address, uint32_t WakeUpMethod) +{ + /* Check the UART handle allocation */ + if(huart == NULL) + { + return HAL_ERROR; + } + + /* Check the wake up method parameter */ + assert_param(IS_UART_WAKEUPMETHOD(WakeUpMethod)); + + if(huart->State == HAL_UART_STATE_RESET) + { + /* Init the low level hardware : GPIO, CLOCK */ + HAL_UART_MspInit(huart); + } + + huart->State = HAL_UART_STATE_BUSY; + + /* Disable the Peripheral */ + __HAL_UART_DISABLE(huart); + + /* Set the UART Communication parameters */ + if (UART_SetConfig(huart) == HAL_ERROR) + { + return HAL_ERROR; + } + + if (huart->AdvancedInit.AdvFeatureInit != UART_ADVFEATURE_NO_INIT) + { + UART_AdvFeatureConfig(huart); + } + + /* In multiprocessor mode, the following bits must be kept cleared: + - LINEN and CLKEN bits in the USART_CR2 register, + - SCEN, HDSEL and IREN bits in the USART_CR3 register. */ + huart->Instance->CR2 &= ~(USART_CR2_LINEN | USART_CR2_CLKEN); + huart->Instance->CR3 &= ~(USART_CR3_SCEN | USART_CR3_HDSEL | USART_CR3_IREN); + + if (WakeUpMethod == UART_WAKEUPMETHOD_ADDRESSMARK) + { + /* If address mark wake up method is chosen, set the USART address node */ + MODIFY_REG(huart->Instance->CR2, USART_CR2_ADD, ((uint32_t)Address << UART_CR2_ADDRESS_LSB_POS)); + } + + /* Set the wake up method by setting the WAKE bit in the CR1 register */ + MODIFY_REG(huart->Instance->CR1, USART_CR1_WAKE, WakeUpMethod); + + /* Enable the Peripheral */ + __HAL_UART_ENABLE(huart); + + /* TEACK and/or REACK to check before moving huart->State to Ready */ + return (UART_CheckIdleState(huart)); +} + + + + +/** + * @brief DeInitializes the UART peripheral + * @param huart: uart handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_UART_DeInit(UART_HandleTypeDef *huart) +{ + /* Check the UART handle allocation */ + if(huart == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_UART_INSTANCE(huart->Instance)); + + huart->State = HAL_UART_STATE_BUSY; + + /* Disable the Peripheral */ + __HAL_UART_DISABLE(huart); + + huart->Instance->CR1 = 0x0; + huart->Instance->CR2 = 0x0; + huart->Instance->CR3 = 0x0; + + /* DeInit the low level hardware */ + HAL_UART_MspDeInit(huart); + + huart->ErrorCode = HAL_UART_ERROR_NONE; + huart->State = HAL_UART_STATE_RESET; + + /* Process Unlock */ + __HAL_UNLOCK(huart); + + return HAL_OK; +} + +/** + * @brief UART MSP Init + * @param huart: uart handle + * @retval None + */ + __weak void HAL_UART_MspInit(UART_HandleTypeDef *huart) +{ + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_UART_MspInit can be implemented in the user file + */ +} + +/** + * @brief UART MSP DeInit + * @param huart: uart handle + * @retval None + */ + __weak void HAL_UART_MspDeInit(UART_HandleTypeDef *huart) +{ + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_UART_MspDeInit can be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup HAL_UART_Group2 IO operation functions + * @brief UART Transmit/Receive functions + * +@verbatim + =============================================================================== + ##### I/O operation functions ##### + =============================================================================== + This subsection provides a set of functions allowing to manage the UART asynchronous + and Half duplex data transfers. + + (#) There are two mode of transfer: + (+) Blocking mode: The communication is performed in polling mode. + The HAL status of all data processing is returned by the same function + after finishing transfer. + (+) No-Blocking mode: The communication is performed using Interrupts + or DMA, These API's return the HAL status. + The end of the data processing will be indicated through the + dedicated UART IRQ when using Interrupt mode or the DMA IRQ when + using DMA mode. + The HAL_UART_TxCpltCallback(), HAL_UART_RxCpltCallback() user callbacks + will be executed respectivelly at the end of the transmit or Receive process + The HAL_UART_ErrorCallback()user callback will be executed when a communication error is detected + + (#) Blocking mode API's are : + (+) HAL_UART_Transmit() + (+) HAL_UART_Receive() + + (#) Non-Blocking mode API's with Interrupt are : + (+) HAL_UART_Transmit_IT() + (+) HAL_UART_Receive_IT() + (+) HAL_UART_IRQHandler() + (+) UART_Transmit_IT() + (+) UART_Receive_IT() + + (#) No-Blocking mode API's with DMA are : + (+) HAL_UART_Transmit_DMA() + (+) HAL_UART_Receive_DMA() + (+) HAL_UART_DMAPause() + (+) HAL_UART_DMAResume() + (+) HAL_UART_DMAStop() + + (#) A set of Transfer Complete Callbacks are provided in No_Blocking mode: + (+) HAL_UART_TxHalfCpltCallback() + (+) HAL_UART_TxCpltCallback() + (+) HAL_UART_RxHalfCpltCallback() + (+) HAL_UART_RxCpltCallback() + (+) HAL_UART_ErrorCallback() + + + -@- In the Half duplex communication, it is forbidden to run the transmit + and receive process in parallel, the UART state HAL_UART_STATE_BUSY_TX_RX can't be useful. + +@endverbatim + * @{ + */ + +/** + * @brief Send an amount of data in blocking mode + * @param huart: uart handle + * @param pData: pointer to data buffer + * @param Size: amount of data to be sent + * @param Timeout : Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_UART_Transmit(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size, uint32_t Timeout) +{ + uint16_t* tmp; + + if((huart->State == HAL_UART_STATE_READY) || (huart->State == HAL_UART_STATE_BUSY_RX)) + { + if((pData == NULL ) || (Size == 0)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(huart); + + huart->ErrorCode = HAL_UART_ERROR_NONE; + /* Check if a non-blocking receive process is ongoing or not */ + if(huart->State == HAL_UART_STATE_BUSY_RX) + { + huart->State = HAL_UART_STATE_BUSY_TX_RX; + } + else + { + huart->State = HAL_UART_STATE_BUSY_TX; + } + + huart->TxXferSize = Size; + huart->TxXferCount = Size; + while(huart->TxXferCount > 0) + { + huart->TxXferCount--; + if(UART_WaitOnFlagUntilTimeout(huart, UART_FLAG_TXE, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + if ((huart->Init.WordLength == UART_WORDLENGTH_9B) && (huart->Init.Parity == UART_PARITY_NONE)) + { + tmp = (uint16_t*) pData; + huart->Instance->TDR = (*tmp & (uint16_t)0x01FF); + pData += 2; + } + else + { + huart->Instance->TDR = (*pData++ & (uint8_t)0xFF); + } + } + if(UART_WaitOnFlagUntilTimeout(huart, UART_FLAG_TC, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + /* Check if a non-blocking receive Process is ongoing or not */ + if(huart->State == HAL_UART_STATE_BUSY_TX_RX) + { + huart->State = HAL_UART_STATE_BUSY_RX; + } + else + { + huart->State = HAL_UART_STATE_READY; + } + + /* Process Unlocked */ + __HAL_UNLOCK(huart); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive an amount of data in blocking mode + * @param huart: uart handle + * @param pData: pointer to data buffer + * @param Size: amount of data to be received + * @param Timeout : Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_UART_Receive(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size, uint32_t Timeout) +{ + uint16_t* tmp; + uint16_t uhMask; + + if((huart->State == HAL_UART_STATE_READY) || (huart->State == HAL_UART_STATE_BUSY_TX)) + { + if((pData == NULL ) || (Size == 0)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(huart); + + huart->ErrorCode = HAL_UART_ERROR_NONE; + /* Check if a non-blocking transmit process is ongoing or not */ + if(huart->State == HAL_UART_STATE_BUSY_TX) + { + huart->State = HAL_UART_STATE_BUSY_TX_RX; + } + else + { + huart->State = HAL_UART_STATE_BUSY_RX; + } + + huart->RxXferSize = Size; + huart->RxXferCount = Size; + + /* Computation of UART mask to apply to RDR register */ + __HAL_UART_MASK_COMPUTATION(huart); + uhMask = huart->Mask; + + /* as long as data have to be received */ + while(huart->RxXferCount > 0) + { + huart->RxXferCount--; + if(UART_WaitOnFlagUntilTimeout(huart, UART_FLAG_RXNE, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + if ((huart->Init.WordLength == UART_WORDLENGTH_9B) && (huart->Init.Parity == UART_PARITY_NONE)) + { + tmp = (uint16_t*) pData ; + *tmp = (uint16_t)(huart->Instance->RDR & uhMask); + pData +=2; + } + else + { + *pData++ = (uint8_t)(huart->Instance->RDR & (uint8_t)uhMask); + } + } + + /* Check if a non-blocking transmit Process is ongoing or not */ + if(huart->State == HAL_UART_STATE_BUSY_TX_RX) + { + huart->State = HAL_UART_STATE_BUSY_TX; + } + else + { + huart->State = HAL_UART_STATE_READY; + } + /* Process Unlocked */ + __HAL_UNLOCK(huart); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Send an amount of data in interrupt mode + * @param huart: uart handle + * @param pData: pointer to data buffer + * @param Size: amount of data to be sent + * @retval HAL status + */ +HAL_StatusTypeDef HAL_UART_Transmit_IT(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size) +{ + if((huart->State == HAL_UART_STATE_READY) || (huart->State == HAL_UART_STATE_BUSY_RX)) + { + if((pData == NULL ) || (Size == 0)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(huart); + + huart->pTxBuffPtr = pData; + huart->TxXferSize = Size; + huart->TxXferCount = Size; + + huart->ErrorCode = HAL_UART_ERROR_NONE; + /* Check if a receive process is ongoing or not */ + if(huart->State == HAL_UART_STATE_BUSY_RX) + { + huart->State = HAL_UART_STATE_BUSY_TX_RX; + } + else + { + huart->State = HAL_UART_STATE_BUSY_TX; + } + + /* Enable the UART Error Interrupt: (Frame error, noise error, overrun error) */ + __HAL_UART_ENABLE_IT(huart, UART_IT_ERR); + + /* Process Unlocked */ + __HAL_UNLOCK(huart); + + /* Enable the UART Transmit Complete Interrupt */ + __HAL_UART_ENABLE_IT(huart, UART_IT_TC); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive an amount of data in interrupt mode + * @param huart: uart handle + * @param pData: pointer to data buffer + * @param Size: amount of data to be received + * @retval HAL status + */ +HAL_StatusTypeDef HAL_UART_Receive_IT(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size) +{ + if((huart->State == HAL_UART_STATE_READY) || (huart->State == HAL_UART_STATE_BUSY_TX)) + { + if((pData == NULL ) || (Size == 0)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(huart); + + huart->pRxBuffPtr = pData; + huart->RxXferSize = Size; + huart->RxXferCount = Size; + + /* Computation of UART mask to apply to RDR register */ + __HAL_UART_MASK_COMPUTATION(huart); + + huart->ErrorCode = HAL_UART_ERROR_NONE; + /* Check if a transmit process is ongoing or not */ + if(huart->State == HAL_UART_STATE_BUSY_TX) + { + huart->State = HAL_UART_STATE_BUSY_TX_RX; + } + else + { + huart->State = HAL_UART_STATE_BUSY_RX; + } + + /* Enable the UART Parity Error Interrupt */ + __HAL_UART_ENABLE_IT(huart, UART_IT_PE); + + /* Enable the UART Error Interrupt: (Frame error, noise error, overrun error) */ + __HAL_UART_ENABLE_IT(huart, UART_IT_ERR); + + /* Process Unlocked */ + __HAL_UNLOCK(huart); + + /* Enable the UART Data Register not empty Interrupt */ + __HAL_UART_ENABLE_IT(huart, UART_IT_RXNE); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Send an amount of data in DMA mode + * @param huart: uart handle + * @param pData: pointer to data buffer + * @param Size: amount of data to be sent + * @retval HAL status + */ +HAL_StatusTypeDef HAL_UART_Transmit_DMA(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size) +{ + uint32_t *tmp; + + if((huart->State == HAL_UART_STATE_READY) || (huart->State == HAL_UART_STATE_BUSY_RX)) + { + if((pData == NULL ) || (Size == 0)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(huart); + + huart->pTxBuffPtr = pData; + huart->TxXferSize = Size; + huart->TxXferCount = Size; + + huart->ErrorCode = HAL_UART_ERROR_NONE; + /* Check if a receive process is ongoing or not */ + if(huart->State == HAL_UART_STATE_BUSY_RX) + { + huart->State = HAL_UART_STATE_BUSY_TX_RX; + } + else + { + huart->State = HAL_UART_STATE_BUSY_TX; + } + + /* Set the UART DMA transfer complete callback */ + huart->hdmatx->XferCpltCallback = UART_DMATransmitCplt; + + /* Set the UART DMA Half transfer complete callback */ + huart->hdmatx->XferHalfCpltCallback = UART_DMATxHalfCplt; + + /* Set the DMA error callback */ + huart->hdmatx->XferErrorCallback = UART_DMAError; + + /* Enable the UART transmit DMA channel */ + tmp = (uint32_t*)&pData; + HAL_DMA_Start_IT(huart->hdmatx, *(uint32_t*)tmp, (uint32_t)&huart->Instance->TDR, Size); + + /* Enable the DMA transfer for transmit request by setting the DMAT bit + in the UART CR3 register */ + huart->Instance->CR3 |= USART_CR3_DMAT; + + /* Process Unlocked */ + __HAL_UNLOCK(huart); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive an amount of data in DMA mode + * @param huart: uart handle + * @param pData: pointer to data buffer + * @param Size: amount of data to be received + * @note When the UART parity is enabled (PCE = 1), the received data contain + * the parity bit (MSB position) + * @retval HAL status + */ +HAL_StatusTypeDef HAL_UART_Receive_DMA(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size) +{ + uint32_t *tmp; + + if((huart->State == HAL_UART_STATE_READY) || (huart->State == HAL_UART_STATE_BUSY_TX)) + { + if((pData == NULL ) || (Size == 0)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(huart); + + huart->pRxBuffPtr = pData; + huart->RxXferSize = Size; + + huart->ErrorCode = HAL_UART_ERROR_NONE; + /* Check if a transmit rocess is ongoing or not */ + if(huart->State == HAL_UART_STATE_BUSY_TX) + { + huart->State = HAL_UART_STATE_BUSY_TX_RX; + } + else + { + huart->State = HAL_UART_STATE_BUSY_RX; + } + + /* Set the UART DMA transfer complete callback */ + huart->hdmarx->XferCpltCallback = UART_DMAReceiveCplt; + + /* Set the UART DMA Half transfer complete callback */ + huart->hdmarx->XferHalfCpltCallback = UART_DMARxHalfCplt; + + /* Set the DMA error callback */ + huart->hdmarx->XferErrorCallback = UART_DMAError; + + /* Enable the DMA channel */ + tmp = (uint32_t*)&pData; + HAL_DMA_Start_IT(huart->hdmarx, (uint32_t)&huart->Instance->RDR, *(uint32_t*)tmp, Size); + + /* Enable the DMA transfer for the receiver request by setting the DMAR bit + in the UART CR3 register */ + huart->Instance->CR3 |= USART_CR3_DMAR; + + /* Process Unlocked */ + __HAL_UNLOCK(huart); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Pauses the DMA Transfer. + * @param huart: UART handle + * @retval None + */ +HAL_StatusTypeDef HAL_UART_DMAPause(UART_HandleTypeDef *huart) +{ + /* Process Locked */ + __HAL_LOCK(huart); + + if(huart->State == HAL_UART_STATE_BUSY_TX) + { + /* Disable the UART DMA Tx request */ + huart->Instance->CR3 &= (uint32_t)(~USART_CR3_DMAT); + } + else if(huart->State == HAL_UART_STATE_BUSY_RX) + { + /* Disable the UART DMA Rx request */ + huart->Instance->CR3 &= (uint32_t)(~USART_CR3_DMAR); + } + else if(huart->State == HAL_UART_STATE_BUSY_TX_RX) + { + /* Disable the UART DMA Tx request */ + huart->Instance->CR3 &= (uint32_t)(~USART_CR3_DMAT); + /* Disable the UART DMA Rx request */ + huart->Instance->CR3 &= (uint32_t)(~USART_CR3_DMAR); + } + + /* Process Unlocked */ + __HAL_UNLOCK(huart); + + return HAL_OK; +} + +/** + * @brief Resumes the DMA Transfer. + * @param huart: UART handle + * @retval None + */ +HAL_StatusTypeDef HAL_UART_DMAResume(UART_HandleTypeDef *huart) +{ + /* Process Locked */ + __HAL_LOCK(huart); + + if(huart->State == HAL_UART_STATE_BUSY_TX) + { + /* Enable the UART DMA Tx request */ + huart->Instance->CR3 |= USART_CR3_DMAT; + } + else if(huart->State == HAL_UART_STATE_BUSY_RX) + { + /* Enable the UART DMA Rx request */ + huart->Instance->CR3 |= USART_CR3_DMAR; + } + else if(huart->State == HAL_UART_STATE_BUSY_TX_RX) + { + /* Enable the UART DMA Rx request before the DMA Tx request */ + huart->Instance->CR3 |= USART_CR3_DMAR; + /* Enable the UART DMA Tx request */ + huart->Instance->CR3 |= USART_CR3_DMAT; + } + + /* If the UART peripheral is still not enabled, enable it */ + if ((huart->Instance->CR1 & USART_CR1_UE) == 0) + { + /* Enable UART peripheral */ + __HAL_UART_ENABLE(huart); + } + + /* TEACK and/or REACK to check before moving huart->State to Ready */ + return (UART_CheckIdleState(huart)); +} + +/** + * @brief Stops the DMA Transfer. + * @param huart: UART handle + * @retval None + */ +HAL_StatusTypeDef HAL_UART_DMAStop(UART_HandleTypeDef *huart) +{ + /* Process Locked */ + __HAL_LOCK(huart); + + /* Disable the UART Tx/Rx DMA requests */ + huart->Instance->CR3 &= ~USART_CR3_DMAT; + huart->Instance->CR3 &= ~USART_CR3_DMAR; + + /* Abort the UART DMA tx Stream */ + if(huart->hdmatx != NULL) + { + HAL_DMA_Abort(huart->hdmatx); + } + /* Abort the UART DMA rx Stream */ + if(huart->hdmarx != NULL) + { + HAL_DMA_Abort(huart->hdmarx); + } + + /* Disable UART peripheral */ + __HAL_UART_DISABLE(huart); + + huart->State = HAL_UART_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(huart); + + return HAL_OK; +} + + + + +/** + * @brief This function handles UART Communication Timeout. + * @param huart: UART handle + * @param Flag: specifies the UART flag to check. + * @param Status: The new Flag status (SET or RESET). + * @param Timeout: Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef UART_WaitOnFlagUntilTimeout(UART_HandleTypeDef *huart, uint32_t Flag, FlagStatus Status, uint32_t Timeout) +{ + uint32_t tickstart = HAL_GetTick(); + + /* Wait until flag is set */ + if(Status == RESET) + { + while(__HAL_UART_GET_FLAG(huart, Flag) == RESET) + { + /* Check for the Timeout */ + if(Timeout != HAL_MAX_DELAY) + { + if((HAL_GetTick() - tickstart) >= Timeout) + { + /* Disable TXE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts for the interrupt process */ + __HAL_UART_DISABLE_IT(huart, UART_IT_TXE); + __HAL_UART_DISABLE_IT(huart, UART_IT_RXNE); + __HAL_UART_DISABLE_IT(huart, UART_IT_PE); + __HAL_UART_DISABLE_IT(huart, UART_IT_ERR); + + huart->State = HAL_UART_STATE_TIMEOUT; + + /* Process Unlocked */ + __HAL_UNLOCK(huart); + + return HAL_TIMEOUT; + } + } + } + } + else + { + while(__HAL_UART_GET_FLAG(huart, Flag) != RESET) + { + /* Check for the Timeout */ + if(Timeout != HAL_MAX_DELAY) + { + if((HAL_GetTick() - tickstart) >= Timeout) + { + /* Disable TXE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts for the interrupt process */ + __HAL_UART_DISABLE_IT(huart, UART_IT_TXE); + __HAL_UART_DISABLE_IT(huart, UART_IT_RXNE); + __HAL_UART_DISABLE_IT(huart, UART_IT_PE); + __HAL_UART_DISABLE_IT(huart, UART_IT_ERR); + + huart->State = HAL_UART_STATE_TIMEOUT; + + /* Process Unlocked */ + __HAL_UNLOCK(huart); + + return HAL_TIMEOUT; + } + } + } + } + return HAL_OK; +} + + +/** + * @brief DMA UART transmit process complete callback + * @param hdma: DMA handle + * @retval None + */ +static void UART_DMATransmitCplt(DMA_HandleTypeDef *hdma) +{ + UART_HandleTypeDef* huart = ( UART_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + huart->TxXferCount = 0; + + /* Disable the DMA transfer for transmit request by setting the DMAT bit + in the UART CR3 register */ + huart->Instance->CR3 &= (uint16_t)~((uint16_t)USART_CR3_DMAT); + + /* Wait for UART TC Flag */ + if(UART_WaitOnFlagUntilTimeout(huart, UART_FLAG_TC, RESET, HAL_UART_TXDMA_TIMEOUTVALUE) != HAL_OK) + { + /* Timeout Occured */ + HAL_UART_ErrorCallback(huart); + } + else + { + /* No Timeout */ + /* Check if a receive Process is ongoing or not */ + if(huart->State == HAL_UART_STATE_BUSY_TX_RX) + { + huart->State = HAL_UART_STATE_BUSY_RX; + } + else + { + huart->State = HAL_UART_STATE_READY; + } + HAL_UART_TxCpltCallback(huart); + } +} + +/** + * @brief DMA UART transmit process half complete callback + * @param hdma : DMA handle + * @retval None + */ +static void UART_DMATxHalfCplt(DMA_HandleTypeDef *hdma) +{ + UART_HandleTypeDef* huart = (UART_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent; + + HAL_UART_TxHalfCpltCallback(huart); +} + +/** + * @brief DMA UART receive process complete callback + * @param hdma: DMA handle + * @retval None + */ +static void UART_DMAReceiveCplt(DMA_HandleTypeDef *hdma) +{ + UART_HandleTypeDef* huart = ( UART_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + huart->RxXferCount = 0; + + /* Disable the DMA transfer for the receiver request by setting the DMAR bit + in the UART CR3 register */ + huart->Instance->CR3 &= (uint16_t)~((uint16_t)USART_CR3_DMAR); + + /* Check if a transmit Process is ongoing or not */ + if(huart->State == HAL_UART_STATE_BUSY_TX_RX) + { + huart->State = HAL_UART_STATE_BUSY_TX; + } + else + { + huart->State = HAL_UART_STATE_READY; + } + HAL_UART_RxCpltCallback(huart); +} + +/** + * @brief DMA UART receive process half complete callback + * @param hdma : DMA handle + * @retval None + */ +static void UART_DMARxHalfCplt(DMA_HandleTypeDef *hdma) +{ + UART_HandleTypeDef* huart = (UART_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent; + + HAL_UART_RxHalfCpltCallback(huart); +} + +/** + * @brief DMA UART communication error callback + * @param hdma: DMA handle + * @retval None + */ +static void UART_DMAError(DMA_HandleTypeDef *hdma) +{ + UART_HandleTypeDef* huart = ( UART_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + huart->RxXferCount = 0; + huart->TxXferCount = 0; + huart->State= HAL_UART_STATE_READY; + huart->ErrorCode |= HAL_UART_ERROR_DMA; + HAL_UART_ErrorCallback(huart); +} + +/** + * @brief Tx Transfer completed callbacks + * @param huart: uart handle + * @retval None + */ + __weak void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart) +{ + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_UART_TxCpltCallback can be implemented in the user file + */ +} + +/** + * @brief Tx Half Transfer completed callbacks. + * @param huart: UART handle + * @retval None + */ + __weak void HAL_UART_TxHalfCpltCallback(UART_HandleTypeDef *huart) +{ + /* NOTE: This function should not be modified, when the callback is needed, + the HAL_UART_TxCpltCallback can be implemented in the user file + */ +} + +/** + * @brief Rx Transfer completed callbacks + * @param huart: uart handle + * @retval None + */ +__weak void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart) +{ + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_UART_TxCpltCallback can be implemented in the user file + */ +} + +/** + * @brief Rx Half Transfer completed callbacks. + * @param huart: UART handle + * @retval None + */ +__weak void HAL_UART_RxHalfCpltCallback(UART_HandleTypeDef *huart) +{ + /* NOTE: This function should not be modified, when the callback is needed, + the HAL_UART_TxCpltCallback can be implemented in the user file + */ +} + +/** + * @brief UART error callbacks + * @param huart: uart handle + * @retval None + */ + __weak void HAL_UART_ErrorCallback(UART_HandleTypeDef *huart) +{ + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_UART_ErrorCallback can be implemented in the user file + */ +} + + +/** + * @brief Send an amount of data in interrupt mode + * Function called under interruption only, once + * interruptions have been enabled by HAL_UART_Transmit_IT() + * @param huart: UART handle + * @retval HAL status + */ +HAL_StatusTypeDef UART_Transmit_IT(UART_HandleTypeDef *huart) +{ + uint16_t* tmp; + + if ((huart->State == HAL_UART_STATE_BUSY_TX) || (huart->State == HAL_UART_STATE_BUSY_TX_RX)) + { + + if(huart->TxXferCount == 0) + { + /* Disable the UART Transmit Complete Interrupt */ + __HAL_UART_DISABLE_IT(huart, UART_IT_TC); + + /* Check if a receive Process is ongoing or not */ + if(huart->State == HAL_UART_STATE_BUSY_TX_RX) + { + huart->State = HAL_UART_STATE_BUSY_RX; + } + else + { + /* Disable the UART Error Interrupt: (Frame error, noise error, overrun error) */ + __HAL_UART_DISABLE_IT(huart, UART_IT_ERR); + + huart->State = HAL_UART_STATE_READY; + } + + HAL_UART_TxCpltCallback(huart); + + return HAL_OK; + } + else + { + if ((huart->Init.WordLength == UART_WORDLENGTH_9B) && (huart->Init.Parity == UART_PARITY_NONE)) + { + tmp = (uint16_t*) huart->pTxBuffPtr; + huart->Instance->TDR = (*tmp & (uint16_t)0x01FF); + huart->pTxBuffPtr += 2; + } + else + { + huart->Instance->TDR = (uint8_t)(*huart->pTxBuffPtr++ & (uint8_t)0xFF); + } + + huart->TxXferCount--; + + return HAL_OK; + } + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive an amount of data in interrupt mode + * Function called under interruption only, once + * interruptions have been enabled by HAL_UART_Receive_IT() + * @param huart: UART handle + * @retval HAL status + */ +HAL_StatusTypeDef UART_Receive_IT(UART_HandleTypeDef *huart) +{ + uint16_t* tmp; + uint16_t uhMask = huart->Mask; + + if((huart->State == HAL_UART_STATE_BUSY_RX) || (huart->State == HAL_UART_STATE_BUSY_TX_RX)) + { + + if ((huart->Init.WordLength == UART_WORDLENGTH_9B) && (huart->Init.Parity == UART_PARITY_NONE)) + { + tmp = (uint16_t*) huart->pRxBuffPtr ; + *tmp = (uint16_t)(huart->Instance->RDR & uhMask); + huart->pRxBuffPtr +=2; + } + else + { + *huart->pRxBuffPtr++ = (uint8_t)(huart->Instance->RDR & (uint8_t)uhMask); + } + + if(--huart->RxXferCount == 0) + { + __HAL_UART_DISABLE_IT(huart, UART_IT_RXNE); + + /* Check if a transmit Process is ongoing or not */ + if(huart->State == HAL_UART_STATE_BUSY_TX_RX) + { + huart->State = HAL_UART_STATE_BUSY_TX; + } + else + { + /* Disable the UART Parity Error Interrupt */ + __HAL_UART_DISABLE_IT(huart, UART_IT_PE); + + /* Disable the UART Error Interrupt: (Frame error, noise error, overrun error) */ + __HAL_UART_DISABLE_IT(huart, UART_IT_ERR); + + huart->State = HAL_UART_STATE_READY; + } + + HAL_UART_RxCpltCallback(huart); + + return HAL_OK; + } + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @} + */ + +/** @defgroup HAL_UART_Group3 Peripheral Control functions + * @brief UART control functions + * +@verbatim + =============================================================================== + ##### Peripheral Control functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to control the UART. + (+) HAL_UART_GetState() API is helpful to check in run-time the state of the UART peripheral. + (+) HAL_MultiProcessor_EnableMuteMode() API enables mute mode + (+) HAL_MultiProcessor_DisableMuteMode() API disables mute mode + (+) HAL_MultiProcessor_EnterMuteMode() API enters mute mode + (+) HAL_MultiProcessor_EnableMuteMode() API enables mute mode + (+) HAL_UART_EnableStopMode() API enables the UART to wake up the MCU from stop mode + (+) HAL_UART_DisableStopMode() API disables the above functionality + (+) UART_SetConfig() API configures the UART peripheral + (+) UART_AdvFeatureConfig() API optionally configures the UART advanced features + (+) UART_CheckIdleState() API ensures that TEACK and/or REACK are set after initialization + (+) UART_Wakeup_AddressConfig() API configures the wake-up from stop mode parameters + (+) HAL_HalfDuplex_EnableTransmitter() API disables receiver and enables transmitter + (+) HAL_HalfDuplex_EnableReceiver() API disables transmitter and enables receiver +@endverbatim + * @{ + */ + +/** + * @brief Enable UART in mute mode (doesn't mean UART enters mute mode; + * to enter mute mode, HAL_MultiProcessor_EnterMuteMode() API must be called) + * @param huart: UART handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_MultiProcessor_EnableMuteMode(UART_HandleTypeDef *huart) +{ + /* Process Locked */ + __HAL_LOCK(huart); + + huart->State = HAL_UART_STATE_BUSY; + + /* Enable USART mute mode by setting the MME bit in the CR1 register */ + huart->Instance->CR1 |= USART_CR1_MME; + + huart->State = HAL_UART_STATE_READY; + + return (UART_CheckIdleState(huart)); +} + +/** + * @brief Disable UART mute mode (doesn't mean it actually wakes up the software, + * as it may not have been in mute mode at this very moment). + * @param huart: uart handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_MultiProcessor_DisableMuteMode(UART_HandleTypeDef *huart) +{ + /* Process Locked */ + __HAL_LOCK(huart); + + huart->State = HAL_UART_STATE_BUSY; + + /* Disable USART mute mode by clearing the MME bit in the CR1 register */ + huart->Instance->CR1 &= ~(USART_CR1_MME); + + huart->State = HAL_UART_STATE_READY; + + return (UART_CheckIdleState(huart)); +} + +/** + * @brief Enter UART mute mode (means UART actually enters mute mode). + * To exit from mute mode, HAL_MultiProcessor_DisableMuteMode() API must be called. + * @param huart: uart handle + * @retval HAL status + */ +void HAL_MultiProcessor_EnterMuteMode(UART_HandleTypeDef *huart) +{ + __HAL_UART_SEND_REQ(huart, UART_MUTE_MODE_REQUEST); +} + + + +/** + * @brief return the UART state + * @param huart: uart handle + * @retval HAL state + */ +HAL_UART_StateTypeDef HAL_UART_GetState(UART_HandleTypeDef *huart) +{ + return huart->State; +} + +/** +* @brief Return the UART error code +* @param huart : pointer to a UART_HandleTypeDef structure that contains + * the configuration information for the specified UART. +* @retval UART Error Code +*/ +uint32_t HAL_UART_GetError(UART_HandleTypeDef *huart) +{ + return huart->ErrorCode; +} + +/** + * @brief Configure the UART peripheral + * @param huart: uart handle + * @retval None + */ +HAL_StatusTypeDef UART_SetConfig(UART_HandleTypeDef *huart) +{ + uint32_t tmpreg = 0x00000000; + UART_ClockSourceTypeDef clocksource = UART_CLOCKSOURCE_UNDEFINED; + uint16_t brrtemp = 0x0000; + uint16_t usartdiv = 0x0000; + HAL_StatusTypeDef ret = HAL_OK; + + /* Check the parameters */ + assert_param(IS_UART_BAUDRATE(huart->Init.BaudRate)); + assert_param(IS_UART_WORD_LENGTH(huart->Init.WordLength)); + assert_param(IS_UART_STOPBITS(huart->Init.StopBits)); + assert_param(IS_UART_PARITY(huart->Init.Parity)); + assert_param(IS_UART_MODE(huart->Init.Mode)); + assert_param(IS_UART_HARDWARE_FLOW_CONTROL(huart->Init.HwFlowCtl)); + assert_param(IS_UART_ONEBIT_SAMPLING(huart->Init.OneBitSampling)); + + + /*-------------------------- USART CR1 Configuration -----------------------*/ + /* Clear M, PCE, PS, TE, RE and OVER8 bits and configure + * the UART Word Length, Parity, Mode and oversampling: + * set the M bits according to huart->Init.WordLength value + * set PCE and PS bits according to huart->Init.Parity value + * set TE and RE bits according to huart->Init.Mode value + * set OVER8 bit according to huart->Init.OverSampling value */ + tmpreg = (uint32_t)huart->Init.WordLength | huart->Init.Parity | huart->Init.Mode | huart->Init.OverSampling ; + MODIFY_REG(huart->Instance->CR1, UART_CR1_FIELDS, tmpreg); + + /*-------------------------- USART CR2 Configuration -----------------------*/ + /* Configure the UART Stop Bits: Set STOP[13:12] bits according + * to huart->Init.StopBits value */ + MODIFY_REG(huart->Instance->CR2, USART_CR2_STOP, huart->Init.StopBits); + + /*-------------------------- USART CR3 Configuration -----------------------*/ + /* Configure + * - UART HardWare Flow Control: set CTSE and RTSE bits according + * to huart->Init.HwFlowCtl value + * - one-bit sampling method versus three samples' majority rule according + * to huart->Init.OneBitSampling */ + tmpreg = (uint32_t)huart->Init.HwFlowCtl | huart->Init.OneBitSampling ; + MODIFY_REG(huart->Instance->CR3, (USART_CR3_RTSE | USART_CR3_CTSE | USART_CR3_ONEBIT), tmpreg); + + /*-------------------------- USART BRR Configuration -----------------------*/ + __HAL_UART_GETCLOCKSOURCE(huart, clocksource); + + /* Check the Over Sampling to set Baud Rate Register */ + if (huart->Init.OverSampling == UART_OVERSAMPLING_8) + { + switch (clocksource) + { + case UART_CLOCKSOURCE_PCLK1: + usartdiv = (uint16_t)(__DIV_SAMPLING8(HAL_RCC_GetPCLK1Freq(), huart->Init.BaudRate)); + break; + case UART_CLOCKSOURCE_HSI: + usartdiv = (uint16_t)(__DIV_SAMPLING8(HSI_VALUE, huart->Init.BaudRate)); + break; + case UART_CLOCKSOURCE_SYSCLK: + usartdiv = (uint16_t)(__DIV_SAMPLING8(HAL_RCC_GetSysClockFreq(), huart->Init.BaudRate)); + break; + case UART_CLOCKSOURCE_LSE: + usartdiv = (uint16_t)(__DIV_SAMPLING8(LSE_VALUE, huart->Init.BaudRate)); + break; + case UART_CLOCKSOURCE_UNDEFINED: + default: + ret = HAL_ERROR; + break; + } + + brrtemp = usartdiv & 0xFFF0; + brrtemp |= ((usartdiv & 0x000F) >> 1U); + huart->Instance->BRR = brrtemp; + } + else + { + switch (clocksource) + { + case UART_CLOCKSOURCE_PCLK1: + huart->Instance->BRR = (uint16_t)(__DIV_SAMPLING16(HAL_RCC_GetPCLK1Freq(), huart->Init.BaudRate)); + break; + case UART_CLOCKSOURCE_HSI: + huart->Instance->BRR = (uint16_t)(__DIV_SAMPLING16(HSI_VALUE, huart->Init.BaudRate)); + break; + case UART_CLOCKSOURCE_SYSCLK: + huart->Instance->BRR = (uint16_t)(__DIV_SAMPLING16(HAL_RCC_GetSysClockFreq(), huart->Init.BaudRate)); + break; + case UART_CLOCKSOURCE_LSE: + huart->Instance->BRR = (uint16_t)(__DIV_SAMPLING16(LSE_VALUE, huart->Init.BaudRate)); + break; + case UART_CLOCKSOURCE_UNDEFINED: + default: + ret = HAL_ERROR; + break; + } + } + + return ret; + +} + + +/** + * @brief Configure the UART peripheral advanced feautures + * @param huart: uart handle + * @retval None + */ +void UART_AdvFeatureConfig(UART_HandleTypeDef *huart) +{ + /* Check whether the set of advanced features to configure is properly set */ + assert_param(IS_UART_ADVFEATURE_INIT(huart->AdvancedInit.AdvFeatureInit)); + + /* if required, configure TX pin active level inversion */ + if (HAL_IS_BIT_SET(huart->AdvancedInit.AdvFeatureInit, UART_ADVFEATURE_TXINVERT_INIT)) + { + assert_param(IS_UART_ADVFEATURE_TXINV(huart->AdvancedInit.TxPinLevelInvert)); + MODIFY_REG(huart->Instance->CR2, USART_CR2_TXINV, huart->AdvancedInit.TxPinLevelInvert); + } + + /* if required, configure RX pin active level inversion */ + if (HAL_IS_BIT_SET(huart->AdvancedInit.AdvFeatureInit, UART_ADVFEATURE_RXINVERT_INIT)) + { + assert_param(IS_UART_ADVFEATURE_RXINV(huart->AdvancedInit.RxPinLevelInvert)); + MODIFY_REG(huart->Instance->CR2, USART_CR2_RXINV, huart->AdvancedInit.RxPinLevelInvert); + } + + /* if required, configure data inversion */ + if (HAL_IS_BIT_SET(huart->AdvancedInit.AdvFeatureInit, UART_ADVFEATURE_DATAINVERT_INIT)) + { + assert_param(IS_UART_ADVFEATURE_DATAINV(huart->AdvancedInit.DataInvert)); + MODIFY_REG(huart->Instance->CR2, USART_CR2_DATAINV, huart->AdvancedInit.DataInvert); + } + + /* if required, configure RX/TX pins swap */ + if (HAL_IS_BIT_SET(huart->AdvancedInit.AdvFeatureInit, UART_ADVFEATURE_SWAP_INIT)) + { + assert_param(IS_UART_ADVFEATURE_SWAP(huart->AdvancedInit.Swap)); + MODIFY_REG(huart->Instance->CR2, USART_CR2_SWAP, huart->AdvancedInit.Swap); + } + + /* if required, configure RX overrun detection disabling */ + if (HAL_IS_BIT_SET(huart->AdvancedInit.AdvFeatureInit, UART_ADVFEATURE_RXOVERRUNDISABLE_INIT)) + { + assert_param(IS_UART_OVERRUN(huart->AdvancedInit.OverrunDisable)); + MODIFY_REG(huart->Instance->CR3, USART_CR3_OVRDIS, huart->AdvancedInit.OverrunDisable); + } + + /* if required, configure DMA disabling on reception error */ + if (HAL_IS_BIT_SET(huart->AdvancedInit.AdvFeatureInit, UART_ADVFEATURE_DMADISABLEONERROR_INIT)) + { + assert_param(IS_UART_ADVFEATURE_DMAONRXERROR(huart->AdvancedInit.DMADisableonRxError)); + MODIFY_REG(huart->Instance->CR3, USART_CR3_DDRE, huart->AdvancedInit.DMADisableonRxError); + } + + /* if required, configure auto Baud rate detection scheme */ + if (HAL_IS_BIT_SET(huart->AdvancedInit.AdvFeatureInit, UART_ADVFEATURE_AUTOBAUDRATE_INIT)) + { + assert_param(IS_USART_AUTOBAUDRATE_DETECTION_INSTANCE(huart->Instance)); + assert_param(IS_UART_ADVFEATURE_AUTOBAUDRATE(huart->AdvancedInit.AutoBaudRateEnable)); + MODIFY_REG(huart->Instance->CR2, USART_CR2_ABREN, huart->AdvancedInit.AutoBaudRateEnable); + /* set auto Baudrate detection parameters if detection is enabled */ + if (huart->AdvancedInit.AutoBaudRateEnable == UART_ADVFEATURE_AUTOBAUDRATE_ENABLE) + { + assert_param(IS_UART_ADVFEATURE_AUTOBAUDRATEMODE(huart->AdvancedInit.AutoBaudRateMode)); + MODIFY_REG(huart->Instance->CR2, USART_CR2_ABRMODE, huart->AdvancedInit.AutoBaudRateMode); + } + } + + /* if required, configure MSB first on communication line */ + if (HAL_IS_BIT_SET(huart->AdvancedInit.AdvFeatureInit, UART_ADVFEATURE_MSBFIRST_INIT)) + { + assert_param(IS_UART_ADVFEATURE_MSBFIRST(huart->AdvancedInit.MSBFirst)); + MODIFY_REG(huart->Instance->CR2, USART_CR2_MSBFIRST, huart->AdvancedInit.MSBFirst); + } +} + + + +/** + * @brief Check the UART Idle State + * @param huart: uart handle + * @retval HAL status + */ +HAL_StatusTypeDef UART_CheckIdleState(UART_HandleTypeDef *huart) +{ + /* Initialize the UART ErrorCode */ + huart->ErrorCode = HAL_UART_ERROR_NONE; + + /* Check if the Transmitter is enabled */ + if((huart->Instance->CR1 & USART_CR1_TE) == USART_CR1_TE) + { + /* Wait until TEACK flag is set */ + if(UART_WaitOnFlagUntilTimeout(huart, USART_ISR_TEACK, RESET, HAL_UART_TIMEOUT_VALUE) != HAL_OK) + { + /* Timeout Occured */ + return HAL_TIMEOUT; + } + } + /* Check if the Receiver is enabled */ + if((huart->Instance->CR1 & USART_CR1_RE) == USART_CR1_RE) + { + /* Wait until REACK flag is set */ + if(UART_WaitOnFlagUntilTimeout(huart, USART_ISR_REACK, RESET, HAL_UART_TIMEOUT_VALUE) != HAL_OK) + { + /* Timeout Occured */ + return HAL_TIMEOUT; + } + } + + /* Initialize the UART State */ + huart->State= HAL_UART_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(huart); + + return HAL_OK; +} + + + + + + +/** + * @brief Enables the UART transmitter and disables the UART receiver. + * @param huart: UART handle + * @retval HAL status + * @retval None + */ +HAL_StatusTypeDef HAL_HalfDuplex_EnableTransmitter(UART_HandleTypeDef *huart) +{ + /* Process Locked */ + __HAL_LOCK(huart); + huart->State = HAL_UART_STATE_BUSY; + + /* Clear TE and RE bits */ + CLEAR_BIT(huart->Instance->CR1, (USART_CR1_TE | USART_CR1_RE)); + /* Enable the USART's transmit interface by setting the TE bit in the USART CR1 register */ + SET_BIT(huart->Instance->CR1, USART_CR1_TE); + + huart->State = HAL_UART_STATE_READY; + /* Process Unlocked */ + __HAL_UNLOCK(huart); + + return HAL_OK; +} + +/** + * @brief Enables the UART receiver and disables the UART transmitter. + * @param huart: UART handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_HalfDuplex_EnableReceiver(UART_HandleTypeDef *huart) +{ + /* Process Locked */ + __HAL_LOCK(huart); + huart->State = HAL_UART_STATE_BUSY; + + /* Clear TE and RE bits */ + CLEAR_BIT(huart->Instance->CR1, (USART_CR1_TE | USART_CR1_RE)); + /* Enable the USART's receive interface by setting the RE bit in the USART CR1 register */ + SET_BIT(huart->Instance->CR1, USART_CR1_RE); + + huart->State = HAL_UART_STATE_READY; + /* Process Unlocked */ + __HAL_UNLOCK(huart); + + return HAL_OK; +} + + +/** + * @} + */ + +/** + * @} + */ + +#endif /* HAL_UART_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_uart.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_uart.h new file mode 100644 index 0000000000..126ede6ce8 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_uart.h @@ -0,0 +1,877 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_uart.h + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief Header file of UART HAL module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32F0xx_HAL_UART_H +#define __STM32F0xx_HAL_UART_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal_def.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @addtogroup UART + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ + +/** + * @brief UART Init Structure definition + */ +typedef struct +{ + uint32_t BaudRate; /*!< This member configures the UART communication baud rate. + The baud rate register is computed using the following formula: + - If oversampling is 16 or in LIN mode (LIN mode not available on F030xx devices), + Baud Rate Register = ((PCLKx) / ((huart->Init.BaudRate))) + - If oversampling is 8, + Baud Rate Register[15:4] = ((2 * PCLKx) / ((huart->Init.BaudRate)))[15:4] + Baud Rate Register[3] = 0 + Baud Rate Register[2:0] = (((2 * PCLKx) / ((huart->Init.BaudRate)))[3:0]) >> 1 */ + + uint32_t WordLength; /*!< Specifies the number of data bits transmitted or received in a frame. + This parameter can be a value of @ref UARTEx_Word_Length */ + + uint32_t StopBits; /*!< Specifies the number of stop bits transmitted. + This parameter can be a value of @ref UART_Stop_Bits */ + + uint32_t Parity; /*!< Specifies the parity mode. + This parameter can be a value of @ref UART_Parity + @note When parity is enabled, the computed parity is inserted + at the MSB position of the transmitted data (9th bit when + the word length is set to 9 data bits; 8th bit when the + word length is set to 8 data bits). */ + + uint32_t Mode; /*!< Specifies wether the Receive or Transmit mode is enabled or disabled. + This parameter can be a value of @ref UART_Mode */ + + uint32_t HwFlowCtl; /*!< Specifies wether the hardware flow control mode is enabled + or disabled. + This parameter can be a value of @ref UART_Hardware_Flow_Control */ + + uint32_t OverSampling; /*!< Specifies wether the Over sampling 8 is enabled or disabled, to achieve higher speed (up to fPCLK/8). + This parameter can be a value of @ref UART_Over_Sampling */ + + uint32_t OneBitSampling; /*!< Specifies wether a single sample or three samples' majority vote is selected. + Selecting the single sample method increases the receiver tolerance to clock + deviations. This parameter can be a value of @ref UART_OneBit_Sampling. */ +}UART_InitTypeDef; + +/** + * @brief UART Advanced Features initalization structure definition + */ +typedef struct +{ + uint32_t AdvFeatureInit; /*!< Specifies which advanced UART features is initialized. Several + Advanced Features may be initialized at the same time . + This parameter can be a value of @ref UART_Advanced_Features_Initialization_Type */ + + uint32_t TxPinLevelInvert; /*!< Specifies whether the TX pin active level is inverted. + This parameter can be a value of @ref UART_Tx_Inv */ + + uint32_t RxPinLevelInvert; /*!< Specifies whether the RX pin active level is inverted. + This parameter can be a value of @ref UART_Rx_Inv */ + + uint32_t DataInvert; /*!< Specifies whether data are inverted (positive/direct logic + vs negative/inverted logic). + This parameter can be a value of @ref UART_Data_Inv */ + + uint32_t Swap; /*!< Specifies whether TX and RX pins are swapped. + This parameter can be a value of @ref UART_Rx_Tx_Swap */ + + uint32_t OverrunDisable; /*!< Specifies whether the reception overrun detection is disabled. + This parameter can be a value of @ref UART_Overrun_Disable */ + + uint32_t DMADisableonRxError; /*!< Specifies whether the DMA is disabled in case of reception error. + This parameter can be a value of @ref UART_DMA_Disable_on_Rx_Error */ + + uint32_t AutoBaudRateEnable; /*!< Specifies whether auto Baud rate detection is enabled. + This parameter can be a value of @ref UART_AutoBaudRate_Enable */ + + uint32_t AutoBaudRateMode; /*!< If auto Baud rate detection is enabled, specifies how the rate + detection is carried out. + This parameter can be a value of @ref UARTEx_AutoBaud_Rate_Mode */ + + uint32_t MSBFirst; /*!< Specifies whether MSB is sent first on UART line. + This parameter can be a value of @ref UART_MSB_First */ +} UART_AdvFeatureInitTypeDef; + +/** + * @brief UART wake up from stop mode parameters + */ +typedef struct +{ + uint32_t WakeUpEvent; /*!< Specifies which event will activat the Wakeup from Stop mode flag (WUF). + This parameter can be a value of @ref UART_WakeUp_from_Stop_Selection. + If set to UART_WAKEUP_ON_ADDRESS, the two other fields below must + be filled up. */ + + uint16_t AddressLength; /*!< Specifies whether the address is 4 or 7-bit long. + This parameter can be a value of @ref UART_WakeUp_Address_Length */ + + uint8_t Address; /*!< UART/USART node address (7-bit long max) */ +} UART_WakeUpTypeDef; + +/** + * @brief HAL UART State structures definition + */ +typedef enum +{ + HAL_UART_STATE_RESET = 0x00, /*!< Peripheral is not initialized */ + HAL_UART_STATE_READY = 0x01, /*!< Peripheral Initialized and ready for use */ + HAL_UART_STATE_BUSY = 0x02, /*!< an internal process is ongoing */ + HAL_UART_STATE_BUSY_TX = 0x12, /*!< Data Transmission process is ongoing */ + HAL_UART_STATE_BUSY_RX = 0x22, /*!< Data Reception process is ongoing */ + HAL_UART_STATE_BUSY_TX_RX = 0x32, /*!< Data Transmission and Reception process is ongoing */ + HAL_UART_STATE_TIMEOUT = 0x03, /*!< Timeout state */ + HAL_UART_STATE_ERROR = 0x04 /*!< Error */ +}HAL_UART_StateTypeDef; + +/** + * @brief HAL UART Error Code structure definition + */ +typedef enum +{ + HAL_UART_ERROR_NONE = 0x00, /*!< No error */ + HAL_UART_ERROR_PE = 0x01, /*!< Parity error */ + HAL_UART_ERROR_NE = 0x02, /*!< Noise error */ + HAL_UART_ERROR_FE = 0x04, /*!< frame error */ + HAL_UART_ERROR_ORE = 0x08, /*!< Overrun error */ + HAL_UART_ERROR_DMA = 0x10 /*!< DMA transfer error */ +}HAL_UART_ErrorTypeDef; + +/** + * @brief UART clock sources definition + */ +typedef enum +{ + UART_CLOCKSOURCE_PCLK1 = 0x00, /*!< PCLK1 clock source */ + UART_CLOCKSOURCE_HSI = 0x02, /*!< HSI clock source */ + UART_CLOCKSOURCE_SYSCLK = 0x04, /*!< SYSCLK clock source */ + UART_CLOCKSOURCE_LSE = 0x08, /*!< LSE clock source */ + UART_CLOCKSOURCE_UNDEFINED = 0x10 /*!< undefined clock source */ +}UART_ClockSourceTypeDef; + +/** + * @brief UART handle Structure definition + */ +typedef struct +{ + USART_TypeDef *Instance; /* UART registers base address */ + + UART_InitTypeDef Init; /* UART communication parameters */ + + UART_AdvFeatureInitTypeDef AdvancedInit; /* UART Advanced Features initialization parameters */ + + uint8_t *pTxBuffPtr; /* Pointer to UART Tx transfer Buffer */ + + uint16_t TxXferSize; /* UART Tx Transfer size */ + + uint16_t TxXferCount; /* UART Tx Transfer Counter */ + + uint8_t *pRxBuffPtr; /* Pointer to UART Rx transfer Buffer */ + + uint16_t RxXferSize; /* UART Rx Transfer size */ + + uint16_t RxXferCount; /* UART Rx Transfer Counter */ + + uint16_t Mask; /* UART Rx RDR register mask */ + + DMA_HandleTypeDef *hdmatx; /* UART Tx DMA Handle parameters */ + + DMA_HandleTypeDef *hdmarx; /* UART Rx DMA Handle parameters */ + + HAL_LockTypeDef Lock; /* Locking object */ + + HAL_UART_StateTypeDef State; /* UART communication state */ + + HAL_UART_ErrorTypeDef ErrorCode; /* UART Error code */ + +}UART_HandleTypeDef; + + +/* Exported constants --------------------------------------------------------*/ +/** @defgroup UART_Exported_Constants + * @{ + */ + +/** @defgroup UART_Stop_Bits UART Number of Stop Bits + * @{ + */ +#define UART_STOPBITS_1 ((uint32_t)0x0000) +#define UART_STOPBITS_2 ((uint32_t)USART_CR2_STOP_1) +#define IS_UART_STOPBITS(STOPBITS) (((STOPBITS) == UART_STOPBITS_1) || \ + ((STOPBITS) == UART_STOPBITS_2)) +/** + * @} + */ + +/** @defgroup UART_Parity UART Parity + * @{ + */ +#define UART_PARITY_NONE ((uint32_t)0x0000) +#define UART_PARITY_EVEN ((uint32_t)USART_CR1_PCE) +#define UART_PARITY_ODD ((uint32_t)(USART_CR1_PCE | USART_CR1_PS)) +#define IS_UART_PARITY(PARITY) (((PARITY) == UART_PARITY_NONE) || \ + ((PARITY) == UART_PARITY_EVEN) || \ + ((PARITY) == UART_PARITY_ODD)) +/** + * @} + */ + +/** @defgroup UART_Hardware_Flow_Control UART Hardware Flow Control + * @{ + */ +#define UART_HWCONTROL_NONE ((uint32_t)0x0000) +#define UART_HWCONTROL_RTS ((uint32_t)USART_CR3_RTSE) +#define UART_HWCONTROL_CTS ((uint32_t)USART_CR3_CTSE) +#define UART_HWCONTROL_RTS_CTS ((uint32_t)(USART_CR3_RTSE | USART_CR3_CTSE)) +#define IS_UART_HARDWARE_FLOW_CONTROL(CONTROL)\ + (((CONTROL) == UART_HWCONTROL_NONE) || \ + ((CONTROL) == UART_HWCONTROL_RTS) || \ + ((CONTROL) == UART_HWCONTROL_CTS) || \ + ((CONTROL) == UART_HWCONTROL_RTS_CTS)) +/** + * @} + */ + +/** @defgroup UART_Mode UART Transfer Mode + * @{ + */ +#define UART_MODE_RX ((uint32_t)USART_CR1_RE) +#define UART_MODE_TX ((uint32_t)USART_CR1_TE) +#define UART_MODE_TX_RX ((uint32_t)(USART_CR1_TE |USART_CR1_RE)) +#define IS_UART_MODE(MODE) ((((MODE) & (~((uint32_t)(UART_MODE_TX_RX)))) == (uint32_t)0x00) && ((MODE) != (uint32_t)0x00)) +/** + * @} + */ + + /** @defgroup UART_State UART State + * @{ + */ +#define UART_STATE_DISABLE ((uint32_t)0x0000) +#define UART_STATE_ENABLE ((uint32_t)USART_CR1_UE) +#define IS_UART_STATE(STATE) (((STATE) == UART_STATE_DISABLE) || \ + ((STATE) == UART_STATE_ENABLE)) +/** + * @} + */ + +/** @defgroup UART_Over_Sampling UART Over Sampling + * @{ + */ +#define UART_OVERSAMPLING_16 ((uint32_t)0x0000) +#define UART_OVERSAMPLING_8 ((uint32_t)USART_CR1_OVER8) +#define IS_UART_OVERSAMPLING(SAMPLING) (((SAMPLING) == UART_OVERSAMPLING_16) || \ + ((SAMPLING) == UART_OVERSAMPLING_8)) +/** + * @} + */ + +/** @defgroup UART_OneBit_Sampling UART One Bit Sampling Method + * @{ + */ +#define UART_ONEBIT_SAMPLING_DISABLED ((uint32_t)0x0000) +#define UART_ONEBIT_SAMPLING_ENABLED ((uint32_t)USART_CR3_ONEBIT) +#define IS_UART_ONEBIT_SAMPLING(ONEBIT) (((ONEBIT) == UART_ONEBIT_SAMPLING_DISABLED) || \ + ((ONEBIT) == UART_ONEBIT_SAMPLING_ENABLED)) +/** + * @} + */ + + +/** @defgroup UART_Receiver_TimeOut UART Receiver TimeOut + * @{ + */ +#define UART_RECEIVER_TIMEOUT_DISABLE ((uint32_t)0x00000000) +#define UART_RECEIVER_TIMEOUT_ENABLE ((uint32_t)USART_CR2_RTOEN) +#define IS_UART_RECEIVER_TIMEOUT(TIMEOUT) (((TIMEOUT) == UART_RECEIVER_TIMEOUT_DISABLE) || \ + ((TIMEOUT) == UART_RECEIVER_TIMEOUT_ENABLE)) +/** + * @} + */ + +/** @defgroup UART_One_Bit UART One Bit sampling + * @{ + */ +#define UART_ONE_BIT_SAMPLE_DISABLED ((uint32_t)0x00000000) +#define UART_ONE_BIT_SAMPLE_ENABLED ((uint32_t)USART_CR3_ONEBIT) +#define IS_UART_ONEBIT_SAMPLE(ONEBIT) (((ONEBIT) == UART_ONE_BIT_SAMPLE_DISABLED) || \ + ((ONEBIT) == UART_ONE_BIT_SAMPLE_ENABLED)) +/** + * @} + */ + +/** @defgroup UART_DMA_Tx UART DMA Tx + * @{ + */ +#define UART_DMA_TX_DISABLE ((uint32_t)0x00000000) +#define UART_DMA_TX_ENABLE ((uint32_t)USART_CR3_DMAT) +#define IS_UART_DMA_TX(DMATX) (((DMATX) == UART_DMA_TX_DISABLE) || \ + ((DMATX) == UART_DMA_TX_ENABLE)) +/** + * @} + */ + +/** @defgroup UART_DMA_Rx UART DMA Rx + * @{ + */ +#define UART_DMA_RX_DISABLE ((uint32_t)0x0000) +#define UART_DMA_RX_ENABLE ((uint32_t)USART_CR3_DMAR) +#define IS_UART_DMA_RX(DMARX) (((DMARX) == UART_DMA_RX_DISABLE) || \ + ((DMARX) == UART_DMA_RX_ENABLE)) +/** + * @} + */ + +/** @defgroup UART_Half_Duplex_Selection UART Half Duplex Selection + * @{ + */ +#define UART_HALF_DUPLEX_DISABLE ((uint32_t)0x0000) +#define UART_HALF_DUPLEX_ENABLE ((uint32_t)USART_CR3_HDSEL) +#define IS_UART_HALF_DUPLEX(HDSEL) (((HDSEL) == UART_HALF_DUPLEX_DISABLE) || \ + ((HDSEL) == UART_HALF_DUPLEX_ENABLE)) +/** + * @} + */ + +/** @defgroup UART_WakeUp_Address_Length UART WakeUp Address Length + * @{ + */ +#define UART_ADDRESS_DETECT_4B ((uint32_t)0x00000000) +#define UART_ADDRESS_DETECT_7B ((uint32_t)USART_CR2_ADDM7) +#define IS_UART_ADDRESSLENGTH_DETECT(ADDRESS) (((ADDRESS) == UART_ADDRESS_DETECT_4B) || \ + ((ADDRESS) == UART_ADDRESS_DETECT_7B)) +/** + * @} + */ + +/** @defgroup UART_WakeUp_Methods UART WakeUp Methods + * @{ + */ +#define UART_WAKEUPMETHOD_IDLELINE ((uint32_t)0x00000000) +#define UART_WAKEUPMETHOD_ADDRESSMARK ((uint32_t)USART_CR1_WAKE) +#define IS_UART_WAKEUPMETHOD(WAKEUP) (((WAKEUP) == UART_WAKEUPMETHOD_IDLELINE) || \ + ((WAKEUP) == UART_WAKEUPMETHOD_ADDRESSMARK)) +/** + * @} + */ + +/** Elements values convention: 000000000XXYYYYYb + * - YYYYY : Interrupt source position in the XX register (5bits) + * - XX : Interrupt source register (2bits) + * - 01: CR1 register + * - 10: CR2 register + * - 11: CR3 register + */ +#define UART_IT_ERR ((uint16_t)0x0060) + +/** Elements values convention: 0000ZZZZ00000000b + * - ZZZZ : Flag position in the ISR register(4bits) + */ +#define UART_IT_ORE ((uint16_t)0x0300) +#define UART_IT_NE ((uint16_t)0x0200) +#define UART_IT_FE ((uint16_t)0x0100) + +/** @defgroup UART_Advanced_Features_Initialization_Type UART Advanced Feature Initialization Type + * @{ + */ +#define UART_ADVFEATURE_NO_INIT ((uint32_t)0x00000000) +#define UART_ADVFEATURE_TXINVERT_INIT ((uint32_t)0x00000001) +#define UART_ADVFEATURE_RXINVERT_INIT ((uint32_t)0x00000002) +#define UART_ADVFEATURE_DATAINVERT_INIT ((uint32_t)0x00000004) +#define UART_ADVFEATURE_SWAP_INIT ((uint32_t)0x00000008) +#define UART_ADVFEATURE_RXOVERRUNDISABLE_INIT ((uint32_t)0x00000010) +#define UART_ADVFEATURE_DMADISABLEONERROR_INIT ((uint32_t)0x00000020) +#define UART_ADVFEATURE_AUTOBAUDRATE_INIT ((uint32_t)0x00000040) +#define UART_ADVFEATURE_MSBFIRST_INIT ((uint32_t)0x00000080) +#define IS_UART_ADVFEATURE_INIT(INIT) ((INIT) <= (UART_ADVFEATURE_NO_INIT | \ + UART_ADVFEATURE_TXINVERT_INIT | \ + UART_ADVFEATURE_RXINVERT_INIT | \ + UART_ADVFEATURE_DATAINVERT_INIT | \ + UART_ADVFEATURE_SWAP_INIT | \ + UART_ADVFEATURE_RXOVERRUNDISABLE_INIT | \ + UART_ADVFEATURE_DMADISABLEONERROR_INIT | \ + UART_ADVFEATURE_AUTOBAUDRATE_INIT | \ + UART_ADVFEATURE_MSBFIRST_INIT)) +/** + * @} + */ + +/** @defgroup UART_Tx_Inv UART Advanced Feature TX Pin Active Level Inversion + * @{ + */ +#define UART_ADVFEATURE_TXINV_DISABLE ((uint32_t)0x00000000) +#define UART_ADVFEATURE_TXINV_ENABLE ((uint32_t)USART_CR2_TXINV) +#define IS_UART_ADVFEATURE_TXINV(TXINV) (((TXINV) == UART_ADVFEATURE_TXINV_DISABLE) || \ + ((TXINV) == UART_ADVFEATURE_TXINV_ENABLE)) +/** + * @} + */ + +/** @defgroup UART_Rx_Inv UART Advanced Feature RX Pin Active Level Inversion + * @{ + */ +#define UART_ADVFEATURE_RXINV_DISABLE ((uint32_t)0x00000000) +#define UART_ADVFEATURE_RXINV_ENABLE ((uint32_t)USART_CR2_RXINV) +#define IS_UART_ADVFEATURE_RXINV(RXINV) (((RXINV) == UART_ADVFEATURE_RXINV_DISABLE) || \ + ((RXINV) == UART_ADVFEATURE_RXINV_ENABLE)) +/** + * @} + */ + +/** @defgroup UART_Data_Inv UART Advanced Feature Binary Data Inversion + * @{ + */ +#define UART_ADVFEATURE_DATAINV_DISABLE ((uint32_t)0x00000000) +#define UART_ADVFEATURE_DATAINV_ENABLE ((uint32_t)USART_CR2_DATAINV) +#define IS_UART_ADVFEATURE_DATAINV(DATAINV) (((DATAINV) == UART_ADVFEATURE_DATAINV_DISABLE) || \ + ((DATAINV) == UART_ADVFEATURE_DATAINV_ENABLE)) +/** + * @} + */ + +/** @defgroup UART_Rx_Tx_Swap UART Advanced Feature RX TX Pins Swap + * @{ + */ +#define UART_ADVFEATURE_SWAP_DISABLE ((uint32_t)0x00000000) +#define UART_ADVFEATURE_SWAP_ENABLE ((uint32_t)USART_CR2_SWAP) +#define IS_UART_ADVFEATURE_SWAP(SWAP) (((SWAP) == UART_ADVFEATURE_SWAP_DISABLE) || \ + ((SWAP) == UART_ADVFEATURE_SWAP_ENABLE)) +/** + * @} + */ + +/** @defgroup UART_Overrun_Disable UART Advanced Feature Overrun Disable + * @{ + */ +#define UART_ADVFEATURE_OVERRUN_ENABLE ((uint32_t)0x00000000) +#define UART_ADVFEATURE_OVERRUN_DISABLE ((uint32_t)USART_CR3_OVRDIS) +#define IS_UART_OVERRUN(OVERRUN) (((OVERRUN) == UART_ADVFEATURE_OVERRUN_ENABLE) || \ + ((OVERRUN) == UART_ADVFEATURE_OVERRUN_DISABLE)) +/** + * @} + */ + +/** @defgroup UART_AutoBaudRate_Enable UART Advanced Feature Auto BaudRate Enable + * @{ + */ +#define UART_ADVFEATURE_AUTOBAUDRATE_DISABLE ((uint32_t)0x00000000) +#define UART_ADVFEATURE_AUTOBAUDRATE_ENABLE ((uint32_t)USART_CR2_ABREN) +#define IS_UART_ADVFEATURE_AUTOBAUDRATE(AUTOBAUDRATE) (((AUTOBAUDRATE) == UART_ADVFEATURE_AUTOBAUDRATE_DISABLE) || \ + ((AUTOBAUDRATE) == UART_ADVFEATURE_AUTOBAUDRATE_ENABLE)) +/** + * @} + */ + +/** @defgroup UART_DMA_Disable_on_Rx_Error UART Advanced Feature DMA Disable On Rx Error + * @{ + */ +#define UART_ADVFEATURE_DMA_ENABLEONRXERROR ((uint32_t)0x00000000) +#define UART_ADVFEATURE_DMA_DISABLEONRXERROR ((uint32_t)USART_CR3_DDRE) +#define IS_UART_ADVFEATURE_DMAONRXERROR(DMA) (((DMA) == UART_ADVFEATURE_DMA_ENABLEONRXERROR) || \ + ((DMA) == UART_ADVFEATURE_DMA_DISABLEONRXERROR)) +/** + * @} + */ + +/** @defgroup UART_MSB_First UART Advanced Feature MSB First + * @{ + */ +#define UART_ADVFEATURE_MSBFIRST_DISABLE ((uint32_t)0x00000000) +#define UART_ADVFEATURE_MSBFIRST_ENABLE ((uint32_t)USART_CR2_MSBFIRST) +#define IS_UART_ADVFEATURE_MSBFIRST(MSBFIRST) (((MSBFIRST) == UART_ADVFEATURE_MSBFIRST_DISABLE) || \ + ((MSBFIRST) == UART_ADVFEATURE_MSBFIRST_ENABLE)) +/** + * @} + */ + +/** @defgroup UART_Mute_Mode UART Advanced Feature Mute Mode Enable + * @{ + */ +#define UART_ADVFEATURE_MUTEMODE_DISABLE ((uint32_t)0x00000000) +#define UART_ADVFEATURE_MUTEMODE_ENABLE ((uint32_t)USART_CR1_MME) +#define IS_UART_MUTE_MODE(MUTE) (((MUTE) == UART_ADVFEATURE_MUTEMODE_DISABLE) || \ + ((MUTE) == UART_ADVFEATURE_MUTEMODE_ENABLE)) +/** + * @} + */ + +/** @defgroup UART_CR2_ADDRESS_LSB_POS UART Address-matching LSB Position In CR2 Register + * @{ + */ +#define UART_CR2_ADDRESS_LSB_POS ((uint32_t) 24) +/** + * @} + */ + +/** @defgroup UART_DriverEnable_Polarity UART DriverEnable Polarity + * @{ + */ +#define UART_DE_POLARITY_HIGH ((uint32_t)0x00000000) +#define UART_DE_POLARITY_LOW ((uint32_t)USART_CR3_DEP) +#define IS_UART_DE_POLARITY(POLARITY) (((POLARITY) == UART_DE_POLARITY_HIGH) || \ + ((POLARITY) == UART_DE_POLARITY_LOW)) +/** + * @} + */ + +/** @defgroup UART_CR1_DEAT_ADDRESS_LSB_POS UART Driver Enable Assertion Time LSB Position In CR1 Register + * @{ + */ +#define UART_CR1_DEAT_ADDRESS_LSB_POS ((uint32_t) 21) +/** + * @} + */ + +/** @defgroup UART_CR1_DEDT_ADDRESS_LSB_POS UART Driver Enable DeAssertion Time LSB Position In CR1 Register + * @{ + */ +#define UART_CR1_DEDT_ADDRESS_LSB_POS ((uint32_t) 16) +/** + * @} + */ + +/** @defgroup UART_Interruption_Mask UART Interruptions Flag Mask + * @{ + */ +#define UART_IT_MASK ((uint32_t)0x001F) +/** + * @} + */ + +/** @defgroup UART_TimeOut_Value UART polling-based communications time-out value + * @{ + */ +#define HAL_UART_TIMEOUT_VALUE 0x1FFFFFF +/** + * @} + */ + +/** + * @} + */ + +/* Exported macros -----------------------------------------------------------*/ +/** @defgroup UART_Exported_Macros + * @{ + */ + +/** @brief Reset UART handle state + * @param __HANDLE__: UART handle. + * @retval None + */ +#define __HAL_UART_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_UART_STATE_RESET) + +/** @brief Checks whether the specified UART flag is set or not. + * @param __HANDLE__: specifies the UART Handle. + * This parameter can be UARTx where x: 1, 2, 3 or 4 to select the USART or + * UART peripheral (datasheet: up to four USART/UARTs) + * @param __FLAG__: specifies the flag to check. + * This parameter can be one of the following values: + * @arg UART_FLAG_REACK: Receive enable ackowledge flag + * @arg UART_FLAG_TEACK: Transmit enable ackowledge flag + * @arg UART_FLAG_WUF: Wake up from stop mode flag (not available on F030xx devices) + * @arg UART_FLAG_RWU: Receiver wake up flag (not available on F030xx devices) + * @arg UART_FLAG_SBKF: Send Break flag + * @arg UART_FLAG_CMF: Character match flag + * @arg UART_FLAG_BUSY: Busy flag + * @arg UART_FLAG_ABRF: Auto Baud rate detection flag + * @arg UART_FLAG_ABRE: Auto Baud rate detection error flag + * @arg UART_FLAG_EOBF: End of block flag (not available on F030xx devices) + * @arg UART_FLAG_RTOF: Receiver timeout flag + * @arg UART_FLAG_CTS: CTS Change flag + * @arg UART_FLAG_LBD: LIN Break detection flag (not available on F030xx devices) + * @arg UART_FLAG_TXE: Transmit data register empty flag + * @arg UART_FLAG_TC: Transmission Complete flag + * @arg UART_FLAG_RXNE: Receive data register not empty flag + * @arg UART_FLAG_IDLE: Idle Line detection flag + * @arg UART_FLAG_ORE: OverRun Error flag + * @arg UART_FLAG_NE: Noise Error flag + * @arg UART_FLAG_FE: Framing Error flag + * @arg UART_FLAG_PE: Parity Error flag + * @retval The new state of __FLAG__ (TRUE or FALSE). + */ +#define __HAL_UART_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->ISR & (__FLAG__)) == (__FLAG__)) + +/** @brief Enables the specified UART interrupt. + * @param __HANDLE__: specifies the UART Handle. + * This parameter can be UARTx where x: 1, 2, 3 or 4 to select the USART or + * UART peripheral. (datasheet: up to four USART/UARTs) + * @param __INTERRUPT__: specifies the UART interrupt source to enable. + * This parameter can be one of the following values: + * @arg UART_IT_WUF: Wakeup from stop mode interrupt (not available on F030xx devices) + * @arg UART_IT_CM: Character match interrupt + * @arg UART_IT_CTS: CTS change interrupt + * @arg UART_IT_LBD: LIN Break detection interrupt (not available on F030xx devices) + * @arg UART_IT_TXE: Transmit Data Register empty interrupt + * @arg UART_IT_TC: Transmission complete interrupt + * @arg UART_IT_RXNE: Receive Data register not empty interrupt + * @arg UART_IT_IDLE: Idle line detection interrupt + * @arg UART_IT_PE: Parity Error interrupt + * @arg UART_IT_ERR: Error interrupt(Frame error, noise error, overrun error) + * @retval None + */ +#define __HAL_UART_ENABLE_IT(__HANDLE__, __INTERRUPT__) (((((uint8_t)(__INTERRUPT__)) >> 5U) == 1)? ((__HANDLE__)->Instance->CR1 |= (1U << ((__INTERRUPT__) & UART_IT_MASK))): \ + ((((uint8_t)(__INTERRUPT__)) >> 5U) == 2)? ((__HANDLE__)->Instance->CR2 |= (1U << ((__INTERRUPT__) & UART_IT_MASK))): \ + ((__HANDLE__)->Instance->CR3 |= (1U << ((__INTERRUPT__) & UART_IT_MASK)))) + + +/** @brief Disables the specified UART interrupt. + * @param __HANDLE__: specifies the UART Handle. + * This parameter can be UARTx where x: 1, 2, 3 or 4 to select the USART or + * UART peripheral. (datasheet: up to four USART/UARTs) + * @param __INTERRUPT__: specifies the UART interrupt source to disable. + * This parameter can be one of the following values: + * @arg UART_IT_WUF: Wakeup from stop mode interrupt (not available on F030xx devices) + * @arg UART_IT_CM: Character match interrupt + * @arg UART_IT_CTS: CTS change interrupt + * @arg UART_IT_LBD: LIN Break detection interrupt (not available on F030xx devices) + * @arg UART_IT_TXE: Transmit Data Register empty interrupt + * @arg UART_IT_TC: Transmission complete interrupt + * @arg UART_IT_RXNE: Receive Data register not empty interrupt + * @arg UART_IT_IDLE: Idle line detection interrupt + * @arg UART_IT_PE: Parity Error interrupt + * @arg UART_IT_ERR: Error interrupt(Frame error, noise error, overrun error) + * @retval None + */ +#define __HAL_UART_DISABLE_IT(__HANDLE__, __INTERRUPT__) (((((uint8_t)(__INTERRUPT__)) >> 5U) == 1)? ((__HANDLE__)->Instance->CR1 &= ~ (1U << ((__INTERRUPT__) & UART_IT_MASK))): \ + ((((uint8_t)(__INTERRUPT__)) >> 5U) == 2)? ((__HANDLE__)->Instance->CR2 &= ~ (1U << ((__INTERRUPT__) & UART_IT_MASK))): \ + ((__HANDLE__)->Instance->CR3 &= ~ (1U << ((__INTERRUPT__) & UART_IT_MASK)))) + +/** @brief Checks whether the specified UART interrupt has occurred or not. + * @param __HANDLE__: specifies the UART Handle. + * This parameter can be UARTx where x: 1, 2, 3 or 4 to select the USART or + * UART peripheral. (datasheet: up to four USART/UARTs) + * @param __IT__: specifies the UART interrupt to check. + * This parameter can be one of the following values: + * @arg UART_IT_WUF: Wakeup from stop mode interrupt (not available on F030xx devices) + * @arg UART_IT_CM: Character match interrupt + * @arg UART_IT_CTS: CTS change interrupt + * @arg UART_IT_LBD: LIN Break detection interrupt (not available on F030xx devices) + * @arg UART_IT_TXE: Transmit Data Register empty interrupt + * @arg UART_IT_TC: Transmission complete interrupt + * @arg UART_IT_RXNE: Receive Data register not empty interrupt + * @arg UART_IT_IDLE: Idle line detection interrupt + * @arg UART_IT_ORE: OverRun Error interrupt + * @arg UART_IT_NE: Noise Error interrupt + * @arg UART_IT_FE: Framing Error interrupt + * @arg UART_IT_PE: Parity Error interrupt + * @retval The new state of __IT__ (TRUE or FALSE). + */ +#define __HAL_UART_GET_IT(__HANDLE__, __IT__) ((__HANDLE__)->Instance->ISR & ((uint32_t)1 << ((__IT__)>> 0x08))) + +/** @brief Checks whether the specified UART interrupt source is enabled. + * @param __HANDLE__: specifies the UART Handle. + * This parameter can be UARTx where x: 1, 2, 3 or 4 to select the USART or + * UART peripheral. (datasheet: up to four USART/UARTs) + * @param __IT__: specifies the UART interrupt source to check. + * This parameter can be one of the following values: + * @arg UART_IT_WUF: Wakeup from stop mode interrupt (not available on F030xx devices) + * @arg UART_IT_CM: Character match interrupt + * @arg UART_IT_CTS: CTS change interrupt + * @arg UART_IT_LBD: LIN Break detection interrupt (not available on F030xx devices) + * @arg UART_IT_TXE: Transmit Data Register empty interrupt + * @arg UART_IT_TC: Transmission complete interrupt + * @arg UART_IT_RXNE: Receive Data register not empty interrupt + * @arg UART_IT_IDLE: Idle line detection interrupt + * @arg UART_IT_ORE: OverRun Error interrupt + * @arg UART_IT_NE: Noise Error interrupt + * @arg UART_IT_FE: Framing Error interrupt + * @arg UART_IT_PE: Parity Error interrupt + * @retval The new state of __IT__ (TRUE or FALSE). + */ +#define __HAL_UART_GET_IT_SOURCE(__HANDLE__, __IT__) ((((((uint8_t)(__IT__)) >> 5U) == 1)? (__HANDLE__)->Instance->CR1:(((((uint8_t)(__IT__)) >> 5U) == 2)? \ + (__HANDLE__)->Instance->CR2 : (__HANDLE__)->Instance->CR3)) & ((uint32_t)1 << (((uint16_t)(__IT__)) & UART_IT_MASK))) + +/** @brief Clears the specified UART ISR flag, in setting the proper ICR register flag. + * @param __HANDLE__: specifies the UART Handle. + * This parameter can be UARTx where x: 1, 2, 3 or 4 to select the USART or + * UART peripheral. (datasheet: up to four USART/UARTs) + * @param __IT_CLEAR__: specifies the interrupt clear register flag that needs to be set + * to clear the corresponding interrupt + * This parameter can be one of the following values: + * @arg UART_CLEAR_PEF: Parity Error Clear Flag + * @arg UART_CLEAR_FEF: Framing Error Clear Flag + * @arg UART_CLEAR_NEF: Noise detected Clear Flag + * @arg UART_CLEAR_OREF: OverRun Error Clear Flag + * @arg UART_CLEAR_IDLEF: IDLE line detected Clear Flag + * @arg UART_CLEAR_TCF: Transmission Complete Clear Flag + * @arg UART_CLEAR_LBDF: LIN Break Detection Clear Flag (not available on F030xx devices) + * @arg UART_CLEAR_CTSF: CTS Interrupt Clear Flag + * @arg UART_CLEAR_RTOF: Receiver Time Out Clear Flag + * @arg UART_CLEAR_EOBF: End Of Block Clear Flag (not available on F030xx devices) + * @arg UART_CLEAR_CMF: Character Match Clear Flag + * @arg UART_CLEAR_WUF: Wake Up from stop mode Clear Flag (not available on F030xx devices) + * @retval None + */ +#define __HAL_UART_CLEAR_IT(__HANDLE__, __IT_CLEAR__) ((__HANDLE__)->Instance->ICR |= (uint32_t)(__IT_CLEAR__)) + +/** @brief Set a specific UART request flag. + * @param __HANDLE__: specifies the UART Handle. + * This parameter can be UARTx where x: 1, 2, 3 or 4 to select the USART or + * UART peripheral. (datasheet: up to four USART/UARTs) + * @param __REQ__: specifies the request flag to set + * This parameter can be one of the following values: + * @arg UART_AUTOBAUD_REQUEST: Auto-Baud Rate Request + * @arg UART_SENDBREAK_REQUEST: Send Break Request + * @arg UART_MUTE_MODE_REQUEST: Mute Mode Request + * @arg UART_RXDATA_FLUSH_REQUEST: Receive Data flush Request + * @arg UART_TXDATA_FLUSH_REQUEST: Transmit data flush Request (not available on F030xx devices) + * @retval None + */ +#define __HAL_UART_SEND_REQ(__HANDLE__, __REQ__) ((__HANDLE__)->Instance->RQR |= (uint32_t)(__REQ__)) + +/** @brief Enable UART + * @param __HANDLE__: specifies the UART Handle. + * The Handle Instance can be UARTx where x: 1, 2, 3, 4 or 5 to select the UART peripheral + * @retval None + */ +#define __HAL_UART_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 |= USART_CR1_UE) + +/** @brief Disable UART + * @param __HANDLE__: specifies the UART Handle. + * The Handle Instance can be UARTx where x: 1, 2, 3, 4 or 5 to select the UART peripheral + * @retval None + */ +#define __HAL_UART_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 &= ~USART_CR1_UE) + +/** @brief BRR division operation to set BRR register in 8-bit oversampling mode + * @param _PCLK_: UART clock + * @param _BAUD_: Baud rate set by the user + * @retval Division result + */ +#define __DIV_SAMPLING8(_PCLK_, _BAUD_) (((_PCLK_)*2)/((_BAUD_))) + +/** @brief BRR division operation to set BRR register in 16-bit oversampling mode + * @param _PCLK_: UART clock + * @param _BAUD_: Baud rate set by the user + * @retval Division result + */ +#define __DIV_SAMPLING16(_PCLK_, _BAUD_) (((_PCLK_))/((_BAUD_))) + +/** @brief Check UART Baud rate + * @param BAUDRATE: Baudrate specified by the user + * The maximum Baud Rate is derived from the maximum clock on F0 (i.e. 48 MHz) + * divided by the smallest oversampling used on the USART (i.e. 8) + * @retval Test result (TRUE or FALSE). + */ +#define IS_UART_BAUDRATE(BAUDRATE) ((BAUDRATE) < 9000001) + +/** @brief Check UART assertion time + * @param TIME: 5-bit value assertion time + * @retval Test result (TRUE or FALSE). + */ +#define IS_UART_ASSERTIONTIME(TIME) ((TIME) <= 0x1F) + +/** @brief Check UART deassertion time + * @param TIME: 5-bit value deassertion time + * @retval Test result (TRUE or FALSE). + */ +#define IS_UART_DEASSERTIONTIME(TIME) ((TIME) <= 0x1F) + +/** + * @} + */ + +/* Include UART HAL Extension module */ +#include "stm32f0xx_hal_uart_ex.h" + +/* Exported functions --------------------------------------------------------*/ +/* Initialization and de-initialization functions ****************************/ +HAL_StatusTypeDef UART_SetConfig(UART_HandleTypeDef *huart); +void UART_AdvFeatureConfig(UART_HandleTypeDef *huart); +HAL_StatusTypeDef UART_CheckIdleState(UART_HandleTypeDef *huart); +HAL_StatusTypeDef HAL_UART_Init(UART_HandleTypeDef *huart); +HAL_StatusTypeDef HAL_HalfDuplex_Init(UART_HandleTypeDef *huart); +HAL_StatusTypeDef HAL_MultiProcessor_Init(UART_HandleTypeDef *huart, uint8_t Address, uint32_t WakeUpMethod); +HAL_StatusTypeDef HAL_UART_DeInit (UART_HandleTypeDef *huart); +void HAL_UART_MspInit(UART_HandleTypeDef *huart); +void HAL_UART_MspDeInit(UART_HandleTypeDef *huart); +HAL_StatusTypeDef HAL_MultiProcessor_EnableMuteMode(UART_HandleTypeDef *huart); +HAL_StatusTypeDef HAL_MultiProcessor_DisableMuteMode(UART_HandleTypeDef *huart); +void HAL_MultiProcessor_EnterMuteMode(UART_HandleTypeDef *huart); +HAL_StatusTypeDef HAL_HalfDuplex_EnableTransmitter(UART_HandleTypeDef *huart); +HAL_StatusTypeDef HAL_HalfDuplex_EnableReceiver(UART_HandleTypeDef *huart); +HAL_StatusTypeDef UART_WaitOnFlagUntilTimeout(UART_HandleTypeDef *huart, uint32_t Flag, FlagStatus Status, uint32_t Timeout); + +/* IO operation functions *****************************************************/ +HAL_StatusTypeDef HAL_UART_Transmit(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size, uint32_t Timeout); +HAL_StatusTypeDef HAL_UART_Receive(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size, uint32_t Timeout); +HAL_StatusTypeDef HAL_UART_Transmit_IT(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size); +HAL_StatusTypeDef HAL_UART_Receive_IT(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size); +HAL_StatusTypeDef HAL_UART_Transmit_DMA(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size); +HAL_StatusTypeDef HAL_UART_Receive_DMA(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size); +HAL_StatusTypeDef HAL_UART_DMAPause(UART_HandleTypeDef *huart); +HAL_StatusTypeDef HAL_UART_DMAResume(UART_HandleTypeDef *huart); +HAL_StatusTypeDef HAL_UART_DMAStop(UART_HandleTypeDef *huart); +void HAL_UART_TxHalfCpltCallback(UART_HandleTypeDef *huart); +void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart); +void HAL_UART_RxHalfCpltCallback(UART_HandleTypeDef *huart); +void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart); +void HAL_UART_ErrorCallback(UART_HandleTypeDef *huart); +HAL_StatusTypeDef UART_Transmit_IT(UART_HandleTypeDef *huart); +HAL_StatusTypeDef UART_Receive_IT(UART_HandleTypeDef *huart); + +/* Peripheral Control functions ***********************************************/ + +/* Peripheral State and Error functions ***************************************/ +HAL_UART_StateTypeDef HAL_UART_GetState(UART_HandleTypeDef *huart); +uint32_t HAL_UART_GetError(UART_HandleTypeDef *huart); + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __STM32F0xx_HAL_UART_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_uart_ex.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_uart_ex.c new file mode 100644 index 0000000000..a5bddf675d --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_uart_ex.c @@ -0,0 +1,634 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_uart_ex.c + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief Extended UART HAL module driver. + * + * This file provides firmware functions to manage the following extended + * functionalities of the Universal Asynchronous Receiver Transmitter Peripheral (UART). + * + Initialization and de-initialization functions + * + Peripheral Control functions + * + * + @verbatim + =============================================================================== + ##### How to use this driver ##### + =============================================================================== + [..] + The UART HAL driver can be used as follows: + + (#) Declare a UART_HandleTypeDef handle structure. + + (#) For the UART RS485 Driver Enabled mode, initialize the UART registers + by calling the HAL_RS485Ex_Init() API. + + + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +#ifdef HAL_UART_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +#if !defined(STM32F030x6) && !defined(STM32F030x8) +static void UART_Wakeup_AddressConfig(UART_HandleTypeDef *huart, UART_WakeUpTypeDef WakeUpSelection); +#endif /* !defined(STM32F030x6) && !defined(STM32F030x8) */ +/* Private functions ---------------------------------------------------------*/ + +/** @addtogroup UART + * @brief UART HAL module driver + * @{ + */ + +/** @addtogroup UART_Private_Functions + * @{ + */ + +/** @defgroup UART_Group4 Extended IO operation function + * @brief UART Interrupt handling function + * +@verbatim + =============================================================================== + ##### I/O operation function ##### + =============================================================================== + This subsection provides functions allowing to manage the UART interrupts + and to handle Wake up interrupt call-back. + + (#) Non-Blocking mode API with Interrupt is : + (+) HAL_UART_IRQHandler() + + (#) Callback provided in No_Blocking mode: + (+) HAL_UART_WakeupCallback() + + +@endverbatim + * @{ + */ + + +/** + * @brief This function handles UART interrupt request. + * @param huart: uart handle + * @retval None + */ +void HAL_UART_IRQHandler(UART_HandleTypeDef *huart) +{ + /* UART parity error interrupt occurred -------------------------------------*/ + if((__HAL_UART_GET_IT(huart, UART_IT_PE) != RESET) && (__HAL_UART_GET_IT_SOURCE(huart, UART_IT_PE) != RESET)) + { + __HAL_UART_CLEAR_IT(huart, UART_CLEAR_PEF); + + huart->ErrorCode |= HAL_UART_ERROR_PE; + /* Set the UART state ready to be able to start again the process */ + huart->State = HAL_UART_STATE_READY; + } + + /* UART frame error interrupt occured --------------------------------------*/ + if((__HAL_UART_GET_IT(huart, UART_IT_FE) != RESET) && (__HAL_UART_GET_IT_SOURCE(huart, UART_IT_ERR) != RESET)) + { + __HAL_UART_CLEAR_IT(huart, UART_CLEAR_FEF); + + huart->ErrorCode |= HAL_UART_ERROR_FE; + /* Set the UART state ready to be able to start again the process */ + huart->State = HAL_UART_STATE_READY; + } + + /* UART noise error interrupt occured --------------------------------------*/ + if((__HAL_UART_GET_IT(huart, UART_IT_NE) != RESET) && (__HAL_UART_GET_IT_SOURCE(huart, UART_IT_ERR) != RESET)) + { + __HAL_UART_CLEAR_IT(huart, UART_CLEAR_NEF); + + huart->ErrorCode |= HAL_UART_ERROR_NE; + /* Set the UART state ready to be able to start again the process */ + huart->State = HAL_UART_STATE_READY; + } + + /* UART Over-Run interrupt occured -----------------------------------------*/ + if((__HAL_UART_GET_IT(huart, UART_IT_ORE) != RESET) && (__HAL_UART_GET_IT_SOURCE(huart, UART_IT_ERR) != RESET)) + { + __HAL_UART_CLEAR_IT(huart, UART_CLEAR_OREF); + + huart->ErrorCode |= HAL_UART_ERROR_ORE; + /* Set the UART state ready to be able to start again the process */ + huart->State = HAL_UART_STATE_READY; + } + + /* Call UART Error Call back function if need be --------------------------*/ + if(huart->ErrorCode != HAL_UART_ERROR_NONE) + { + HAL_UART_ErrorCallback(huart); + } + +#if !defined(STM32F030x6) && !defined(STM32F030x8) + /* UART wakeup from Stop mode interrupt occurred -------------------------------------*/ + if((__HAL_UART_GET_IT(huart, UART_IT_WUF) != RESET) && (__HAL_UART_GET_IT_SOURCE(huart, UART_IT_WUF) != RESET)) + { + __HAL_UART_CLEAR_IT(huart, UART_CLEAR_WUF); + /* Set the UART state ready to be able to start again the process */ + huart->State = HAL_UART_STATE_READY; + HAL_UART_WakeupCallback(huart); + } +#endif /* !defined(STM32F030x6) && !defined(STM32F030x8) */ + + /* UART in mode Receiver ---------------------------------------------------*/ + if((__HAL_UART_GET_IT(huart, UART_IT_RXNE) != RESET) && (__HAL_UART_GET_IT_SOURCE(huart, UART_IT_RXNE) != RESET)) + { + UART_Receive_IT(huart); + /* Clear RXNE interrupt flag */ + __HAL_UART_SEND_REQ(huart, UART_RXDATA_FLUSH_REQUEST); + } + + + /* UART in mode Transmitter ------------------------------------------------*/ + if((__HAL_UART_GET_IT(huart, UART_IT_TC) != RESET) &&(__HAL_UART_GET_IT_SOURCE(huart, UART_IT_TC) != RESET)) + { + UART_Transmit_IT(huart); + } + +} + +#if !defined(STM32F030x6) && !defined(STM32F030x8) +/** + * @brief UART wakeup from Stop mode callback + * @param huart: uart handle + * @retval None + */ + __weak void HAL_UART_WakeupCallback(UART_HandleTypeDef *huart) +{ + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_UART_WakeupCallback can be implemented in the user file + */ +} +#endif /*!defined(STM32F030x6) && !defined(STM32F030x8)*/ + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +/** @defgroup UARTEx + * @brief UART Extended HAL module driver + * @{ + */ + +/** @defgroup UARTEx_Private_Functions + * @{ + */ + +/** @defgroup UARTEx_Group1 Extended Initialization/de-initialization functions + * @brief Extended Initialization and Configuration Functions + * +@verbatim +=============================================================================== + ##### Initialization and Configuration functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to initialize the USARTx or the UARTy + in asynchronous mode. + (+) For the asynchronous mode only these parameters can be configured: + (++) Baud Rate + (++) Word Length + (++) Stop Bit + (++) Parity: If the parity is enabled, then the MSB bit of the data written + in the data register is transmitted but is changed by the parity bit. + Depending on the frame length defined by the M bit (8-bits or 9-bits), + the possible UART frame formats are as listed in the following table: + |-----------|-----------|---------------------------------------| + | M1M0 bits | PCE bit | UART frame | + |-----------------------|---------------------------------------| + | 00 | 0 | | SB | 8-bit data | STB | | + |-----------|-----------|---------------------------------------| + | 00 | 1 | | SB | 7-bit data | PB | STB | | + |-----------|-----------|---------------------------------------| + | 01 | 0 | | SB | 9-bit data | STB | | + |-----------|-----------|---------------------------------------| + | 01 | 1 | | SB | 8-bit data | PB | STB | | + +---------------------------------------------------------------+ + | 10 | 0 | | SB | 7-bit data | STB | | + |-----------|-----------|---------------------------------------| + | 10 | 1 | | SB | 6-bit data | PB | STB | | + +---------------------------------------------------------------+ + (++) Hardware flow control + (++) Receiver/transmitter modes + (++) Over Sampling Method + (++) One-Bit Sampling Method + (+) For the asynchronous mode, the following advanced features can be configured as well: + (++) TX and/or RX pin level inversion + (++) data logical level inversion + (++) RX and TX pins swap + (++) RX overrun detection disabling + (++) DMA disabling on RX error + (++) MSB first on communication line + (++) auto Baud rate detection + [..] + The HAL_LIN_Init() and HAL_RS485Ex_Init() APIs follows respectively the LIN and + the UART RS485 mode configuration procedures (details for the procedures are + available in reference manual). + +@endverbatim + * @{ + */ + + +/** + * @brief Initializes the RS485 Driver enable feature according to the specified + * parameters in the UART_InitTypeDef and creates the associated handle . + * @param huart: uart handle + * @param UART_DEPolarity: select the driver enable polarity + * This parameter can be one of the following values: + * @arg UART_DE_POLARITY_HIGH: DE signal is active high + * @arg UART_DE_POLARITY_LOW: DE signal is active low + * @param UART_DEAssertionTime: Driver Enable assertion time + * 5-bit value defining the time between the activation of the DE (Driver Enable) + * signal and the beginning of the start bit. It is expressed in sample time + * units (1/8 or 1/16 bit time, depending on the oversampling rate) + * @param UART_DEDeassertionTime: Driver Enable deassertion time + * 5-bit value defining the time between the end of the last stop bit, in a + * transmitted message, and the de-activation of the DE (Driver Enable) signal. + * It is expressed in sample time units (1/8 or 1/16 bit time, depending on the + * oversampling rate). + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RS485Ex_Init(UART_HandleTypeDef *huart, uint32_t UART_DEPolarity, uint32_t UART_DEAssertionTime, uint32_t UART_DEDeassertionTime) +{ + uint32_t temp = 0x0; + + /* Check the UART handle allocation */ + if(huart == NULL) + { + return HAL_ERROR; + } + /* Check the Driver Enable UART instance */ + assert_param(IS_UART_DRIVER_ENABLE_INSTANCE(huart->Instance)); + + /* Check the Driver Enable polarity */ + assert_param(IS_UART_DE_POLARITY(UART_DEPolarity)); + + /* Check the Driver Enable assertion time */ + assert_param(IS_UART_ASSERTIONTIME(UART_DEAssertionTime)); + + /* Check the Driver Enable deassertion time */ + assert_param(IS_UART_DEASSERTIONTIME(UART_DEDeassertionTime)); + + if(huart->State == HAL_UART_STATE_RESET) + { + /* Init the low level hardware : GPIO, CLOCK */ + HAL_UART_MspInit(huart); + } + + huart->State = HAL_UART_STATE_BUSY; + + /* Disable the Peripheral */ + __HAL_UART_DISABLE(huart); + + /* Set the UART Communication parameters */ + if (UART_SetConfig(huart) == HAL_ERROR) + { + return HAL_ERROR; + } + + if (huart->AdvancedInit.AdvFeatureInit != UART_ADVFEATURE_NO_INIT) + { + UART_AdvFeatureConfig(huart); + } + + /* Enable the Driver Enable mode by setting the DEM bit in the CR3 register */ + huart->Instance->CR3 |= USART_CR3_DEM; + + /* Set the Driver Enable polarity */ + MODIFY_REG(huart->Instance->CR3, USART_CR3_DEP, UART_DEPolarity); + + /* Set the Driver Enable assertion and deassertion times */ + temp = (UART_DEAssertionTime << UART_CR1_DEAT_ADDRESS_LSB_POS); + temp |= (UART_DEDeassertionTime << UART_CR1_DEDT_ADDRESS_LSB_POS); + MODIFY_REG(huart->Instance->CR1, (USART_CR1_DEDT|USART_CR1_DEAT), temp); + + /* Enable the Peripheral */ + __HAL_UART_ENABLE(huart); + + /* TEACK and/or REACK to check before moving huart->State to Ready */ + return (UART_CheckIdleState(huart)); +} + + +#if !defined(STM32F030x6) && !defined(STM32F030x8) +/** + * @brief Initializes the LIN mode according to the specified + * parameters in the UART_InitTypeDef and creates the associated handle . + * @param huart: uart handle + * @param BreakDetectLength: specifies the LIN break detection length. + * This parameter can be one of the following values: + * @arg UART_LINBREAKDETECTLENGTH_10B: 10-bit break detection + * @arg UART_LINBREAKDETECTLENGTH_11B: 11-bit break detection + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LIN_Init(UART_HandleTypeDef *huart, uint16_t BreakDetectLength) +{ + /* Check the UART handle allocation */ + if(huart == NULL) + { + return HAL_ERROR; + } + /* Check the Break detection length parameter */ + assert_param(IS_UART_LIN_BREAK_DETECT_LENGTH(BreakDetectLength)); + + /* LIN mode limited to 16-bit oversampling only */ + if(huart->Init.OverSampling == UART_OVERSAMPLING_8) + { + return HAL_ERROR; + } + + /* Init the low level hardware : GPIO, CLOCK, CORTEX */ + HAL_UART_MspInit(huart); + + /* Disable the Peripheral */ + __HAL_UART_DISABLE(huart); + + /* Set the UART Communication parameters */ + if (UART_SetConfig(huart) == HAL_ERROR) + { + return HAL_ERROR; + } + + if (huart->AdvancedInit.AdvFeatureInit != UART_ADVFEATURE_NO_INIT) + { + UART_AdvFeatureConfig(huart); + } + + /* In LIN mode, the following bits must be kept cleared: + - LINEN and CLKEN bits in the USART_CR2 register, + - SCEN and IREN bits in the USART_CR3 register.*/ + huart->Instance->CR2 &= ~(USART_CR2_CLKEN); + huart->Instance->CR3 &= ~(USART_CR3_HDSEL | USART_CR3_IREN | USART_CR3_SCEN); + + /* Enable the LIN mode by setting the LINEN bit in the CR2 register */ + huart->Instance->CR2 |= USART_CR2_LINEN; + + /* Set the USART LIN Break detection length. */ + MODIFY_REG(huart->Instance->CR2, USART_CR2_LBDL, BreakDetectLength); + + /* Enable the Peripheral */ + __HAL_UART_ENABLE(huart); + + /* TEACK and/or REACK to check before moving huart->State to Ready */ + return (UART_CheckIdleState(huart)); +} +#endif /* !defined(STM32F030x6) && !defined(STM32F030x8) */ +/** + * @} + */ + +/** @defgroup UARTEx_Group3 Extended Peripheral Control functions + * @brief Extended Peripheral Control functions + * +@verbatim + =============================================================================== + ##### Peripheral Control function ##### + =============================================================================== + [..] + This subsection provides extended functions allowing to control the UART. + (+) HAL_MultiProcessorEx_AddressLength_Set() API optionally sets the UART node address + detection length to more than 4 bits for multiprocessor address mark wake up. + (+) HAL_UART_EnableStopMode() API allows the UART to wake up the MCU from Stop mode as + long as UART clock is HSI or LSE + (+) HAL_UART_DisableStopMode() API disables the above feature + (+) HAL_MultiProcessorEx_AddressLength_Set() API configures the address length when the + wake-up event is the address match feature + (+) UART_Wakeup_AddressConfig() API sets the reference address used when address + match feature is carried out + +@endverbatim + * @{ + */ + + + + +#if !defined(STM32F030x6) && !defined(STM32F030x8) +/** + * @brief Set Wakeup from Stop mode interrupt flag selection + * @param huart: uart handle, + * @param WakeUpSelection: address match, Start Bit detection or RXNE bit status. + * This parameter can be one of the following values: + * @arg UART_WAKEUP_ON_ADDRESS + * @arg UART_WAKEUP_ON_STARTBIT + * @arg UART_WAKEUP_ON_READDATA_NONEMPTY + * @retval HAL status + */ +HAL_StatusTypeDef HAL_UARTEx_StopModeWakeUpSourceConfig(UART_HandleTypeDef *huart, UART_WakeUpTypeDef WakeUpSelection) +{ + /* Check the wake-up selection parameter */ + assert_param(IS_UART_WAKEUP_SELECTION(WakeUpSelection.WakeUpEvent)); + + /* Process Locked */ + __HAL_LOCK(huart); + + huart->State = HAL_UART_STATE_BUSY; + + /* Disable the Peripheral */ + __HAL_UART_DISABLE(huart); + + /* Set the wake-up selection scheme */ + MODIFY_REG(huart->Instance->CR3, USART_CR3_WUS, WakeUpSelection.WakeUpEvent); + + if (WakeUpSelection.WakeUpEvent == UART_WAKEUP_ON_ADDRESS) + { + UART_Wakeup_AddressConfig(huart, WakeUpSelection); + } + + /* Enable the Peripheral */ + __HAL_UART_ENABLE(huart); + + /* Wait until REACK flag is set */ + if(UART_WaitOnFlagUntilTimeout(huart, USART_ISR_REACK, RESET, HAL_UART_TIMEOUT_VALUE) != HAL_OK) + { + return HAL_TIMEOUT; + } + else + { + /* Initialize the UART State */ + huart->State= HAL_UART_STATE_READY; + /* Process Unlocked */ + __HAL_UNLOCK(huart); + return HAL_OK; + } +} + + +/** + * @brief Enable UART Stop Mode + * The UART is able to wake up the MCU from Stop mode as long as UART clock is HSI or LSE + * @param huart: uart handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_UARTEx_EnableStopMode(UART_HandleTypeDef *huart) +{ + /* Process Locked */ + __HAL_LOCK(huart); + + huart->State = HAL_UART_STATE_BUSY; + + /* Set the USART UESM bit */ + huart->Instance->CR1 |= USART_CR1_UESM; + + huart->State = HAL_UART_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(huart); + + return HAL_OK; +} + +/** + * @brief Disable UART Stop Mode + * @param huart: uart handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_UARTEx_DisableStopMode(UART_HandleTypeDef *huart) +{ + /* Process Locked */ + __HAL_LOCK(huart); + + huart->State = HAL_UART_STATE_BUSY; + + /* Clear USART UESM bit */ + huart->Instance->CR1 &= ~(USART_CR1_UESM); + + huart->State = HAL_UART_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(huart); + + return HAL_OK; +} + +#endif /* !defined(STM32F030x6) && !defined(STM32F030x8) */ + + + +/** + * @brief By default in multiprocessor mode, when the wake up method is set + * to address mark, the UART handles only 4-bit long addresses detection. + * This API allows to enable longer addresses detection (6-, 7- or 8-bit + * long): + * - 6-bit address detection in 7-bit data mode + * - 7-bit address detection in 8-bit data mode + * - 8-bit address detection in 9-bit data mode + * @param huart: UART handle + * @param AddressLength: this parameter can be one of the following values: + * @arg UART_ADDRESS_DETECT_4B: 4-bit long address + * @arg UART_ADDRESS_DETECT_7B: 6-, 7- or 8-bit long address + * @retval HAL status + */ +HAL_StatusTypeDef HAL_MultiProcessorEx_AddressLength_Set(UART_HandleTypeDef *huart, uint32_t AddressLength) +{ + /* Check the UART handle allocation */ + if(huart == NULL) + { + return HAL_ERROR; + } + + /* Check the address length parameter */ + assert_param(IS_UART_ADDRESSLENGTH_DETECT(AddressLength)); + + huart->State = HAL_UART_STATE_BUSY; + + /* Disable the Peripheral */ + __HAL_UART_DISABLE(huart); + + /* Set the address length */ + MODIFY_REG(huart->Instance->CR2, USART_CR2_ADDM7, AddressLength); + + /* Enable the Peripheral */ + __HAL_UART_ENABLE(huart); + + /* TEACK and/or REACK to check before moving huart->State to Ready */ + return (UART_CheckIdleState(huart)); +} + + +#if !defined(STM32F030x6) && !defined(STM32F030x8) +/** + * @brief Initializes the UART wake-up from stop mode parameters when triggered by address detection. + * @param huart: uart handle + * @param WakeUpSelection: UART wake up from stop mode parameters + * @retval HAL status + */ +static void UART_Wakeup_AddressConfig(UART_HandleTypeDef *huart, UART_WakeUpTypeDef WakeUpSelection) +{ + assert_param(IS_UART_ADDRESSLENGTH_DETECT(WakeUpSelection.AddressLength)); + + /* Set the USART address length */ + MODIFY_REG(huart->Instance->CR2, USART_CR2_ADDM7, WakeUpSelection.AddressLength); + + /* Set the USART address node */ + MODIFY_REG(huart->Instance->CR2, USART_CR2_ADD, ((uint32_t)WakeUpSelection.Address << UART_CR2_ADDRESS_LSB_POS)); +} +#endif /* !defined(STM32F030x6) && !defined(STM32F030x8) */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* HAL_UART_MODULE_ENABLED */ + +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_uart_ex.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_uart_ex.h new file mode 100644 index 0000000000..7a43388b7a --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_uart_ex.h @@ -0,0 +1,519 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_uart_ex.h + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief Header file of UART HAL Extension module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32F0xx_HAL_UART_EX_H +#define __STM32F0xx_HAL_UART_EX_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal_def.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @addtogroup UARTEx + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/* Exported constants --------------------------------------------------------*/ +/** @defgroup UARTEx_Exported_Constants + * @{ + */ + +/** @defgroup UARTEx_Word_Length UART Word Length + * @{ + */ +#if defined (STM32F042x6) || defined (STM32F048xx) || \ + defined (STM32F071xB) || defined (STM32F072xB) || defined (STM32F078xx) +#define UART_WORDLENGTH_7B ((uint32_t)USART_CR1_M1) +#define UART_WORDLENGTH_8B ((uint32_t)0x00000000) +#define UART_WORDLENGTH_9B ((uint32_t)USART_CR1_M0) +#define IS_UART_WORD_LENGTH(LENGTH) (((LENGTH) == UART_WORDLENGTH_7B) || \ + ((LENGTH) == UART_WORDLENGTH_8B) || \ + ((LENGTH) == UART_WORDLENGTH_9B)) +#else +#define UART_WORDLENGTH_8B ((uint32_t)0x00000000) +#define UART_WORDLENGTH_9B ((uint32_t)USART_CR1_M) +#define IS_UART_WORD_LENGTH(LENGTH) (((LENGTH) == UART_WORDLENGTH_8B) || \ + ((LENGTH) == UART_WORDLENGTH_9B)) +#endif /* defined (STM32F042x6) || defined (STM32F048xx) || \ + defined (STM32F071xB) || defined (STM32F072xB) || defined (STM32F078xx) */ +/** + * @} + */ + +/** @defgroup UARTEx_AutoBaud_Rate_Mode UART Advanced Feature AutoBaud Rate Mode + * @{ + */ +#if defined (STM32F042x6) || defined (STM32F048xx) || \ + defined (STM32F071xB) || defined (STM32F072xB) || defined (STM32F078xx) +#define UART_ADVFEATURE_AUTOBAUDRATE_ONSTARTBIT ((uint32_t)0x0000) +#define UART_ADVFEATURE_AUTOBAUDRATE_ONFALLINGEDGE ((uint32_t)USART_CR2_ABRMODE_0) +#define UART_ADVFEATURE_AUTOBAUDRATE_ON0X7FFRAME ((uint32_t)USART_CR2_ABRMODE_1) +#define UART_ADVFEATURE_AUTOBAUDRATE_ON0X55FRAME ((uint32_t)USART_CR2_ABRMODE) +#define IS_UART_ADVFEATURE_AUTOBAUDRATEMODE(MODE) (((MODE) == UART_ADVFEATURE_AUTOBAUDRATE_ONSTARTBIT) || \ + ((MODE) == UART_ADVFEATURE_AUTOBAUDRATE_ONFALLINGEDGE) || \ + ((MODE) == UART_ADVFEATURE_AUTOBAUDRATE_ON0X7FFRAME) || \ + ((MODE) == UART_ADVFEATURE_AUTOBAUDRATE_ON0X55FRAME)) +#else +#define UART_ADVFEATURE_AUTOBAUDRATE_ONSTARTBIT ((uint32_t)0x0000) +#define UART_ADVFEATURE_AUTOBAUDRATE_ONFALLINGEDGE ((uint32_t)USART_CR2_ABRMODE_0) +#define IS_UART_ADVFEATURE_AUTOBAUDRATEMODE(MODE) (((MODE) == UART_ADVFEATURE_AUTOBAUDRATE_ONSTARTBIT) || \ + ((MODE) == UART_ADVFEATURE_AUTOBAUDRATE_ONFALLINGEDGE)) +#endif /* defined (STM32F042x6) || defined (STM32F048xx) || \ + defined (STM32F071xB) || defined (STM32F072xB) || defined (STM32F078xx) */ +/** + * @} + */ + + +#if !defined(STM32F030x6) && !defined(STM32F030x8) +/** @defgroup UARTEx_LIN UART Local Interconnection Network mode + * @{ + */ +#define UART_LIN_DISABLE ((uint32_t)0x00000000) +#define UART_LIN_ENABLE ((uint32_t)USART_CR2_LINEN) +#define IS_UART_LIN(LIN) (((LIN) == UART_LIN_DISABLE) || \ + ((LIN) == UART_LIN_ENABLE)) +/** + * @} + */ + +/** @defgroup UARTEx_LIN_Break_Detection UART LIN Break Detection + * @{ + */ +#define UART_LINBREAKDETECTLENGTH_10B ((uint32_t)0x00000000) +#define UART_LINBREAKDETECTLENGTH_11B ((uint32_t)USART_CR2_LBDL) +#define IS_UART_LIN_BREAK_DETECT_LENGTH(LENGTH) (((LENGTH) == UART_LINBREAKDETECTLENGTH_10B) || \ + ((LENGTH) == UART_LINBREAKDETECTLENGTH_11B)) +/** + * @} + */ +#endif /* !defined(STM32F030x6) && !defined(STM32F030x8) */ + + + +/** @defgroup UART_Flags UART Status Flags + * Elements values convention: 0xXXXX + * - 0xXXXX : Flag mask in the ISR register + * @{ + */ +#define UART_FLAG_REACK ((uint32_t)0x00400000) +#define UART_FLAG_TEACK ((uint32_t)0x00200000) +#if !defined(STM32F030x6) && !defined(STM32F030x8) +#define UART_FLAG_WUF ((uint32_t)0x00100000) +#endif /* !defined(STM32F030x6) && !defined(STM32F030x8) */ +#define UART_FLAG_RWU ((uint32_t)0x00080000) +#define UART_FLAG_SBKF ((uint32_t)0x00040000 +#define UART_FLAG_CMF ((uint32_t)0x00020000) +#define UART_FLAG_BUSY ((uint32_t)0x00010000) +#define UART_FLAG_ABRF ((uint32_t)0x00008000) +#define UART_FLAG_ABRE ((uint32_t)0x00004000) +#if !defined(STM32F030x6) && !defined(STM32F030x8) +#define UART_FLAG_EOBF ((uint32_t)0x00001000) +#endif /* !defined(STM32F030x6) && !defined(STM32F030x8) */ +#define UART_FLAG_RTOF ((uint32_t)0x00000800) +#define UART_FLAG_CTS ((uint32_t)0x00000400) +#define UART_FLAG_CTSIF ((uint32_t)0x00000200) +#if !defined(STM32F030x6) && !defined(STM32F030x8) +#define UART_FLAG_LBDF ((uint32_t)0x00000100) +#endif /* !defined(STM32F030x6) && !defined(STM32F030x8) */ +#define UART_FLAG_TXE ((uint32_t)0x00000080) +#define UART_FLAG_TC ((uint32_t)0x00000040) +#define UART_FLAG_RXNE ((uint32_t)0x00000020) +#define UART_FLAG_IDLE ((uint32_t)0x00000010) +#define UART_FLAG_ORE ((uint32_t)0x00000008) +#define UART_FLAG_NE ((uint32_t)0x00000004) +#define UART_FLAG_FE ((uint32_t)0x00000002) +#define UART_FLAG_PE ((uint32_t)0x00000001) +/** + * @} + */ + +/** @defgroup UART_Interrupt_definition UART Interrupts Definition + * Elements values convention: 0000ZZZZ0XXYYYYYb + * - YYYYY : Interrupt source position in the XX register (5bits) + * - XX : Interrupt source register (2bits) + * - 01: CR1 register + * - 10: CR2 register + * - 11: CR3 register + * - ZZZZ : Flag position in the ISR register(4bits) + * @{ + */ +#define UART_IT_PE ((uint16_t)0x0028) +#define UART_IT_TXE ((uint16_t)0x0727) +#define UART_IT_TC ((uint16_t)0x0626) +#define UART_IT_RXNE ((uint16_t)0x0525) +#define UART_IT_IDLE ((uint16_t)0x0424) +#if !defined(STM32F030x6) && !defined(STM32F030x8) +#define UART_IT_LBD ((uint16_t)0x0846) +#endif /* !defined(STM32F030x6) && !defined(STM32F030x8) */ +#define UART_IT_CTS ((uint16_t)0x096A) +#define UART_IT_CM ((uint16_t)0x142E) +#if !defined(STM32F030x6) && !defined(STM32F030x8) +#define UART_IT_WUF ((uint16_t)0x1476) +#endif /* !defined(STM32F030x6) && !defined(STM32F030x8) */ +/** + * @} + */ + + +/** @defgroup UART_IT_CLEAR_Flags UART Interruption Clear Flags + * @{ + */ +#define UART_CLEAR_PEF USART_ICR_PECF /*!< Parity Error Clear Flag */ +#define UART_CLEAR_FEF USART_ICR_FECF /*!< Framing Error Clear Flag */ +#define UART_CLEAR_NEF USART_ICR_NCF /*!< Noise detected Clear Flag */ +#define UART_CLEAR_OREF USART_ICR_ORECF /*!< OverRun Error Clear Flag */ +#define UART_CLEAR_IDLEF USART_ICR_IDLECF /*!< IDLE line detected Clear Flag */ +#define UART_CLEAR_TCF USART_ICR_TCCF /*!< Transmission Complete Clear Flag */ +#if !defined(STM32F030x6) && !defined(STM32F030x8) +#define UART_CLEAR_LBDF USART_ICR_LBDCF /*!< LIN Break Detection Clear Flag (not available on F030xx devices)*/ +#endif /* !defined(STM32F030x6) && !defined(STM32F030x8) */ +#define UART_CLEAR_CTSF USART_ICR_CTSCF /*!< CTS Interrupt Clear Flag */ +#define UART_CLEAR_RTOF USART_ICR_RTOCF /*!< Receiver Time Out Clear Flag */ +#define UART_CLEAR_EOBF USART_ICR_EOBCF /*!< End Of Block Clear Flag */ +#define UART_CLEAR_CMF USART_ICR_CMCF /*!< Character Match Clear Flag */ +#if !defined(STM32F030x6) && !defined(STM32F030x8) +#define UART_CLEAR_WUF USART_ICR_WUCF /*!< Wake Up from stop mode Clear Flag */ +#endif /* !defined(STM32F030x6) && !defined(STM32F030x8) */ +/** + * @} + */ + +/** @defgroup UART_Request_Parameters UART Request Parameters + * @{ + */ +#define UART_AUTOBAUD_REQUEST ((uint32_t)USART_RQR_ABRRQ) /*!< Auto-Baud Rate Request */ +#define UART_SENDBREAK_REQUEST ((uint32_t)USART_RQR_SBKRQ) /*!< Send Break Request */ +#define UART_MUTE_MODE_REQUEST ((uint32_t)USART_RQR_MMRQ) /*!< Mute Mode Request */ +#define UART_RXDATA_FLUSH_REQUEST ((uint32_t)USART_RQR_RXFRQ) /*!< Receive Data flush Request */ +#if !defined(STM32F030x6) && !defined(STM32F030x8) +#define UART_TXDATA_FLUSH_REQUEST ((uint32_t)USART_RQR_TXFRQ) /*!< Transmit data flush Request */ +#define IS_UART_REQUEST_PARAMETER(PARAM) (((PARAM) == UART_AUTOBAUD_REQUEST) || \ + ((PARAM) == UART_SENDBREAK_REQUEST) || \ + ((PARAM) == UART_MUTE_MODE_REQUEST) || \ + ((PARAM) == UART_RXDATA_FLUSH_REQUEST) || \ + ((PARAM) == UART_TXDATA_FLUSH_REQUEST)) +#else +#define IS_UART_REQUEST_PARAMETER(PARAM) (((PARAM) == UART_AUTOBAUD_REQUEST) || \ + ((PARAM) == UART_SENDBREAK_REQUEST) || \ + ((PARAM) == UART_MUTE_MODE_REQUEST) || \ + ((PARAM) == UART_RXDATA_FLUSH_REQUEST)) +#endif /* !defined(STM32F030x6) && !defined(STM32F030x8) */ +/** + * @} + */ + +#if !defined(STM32F030x6) && !defined(STM32F030x8) +/** @defgroup UART_Stop_Mode_Enable UART Advanced Feature Stop Mode Enable + * @{ + */ +#define UART_ADVFEATURE_STOPMODE_DISABLE ((uint32_t)0x00000000) +#define UART_ADVFEATURE_STOPMODE_ENABLE ((uint32_t)USART_CR1_UESM) +#define IS_UART_ADVFEATURE_STOPMODE(STOPMODE) (((STOPMODE) == UART_ADVFEATURE_STOPMODE_DISABLE) || \ + ((STOPMODE) == UART_ADVFEATURE_STOPMODE_ENABLE)) +/** + * @} + */ + +/** @defgroup UART_WakeUp_from_Stop_Selection UART WakeUp From Stop Selection + * @{ + */ +#define UART_WAKEUP_ON_ADDRESS ((uint32_t)0x0000) +#define UART_WAKEUP_ON_STARTBIT ((uint32_t)USART_CR3_WUS_1) +#define UART_WAKEUP_ON_READDATA_NONEMPTY ((uint32_t)USART_CR3_WUS) +#define IS_UART_WAKEUP_SELECTION(WAKE) (((WAKE) == UART_WAKEUP_ON_ADDRESS) || \ + ((WAKE) == UART_WAKEUP_ON_STARTBIT) || \ + ((WAKE) == UART_WAKEUP_ON_READDATA_NONEMPTY)) +/** + * @} + */ +#endif /* !defined(STM32F030x6) && !defined(STM32F030x8) */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ + +/** @defgroup UARTEx_Exported_Macros + * @{ + */ + +/** @brief Reports the UART clock source. + * @param __HANDLE__: specifies the UART Handle + * @param __CLOCKSOURCE__ : output variable + * @retval UART clocking source, written in __CLOCKSOURCE__. + */ + + +#if defined(STM32F030x6) || defined(STM32F031x6) || defined(STM32F038xx) +#define __HAL_UART_GETCLOCKSOURCE(__HANDLE__,__CLOCKSOURCE__) \ + do { \ + switch(__HAL_RCC_GET_USART1_SOURCE()) \ + { \ + case RCC_USART1CLKSOURCE_PCLK1: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_PCLK1; \ + break; \ + case RCC_USART1CLKSOURCE_HSI: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_HSI; \ + break; \ + case RCC_USART1CLKSOURCE_SYSCLK: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_SYSCLK; \ + break; \ + case RCC_USART1CLKSOURCE_LSE: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_LSE; \ + break; \ + default: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_UNDEFINED; \ + break; \ + } \ + } while(0) +#elif defined (STM32F030x8) || \ + defined (STM32F042x6) || defined (STM32F048xx) || \ + defined (STM32F051x8) || defined (STM32F058xx) +#define __HAL_UART_GETCLOCKSOURCE(__HANDLE__,__CLOCKSOURCE__) \ + do { \ + if((__HANDLE__)->Instance == USART1) \ + { \ + switch(__HAL_RCC_GET_USART1_SOURCE()) \ + { \ + case RCC_USART1CLKSOURCE_PCLK1: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_PCLK1; \ + break; \ + case RCC_USART1CLKSOURCE_HSI: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_HSI; \ + break; \ + case RCC_USART1CLKSOURCE_SYSCLK: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_SYSCLK; \ + break; \ + case RCC_USART1CLKSOURCE_LSE: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_LSE; \ + break; \ + default: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_UNDEFINED; \ + break; \ + } \ + } \ + else if((__HANDLE__)->Instance == USART2) \ + { \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_PCLK1; \ + } \ + else \ + { \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_UNDEFINED; \ + } \ + } while(0) +#elif defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) +#define __HAL_UART_GETCLOCKSOURCE(__HANDLE__,__CLOCKSOURCE__) \ + do { \ + if((__HANDLE__)->Instance == USART1) \ + { \ + switch(__HAL_RCC_GET_USART1_SOURCE()) \ + { \ + case RCC_USART1CLKSOURCE_PCLK1: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_PCLK1; \ + break; \ + case RCC_USART1CLKSOURCE_HSI: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_HSI; \ + break; \ + case RCC_USART1CLKSOURCE_SYSCLK: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_SYSCLK; \ + break; \ + case RCC_USART1CLKSOURCE_LSE: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_LSE; \ + break; \ + default: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_UNDEFINED; \ + break; \ + } \ + } \ + else if((__HANDLE__)->Instance == USART2) \ + { \ + switch(__HAL_RCC_GET_USART2_SOURCE()) \ + { \ + case RCC_USART2CLKSOURCE_PCLK1: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_PCLK1; \ + break; \ + case RCC_USART2CLKSOURCE_HSI: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_HSI; \ + break; \ + case RCC_USART2CLKSOURCE_SYSCLK: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_SYSCLK; \ + break; \ + case RCC_USART2CLKSOURCE_LSE: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_LSE; \ + break; \ + default: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_UNDEFINED; \ + break; \ + } \ + } \ + else if((__HANDLE__)->Instance == USART3) \ + { \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_PCLK1; \ + } \ + else if((__HANDLE__)->Instance == USART4) \ + { \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_PCLK1; \ + } \ + else \ + { \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_UNDEFINED; \ + } \ + } while(0) +#endif /* defined(STM32F030x6) || defined(STM32F031x6) || defined(STM32F038xx) */ + + +/** @brief Computes the UART mask to apply to retrieve the received data + * according to the word length and to the parity bits activation. + * If PCE = 1, the parity bit is not included in the data extracted + * by the reception API(). + * This masking operation is not carried out in the case of + * DMA transfers. + * @param __HANDLE__: specifies the UART Handle + * @retval none + */ +#if defined (STM32F042x6) || defined (STM32F048xx) || \ + defined (STM32F071xB) || defined (STM32F072xB) || defined (STM32F078xx) +#define __HAL_UART_MASK_COMPUTATION(__HANDLE__) \ + do { \ + if ((__HANDLE__)->Init.WordLength == UART_WORDLENGTH_9B) \ + { \ + if ((__HANDLE__)->Init.Parity == UART_PARITY_NONE) \ + { \ + (__HANDLE__)->Mask = 0x01FF ; \ + } \ + else \ + { \ + (__HANDLE__)->Mask = 0x00FF ; \ + } \ + } \ + else if ((__HANDLE__)->Init.WordLength == UART_WORDLENGTH_8B) \ + { \ + if ((__HANDLE__)->Init.Parity == UART_PARITY_NONE) \ + { \ + (__HANDLE__)->Mask = 0x00FF ; \ + } \ + else \ + { \ + (__HANDLE__)->Mask = 0x007F ; \ + } \ + } \ + else if ((__HANDLE__)->Init.WordLength == UART_WORDLENGTH_7B) \ + { \ + if ((__HANDLE__)->Init.Parity == UART_PARITY_NONE) \ + { \ + (__HANDLE__)->Mask = 0x007F ; \ + } \ + else \ + { \ + (__HANDLE__)->Mask = 0x003F ; \ + } \ + } \ +} while(0) +#else +#define __HAL_UART_MASK_COMPUTATION(__HANDLE__) \ + do { \ + if ((__HANDLE__)->Init.WordLength == UART_WORDLENGTH_9B) \ + { \ + if ((__HANDLE__)->Init.Parity == UART_PARITY_NONE) \ + { \ + (__HANDLE__)->Mask = 0x01FF ; \ + } \ + else \ + { \ + (__HANDLE__)->Mask = 0x00FF ; \ + } \ + } \ + else if ((__HANDLE__)->Init.WordLength == UART_WORDLENGTH_8B) \ + { \ + if ((__HANDLE__)->Init.Parity == UART_PARITY_NONE) \ + { \ + (__HANDLE__)->Mask = 0x00FF ; \ + } \ + else \ + { \ + (__HANDLE__)->Mask = 0x007F ; \ + } \ + } \ +} while(0) +#endif /* defined (STM32F042x6) || defined (STM32F048xx) || \ + defined (STM32F071xB) || defined (STM32F072xB) || defined (STM32F078xx) */ +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/* Initialization and de-initialization functions ****************************/ +HAL_StatusTypeDef HAL_RS485Ex_Init(UART_HandleTypeDef *huart, uint32_t UART_DEPolarity, uint32_t UART_DEAssertionTime, uint32_t UART_DEDeassertionTime); +HAL_StatusTypeDef HAL_LIN_Init(UART_HandleTypeDef *huart, uint16_t BreakDetectLength); +HAL_StatusTypeDef HAL_UARTEx_StopModeWakeUpSourceConfig(UART_HandleTypeDef *huart, UART_WakeUpTypeDef WakeUpSelection); +HAL_StatusTypeDef HAL_UARTEx_EnableStopMode(UART_HandleTypeDef *huart); +HAL_StatusTypeDef HAL_UARTEx_DisableStopMode(UART_HandleTypeDef *huart); +/* I/O operation functions ***************************************************/ +void HAL_UART_IRQHandler(UART_HandleTypeDef *huart); +void HAL_UART_WakeupCallback(UART_HandleTypeDef *huart); +/* Peripheral Control functions **********************************************/ +void UART_AdvFeatureConfig(UART_HandleTypeDef *huart); +HAL_StatusTypeDef HAL_MultiProcessorEx_AddressLength_Set(UART_HandleTypeDef *huart, uint32_t AddressLength); +HAL_StatusTypeDef HAL_LIN_SendBreak(UART_HandleTypeDef *huart); +/* Peripheral State functions ************************************************/ + + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __STM32F0xx_HAL_UART_EX_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_usart.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_usart.c new file mode 100644 index 0000000000..8f84c565de --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_usart.c @@ -0,0 +1,1746 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_usart.c + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief USART HAL module driver. + * + * This file provides firmware functions to manage the following + * functionalities of the Universal Synchronous/Asynchronous Receiver Transmitter + * Peripheral (USART). + * + Initialization and de-initialization function + * + IO operation function + * + Peripheral Control function + * + @verbatim + =============================================================================== + ##### How to use this driver ##### + =============================================================================== + [..] + The USART HAL driver can be used as follows: + + (#) Declare a USART_HandleTypeDef handle structure. + (#) Initialize the USART low level resources by implement the HAL_USART_MspInit ()API: + (##) Enable the USARTx interface clock. + (##) USART pins configuration: + (+) Enable the clock for the USART GPIOs. + (+) Configure these USART pins as alternate function pull-up. + (##) NVIC configuration if you need to use interrupt process (HAL_USART_Transmit_IT(), + HAL_USART_Receive_IT() and HAL_USART_TransmitReceive_IT() APIs): + (+) Configure the USARTx interrupt priority. + (+) Enable the NVIC USART IRQ handle. + (@) The specific USART interrupts (Transmission complete interrupt, + RXNE interrupt and Error Interrupts) will be managed using the macros + __HAL_USART_ENABLE_IT() and __HAL_USART_DISABLE_IT() inside the transmit and receive process. + (##) DMA Configuration if you need to use DMA process (HAL_USART_Transmit_DMA() + HAL_USART_Receive_IT() and HAL_USART_TransmitReceive_IT() APIs): + (+) Declare a DMA handle structure for the Tx/Rx stream. + (+) Enable the DMAx interface clock. + (+) Configure the declared DMA handle structure with the required Tx/Rx parameters. + (+) Configure the DMA Tx/Rx Stream. + (+) Associate the initilalized DMA handle to the USART DMA Tx/Rx handle. + (+) Configure the priority and enable the NVIC for the transfer complete interrupt on the DMA Tx/Rx Stream. + + (#) Program the Baud Rate, Word Length , Stop Bit, Parity, Hardware + flow control and Mode(Receiver/Transmitter) in the husart Init structure. + + (#) Initialize the USART registers by calling the HAL_USART_Init() API: + (+) These API's configures also the low level Hardware GPIO, CLOCK, CORTEX...etc) + by calling the customed HAL_USART_MspInit(&husart) API. + + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @defgroup USART + * @brief HAL USART Synchronous module driver + * @{ + */ +#ifdef HAL_USART_MODULE_ENABLED +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +#define DUMMY_DATA ((uint16_t) 0xFFFF) +#define TEACK_REACK_TIMEOUT ((uint32_t) 1000) +#define HAL_USART_TXDMA_TIMEOUTVALUE 22000 +#define USART_CR1_FIELDS ((uint32_t)(USART_CR1_M | USART_CR1_PCE | \ + USART_CR1_PS | USART_CR1_TE | USART_CR1_RE)) +#define USART_CR2_FIELDS ((uint32_t)(USART_CR2_CPHA | USART_CR2_CPOL | \ + USART_CR2_CLKEN | USART_CR2_LBCL | USART_CR2_STOP)) +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +static void USART_DMATransmitCplt(DMA_HandleTypeDef *hdma); +static void USART_DMAReceiveCplt(DMA_HandleTypeDef *hdma); +static void USART_DMATxHalfCplt(DMA_HandleTypeDef *hdma); +static void USART_DMARxHalfCplt(DMA_HandleTypeDef *hdma); +static void USART_DMAError(DMA_HandleTypeDef *hdma); +static HAL_StatusTypeDef USART_WaitOnFlagUntilTimeout(USART_HandleTypeDef *husart, uint32_t Flag, FlagStatus Status, uint32_t Timeout); +static HAL_StatusTypeDef USART_SetConfig(USART_HandleTypeDef *husart); +static HAL_StatusTypeDef USART_CheckIdleState(USART_HandleTypeDef *husart); +static HAL_StatusTypeDef USART_Transmit_IT(USART_HandleTypeDef *husart); +static HAL_StatusTypeDef USART_Receive_IT(USART_HandleTypeDef *husart); +static HAL_StatusTypeDef USART_TransmitReceive_IT(USART_HandleTypeDef *husart); +/* Private functions ---------------------------------------------------------*/ + + +/** @defgroup USART_Private_Functions + * @{ + */ + +/** @defgroup USART_Group1 USART Initialization/de-initialization function + * @brief Initialization and Configuration functions + * +@verbatim + =============================================================================== + ##### Initialization and Configuration functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to initialize the USART + in asynchronous and in synchronous modes. + (+) For the asynchronous mode only these parameters can be configured: + (++) Baud Rate + (++) Word Length + (++) Stop Bit + (++) Parity: If the parity is enabled, then the MSB bit of the data written + in the data register is transmitted but is changed by the parity bit. + Depending on the frame length defined by the M bit (8-bits or 9-bits) + or by the M1 and M0 bits (7-bit, 8-bit or 9-bit), + the possible USART frame formats are as listed in the following table: + +---------------------------------------------------------------+ + | M bit | PCE bit | USART frame | + |-----------|-----------|---------------------------------------| + | 0 | 0 | | SB | 8-bit data | STB | | + |-----------|-----------|---------------------------------------| + | 0 | 1 | | SB | 7-bit data | PB | STB | | + |-----------|-----------|---------------------------------------| + | 1 | 0 | | SB | 9-bit data | STB | | + |-----------|-----------|---------------------------------------| + | 1 | 1 | | SB | 8-bit data | PB | STB | | + +---------------------------------------------------------------+ + | M1M0 bits | PCE bit | USART frame | + |-----------------------|---------------------------------------| + | 10 | 0 | | SB | 7-bit data | STB | | + |-----------|-----------|---------------------------------------| + | 10 | 1 | | SB | 6-bit data | PB | STB | | + +---------------------------------------------------------------+ + (++) USART polarity + (++) USART phase + (++) USART LastBit + (++) Receiver/transmitter modes + + [..] + The HAL_USART_Init() function follows the USART synchronous configuration + procedure (details for the procedure are available in reference manual). + +@endverbatim + * @{ + */ + +/** + * @brief Initializes the USART mode according to the specified + * parameters in the USART_InitTypeDef and create the associated handle . + * @param husart: usart handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_USART_Init(USART_HandleTypeDef *husart) +{ + /* Check the USART handle allocation */ + if(husart == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_USART_INSTANCE(husart->Instance)); + + if(husart->State == HAL_USART_STATE_RESET) + { + /* Init the low level hardware : GPIO, CLOCK */ + HAL_USART_MspInit(husart); + } + + husart->State = HAL_USART_STATE_BUSY; + + /* Disable the Peripheral */ + __USART_DISABLE(husart); + + /* Set the Usart Communication parameters */ + if (USART_SetConfig(husart) == HAL_ERROR) + { + return HAL_ERROR; + } + + /* In Synchronous mode, the following bits must be kept cleared: + - LINEN bit in the USART_CR2 register + - HDSEL, SCEN and IREN bits in the USART_CR3 register.*/ + husart->Instance->CR2 &= ~USART_CR2_LINEN; + husart->Instance->CR3 &= ~(USART_CR3_SCEN | USART_CR3_HDSEL | USART_CR3_IREN); + + /* Enable the Peripharal */ + __USART_ENABLE(husart); + + /* TEACK and/or REACK to check before moving husart->State to Ready */ + return (USART_CheckIdleState(husart)); +} + +/** + * @brief DeInitializes the USART peripheral + * @param husart: usart handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_USART_DeInit(USART_HandleTypeDef *husart) +{ + /* Check the USART handle allocation */ + if(husart == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_USART_INSTANCE(husart->Instance)); + + husart->State = HAL_USART_STATE_BUSY; + + husart->Instance->CR1 = 0x0; + husart->Instance->CR2 = 0x0; + husart->Instance->CR3 = 0x0; + + /* DeInit the low level hardware */ + HAL_USART_MspDeInit(husart); + + husart->ErrorCode = HAL_USART_ERROR_NONE; + husart->State = HAL_USART_STATE_RESET; + + /* Process Unlock */ + __HAL_UNLOCK(husart); + + return HAL_OK; +} + +/** + * @brief USART MSP Init + * @param husart: usart handle + * @retval None + */ + __weak void HAL_USART_MspInit(USART_HandleTypeDef *husart) +{ + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_USART_MspInit can be implemented in the user file + */ +} + +/** + * @brief USART MSP DeInit + * @param husart: usart handle + * @retval None + */ + __weak void HAL_USART_MspDeInit(USART_HandleTypeDef *husart) +{ + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_USART_MspDeInit can be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup HAL_USART_Group2 IO operation function + * @brief USART Transmit/Receive functions + * +@verbatim + =============================================================================== + ##### I/O operation function ##### + =============================================================================== + This subsection provides a set of functions allowing to manage the USART synchronous + data transfers. + + [..] The USART supports master mode only: it cannot receive or send data related to an input + clock (SCLK is always an output). + + (#) There are two mode of transfer: + (+) Blocking mode: The communication is performed in polling mode. + The HAL status of all data processing is returned by the same function + after finishing transfer. + (+) No-Blocking mode: The communication is performed using Interrupts + or DMA, These API's return the HAL status. + The end of the data processing will be indicated through the + dedicated USART IRQ when using Interrupt mode or the DMA IRQ when + using DMA mode. + The HAL_USART_TxCpltCallback(), HAL_USART_RxCpltCallback() and HAL_USART_TxRxCpltCallback() user callbacks + will be executed respectivelly at the end of the transmit or Receive process + The HAL_USART_ErrorCallback()user callback will be executed when a communication error is detected + + (#) Blocking mode API's are : + (+) HAL_USART_Transmit()in simplex mode + (+) HAL_USART_Receive() in full duplex receive only + (+) HAL_USART_TransmitReceive() in full duplex mode + + (#) Non-Blocking mode API's with Interrupt are : + (+) HAL_USART_Transmit_IT()in simplex mode + (+) HAL_USART_Receive_IT() in full duplex receive only + (+) HAL_USART_TransmitReceive_IT()in full duplex mode + (+) HAL_USART_IRQHandler() + + (#) No-Blocking mode functions with DMA are : + (+) HAL_USART_Transmit_DMA()in simplex mode + (+) HAL_USART_Receive_DMA() in full duplex receive only + (+) HAL_USART_TransmitReceive_DMA() in full duplex mode + (+) HAL_USART_DMAPause() + (+) HAL_USART_DMAResume() + (+) HAL_USART_DMAStop() + + (#) A set of Transfer Complete Callbacks are provided in No_Blocking mode: + (+) HAL_USART_TxCpltCallback() + (+) HAL_USART_RxCpltCallback() + (+) HAL_USART_TxHalfCpltCallback() + (+) HAL_USART_RxHalfCpltCallback() + (+) HAL_USART_ErrorCallback() + (+) HAL_USART_TxRxCpltCallback() + +@endverbatim + * @{ + */ + +/** + * @brief Simplex Send an amount of data in blocking mode + * @param husart: USART handle + * @param pTxData: pointer to data buffer + * @param Size: amount of data to be sent + * @param Timeout : Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_USART_Transmit(USART_HandleTypeDef *husart, uint8_t *pTxData, uint16_t Size, uint32_t Timeout) +{ + uint16_t* tmp; + + if(husart->State == HAL_USART_STATE_READY) + { + if((pTxData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(husart); + + husart->ErrorCode = HAL_USART_ERROR_NONE; + husart->State = HAL_USART_STATE_BUSY_TX; + + husart->TxXferSize = Size; + husart->TxXferCount = Size; + + /* Check the remaining data to be sent */ + while(husart->TxXferCount > 0) + { + husart->TxXferCount--; + if(USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_TXE, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + if ((husart->Init.WordLength == USART_WORDLENGTH_9B) && (husart->Init.Parity == USART_PARITY_NONE)) + { + tmp = (uint16_t*) pTxData; + husart->Instance->TDR = (*tmp & (uint16_t)0x01FF); + pTxData += 2; + } + else + { + husart->Instance->TDR = (*pTxData++ & (uint8_t)0xFF); + } + } + + if(USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_TC, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + husart->State = HAL_USART_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(husart); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive an amount of data in blocking mode + * To receive synchronous data, dummy data are simultaneously transmitted + * @param husart: USART handle + * @param pRxData: pointer to data buffer + * @param Size: amount of data to be received + * @param Timeout : Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_USART_Receive(USART_HandleTypeDef *husart, uint8_t *pRxData, uint16_t Size, uint32_t Timeout) +{ + uint16_t* tmp; + uint16_t uhMask; + + if(husart->State == HAL_USART_STATE_READY) + { + if((pRxData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + /* Process Locked */ + __HAL_LOCK(husart); + + husart->ErrorCode = HAL_USART_ERROR_NONE; + husart->State = HAL_USART_STATE_BUSY_RX; + + husart->RxXferSize = Size; + husart->RxXferCount = Size; + + /* Computation of UART mask to apply to RDR register */ + __HAL_USART_MASK_COMPUTATION(husart); + uhMask = husart->Mask; + + /* as long as data have to be received */ + while(husart->RxXferCount > 0) + { + husart->RxXferCount--; + + /* Wait until TC flag is set to send dummy byte in order to generate the + * clock for the slave to send data. + * Whatever the frame length (7, 8 or 9-bit long), the same dummy value + * can be written for all the cases. */ + if(USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_TC, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + husart->Instance->TDR = (DUMMY_DATA & (uint16_t)0x0FF); + + /* Wait for RXNE Flag */ + if(USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_RXNE, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + if ((husart->Init.WordLength == USART_WORDLENGTH_9B) && (husart->Init.Parity == USART_PARITY_NONE)) + { + tmp = (uint16_t*) pRxData ; + *tmp = (uint16_t)(husart->Instance->RDR & uhMask); + pRxData +=2; + } + else + { + *pRxData++ = (uint8_t)(husart->Instance->RDR & (uint8_t)uhMask); + } + } + + husart->State = HAL_USART_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(husart); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Full-Duplex Send and Receive an amount of data in blocking mode + * @param husart: USART handle + * @param pTxData: pointer to TX data buffer + * @param pRxData: pointer to RX data buffer + * @param Size: amount of data to be sent (same amount to be received) + * @param Timeout : Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_USART_TransmitReceive(USART_HandleTypeDef *husart, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size, uint32_t Timeout) +{ + uint16_t* tmp; + uint16_t uhMask; + + if(husart->State == HAL_USART_STATE_READY) + { + if((pTxData == NULL) || (pRxData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + /* Process Locked */ + __HAL_LOCK(husart); + + husart->ErrorCode = HAL_USART_ERROR_NONE; + husart->State = HAL_USART_STATE_BUSY_RX; + + husart->RxXferSize = Size; + husart->TxXferSize = Size; + husart->TxXferCount = Size; + husart->RxXferCount = Size; + + /* Computation of USART mask to apply to RDR register */ + __HAL_USART_MASK_COMPUTATION(husart); + uhMask = husart->Mask; + + /* Check the remain data to be sent */ + while(husart->TxXferCount > 0) + { + husart->TxXferCount--; + husart->RxXferCount--; + + /* Wait until TC flag is set to send data */ + if(USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_TC, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + if ((husart->Init.WordLength == USART_WORDLENGTH_9B) && (husart->Init.Parity == USART_PARITY_NONE)) + { + tmp = (uint16_t*) pTxData; + husart->Instance->TDR = (*tmp & uhMask); + pTxData += 2; + } + else + { + husart->Instance->TDR = (*pTxData++ & (uint8_t)uhMask); + } + + /* Wait for RXNE Flag */ + if(USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_RXNE, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + if ((husart->Init.WordLength == USART_WORDLENGTH_9B) && (husart->Init.Parity == USART_PARITY_NONE)) + { + tmp = (uint16_t*) pRxData ; + *tmp = (uint16_t)(husart->Instance->RDR & uhMask); + pRxData +=2; + } + else + { + *pRxData++ = (uint8_t)(husart->Instance->RDR & (uint8_t)uhMask); + } + } + + husart->State = HAL_USART_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(husart); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Send an amount of data in interrupt mode + * @param husart: USART handle + * @param pTxData: pointer to data buffer + * @param Size: amount of data to be sent + * @retval HAL status + */ +HAL_StatusTypeDef HAL_USART_Transmit_IT(USART_HandleTypeDef *husart, uint8_t *pTxData, uint16_t Size) +{ + if(husart->State == HAL_USART_STATE_READY) + { + if((pTxData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(husart); + + husart->pTxBuffPtr = pTxData; + husart->TxXferSize = Size; + husart->TxXferCount = Size; + + husart->ErrorCode = HAL_USART_ERROR_NONE; + husart->State = HAL_USART_STATE_BUSY_TX; + + /* The USART Error Interrupts: (Frame error, noise error, overrun error) + are not managed by the USART Transmit Process to avoid the overrun interrupt + when the usart mode is configured for transmit and receive "USART_MODE_TX_RX" + to benefit for the frame error and noise interrupts the usart mode should be + configured only for transmit "USART_MODE_TX" */ + + /* Process Unlocked */ + __HAL_UNLOCK(husart); + + /* Enable the USART Transmit Complete Interrupt */ + __HAL_USART_ENABLE_IT(husart, USART_IT_TC); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive an amount of data in blocking mode + * To receive synchronous data, dummy data are simultaneously transmitted + * @param husart: usart handle + * @param pRxData: pointer to data buffer + * @param Size: amount of data to be received + * @retval HAL status + */ +HAL_StatusTypeDef HAL_USART_Receive_IT(USART_HandleTypeDef *husart, uint8_t *pRxData, uint16_t Size) +{ + if(husart->State == HAL_USART_STATE_READY) + { + if((pRxData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + /* Process Locked */ + __HAL_LOCK(husart); + + husart->pRxBuffPtr = pRxData; + husart->RxXferSize = Size; + husart->RxXferCount = Size; + + __HAL_USART_MASK_COMPUTATION(husart); + + husart->ErrorCode = HAL_USART_ERROR_NONE; + husart->State = HAL_USART_STATE_BUSY_RX; + + /* Enable the USART Parity Error Interrupt */ + __HAL_USART_ENABLE_IT(husart, USART_IT_PE); + + /* Enable the USART Error Interrupt: (Frame error, noise error, overrun error) */ + __HAL_USART_ENABLE_IT(husart, USART_IT_ERR); + + /* Enable the USART Data Register not empty Interrupt */ + __HAL_USART_ENABLE_IT(husart, USART_IT_RXNE); + + /* Process Unlocked */ + __HAL_UNLOCK(husart); + + + /* Send dummy byte in order to generate the clock for the Slave to send the next data */ + if(husart->Init.WordLength == USART_WORDLENGTH_9B) + { + husart->Instance->TDR = (DUMMY_DATA & (uint16_t)0x01FF); + } + else + { + husart->Instance->TDR = (DUMMY_DATA & (uint16_t)0x00FF); + } + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Full-Duplex Send and Receive an amount of data in interrupt mode + * @param husart: USART handle + * @param pTxData: pointer to TX data buffer + * @param pRxData: pointer to RX data buffer + * @param Size: amount of data to be sent (same amount to be received) + * @retval HAL status + */ +HAL_StatusTypeDef HAL_USART_TransmitReceive_IT(USART_HandleTypeDef *husart, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size) +{ + + if(husart->State == HAL_USART_STATE_READY) + { + if((pTxData == NULL) || (pRxData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + /* Process Locked */ + __HAL_LOCK(husart); + + husart->pRxBuffPtr = pRxData; + husart->RxXferSize = Size; + husart->RxXferCount = Size; + husart->pTxBuffPtr = pTxData; + husart->TxXferSize = Size; + husart->TxXferCount = Size; + + __HAL_USART_MASK_COMPUTATION(husart); + + husart->ErrorCode = HAL_USART_ERROR_NONE; + husart->State = HAL_USART_STATE_BUSY_TX_RX; + + /* Enable the USART Data Register not empty Interrupt */ + __HAL_USART_ENABLE_IT(husart, USART_IT_RXNE); + + /* Enable the USART Parity Error Interrupt */ + __HAL_USART_ENABLE_IT(husart, USART_IT_PE); + + /* Enable the USART Error Interrupt: (Frame error, noise error, overrun error) */ + __HAL_USART_ENABLE_IT(husart, USART_IT_ERR); + + /* Process Unlocked */ + __HAL_UNLOCK(husart); + + /* Enable the USART Transmit Complete Interrupt */ + __HAL_USART_ENABLE_IT(husart, USART_IT_TC); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } + +} + +/** + * @brief Send an amount of data in DMA mode + * @param husart: USART handle + * @param pTxData: pointer to data buffer + * @param Size: amount of data to be sent + * @retval HAL status + */ +HAL_StatusTypeDef HAL_USART_Transmit_DMA(USART_HandleTypeDef *husart, uint8_t *pTxData, uint16_t Size) +{ + uint32_t *tmp; + + if(husart->State == HAL_USART_STATE_READY) + { + if((pTxData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + /* Process Locked */ + __HAL_LOCK(husart); + + husart->pTxBuffPtr = pTxData; + husart->TxXferSize = Size; + husart->TxXferCount = Size; + + husart->ErrorCode = HAL_USART_ERROR_NONE; + husart->State = HAL_USART_STATE_BUSY_TX; + + /* Set the USART DMA transfert complete callback */ + husart->hdmatx->XferCpltCallback = USART_DMATransmitCplt; + + /* Set the USART DMA Half transfer complete callback */ + husart->hdmatx->XferHalfCpltCallback = USART_DMATxHalfCplt; + + /* Set the DMA error callback */ + husart->hdmatx->XferErrorCallback = USART_DMAError; + + /* Enable the USART transmit DMA channel */ + tmp = (uint32_t*)&pTxData; + HAL_DMA_Start_IT(husart->hdmatx, *(uint32_t*)tmp, (uint32_t)&husart->Instance->TDR, Size); + + /* Enable the DMA transfer for transmit request by setting the DMAT bit + in the USART CR3 register */ + husart->Instance->CR3 |= USART_CR3_DMAT; + + /* Process Unlocked */ + __HAL_UNLOCK(husart); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive an amount of data in DMA mode + * @param husart: USART handle + * @param pRxData: pointer to data buffer + * @param Size: amount of data to be received + * @note When the USART parity is enabled (PCE = 1), the received data contain + * the parity bit (MSB position) + * @retval HAL status + * @note The USART DMA transmit stream must be configured in order to generate the clock for the slave. + */ +HAL_StatusTypeDef HAL_USART_Receive_DMA(USART_HandleTypeDef *husart, uint8_t *pRxData, uint16_t Size) +{ + uint32_t *tmp; + + if(husart->State == HAL_USART_STATE_READY) + { + if((pRxData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(husart); + + husart->pRxBuffPtr = pRxData; + husart->RxXferSize = Size; + husart->pTxBuffPtr = pRxData; + husart->TxXferSize = Size; + + husart->ErrorCode = HAL_USART_ERROR_NONE; + husart->State = HAL_USART_STATE_BUSY_RX; + + /* Set the USART DMA Rx transfert complete callback */ + husart->hdmarx->XferCpltCallback = USART_DMAReceiveCplt; + + /* Set the USART DMA Half transfer complete callback */ + husart->hdmarx->XferHalfCpltCallback = USART_DMARxHalfCplt; + + /* Set the USART DMA Rx transfert error callback */ + husart->hdmarx->XferErrorCallback = USART_DMAError; + + /* Enable the USART receive DMA channel */ + tmp = (uint32_t*)&pRxData; + HAL_DMA_Start_IT(husart->hdmarx, (uint32_t)&husart->Instance->RDR, *(uint32_t*)tmp, Size); + + /* Enable the USART transmit DMA channel: the transmit stream is used in order + to generate in the non-blocking mode the clock to the slave device, + this mode isn't a simplex receive mode but a full-duplex receive mode */ + tmp = (uint32_t*)&pRxData; + HAL_DMA_Start_IT(husart->hdmatx, *(uint32_t*)tmp, (uint32_t)&husart->Instance->TDR, Size); + + /* Enable the DMA transfer for the receiver request by setting the DMAR bit + in the USART CR3 register */ + husart->Instance->CR3 |= USART_CR3_DMAR; + + /* Enable the DMA transfer for transmit request by setting the DMAT bit + in the USART CR3 register */ + husart->Instance->CR3 |= USART_CR3_DMAT; + + /* Process Unlocked */ + __HAL_UNLOCK(husart); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Full-Duplex Transmit Receive an amount of data in non blocking mode + * @param husart: usart handle + * @param pTxData: pointer to TX data buffer + * @param pRxData: pointer to RX data buffer + * @param Size: amount of data to be received/sent + * @retval HAL status + */ +HAL_StatusTypeDef HAL_USART_TransmitReceive_DMA(USART_HandleTypeDef *husart, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size) +{ + uint32_t *tmp; + + if(husart->State == HAL_USART_STATE_READY) + { + if((pTxData == NULL) || (pRxData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + /* Process Locked */ + __HAL_LOCK(husart); + + husart->pRxBuffPtr = pRxData; + husart->RxXferSize = Size; + husart->pTxBuffPtr = pTxData; + husart->TxXferSize = Size; + + husart->ErrorCode = HAL_USART_ERROR_NONE; + husart->State = HAL_USART_STATE_BUSY_TX_RX; + + /* Set the USART DMA Rx transfert complete callback */ + husart->hdmarx->XferCpltCallback = USART_DMAReceiveCplt; + + /* Set the USART DMA Tx transfert complete callback */ + husart->hdmatx->XferCpltCallback = USART_DMATransmitCplt; + + /* Set the USART DMA Tx transfert error callback */ + husart->hdmatx->XferErrorCallback = USART_DMAError; + + /* Set the USART DMA Rx transfert error callback */ + husart->hdmarx->XferErrorCallback = USART_DMAError; + + /* Enable the USART receive DMA channel */ + tmp = (uint32_t*)&pRxData; + HAL_DMA_Start_IT(husart->hdmarx, (uint32_t)&husart->Instance->RDR, *(uint32_t*)tmp, Size); + + /* Enable the USART transmit DMA channel */ + tmp = (uint32_t*)&pTxData; + HAL_DMA_Start_IT(husart->hdmatx, *(uint32_t*)tmp, (uint32_t)&husart->Instance->TDR, Size); + + /* Enable the DMA transfer for the receiver request by setting the DMAR bit + in the USART CR3 register */ + husart->Instance->CR3 |= USART_CR3_DMAR; + + /* Enable the DMA transfer for transmit request by setting the DMAT bit + in the USART CR3 register */ + husart->Instance->CR3 |= USART_CR3_DMAT; + + /* Process Unlocked */ + __HAL_UNLOCK(husart); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Pauses the DMA Transfer. + * @param husart: USART handle + * @retval None + */ +HAL_StatusTypeDef HAL_USART_DMAPause(USART_HandleTypeDef *husart) +{ + /* Process Locked */ + __HAL_LOCK(husart); + + if(husart->State == HAL_USART_STATE_BUSY_TX) + { + /* Disable the USART DMA Tx request */ + husart->Instance->CR3 &= (uint32_t)(~USART_CR3_DMAT); + } + else if(husart->State == HAL_USART_STATE_BUSY_RX) + { + /* Disable the USART DMA Rx request */ + husart->Instance->CR3 &= (uint32_t)(~USART_CR3_DMAR); + } + else if(husart->State == HAL_USART_STATE_BUSY_TX_RX) + { + /* Disable the USART DMA Tx request */ + husart->Instance->CR3 &= (uint32_t)(~USART_CR3_DMAT); + /* Disable the USART DMA Rx request */ + husart->Instance->CR3 &= (uint32_t)(~USART_CR3_DMAR); + } + + /* Process Unlocked */ + __HAL_UNLOCK(husart); + + return HAL_OK; +} + +/** + * @brief Resumes the DMA Transfer. + * @param husart: USART handle + * @retval None + */ +HAL_StatusTypeDef HAL_USART_DMAResume(USART_HandleTypeDef *husart) +{ + /* Process Locked */ + __HAL_LOCK(husart); + + if(husart->State == HAL_USART_STATE_BUSY_TX) + { + /* Enable the USART DMA Tx request */ + husart->Instance->CR3 |= USART_CR3_DMAT; + } + else if(husart->State == HAL_USART_STATE_BUSY_RX) + { + /* Enable the USART DMA Rx request */ + husart->Instance->CR3 |= USART_CR3_DMAR; + } + else if(husart->State == HAL_USART_STATE_BUSY_TX_RX) + { + /* Enable the USART DMA Rx request before the DMA Tx request */ + husart->Instance->CR3 |= USART_CR3_DMAR; + /* Enable the USART DMA Tx request */ + husart->Instance->CR3 |= USART_CR3_DMAT; + } + + /* If the USART peripheral is still not enabled, enable it */ + if ((husart->Instance->CR1 & USART_CR1_UE) == 0) + { + /* Enable USART peripheral */ + __USART_ENABLE(husart); + } + + /* Process Unlocked */ + __HAL_UNLOCK(husart); + + return HAL_OK; +} + +/** + * @brief Stops the DMA Transfer. + * @param husart: USART handle + * @retval None + */ +HAL_StatusTypeDef HAL_USART_DMAStop(USART_HandleTypeDef *husart) +{ + /* Process Locked */ + __HAL_LOCK(husart); + + /* Disable the USART Tx/Rx DMA requests */ + husart->Instance->CR3 &= ~USART_CR3_DMAT; + husart->Instance->CR3 &= ~USART_CR3_DMAR; + + /* Abort the USART DMA tx Stream */ + if(husart->hdmatx != NULL) + { + HAL_DMA_Abort(husart->hdmatx); + } + /* Abort the USART DMA rx Stream */ + if(husart->hdmarx != NULL) + { + HAL_DMA_Abort(husart->hdmarx); + } + + /* Disable USART peripheral */ + __USART_DISABLE(husart); + + husart->State = HAL_USART_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(husart); + + return HAL_OK; +} + +/** + * @brief This function handles USART interrupt request. + * @param husart: USART handle + * @retval None + */ +void HAL_USART_IRQHandler(USART_HandleTypeDef *husart) +{ + + /* USART parity error interrupt occured ------------------------------------*/ + if((__HAL_USART_GET_IT(husart, USART_IT_PE) != RESET) && (__HAL_USART_GET_IT_SOURCE(husart, USART_IT_PE) != RESET)) + { + __HAL_USART_CLEAR_IT(husart, USART_IT_PE); + husart->ErrorCode |= HAL_USART_ERROR_PE; + /* Set the USART state ready to be able to start again the process */ + husart->State = HAL_USART_STATE_READY; + } + + /* USART frame error interrupt occured -------------------------------------*/ + if((__HAL_USART_GET_IT(husart, USART_IT_FE) != RESET) && (__HAL_USART_GET_IT_SOURCE(husart, USART_IT_ERR) != RESET)) + { + __HAL_USART_CLEAR_IT(husart, USART_IT_FE); + husart->ErrorCode |= HAL_USART_ERROR_FE; + /* Set the USART state ready to be able to start again the process */ + husart->State = HAL_USART_STATE_READY; + } + + /* USART noise error interrupt occured -------------------------------------*/ + if((__HAL_USART_GET_IT(husart, USART_IT_NE) != RESET) && (__HAL_USART_GET_IT_SOURCE(husart, USART_IT_ERR) != RESET)) + { + __HAL_USART_CLEAR_IT(husart, USART_IT_NE); + husart->ErrorCode |= HAL_USART_ERROR_NE; + /* Set the USART state ready to be able to start again the process */ + husart->State = HAL_USART_STATE_READY; + } + + /* USART Over-Run interrupt occured ----------------------------------------*/ + if((__HAL_USART_GET_IT(husart, USART_IT_ORE) != RESET) && (__HAL_USART_GET_IT_SOURCE(husart, USART_IT_ERR) != RESET)) + { + __HAL_USART_CLEAR_IT(husart, USART_IT_ORE); + husart->ErrorCode |= HAL_USART_ERROR_ORE; + /* Set the USART state ready to be able to start again the process */ + husart->State = HAL_USART_STATE_READY; + } + + /* Call USART Error Call back function if need be --------------------------*/ + if(husart->ErrorCode != HAL_USART_ERROR_NONE) + { + HAL_USART_ErrorCallback(husart); + } + + /* USART in mode Receiver --------------------------------------------------*/ + if((__HAL_USART_GET_IT(husart, USART_IT_RXNE) != RESET) && (__HAL_USART_GET_IT_SOURCE(husart, USART_IT_RXNE) != RESET)) + { + if(husart->State == HAL_USART_STATE_BUSY_RX) + { + USART_Receive_IT(husart); + } + else + { + USART_TransmitReceive_IT(husart); + } + } + + /* USART in mode Transmitter -----------------------------------------------*/ + if((__HAL_USART_GET_IT(husart, USART_IT_TC) != RESET) &&(__HAL_USART_GET_IT_SOURCE(husart, USART_IT_TC) != RESET)) + { + if(husart->State == HAL_USART_STATE_BUSY_TX) + { + USART_Transmit_IT(husart); + } + else + { + USART_TransmitReceive_IT(husart); + } + } + +} + + +/** + * @brief This function handles USART Communication Timeout. + * @param husart: USART handle + * @param Flag: specifies the USART flag to check. + * @param Status: The new Flag status (SET or RESET). + * @param Timeout: Timeout duration + * @retval HAL status + */ +static HAL_StatusTypeDef USART_WaitOnFlagUntilTimeout(USART_HandleTypeDef *husart, uint32_t Flag, FlagStatus Status, uint32_t Timeout) +{ + uint32_t tickstart = HAL_GetTick(); + + /* Wait until flag is set */ + if(Status == RESET) + { + while(__HAL_USART_GET_FLAG(husart, Flag) == RESET) + { + /* Check for the Timeout */ + if(Timeout != HAL_MAX_DELAY) + { + if((HAL_GetTick() - tickstart) >= Timeout) + { + /* Disable TXE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts for the interrupt process */ + __HAL_USART_DISABLE_IT(husart, USART_IT_TXE); + __HAL_USART_DISABLE_IT(husart, USART_IT_RXNE); + __HAL_USART_DISABLE_IT(husart, USART_IT_PE); + __HAL_USART_DISABLE_IT(husart, USART_IT_ERR); + + husart->State= HAL_USART_STATE_TIMEOUT; + + /* Process Unlocked */ + __HAL_UNLOCK(husart); + + return HAL_TIMEOUT; + } + } + } + } + else + { + while(__HAL_USART_GET_FLAG(husart, Flag) != RESET) + { + /* Check for the Timeout */ + if(Timeout != HAL_MAX_DELAY) + { + if((HAL_GetTick() - tickstart) >= Timeout) + { + /* Disable TXE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts for the interrupt process */ + __HAL_USART_DISABLE_IT(husart, USART_IT_TXE); + __HAL_USART_DISABLE_IT(husart, USART_IT_RXNE); + __HAL_USART_DISABLE_IT(husart, USART_IT_PE); + __HAL_USART_DISABLE_IT(husart, USART_IT_ERR); + + husart->State= HAL_USART_STATE_TIMEOUT; + + /* Process Unlocked */ + __HAL_UNLOCK(husart); + + return HAL_TIMEOUT; + } + } + } + } + return HAL_OK; +} + + +/** + * @brief DMA USART transmit process complete callback + * @param hdma : DMA handle + * @retval None + */ +static void USART_DMATransmitCplt(DMA_HandleTypeDef *hdma) +{ + USART_HandleTypeDef* husart = ( USART_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + + husart->TxXferCount = 0; + + if(husart->State == HAL_USART_STATE_BUSY_TX) + { + /* Wait for USART TC Flag */ + if(USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_TC, RESET, HAL_USART_TXDMA_TIMEOUTVALUE) != HAL_OK) + { + /* Timeout Occured */ + husart->State = HAL_USART_STATE_TIMEOUT; + HAL_USART_ErrorCallback(husart); + } + else + { + /* No Timeout */ + /* Disable the DMA transfer for transmit request by setting the DMAT bit + in the USART CR3 register */ + husart->Instance->CR3 &= ~(USART_CR3_DMAT); + husart->State= HAL_USART_STATE_READY; + } + } + /* the usart state is HAL_USART_STATE_BUSY_TX_RX*/ + else + { + husart->State= HAL_USART_STATE_BUSY_RX; + HAL_USART_TxCpltCallback(husart); +} +} + + +/** + * @brief DMA USART transmit process half complete callback + * @param hdma : DMA handle + * @retval None + */ +static void USART_DMATxHalfCplt(DMA_HandleTypeDef *hdma) +{ + USART_HandleTypeDef* husart = (USART_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent; + + HAL_USART_TxHalfCpltCallback(husart); +} + +/** + * @brief DMA USART receive process complete callback + * @param hdma : DMA handle + * @retval None + */ +static void USART_DMAReceiveCplt(DMA_HandleTypeDef *hdma) +{ + USART_HandleTypeDef* husart = ( USART_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + + husart->RxXferCount = 0; + + /* Disable the DMA RX transfer for the receiver request by resetting the DMAR bit + in USART CR3 register */ + husart->Instance->CR3 &= (uint16_t)~((uint16_t)USART_CR3_DMAR); + /* similarly, disable the DMA TX transfer that was started to provide the + clock to the slave device */ + husart->Instance->CR3 &= (uint16_t)~((uint16_t)USART_CR3_DMAT); + + husart->State= HAL_USART_STATE_READY; + + HAL_USART_RxCpltCallback(husart); +} + +/** + * @brief DMA USART receive process half complete callback + * @param hdma : DMA handle + * @retval None + */ +static void USART_DMARxHalfCplt(DMA_HandleTypeDef *hdma) +{ + USART_HandleTypeDef* husart = (USART_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent; + + HAL_USART_RxHalfCpltCallback(husart); +} + +/** + * @brief DMA USART communication error callback + * @param hdma : DMA handle + * @retval None + */ +static void USART_DMAError(DMA_HandleTypeDef *hdma) +{ + USART_HandleTypeDef* husart = ( USART_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + + husart->RxXferCount = 0; + husart->TxXferCount = 0; + husart->ErrorCode |= HAL_USART_ERROR_DMA; + husart->State= HAL_USART_STATE_READY; + + HAL_USART_ErrorCallback(husart); +} + +/** + * @brief Tx Transfer completed callbacks + * @param husart: usart handle + * @retval None + */ +__weak void HAL_USART_TxCpltCallback(USART_HandleTypeDef *husart) +{ + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_USART_TxCpltCallback can be implemented in the user file + */ +} + +/** + * @brief Tx Half Transfer completed callbacks. + * @param husart: USART handle + * @retval None + */ + __weak void HAL_USART_TxHalfCpltCallback(USART_HandleTypeDef *husart) +{ + /* NOTE: This function should not be modified, when the callback is needed, + the HAL_USART_TxHalfCpltCallback can be implemented in the user file + */ +} + +/** + * @brief Rx Transfer completed callbacks. + * @param husart: USART handle + * @retval None + */ +__weak void HAL_USART_RxCpltCallback(USART_HandleTypeDef *husart) +{ + /* NOTE: This function should not be modified, when the callback is needed, + the HAL_USART_RxCpltCallback can be implemented in the user file + */ +} + +/** + * @brief Rx Half Transfer completed callbacks + * @param husart: usart handle + * @retval None + */ +__weak void HAL_USART_RxHalfCpltCallback(USART_HandleTypeDef *husart) +{ + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_USART_RxHalfCpltCallback can be implemented in the user file + */ +} + +/** + * @brief Tx/Rx Transfers completed callback for the non-blocking process + * @param husart: usart handle + * @retval None + */ +__weak void HAL_USART_TxRxCpltCallback(USART_HandleTypeDef *husart) +{ + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_USART_TxRxCpltCallback can be implemented in the user file + */ +} + +/** + * @brief USART error callbacks + * @param husart: usart handle + * @retval None + */ +__weak void HAL_USART_ErrorCallback(USART_HandleTypeDef *husart) +{ + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_USART_ErrorCallback can be implemented in the user file + */ +} + + +/** + * @brief Simplex Send an amount of data in non-blocking mode. + * Function called under interruption only, once + * interruptions have been enabled by HAL_USART_Transmit_IT() + * @param husart: USART handle + * @retval HAL status + * @note The USART errors are not managed to avoid the overrun error. + */ +static HAL_StatusTypeDef USART_Transmit_IT(USART_HandleTypeDef *husart) +{ + uint16_t* tmp; + + if (husart->State == HAL_USART_STATE_BUSY_TX) + { + /* Process Locked */ + __HAL_LOCK(husart); + + if(husart->TxXferCount == 0) + { + /* Disable the USART Transmit Complete Interrupt */ + __HAL_USART_DISABLE_IT(husart, USART_IT_TC); + + /* Disable the USART Error Interrupt: (Frame error, noise error, overrun error) */ + __HAL_USART_DISABLE_IT(husart, USART_IT_ERR); + + husart->State = HAL_USART_STATE_READY; + + /* Call the Process Unlocked before calling the Tx call back API to give the possibiity to + start again the Transmission under the Tx call back API */ + __HAL_UNLOCK(husart); + + HAL_USART_TxCpltCallback(husart); + + return HAL_OK; + } + else + { + if ((husart->Init.WordLength == USART_WORDLENGTH_9B) && (husart->Init.Parity == USART_PARITY_NONE)) + { + tmp = (uint16_t*) husart->pTxBuffPtr; + husart->Instance->TDR = (*tmp & (uint16_t)0x01FF); + husart->pTxBuffPtr += 2; + } + else + { + husart->Instance->TDR = (uint8_t)(*husart->pTxBuffPtr++ & (uint8_t)0xFF); + } + + husart->TxXferCount--; + + /* Process Unlocked */ + __HAL_UNLOCK(husart); + + return HAL_OK; + } + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Simplex Receive an amount of data in non-blocking mode. + * Function called under interruption only, once + * interruptions have been enabled by HAL_USART_Receive_IT() + * @param husart: USART handle + * @retval HAL status + */ +static HAL_StatusTypeDef USART_Receive_IT(USART_HandleTypeDef *husart) +{ + uint16_t* tmp; + uint16_t uhMask = husart->Mask; + + if(husart->State == HAL_USART_STATE_BUSY_RX) + { + /* Process Locked */ + __HAL_LOCK(husart); + + if ((husart->Init.WordLength == USART_WORDLENGTH_9B) && (husart->Init.Parity == USART_PARITY_NONE)) + { + tmp = (uint16_t*) husart->pRxBuffPtr ; + *tmp = (uint16_t)(husart->Instance->RDR & uhMask); + husart->pRxBuffPtr += 2; + } + else + { + *husart->pRxBuffPtr++ = (uint8_t)(husart->Instance->RDR & (uint8_t)uhMask); + } + /* Send dummy byte in order to generate the clock for the Slave to Send the next data */ + husart->Instance->TDR = (DUMMY_DATA & (uint16_t)0x00FF); + + if(--husart->RxXferCount == 0) + { + __HAL_USART_DISABLE_IT(husart, USART_IT_RXNE); + + /* Disable the USART Parity Error Interrupt */ + __HAL_USART_DISABLE_IT(husart, USART_IT_PE); + + /* Disable the USART Error Interrupt: (Frame error, noise error, overrun error) */ + __HAL_USART_DISABLE_IT(husart, USART_IT_ERR); + + husart->State = HAL_USART_STATE_READY; + + /* Call the Process Unlocked before calling the Rx call back API to give the possibility to + start again the reception under the Rx call back API */ + __HAL_UNLOCK(husart); + + HAL_USART_RxCpltCallback(husart); + + return HAL_OK; + } + + /* Process Unlocked */ + __HAL_UNLOCK(husart); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Full-Duplex Send receive an amount of data in full-duplex mode (non-blocking). + * Function called under interruption only, once + * interruptions have been enabled by HAL_USART_TransmitReceive_IT() + * @param husart: USART handle + * @retval HAL status + */ +static HAL_StatusTypeDef USART_TransmitReceive_IT(USART_HandleTypeDef *husart) +{ + uint16_t* tmp; + uint16_t uhMask = husart->Mask; + + if(husart->State == HAL_USART_STATE_BUSY_TX_RX) + { + /* Process Locked */ + __HAL_LOCK(husart); + if(husart->TxXferCount != 0x00) + { + if(__HAL_USART_GET_FLAG(husart, USART_FLAG_TC) != RESET) + { + if ((husart->Init.WordLength == USART_WORDLENGTH_9B) && (husart->Init.Parity == USART_PARITY_NONE)) + { + tmp = (uint16_t*) husart->pTxBuffPtr; + husart->Instance->TDR = (uint16_t)(*tmp & uhMask); + husart->pTxBuffPtr += 2; + } + else + { + husart->Instance->TDR = (uint8_t)(*husart->pTxBuffPtr++ & (uint8_t)uhMask); + } + husart->TxXferCount--; + + /* Check the latest data transmitted */ + if(husart->TxXferCount == 0) + { + __HAL_USART_DISABLE_IT(husart, USART_IT_TC); + } + } + } + + if(husart->RxXferCount != 0x00) + { + if(__HAL_USART_GET_FLAG(husart, USART_FLAG_RXNE) != RESET) + { + if ((husart->Init.WordLength == USART_WORDLENGTH_9B) && (husart->Init.Parity == USART_PARITY_NONE)) + { + tmp = (uint16_t*) husart->pRxBuffPtr ; + *tmp = (uint16_t)(husart->Instance->RDR & uhMask); + husart->pRxBuffPtr += 2; + } + else + { + *husart->pRxBuffPtr++ = (uint8_t)(husart->Instance->RDR & (uint8_t)uhMask); + } + husart->RxXferCount--; + } + } + + /* Check the latest data received */ + if(husart->RxXferCount == 0) + { + __HAL_USART_DISABLE_IT(husart, USART_IT_RXNE); + + /* Disable the USART Parity Error Interrupt */ + __HAL_USART_DISABLE_IT(husart, USART_IT_PE); + + /* Disable the USART Error Interrupt: (Frame error, noise error, overrun error) */ + __HAL_USART_DISABLE_IT(husart, USART_IT_ERR); + + husart->State = HAL_USART_STATE_READY; + + /* Call the Process Unlocked before calling the Tx\Rx call back API to give the possibility to + start again the Transmission\reception under the Tx\Rx call back API */ + __HAL_UNLOCK(husart); + + HAL_USART_TxRxCpltCallback(husart); + + return HAL_OK; + } + + /* Process Unlocked */ + __HAL_UNLOCK(husart); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @} + */ + +/** @defgroup HAL_USART_Group3 Peripheral Control function + * @brief USART control functions + * +@verbatim + =============================================================================== + ##### Peripheral Control function ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to control the USART. + (+) HAL_USART_GetState() API can be helpful to check in run-time the state of the USART peripheral. + (+) USART_SetConfig() API is used to set the USART communication parameters. + (+) USART_CheckIdleState() APi ensures that TEACK and/or REACK bits are set after initialization + +@endverbatim + * @{ + */ + + + +/** + * @brief return the USART state + * @param husart: USART handle + * @retval HAL state + */ +HAL_USART_StateTypeDef HAL_USART_GetState(USART_HandleTypeDef *husart) +{ + return husart->State; +} + +/** + * @brief Return the USART error code + * @param husart : pointer to a USART_HandleTypeDef structure that contains + * the configuration information for the specified USART. + * @retval USART Error Code + */ +uint32_t HAL_USART_GetError(USART_HandleTypeDef *husart) +{ + return husart->ErrorCode; +} + +/** + * @brief Configure the USART peripheral + * @param husart: USART handle + * @retval None + */ +static HAL_StatusTypeDef USART_SetConfig(USART_HandleTypeDef *husart) +{ + uint32_t tmpreg = 0x0; + USART_ClockSourceTypeDef clocksource = USART_CLOCKSOURCE_UNDEFINED; + HAL_StatusTypeDef ret = HAL_OK; + + /* Check the parameters */ + assert_param(IS_USART_POLARITY(husart->Init.CLKPolarity)); + assert_param(IS_USART_PHASE(husart->Init.CLKPhase)); + assert_param(IS_USART_LASTBIT(husart->Init.CLKLastBit)); + assert_param(IS_USART_BAUDRATE(husart->Init.BaudRate)); + assert_param(IS_USART_WORD_LENGTH(husart->Init.WordLength)); + assert_param(IS_USART_STOPBITS(husart->Init.StopBits)); + assert_param(IS_USART_PARITY(husart->Init.Parity)); + assert_param(IS_USART_MODE(husart->Init.Mode)); + + + /*-------------------------- USART CR1 Configuration -----------------------*/ + /* Clear M, PCE, PS, TE and RE bits and configure + * the USART Word Length, Parity, Mode and oversampling: + * set the M bits according to husart->Init.WordLength value + * set PCE and PS bits according to husart->Init.Parity value + * set TE and RE bits according to husart->Init.Mode value */ + tmpreg = (uint32_t)husart->Init.WordLength | husart->Init.Parity | husart->Init.Mode ; + MODIFY_REG(husart->Instance->CR1, USART_CR1_FIELDS, tmpreg); + + /*---------------------------- USART CR2 Configuration ---------------------*/ + /* Clear and configure the USART Clock, CPOL, CPHA, LBCL and STOP bits: + * set CPOL bit according to husart->Init.CLKPolarity value + * set CPHA bit according to husart->Init.CLKPhase value + * set LBCL bit according to husart->Init.CLKLastBit value + * set STOP[13:12] bits according to husart->Init.StopBits value */ + tmpreg = (uint32_t)(USART_CLOCK_ENABLED); + tmpreg |= (uint32_t)(husart->Init.CLKPolarity | husart->Init.CLKPhase); + tmpreg |= (uint32_t)(husart->Init.CLKLastBit | husart->Init.StopBits); + MODIFY_REG(husart->Instance->CR2, USART_CR2_FIELDS, tmpreg); + + /*-------------------------- USART CR3 Configuration -----------------------*/ + /* no CR3 register configuration */ + + /*-------------------------- USART BRR Configuration -----------------------*/ + __HAL_USART_GETCLOCKSOURCE(husart, clocksource); + switch (clocksource) + { + case USART_CLOCKSOURCE_PCLK1: + husart->Instance->BRR = (uint16_t)(HAL_RCC_GetPCLK1Freq() / husart->Init.BaudRate); + break; + case USART_CLOCKSOURCE_HSI: + husart->Instance->BRR = (uint16_t)(HSI_VALUE / husart->Init.BaudRate); + break; + case USART_CLOCKSOURCE_SYSCLK: + husart->Instance->BRR = (uint16_t)(HAL_RCC_GetSysClockFreq() / husart->Init.BaudRate); + break; + case USART_CLOCKSOURCE_LSE: + husart->Instance->BRR = (uint16_t)(LSE_VALUE / husart->Init.BaudRate); + break; + case USART_CLOCKSOURCE_UNDEFINED: + default: + ret = HAL_ERROR; + break; + } + + return ret; +} + + + +/** + * @brief Check the USART Idle State + * @param husart: USART handle + * @retval HAL status + */ +static HAL_StatusTypeDef USART_CheckIdleState(USART_HandleTypeDef *husart) +{ + /* Initialize the USART ErrorCode */ + husart->ErrorCode = HAL_USART_ERROR_NONE; + + /* Check if the Transmitter is enabled */ + if((husart->Instance->CR1 & USART_CR1_TE) == USART_CR1_TE) + { + /* Wait until TEACK flag is set */ + if(USART_WaitOnFlagUntilTimeout(husart, USART_ISR_TEACK, RESET, TEACK_REACK_TIMEOUT) != HAL_OK) + { + husart->State= HAL_USART_STATE_TIMEOUT; + return HAL_TIMEOUT; + } + } + /* Check if the Receiver is enabled */ + if((husart->Instance->CR1 & USART_CR1_RE) == USART_CR1_RE) + { + /* Wait until REACK flag is set */ + if(USART_WaitOnFlagUntilTimeout(husart, USART_ISR_REACK, RESET, TEACK_REACK_TIMEOUT) != HAL_OK) + { + husart->State= HAL_USART_STATE_TIMEOUT; + return HAL_TIMEOUT; + } + } + + /* Initialize the USART state*/ + husart->State= HAL_USART_STATE_READY; + /* Process Unlocked */ + __HAL_UNLOCK(husart); + + return HAL_OK; +} + +/** + * @} + */ + +/** + * @} + */ + +#endif /* HAL_USART_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_usart.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_usart.h new file mode 100644 index 0000000000..d35fc8ed32 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_usart.h @@ -0,0 +1,560 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_usart.h + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief Header file of USART HAL module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32F0xx_HAL_USART_H +#define __STM32F0xx_HAL_USART_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal_def.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @addtogroup USART + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ + +/** + * @brief USART Init Structure definition + */ +typedef struct +{ + uint32_t BaudRate; /*!< This member configures the Usart communication baud rate. + The baud rate is computed using the following formula: + Baud Rate Register = ((PCLKx) / ((huart->Init.BaudRate))) */ + + uint32_t WordLength; /*!< Specifies the number of data bits transmitted or received in a frame. + This parameter can be a value of @ref USARTEx_Word_Length */ + + uint16_t StopBits; /*!< Specifies the number of stop bits transmitted. + This parameter can be a value of @ref USART_Stop_Bits */ + + uint16_t Parity; /*!< Specifies the parity mode. + This parameter can be a value of @ref USART_Parity + @note When parity is enabled, the computed parity is inserted + at the MSB position of the transmitted data (9th bit when + the word length is set to 9 data bits; 8th bit when the + word length is set to 8 data bits). */ + + uint16_t Mode; /*!< Specifies wether the Receive or Transmit mode is enabled or disabled. + This parameter can be a value of @ref USART_Mode */ + + uint16_t CLKPolarity; /*!< Specifies the steady state of the serial clock. + This parameter can be a value of @ref USART_Clock_Polarity */ + + uint16_t CLKPhase; /*!< Specifies the clock transition on which the bit capture is made. + This parameter can be a value of @ref USART_Clock_Phase */ + + uint16_t CLKLastBit; /*!< Specifies whether the clock pulse corresponding to the last transmitted + data bit (MSB) has to be output on the SCLK pin in synchronous mode. + This parameter can be a value of @ref USART_Last_Bit */ +}USART_InitTypeDef; + +/** + * @brief HAL State structures definition + */ +typedef enum +{ + HAL_USART_STATE_RESET = 0x00, /*!< Peripheral is not initialized */ + HAL_USART_STATE_READY = 0x01, /*!< Peripheral Initialized and ready for use */ + HAL_USART_STATE_BUSY = 0x02, /*!< an internal process is ongoing */ + HAL_USART_STATE_BUSY_TX = 0x12, /*!< Data Transmission process is ongoing */ + HAL_USART_STATE_BUSY_RX = 0x22, /*!< Data Reception process is ongoing */ + HAL_USART_STATE_BUSY_TX_RX = 0x32, /*!< Data Transmission Reception process is ongoing */ + HAL_USART_STATE_TIMEOUT = 0x03, /*!< Timeout state */ + HAL_USART_STATE_ERROR = 0x04 /*!< Error */ +}HAL_USART_StateTypeDef; + +/** + * @brief HAL USART Error Code structure definition + */ +typedef enum +{ + HAL_USART_ERROR_NONE = 0x00, /*!< No error */ + HAL_USART_ERROR_PE = 0x01, /*!< Parity error */ + HAL_USART_ERROR_NE = 0x02, /*!< Noise error */ + HAL_USART_ERROR_FE = 0x04, /*!< frame error */ + HAL_USART_ERROR_ORE = 0x08, /*!< Overrun error */ + HAL_USART_ERROR_DMA = 0x10 /*!< DMA transfer error */ +}HAL_USART_ErrorTypeDef; + +/** + * @brief USART clock sources definitions + */ +typedef enum +{ + USART_CLOCKSOURCE_PCLK1 = 0x00, /*!< PCLK1 clock source */ + USART_CLOCKSOURCE_HSI = 0x02, /*!< HSI clock source */ + USART_CLOCKSOURCE_SYSCLK = 0x04, /*!< SYSCLK clock source */ + USART_CLOCKSOURCE_LSE = 0x08, /*!< LSE clock source */ + USART_CLOCKSOURCE_UNDEFINED = 0x10 /*!< undefined clock source */ +}USART_ClockSourceTypeDef; + +/** + * @brief USART handle Structure definition + */ +typedef struct +{ + USART_TypeDef *Instance; /* USART registers base address */ + + USART_InitTypeDef Init; /* USART communication parameters */ + + uint8_t *pTxBuffPtr; /* Pointer to USART Tx transfer Buffer */ + + uint16_t TxXferSize; /* USART Tx Transfer size */ + + uint16_t TxXferCount; /* USART Tx Transfer Counter */ + + uint8_t *pRxBuffPtr; /* Pointer to USART Rx transfer Buffer */ + + uint16_t RxXferSize; /* USART Rx Transfer size */ + + uint16_t RxXferCount; /* USART Rx Transfer Counter */ + + uint16_t Mask; /* USART Rx RDR register mask */ + + DMA_HandleTypeDef *hdmatx; /* USART Tx DMA Handle parameters */ + + DMA_HandleTypeDef *hdmarx; /* USART Rx DMA Handle parameters */ + + HAL_LockTypeDef Lock; /* Locking object */ + + HAL_USART_StateTypeDef State; /* USART communication state */ + + HAL_USART_ErrorTypeDef ErrorCode; /* USART Error code */ + +}USART_HandleTypeDef; + + +/* Exported constants --------------------------------------------------------*/ + +/** @defgroup USART_Exported_Constants + * @{ + */ + +/** @defgroup USART_Stop_Bits USART Number of Stop Bits + * @{ + */ +#define USART_STOPBITS_1 ((uint16_t)0x0000) +#define USART_STOPBITS_0_5 ((uint16_t)USART_CR2_STOP_0) +#define USART_STOPBITS_2 ((uint16_t)USART_CR2_STOP_1) +#define USART_STOPBITS_1_5 ((uint16_t)(USART_CR2_STOP_0 | USART_CR2_STOP_1)) +#define IS_USART_STOPBITS(STOPBITS) (((STOPBITS) == USART_STOPBITS_1) || \ + ((STOPBITS) == USART_STOPBITS_0_5) || \ + ((STOPBITS) == USART_STOPBITS_1_5) || \ + ((STOPBITS) == USART_STOPBITS_2)) +/** + * @} + */ + +/** @defgroup USART_Parity USART Parity + * @{ + */ +#define USART_PARITY_NONE ((uint16_t)0x0000) +#define USART_PARITY_EVEN ((uint16_t)USART_CR1_PCE) +#define USART_PARITY_ODD ((uint16_t)(USART_CR1_PCE | USART_CR1_PS)) +#define IS_USART_PARITY(PARITY) (((PARITY) == USART_PARITY_NONE) || \ + ((PARITY) == USART_PARITY_EVEN) || \ + ((PARITY) == USART_PARITY_ODD)) +/** + * @} + */ + +/** @defgroup USART_Mode USART Mode + * @{ + */ +#define USART_MODE_RX ((uint16_t)USART_CR1_RE) +#define USART_MODE_TX ((uint16_t)USART_CR1_TE) +#define USART_MODE_TX_RX ((uint16_t)(USART_CR1_TE |USART_CR1_RE)) +#define IS_USART_MODE(MODE) ((((MODE) & (uint16_t)0xFFF3) == 0x00) && ((MODE) != (uint16_t)0x00)) +/** + * @} + */ + +/** @defgroup USART_Clock USART Clock + * @{ + */ +#define USART_CLOCK_DISABLED ((uint16_t)0x0000) +#define USART_CLOCK_ENABLED ((uint16_t)USART_CR2_CLKEN) +#define IS_USART_CLOCK(CLOCK) (((CLOCK) == USART_CLOCK_DISABLED) || \ + ((CLOCK) == USART_CLOCK_ENABLED)) +/** + * @} + */ + +/** @defgroup USART_Clock_Polarity USART Clock Polarity + * @{ + */ +#define USART_POLARITY_LOW ((uint16_t)0x0000) +#define USART_POLARITY_HIGH ((uint16_t)USART_CR2_CPOL) +#define IS_USART_POLARITY(CPOL) (((CPOL) == USART_POLARITY_LOW) || ((CPOL) == USART_POLARITY_HIGH)) +/** + * @} + */ + +/** @defgroup USART_Clock_Phase USART Clock Phase + * @{ + */ +#define USART_PHASE_1EDGE ((uint16_t)0x0000) +#define USART_PHASE_2EDGE ((uint16_t)USART_CR2_CPHA) +#define IS_USART_PHASE(CPHA) (((CPHA) == USART_PHASE_1EDGE) || ((CPHA) == USART_PHASE_2EDGE)) +/** + * @} + */ + +/** @defgroup USART_Last_Bit USART Last Bit + * @{ + */ +#define USART_LASTBIT_DISABLE ((uint16_t)0x0000) +#define USART_LASTBIT_ENABLE ((uint16_t)USART_CR2_LBCL) +#define IS_USART_LASTBIT(LASTBIT) (((LASTBIT) == USART_LASTBIT_DISABLE) || \ + ((LASTBIT) == USART_LASTBIT_ENABLE)) +/** + * @} + */ + + +/** @defgroup USART_Flags USART Flags + * Elements values convention: 0xXXXX + * - 0xXXXX : Flag mask in the ISR register + * @{ + */ +#define USART_FLAG_REACK ((uint32_t)0x00400000) +#define USART_FLAG_TEACK ((uint32_t)0x00200000) +#define USART_FLAG_BUSY ((uint32_t)0x00010000) +#define USART_FLAG_CTS ((uint32_t)0x00000400) +#define USART_FLAG_CTSIF ((uint32_t)0x00000200) +#define USART_FLAG_LBDF ((uint32_t)0x00000100) +#define USART_FLAG_TXE ((uint32_t)0x00000080) +#define USART_FLAG_TC ((uint32_t)0x00000040) +#define USART_FLAG_RXNE ((uint32_t)0x00000020) +#define USART_FLAG_IDLE ((uint32_t)0x00000010) +#define USART_FLAG_ORE ((uint32_t)0x00000008) +#define USART_FLAG_NE ((uint32_t)0x00000004) +#define USART_FLAG_FE ((uint32_t)0x00000002) +#define USART_FLAG_PE ((uint32_t)0x00000001) +/** + * @} + */ + +/** @defgroup USART_Interrupt_definition USART Interrupts Definition + * Elements values convention: 0000ZZZZ0XXYYYYYb + * - YYYYY : Interrupt source position in the XX register (5bits) + * - XX : Interrupt source register (2bits) + * - 01: CR1 register + * - 10: CR2 register + * - 11: CR3 register + * - ZZZZ : Flag position in the ISR register(4bits) + * @{ + */ + +#define USART_IT_PE ((uint16_t)0x0028) +#define USART_IT_TXE ((uint16_t)0x0727) +#define USART_IT_TC ((uint16_t)0x0626) +#define USART_IT_RXNE ((uint16_t)0x0525) +#define USART_IT_IDLE ((uint16_t)0x0424) +#define USART_IT_ERR ((uint16_t)0x0060) + +#define USART_IT_ORE ((uint16_t)0x0300) +#define USART_IT_NE ((uint16_t)0x0200) +#define USART_IT_FE ((uint16_t)0x0100) +/** + * @} + */ + +/** @defgroup USART_IT_CLEAR_Flags USART Interruption Clear Flags + * @{ + */ +#define USART_CLEAR_PEF USART_ICR_PECF /*!< Parity Error Clear Flag */ +#define USART_CLEAR_FEF USART_ICR_FECF /*!< Framing Error Clear Flag */ +#define USART_CLEAR_NEF USART_ICR_NCF /*!< Noise detected Clear Flag */ +#define USART_CLEAR_OREF USART_ICR_ORECF /*!< OverRun Error Clear Flag */ +#define USART_CLEAR_IDLEF USART_ICR_IDLECF /*!< IDLE line detected Clear Flag */ +#define USART_CLEAR_TCF USART_ICR_TCCF /*!< Transmission Complete Clear Flag */ +#define USART_CLEAR_CTSF USART_ICR_CTSCF /*!< CTS Interrupt Clear Flag */ +/** + * @} + */ + +/** @defgroup USART_Request_Parameters USART Request Parameters + * @{ + */ +#define USART_RXDATA_FLUSH_REQUEST ((uint16_t)USART_RQR_RXFRQ) /*!< Receive Data flush Request */ +#define USART_TXDATA_FLUSH_REQUEST ((uint16_t)USART_RQR_TXFRQ) /*!< Transmit data flush Request */ +#define IS_USART_REQUEST_PARAMETER(PARAM) (((PARAM) == USART_RXDATA_FLUSH_REQUEST) || \ + ((PARAM) == USART_TXDATA_FLUSH_REQUEST)) +/** + * @} + */ + +/** @defgroup USART_Interruption_Mask USART interruptions flag mask + * @{ + */ +#define USART_IT_MASK ((uint16_t)0x001F) +/** + * @} + */ + +/** + * @} + */ + + +/* Exported macros ------------------------------------------------------------*/ + +/** @defgroup USART_Exported_Macros + * @{ + */ + +/** @brief Reset USART handle state + * @param __HANDLE__: USART handle. + * @retval None + */ +#define __HAL_USART_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_USART_STATE_RESET) + +/** @brief Checks whether the specified USART flag is set or not. + * @param __HANDLE__: specifies the USART Handle. + * This parameter can be UARTx where x: 1, 2, 3 to select the USART peripheral. + * @param __FLAG__: specifies the flag to check. + * This parameter can be one of the following values: + * @arg USART_FLAG_REACK: Receive enable ackowledge flag + * @arg USART_FLAG_TEACK: Transmit enable ackowledge flag + * @arg USART_FLAG_BUSY: Busy flag + * @arg USART_FLAG_CTS: CTS Change flag + * @arg USART_FLAG_TXE: Transmit data register empty flag + * @arg USART_FLAG_TC: Transmission Complete flag + * @arg USART_FLAG_RXNE: Receive data register not empty flag + * @arg USART_FLAG_IDLE: Idle Line detection flag + * @arg USART_FLAG_ORE: OverRun Error flag + * @arg USART_FLAG_NE: Noise Error flag + * @arg USART_FLAG_FE: Framing Error flag + * @arg USART_FLAG_PE: Parity Error flag + * @retval The new state of __FLAG__ (TRUE or FALSE). + */ +#define __HAL_USART_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->ISR & (__FLAG__)) == (__FLAG__)) + + +/** @brief Enables the specified USART interrupt. + * @param __HANDLE__: specifies the USART Handle. + * This parameter can be UARTx where x: 1, 2, 3 to select the USART peripheral. + * @param __INTERRUPT__: specifies the USART interrupt source to enable. + * This parameter can be one of the following values: + * @arg USART_IT_TXE: Transmit Data Register empty interrupt + * @arg USART_IT_TC: Transmission complete interrupt + * @arg USART_IT_RXNE: Receive Data register not empty interrupt + * @arg USART_IT_IDLE: Idle line detection interrupt + * @arg USART_IT_PE: Parity Error interrupt + * @arg USART_IT_ERR: Error interrupt(Frame error, noise error, overrun error) + * @retval None + */ +#define __HAL_USART_ENABLE_IT(__HANDLE__, __INTERRUPT__) (((((uint8_t)(__INTERRUPT__)) >> 5U) == 1)? ((__HANDLE__)->Instance->CR1 |= (1U << ((__INTERRUPT__) & USART_IT_MASK))): \ + ((((uint8_t)(__INTERRUPT__)) >> 5U) == 2)? ((__HANDLE__)->Instance->CR2 |= (1U << ((__INTERRUPT__) & USART_IT_MASK))): \ + ((__HANDLE__)->Instance->CR3 |= (1U << ((__INTERRUPT__) & USART_IT_MASK)))) + +/** @brief Disables the specified USART interrupt. + * @param __HANDLE__: specifies the USART Handle. + * This parameter can be UARTx where x: 1, 2, 3 to select the USART peripheral. + * @param __INTERRUPT__: specifies the USART interrupt source to disable. + * This parameter can be one of the following values: + * @arg USART_IT_TXE: Transmit Data Register empty interrupt + * @arg USART_IT_TC: Transmission complete interrupt + * @arg USART_IT_RXNE: Receive Data register not empty interrupt + * @arg USART_IT_IDLE: Idle line detection interrupt + * @arg USART_IT_PE: Parity Error interrupt + * @arg USART_IT_ERR: Error interrupt(Frame error, noise error, overrun error) + * @retval None + */ +#define __HAL_USART_DISABLE_IT(__HANDLE__, __INTERRUPT__) (((((uint8_t)(__INTERRUPT__)) >> 5U) == 1)? ((__HANDLE__)->Instance->CR1 &= ~ (1U << ((__INTERRUPT__) & USART_IT_MASK))): \ + ((((uint8_t)(__INTERRUPT__)) >> 5U) == 2)? ((__HANDLE__)->Instance->CR2 &= ~ (1U << ((__INTERRUPT__) & USART_IT_MASK))): \ + ((__HANDLE__)->Instance->CR3 &= ~ (1U << ((__INTERRUPT__) & USART_IT_MASK)))) + + +/** @brief Checks whether the specified USART interrupt has occurred or not. + * @param __HANDLE__: specifies the USART Handle. + * This parameter can be USARTx where x: 1, 2 or 3 + * @param __IT__: specifies the USART interrupt source to check. + * This parameter can be one of the following values: + * @arg USART_IT_TXE: Transmit Data Register empty interrupt + * @arg USART_IT_TC: Transmission complete interrupt + * @arg USART_IT_RXNE: Receive Data register not empty interrupt + * @arg USART_IT_IDLE: Idle line detection interrupt + * @arg USART_IT_ORE: OverRun Error interrupt + * @arg USART_IT_NE: Noise Error interrupt + * @arg USART_IT_FE: Framing Error interrupt + * @arg USART_IT_PE: Parity Error interrupt + * @retval The new state of __IT__ (TRUE or FALSE). + */ +#define __HAL_USART_GET_IT(__HANDLE__, __IT__) ((__HANDLE__)->Instance->ISR & ((uint32_t)1 << ((__IT__)>> 0x08))) + +/** @brief Checks whether the specified USART interrupt source is enabled. + * @param __HANDLE__: specifies the USART Handle. + * This parameter can be USARTx where x: 1, 2 or 3 + * @param __IT__: specifies the USART interrupt source to check. + * This parameter can be one of the following values: + * @arg USART_IT_TXE: Transmit Data Register empty interrupt + * @arg USART_IT_TC: Transmission complete interrupt + * @arg USART_IT_RXNE: Receive Data register not empty interrupt + * @arg USART_IT_IDLE: Idle line detection interrupt + * @arg USART_IT_ORE: OverRun Error interrupt + * @arg USART_IT_NE: Noise Error interrupt + * @arg USART_IT_FE: Framing Error interrupt + * @arg USART_IT_PE: Parity Error interrupt + * @retval The new state of __IT__ (TRUE or FALSE). + */ +#define __HAL_USART_GET_IT_SOURCE(__HANDLE__, __IT__) ((((((uint8_t)(__IT__)) >> 5) == 1)? (__HANDLE__)->Instance->CR1:(((((uint8_t)(__IT__)) >> 5) == 2)? \ + (__HANDLE__)->Instance->CR2 : (__HANDLE__)->Instance->CR3)) & ((uint32_t)1 << \ + (((uint16_t)(__IT__)) & USART_IT_MASK))) + + +/** @brief Clears the specified USART ISR flag, in setting the proper ICR register flag. + * @param __HANDLE__: specifies the USART Handle. + * This parameter can be USARTx where x: 1, 2 or 3 + * @param __IT_CLEAR__: specifies the interrupt clear register flag that needs to be set + * to clear the corresponding interrupt + * This parameter can be one of the following values: + * @arg USART_CLEAR_PEF: Parity Error Clear Flag + * @arg USART_CLEAR_FEF: Framing Error Clear Flag + * @arg USART_CLEAR_NEF: Noise detected Clear Flag + * @arg USART_CLEAR_OREF: OverRun Error Clear Flag + * @arg USART_CLEAR_IDLEF: IDLE line detected Clear Flag + * @arg USART_CLEAR_TCF: Transmission Complete Clear Flag + * @arg USART_CLEAR_CTSF: CTS Interrupt Clear Flag + * @retval None + */ +#define __HAL_USART_CLEAR_IT(__HANDLE__, __IT_CLEAR__) ((__HANDLE__)->Instance->ICR |= (uint32_t)(__IT_CLEAR__)) + +/** @brief Set a specific USART request flag. + * @param __HANDLE__: specifies the USART Handle. + * This parameter can be USARTx where x: 1, 2 or 3 + * @param __REQ__: specifies the request flag to set + * This parameter can be one of the following values: + * @arg USART_RXDATA_FLUSH_REQUEST: Receive Data flush Request + * @arg USART_TXDATA_FLUSH_REQUEST: Transmit data flush Request + * + * @retval None + */ +#define __HAL_USART_SEND_REQ(__HANDLE__, __REQ__) ((__HANDLE__)->Instance->RQR |= (uint16_t)(__REQ__)) + +/** @brief Enable USART + * @param __HANDLE__: specifies the USART Handle. + * The Handle Instance can be USARTx where x: 1, 2, 3 to select the USART peripheral + * @retval None + */ +#define __USART_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 |= USART_CR1_UE) + +/** @brief Disable USART + * @param __HANDLE__: specifies the USART Handle. + * The Handle Instance can be USARTx where x: 1, 2, 3 to select the USART peripheral + * @retval None + */ +#define __USART_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 &= ~USART_CR1_UE) + + +/** @brief Check USART Baud rate + * @param BAUDRATE: Baudrate specified by the user + * The maximum Baud Rate is derived from the maximum clock on F0 (i.e. 48 MHz) + * divided by the smallest oversampling used on the USART (i.e. 8) + * @retval Test result (TRUE or FALSE) + */ +#define IS_USART_BAUDRATE(BAUDRATE) ((BAUDRATE) < 9000001) + +/** + * @} + */ + +/* Include USART HAL Extension module */ +#include "stm32f0xx_hal_usart_ex.h" + +/* Exported functions --------------------------------------------------------*/ + +/* Initialization and de-initialization functions ****************************/ +HAL_StatusTypeDef HAL_USART_Init(USART_HandleTypeDef *husart); +HAL_StatusTypeDef HAL_USART_DeInit(USART_HandleTypeDef *husart); +void HAL_USART_MspInit(USART_HandleTypeDef *husart); +void HAL_USART_MspDeInit(USART_HandleTypeDef *husart); +void HAL_USART_SetConfig(USART_HandleTypeDef *husart); +HAL_StatusTypeDef HAL_USART_CheckIdleState(USART_HandleTypeDef *husart); +/* IO operation functions *****************************************************/ +HAL_StatusTypeDef HAL_USART_Transmit(USART_HandleTypeDef *husart, uint8_t *pTxData, uint16_t Size, uint32_t Timeout); +HAL_StatusTypeDef HAL_USART_Receive(USART_HandleTypeDef *husart, uint8_t *pRxData, uint16_t Size, uint32_t Timeout); +HAL_StatusTypeDef HAL_USART_TransmitReceive(USART_HandleTypeDef *husart, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size, uint32_t Timeout); +HAL_StatusTypeDef HAL_USART_Transmit_IT(USART_HandleTypeDef *husart, uint8_t *pTxData, uint16_t Size); +HAL_StatusTypeDef HAL_USART_Receive_IT(USART_HandleTypeDef *husart, uint8_t *pRxData, uint16_t Size); +HAL_StatusTypeDef HAL_USART_TransmitReceive_IT(USART_HandleTypeDef *husart, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size); +HAL_StatusTypeDef HAL_USART_Transmit_DMA(USART_HandleTypeDef *husart, uint8_t *pTxData, uint16_t Size); +HAL_StatusTypeDef HAL_USART_Receive_DMA(USART_HandleTypeDef *husart, uint8_t *pRxData, uint16_t Size); +HAL_StatusTypeDef HAL_USART_TransmitReceive_DMA(USART_HandleTypeDef *husart, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size); +HAL_StatusTypeDef HAL_USART_DMAPause(USART_HandleTypeDef *husart); +HAL_StatusTypeDef HAL_USART_DMAResume(USART_HandleTypeDef *husart); +HAL_StatusTypeDef HAL_USART_DMAStop(USART_HandleTypeDef *husart); +void HAL_USART_IRQHandler(USART_HandleTypeDef *husart); +void HAL_USART_TxCpltCallback(USART_HandleTypeDef *husart); +void HAL_USART_RxCpltCallback(USART_HandleTypeDef *husart); +void HAL_USART_TxHalfCpltCallback(USART_HandleTypeDef *husart); +void HAL_USART_RxHalfCpltCallback(USART_HandleTypeDef *husart); +void HAL_USART_TxRxCpltCallback(USART_HandleTypeDef *husart); +void HAL_USART_ErrorCallback(USART_HandleTypeDef *husart); + +/* Peripheral Control functions ***********************************************/ + +/* Peripheral State and Error functions ***************************************/ +HAL_USART_StateTypeDef HAL_USART_GetState(USART_HandleTypeDef *husart); +uint32_t HAL_USART_GetError(USART_HandleTypeDef *husart); + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __STM32F0xx_HAL_USART_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_usart_ex.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_usart_ex.h new file mode 100644 index 0000000000..c77a179916 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_usart_ex.h @@ -0,0 +1,321 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_usart_ex.h + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief Header file of USART HAL Extension module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32F0xx_HAL_USART_EX_H +#define __STM32F0xx_HAL_USART_EX_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal_def.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @addtogroup USARTEx + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/* Exported constants --------------------------------------------------------*/ +/** @defgroup USARTEx_Exported_Constants + * @{ + */ + +/** @defgroup USARTEx_Word_Length USART Word Length + * @{ + */ +#if defined (STM32F042x6) || defined (STM32F048xx) || \ + defined (STM32F071xB) || defined (STM32F072xB) || defined (STM32F078xx) +#define USART_WORDLENGTH_7B ((uint32_t)USART_CR1_M1) +#define USART_WORDLENGTH_8B ((uint32_t)0x00000000) +#define USART_WORDLENGTH_9B ((uint32_t)USART_CR1_M0) +#define IS_USART_WORD_LENGTH(LENGTH) (((LENGTH) == USART_WORDLENGTH_7B) || \ + ((LENGTH) == USART_WORDLENGTH_8B) || \ + ((LENGTH) == USART_WORDLENGTH_9B)) +#else +#define USART_WORDLENGTH_8B ((uint32_t)0x00000000) +#define USART_WORDLENGTH_9B ((uint32_t)USART_CR1_M) +#define IS_USART_WORD_LENGTH(LENGTH) (((LENGTH) == USART_WORDLENGTH_8B) || \ + ((LENGTH) == USART_WORDLENGTH_9B)) +#endif /* defined (STM32F042x6) || defined (STM32F048xx) || \ + defined (STM32F071xB) || defined (STM32F072xB) || defined (STM32F078xx) */ +/** + * @} + */ + + + + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ + +/** @defgroup USARTEx_Exported_Macros + * @{ + */ + +/** @brief Reports the USART clock source. + * @param __HANDLE__: specifies the USART Handle + * @param __CLOCKSOURCE__ : output variable + * @retval the USART clocking source, written in __CLOCKSOURCE__. + */ +#if defined(STM32F030x6) || defined(STM32F031x6) || defined(STM32F038xx) +#define __HAL_USART_GETCLOCKSOURCE(__HANDLE__,__CLOCKSOURCE__) \ + do { \ + switch(__HAL_RCC_GET_USART1_SOURCE()) \ + { \ + case RCC_USART1CLKSOURCE_PCLK1: \ + (__CLOCKSOURCE__) = USART_CLOCKSOURCE_PCLK1; \ + break; \ + case RCC_USART1CLKSOURCE_HSI: \ + (__CLOCKSOURCE__) = USART_CLOCKSOURCE_HSI; \ + break; \ + case RCC_USART1CLKSOURCE_SYSCLK: \ + (__CLOCKSOURCE__) = USART_CLOCKSOURCE_SYSCLK; \ + break; \ + case RCC_USART1CLKSOURCE_LSE: \ + (__CLOCKSOURCE__) = USART_CLOCKSOURCE_LSE; \ + break; \ + default: \ + (__CLOCKSOURCE__) = USART_CLOCKSOURCE_UNDEFINED; \ + break; \ + } \ + } while(0) +#elif defined (STM32F030x8) || \ + defined (STM32F042x6) || defined (STM32F048xx) || \ + defined (STM32F051x8) || defined (STM32F058xx) +#define __HAL_USART_GETCLOCKSOURCE(__HANDLE__,__CLOCKSOURCE__) \ + do { \ + if((__HANDLE__)->Instance == USART1) \ + { \ + switch(__HAL_RCC_GET_USART1_SOURCE()) \ + { \ + case RCC_USART1CLKSOURCE_PCLK1: \ + (__CLOCKSOURCE__) = USART_CLOCKSOURCE_PCLK1; \ + break; \ + case RCC_USART1CLKSOURCE_HSI: \ + (__CLOCKSOURCE__) = USART_CLOCKSOURCE_HSI; \ + break; \ + case RCC_USART1CLKSOURCE_SYSCLK: \ + (__CLOCKSOURCE__) = USART_CLOCKSOURCE_SYSCLK; \ + break; \ + case RCC_USART1CLKSOURCE_LSE: \ + (__CLOCKSOURCE__) = USART_CLOCKSOURCE_LSE; \ + break; \ + default: \ + (__CLOCKSOURCE__) = USART_CLOCKSOURCE_UNDEFINED; \ + break; \ + } \ + } \ + else if((__HANDLE__)->Instance == USART2) \ + { \ + (__CLOCKSOURCE__) = USART_CLOCKSOURCE_PCLK1; \ + } \ + else \ + { \ + (__CLOCKSOURCE__) = USART_CLOCKSOURCE_UNDEFINED; \ + } \ + } while(0) +#elif defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) +#define __HAL_USART_GETCLOCKSOURCE(__HANDLE__,__CLOCKSOURCE__) \ + do { \ + if((__HANDLE__)->Instance == USART1) \ + { \ + switch(__HAL_RCC_GET_USART1_SOURCE()) \ + { \ + case RCC_USART1CLKSOURCE_PCLK1: \ + (__CLOCKSOURCE__) = USART_CLOCKSOURCE_PCLK1; \ + break; \ + case RCC_USART1CLKSOURCE_HSI: \ + (__CLOCKSOURCE__) = USART_CLOCKSOURCE_HSI; \ + break; \ + case RCC_USART1CLKSOURCE_SYSCLK: \ + (__CLOCKSOURCE__) = USART_CLOCKSOURCE_SYSCLK; \ + break; \ + case RCC_USART1CLKSOURCE_LSE: \ + (__CLOCKSOURCE__) = USART_CLOCKSOURCE_LSE; \ + break; \ + default: \ + (__CLOCKSOURCE__) = USART_CLOCKSOURCE_UNDEFINED; \ + break; \ + } \ + } \ + else if((__HANDLE__)->Instance == USART2) \ + { \ + switch(__HAL_RCC_GET_USART2_SOURCE()) \ + { \ + case RCC_USART2CLKSOURCE_PCLK1: \ + (__CLOCKSOURCE__) = USART_CLOCKSOURCE_PCLK1; \ + break; \ + case RCC_USART2CLKSOURCE_HSI: \ + (__CLOCKSOURCE__) = USART_CLOCKSOURCE_HSI; \ + break; \ + case RCC_USART2CLKSOURCE_SYSCLK: \ + (__CLOCKSOURCE__) = USART_CLOCKSOURCE_SYSCLK; \ + break; \ + case RCC_USART2CLKSOURCE_LSE: \ + (__CLOCKSOURCE__) = USART_CLOCKSOURCE_LSE; \ + break; \ + default: \ + (__CLOCKSOURCE__) = USART_CLOCKSOURCE_UNDEFINED; \ + break; \ + } \ + } \ + else if((__HANDLE__)->Instance == USART3) \ + { \ + (__CLOCKSOURCE__) = USART_CLOCKSOURCE_PCLK1; \ + } \ + else if((__HANDLE__)->Instance == USART4) \ + { \ + (__CLOCKSOURCE__) = USART_CLOCKSOURCE_PCLK1; \ + } \ + else \ + { \ + (__CLOCKSOURCE__) = USART_CLOCKSOURCE_UNDEFINED; \ + } \ + } while(0) +#endif /* defined(STM32F030x6) || defined(STM32F031x6) || defined(STM32F038xx) */ + + +/** @brief Reports the USART mask to apply to retrieve the received data + * according to the word length and to the parity bits activation. + * If PCE = 1, the parity bit is not included in the data extracted + * by the reception API(). + * This masking operation is not carried out in the case of + * DMA transfers. + * @param __HANDLE__: specifies the USART Handle + * @retval none + */ +#if defined (STM32F042x6) || defined (STM32F048xx) || \ + defined (STM32F071xB) || defined (STM32F072xB) || defined (STM32F078xx) +#define __HAL_USART_MASK_COMPUTATION(__HANDLE__) \ + do { \ + if ((__HANDLE__)->Init.WordLength == USART_WORDLENGTH_9B) \ + { \ + if ((__HANDLE__)->Init.Parity == USART_PARITY_NONE) \ + { \ + (__HANDLE__)->Mask = 0x01FF ; \ + } \ + else \ + { \ + (__HANDLE__)->Mask = 0x00FF ; \ + } \ + } \ + else if ((__HANDLE__)->Init.WordLength == USART_WORDLENGTH_8B) \ + { \ + if ((__HANDLE__)->Init.Parity == USART_PARITY_NONE) \ + { \ + (__HANDLE__)->Mask = 0x00FF ; \ + } \ + else \ + { \ + (__HANDLE__)->Mask = 0x007F ; \ + } \ + } \ + else if ((__HANDLE__)->Init.WordLength == USART_WORDLENGTH_7B) \ + { \ + if ((__HANDLE__)->Init.Parity == USART_PARITY_NONE) \ + { \ + (__HANDLE__)->Mask = 0x007F ; \ + } \ + else \ + { \ + (__HANDLE__)->Mask = 0x003F ; \ + } \ + } \ +} while(0) +#else +#define __HAL_USART_MASK_COMPUTATION(__HANDLE__) \ + do { \ + if ((__HANDLE__)->Init.WordLength == USART_WORDLENGTH_9B) \ + { \ + if ((__HANDLE__)->Init.Parity == USART_PARITY_NONE) \ + { \ + (__HANDLE__)->Mask = 0x01FF ; \ + } \ + else \ + { \ + (__HANDLE__)->Mask = 0x00FF ; \ + } \ + } \ + else if ((__HANDLE__)->Init.WordLength == USART_WORDLENGTH_8B) \ + { \ + if ((__HANDLE__)->Init.Parity == USART_PARITY_NONE) \ + { \ + (__HANDLE__)->Mask = 0x00FF ; \ + } \ + else \ + { \ + (__HANDLE__)->Mask = 0x007F ; \ + } \ + } \ +} while(0) +#endif /* defined (STM32F042x6) || defined (STM32F048xx) || \ + defined (STM32F071xB) || defined (STM32F072xB) || defined (STM32F078xx) */ +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/* Initialization and de-initialization functions ****************************/ +/* I/O operation functions ***************************************************/ +/* Peripheral Control functions **********************************************/ +/* Peripheral State functions ************************************************/ + + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __STM32F0xx_HAL_USART_EX_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_wwdg.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_wwdg.c new file mode 100644 index 0000000000..359b6646cc --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_wwdg.c @@ -0,0 +1,439 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_wwdg.c + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief WWDG HAL module driver. + * + * This file provides firmware functions to manage the following + * functionalities of the Window Watchdog (WWDG) peripheral: + * + Initialization/de-initialization function + * + I/O operation function + * + Peripheral State function + * + @verbatim + ============================================================================== + ##### WWDG specific features ##### + ============================================================================== + [..] Once enabled the WWDG generates a system reset on expiry of a programmed + time period, unless the program refreshes the counter (downcounter) + before reaching 0x3F value (i.e. a reset is generated when the counter + value rolls over from 0x40 to 0x3F). + + (+) An MCU reset is also generated if the counter value is refreshed + before the counter has reached the refresh window value. This + implies that the counter must be refreshed in a limited window. + (+) Once enabled the WWDG cannot be disabled except by a system reset. + (+) WWDGRST flag in RCC_CSR register can be used to inform when a WWDG + reset occurs. + (+) The WWDG counter input clock is derived from the APB clock divided + by a programmable prescaler. + (+) WWDG clock = PCLK1 /(4096 * Prescaler) + WWDG timeout = (WWDG clock) * (counter value) + (+) WWDG Counter refresh is allowed between the following limits : + min time (mS) = 1000 * (Counter – Window) / WWDG clock + max time (mS) = 1000 * (Counter – 0x40) / WWDG clock + + (+) Min-max timeout value @24 MHz(PCLK1): ~1.36 ms / ~87.4 ms + + ##### How to use this driver ##### + ============================================================================== + [..] + (+) Enable WWDG APB1 clock using __WWDG_CLK_ENABLE(). + (+) Set the WWDG prescaler, refresh window and counter value + using HAL_WWDG_Init() function. + (+) Start the WWDG using HAL_WWDG_Start() function. + When the WWDG is enabled the counter value should be configured to + a value greater than 0x40 to prevent generating an immediate reset. + (+) Optionally you can enable the Early Wakeup Interrupt (EWI) which is + generated when the counter reaches 0x40, and then start the WWDG using + HAL_WWDG_Start_IT(). + Once enabled, EWI interrupt cannot be disabled except by a system reset. + (+) Then the application program must refresh the WWDG counter at regular + intervals during normal operation to prevent an MCU reset, using + HAL_WWDG_Refresh() function. This operation must occur only when + the counter is lower than the refresh window value already programmed. + + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @defgroup WWDG + * @brief WWDG HAL module driver. + * @{ + */ + +#ifdef HAL_WWDG_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup WWDG_Private_Functions + * @{ + */ + +/** @defgroup HAL_WWDG_Group1 Initialization/de-initialization function + * @brief Initialization and Configuration functions. + * +@verbatim + =============================================================================== + ##### Initialization/de-initialization function ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Initialize the WWDG according to the specified parameters + in the WWDG_InitTypeDef and create the associated handle + (+) DeInitialize the WWDG peripheral + (+) Initialize the WWDG MSP + (+) DeInitialize the WWDG MSP + +@endverbatim + * @{ + */ + +/** + * @brief Initializes the WWDG according to the specified + * parameters in the WWDG_InitTypeDef and creates the associated handle. + * @param hwwdg: WWDG handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_WWDG_Init(WWDG_HandleTypeDef *hwwdg) +{ + uint32_t tmp = 0; + + /* Check the WWDG handle allocation */ + if(hwwdg == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_WWDG_ALL_INSTANCE(hwwdg->Instance)); + assert_param(IS_WWDG_PRESCALER(hwwdg->Init.Prescaler)); + assert_param(IS_WWDG_WINDOW(hwwdg->Init.Window)); + assert_param(IS_WWDG_COUNTER(hwwdg->Init.Counter)); + + if(hwwdg->State == HAL_WWDG_STATE_RESET) + { + /* Init the low level hardware */ + HAL_WWDG_MspInit(hwwdg); + } + + /* Change WWDG peripheral state */ + hwwdg->State = HAL_WWDG_STATE_BUSY; + + /* Set WWDG Prescaler and Window */ + /* Get the CFR register value */ + tmp = hwwdg->Instance->CFR; + + /* Clear WDGTB[1:0] and W[6:0] bits */ + tmp &= ((uint32_t)~(WWDG_CFR_WDGTB | WWDG_CFR_W)); + + /* Prepare the WWDG Prescaler and Window parameters */ + tmp |= hwwdg->Init.Prescaler | hwwdg->Init.Window; + + /* Write to WWDG CFR */ + hwwdg->Instance->CFR = tmp; + + /* Set WWDG Counter */ + /* Get the CR register value */ + tmp = hwwdg->Instance->CR; + + /* Clear T[6:0] bits */ + tmp &= ((uint32_t)~(WWDG_CR_T)); + + /* Prepare the WWDG Counter parameter */ + tmp |= (hwwdg->Init.Counter); + + /* Write to WWDG CR */ + hwwdg->Instance->CR = tmp; + + /* Change WWDG peripheral state */ + hwwdg->State = HAL_WWDG_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief DeInitializes the WWDG peripheral. + * @param hwwdg: WWDG handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_WWDG_DeInit(WWDG_HandleTypeDef *hwwdg) +{ + /* Check the parameters */ + assert_param(IS_WWDG_ALL_INSTANCE(hwwdg->Instance)); + + /* Change WWDG peripheral state */ + hwwdg->State = HAL_WWDG_STATE_BUSY; + + /* DeInit the low level hardware */ + HAL_WWDG_MspDeInit(hwwdg); + + /* Reset WWDG Control register */ + hwwdg->Instance->CR = (uint32_t)0x0000007F; + + /* Reset WWDG Configuration register */ + hwwdg->Instance->CFR = (uint32_t)0x0000007F; + + /* Reset WWDG Status register */ + hwwdg->Instance->SR = 0; + + /* Change WWDG peripheral state */ + hwwdg->State = HAL_WWDG_STATE_RESET; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Initializes the WWDG MSP. + * @param hwwdg: WWDG handle + * @retval None + */ +__weak void HAL_WWDG_MspInit(WWDG_HandleTypeDef *hwwdg) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_WWDG_MspInit could be implemented in the user file + */ +} + +/** + * @brief DeInitializes the WWDG MSP. + * @param hwwdg: WWDG handle + * @retval None + */ +__weak void HAL_WWDG_MspDeInit(WWDG_HandleTypeDef *hwwdg) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_WWDG_MspDeInit could be implemented in the user file + */ +} + +/** + * @brief Early Wakeup WWDG callback. + * @param hwwdg: WWDG handle + * @retval None + */ +__weak void HAL_WWDG_WakeupCallback(WWDG_HandleTypeDef* hwwdg) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_WWDG_WakeupCallback could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup HAL_WWDG_Group2 I/O operation function + * @brief I/O operation function + * +@verbatim + =============================================================================== + ##### IO operation function ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Start the WWDG. + (+) Refresh the WWDG. + (+) Handle WWDG interrupt request. + +@endverbatim + * @{ + */ + +/** + * @brief Starts the WWDG + * @param hwwdg: WWDG handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_WWDG_Start(WWDG_HandleTypeDef *hwwdg) +{ + /* Process locked */ + __HAL_LOCK(hwwdg); + + /* Change WWDG peripheral state */ + hwwdg->State = HAL_WWDG_STATE_BUSY; + + /* Enable the Peripheral */ + __HAL_WWDG_ENABLE(hwwdg); + + /* Change WWDG peripheral state */ + hwwdg->State = HAL_WWDG_STATE_READY; + + /* Process unlocked */ + __HAL_UNLOCK(hwwdg); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Starts the WWDG with interrupt enabled. + * @param hwwdg: WWDG handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_WWDG_Start_IT(WWDG_HandleTypeDef *hwwdg) +{ + /* Process locked */ + __HAL_LOCK(hwwdg); + + /* Change WWDG peripheral state */ + hwwdg->State = HAL_WWDG_STATE_BUSY; + + /* Enable the Early Wakeup Interrupt */ + __HAL_WWDG_ENABLE_IT(WWDG_IT_EWI); + + /* Enable the Peripheral */ + __HAL_WWDG_ENABLE(hwwdg); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Refreshes the WWDG. + * @param hwwdg: WWDG handle + * @param Counter: Counter value to refresh WWDG with + * @retval HAL status + */ +HAL_StatusTypeDef HAL_WWDG_Refresh(WWDG_HandleTypeDef *hwwdg, uint32_t Counter) +{ + /* Process locked */ + __HAL_LOCK(hwwdg); + + /* Change WWDG peripheral state */ + hwwdg->State = HAL_WWDG_STATE_BUSY; + + /* Check the parameters */ + assert_param(IS_WWDG_COUNTER(Counter)); + + /* Write to WWDG CR the WWDG Counter value to refresh with */ + MODIFY_REG(hwwdg->Instance->CR, WWDG_CR_T, Counter); + + /* Change WWDG peripheral state */ + hwwdg->State = HAL_WWDG_STATE_READY; + + /* Process unlocked */ + __HAL_UNLOCK(hwwdg); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Handles WWDG interrupt request. + * @note The Early Wakeup Interrupt (EWI) can be used if specific safety operations + * or data logging must be performed before the actual reset is generated. + * The EWI interrupt is enabled using __HAL_WWDG_ENABLE_IT() macro. + * When the downcounter reaches the value 0x40, and EWI interrupt is + * generated and the corresponding Interrupt Service Routine (ISR) can + * be used to trigger specific actions (such as communications or data + * logging), before resetting the device. + * @param hwwdg: WWDG handle + * @retval None + */ +void HAL_WWDG_IRQHandler(WWDG_HandleTypeDef *hwwdg) +{ + /* WWDG Early Wakeup Interrupt occurred */ + if(__HAL_WWDG_GET_FLAG(hwwdg, WWDG_FLAG_EWIF) != RESET) + { + /* Early Wakeup callback */ + HAL_WWDG_WakeupCallback(hwwdg); + + /* Change WWDG peripheral state */ + hwwdg->State = HAL_WWDG_STATE_READY; + + /* Clear the WWDG Data Ready flag */ + __HAL_WWDG_CLEAR_FLAG(hwwdg, WWDG_FLAG_EWIF); + + /* Process unlocked */ + __HAL_UNLOCK(hwwdg); +} + } + +/** + * @} + */ + +/** @defgroup HAL_WWDG_Group3 Peripheral State function + * @brief Peripheral State functions. + * +@verbatim + =============================================================================== + ##### Peripheral State function ##### + =============================================================================== + [..] + This subsection permits to get in run-time the status of the peripheral + and the data flow. + +@endverbatim + * @{ + */ + +/** + * @brief Returns the WWDG state. + * @param hwwdg: WWDG handle + * @retval HAL state + */ +HAL_WWDG_StateTypeDef HAL_WWDG_GetState(WWDG_HandleTypeDef *hwwdg) +{ + return hwwdg->State; +} +/** + * @} + */ + +/** + * @} + */ + +#endif /* HAL_WWDG_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_wwdg.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_wwdg.h new file mode 100644 index 0000000000..057ffec933 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/stm32f0xx_hal_wwdg.h @@ -0,0 +1,266 @@ +/** + ****************************************************************************** + * @file stm32f0xx_hal_wwdg.h + * @author MCD Application Team + * @version V1.0.0 + * @date 28-May-2014 + * @brief Header file of WWDG HAL module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32F0xx_HAL_WWDG_H +#define __STM32F0xx_HAL_WWDG_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32f0xx_hal_def.h" + +/** @addtogroup STM32F0xx_HAL_Driver + * @{ + */ + +/** @addtogroup WWDG + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ + +/** + * @brief WWDG HAL State Structure definition + */ +typedef enum +{ + HAL_WWDG_STATE_RESET = 0x00, /*!< WWDG not yet initialized or disabled */ + HAL_WWDG_STATE_READY = 0x01, /*!< WWDG initialized and ready for use */ + HAL_WWDG_STATE_BUSY = 0x02, /*!< WWDG internal process is ongoing */ + HAL_WWDG_STATE_TIMEOUT = 0x03, /*!< WWDG timeout state */ + HAL_WWDG_STATE_ERROR = 0x04 /*!< WWDG error state */ + +}HAL_WWDG_StateTypeDef; + +/** + * @brief WWDG Init structure definition + */ +typedef struct +{ + uint32_t Prescaler; /*!< Specifies the prescaler value of the WWDG. + This parameter can be a value of @ref WWDG_Prescaler */ + + uint32_t Window; /*!< Specifies the WWDG window value to be compared to the downcounter. + This parameter must be a number lower than Max_Data = 0x80 */ + + uint32_t Counter; /*!< Specifies the WWDG free-running downcounter value. + This parameter must be a number between Min_Data = 0x40 and Max_Data = 0x7F */ + +} WWDG_InitTypeDef; + +/** + * @brief WWDG handle Structure definition + */ +typedef struct +{ + WWDG_TypeDef *Instance; /*!< Register base address */ + + WWDG_InitTypeDef Init; /*!< WWDG required parameters */ + + HAL_LockTypeDef Lock; /*!< WWDG locking object */ + + __IO HAL_WWDG_StateTypeDef State; /*!< WWDG communication state */ + +} WWDG_HandleTypeDef; + +/* Exported constants --------------------------------------------------------*/ + +/** @defgroup WWDG_Exported_Constants + * @{ + */ + +/** @defgroup WWDG_BitAddress_AliasRegion + * @brief WWDG registers bit address in the alias region + * @{ + */ + +/* --- CFR Register ---*/ +/* Alias word address of EWI bit */ +#define CFR_BASE (uint32_t)(WWDG_BASE + 0x04) + +/** + * @} + */ + +/** @defgroup WWDG_Interrupt_definition + * @{ + */ +#define WWDG_IT_EWI ((uint32_t)WWDG_CFR_EWI) + +#define IS_WWDG_IT(IT) ((IT) == WWDG_IT_EWI) + +/** + * @} + */ + +/** @defgroup WWDG_Flag_definition + * @brief WWDG Flag definition + * @{ + */ +#define WWDG_FLAG_EWIF ((uint32_t)0x0001) /*!< Early wakeup interrupt flag */ + +#define IS_WWDG_FLAG(FLAG) ((FLAG) == WWDG_FLAG_EWIF)) + +/** + * @} + */ + +/** @defgroup WWDG_Prescaler + * @{ + */ +#define WWDG_PRESCALER_1 ((uint32_t)0x00000000) /*!< WWDG counter clock = (PCLK1/4096)/1 */ +#define WWDG_PRESCALER_2 ((uint32_t)0x00000080) /*!< WWDG counter clock = (PCLK1/4096)/2 */ +#define WWDG_PRESCALER_4 ((uint32_t)0x00000100) /*!< WWDG counter clock = (PCLK1/4096)/4 */ +#define WWDG_PRESCALER_8 ((uint32_t)0x00000180) /*!< WWDG counter clock = (PCLK1/4096)/8 */ + +#define IS_WWDG_PRESCALER(PRESCALER) (((PRESCALER) == WWDG_PRESCALER_1) || \ + ((PRESCALER) == WWDG_PRESCALER_2) || \ + ((PRESCALER) == WWDG_PRESCALER_4) || \ + ((PRESCALER) == WWDG_PRESCALER_8)) + +/** + * @} + */ + +/** @defgroup WWDG_Window + * @{ + */ +#define IS_WWDG_WINDOW(WINDOW) ((WINDOW) <= 0x7F) + +/** + * @} + */ + +/** @defgroup WWDG_Counter + * @{ + */ +#define IS_WWDG_COUNTER(COUNTER) (((COUNTER) >= 0x40) && ((COUNTER) <= 0x7F)) + +/** + * @} + */ + +/** + * @} + */ + +/* Exported macros -----------------------------------------------------------*/ + +/** @defgroup WWDG_Exported_Macros + * @{ + */ + +/** @brief Reset WWDG handle state + * @param __HANDLE__: WWDG handle. + * @retval None + */ +#define __HAL_WWDG_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_WWDG_STATE_RESET) + +/** + * @brief Enable the WWDG peripheral. + * @param __HANDLE__: WWDG handle + * @retval None + */ +#define __HAL_WWDG_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= WWDG_CR_WDGA) + +/** + * @brief Get the selected WWDG's flag status. + * @param __HANDLE__: WWDG handle + * @param __FLAG__: specifies the flag to check. + * This parameter can be one of the following values: + * @arg WWDG_FLAG_EWIF: Early wakeup interrupt flag + * @retval The new state of WWDG_FLAG (SET or RESET). + */ +#define __HAL_WWDG_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->SR & (__FLAG__)) == (__FLAG__)) + +/** + * @brief Clear the WWDG's pending flags. + * @param __HANDLE__: WWDG handle + * @param __FLAG__: specifies the flag to clear. + * This parameter can be one of the following values: + * @arg WWDG_FLAG_EWIF: Early wakeup interrupt flag + * @retval None + */ +#define __HAL_WWDG_CLEAR_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->SR) &= ~(__FLAG__)) + +/** + * @brief Enable the WWDG early wakeup interrupt. + * @note Once enabled this interrupt cannot be disabled except by a system reset. + * @retval None + */ +#define __HAL_WWDG_ENABLE_IT(__INTERRUPT__) (*(__IO uint32_t *) CFR_BASE |= (__INTERRUPT__)) + +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ + +/* Initialization/de-initialization functions **********************************/ +HAL_StatusTypeDef HAL_WWDG_Init(WWDG_HandleTypeDef *hwwdg); +HAL_StatusTypeDef HAL_WWDG_DeInit(WWDG_HandleTypeDef *hwwdg); +void HAL_WWDG_MspInit(WWDG_HandleTypeDef *hwwdg); +void HAL_WWDG_MspDeInit(WWDG_HandleTypeDef *hwwdg); +void HAL_WWDG_WakeupCallback(WWDG_HandleTypeDef* hwwdg); + +/* I/O operation functions ******************************************************/ +HAL_StatusTypeDef HAL_WWDG_Start(WWDG_HandleTypeDef *hwwdg); +HAL_StatusTypeDef HAL_WWDG_Start_IT(WWDG_HandleTypeDef *hwwdg); +HAL_StatusTypeDef HAL_WWDG_Refresh(WWDG_HandleTypeDef *hwwdg, uint32_t Counter); +void HAL_WWDG_IRQHandler(WWDG_HandleTypeDef *hwwdg); + +/* Peripheral State functions **************************************************/ +HAL_WWDG_StateTypeDef HAL_WWDG_GetState(WWDG_HandleTypeDef *hwwdg); + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __STM32F0xx_HAL_WWDG_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/system_stm32f0xx.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/system_stm32f0xx.c new file mode 100644 index 0000000000..3a283cc375 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/system_stm32f0xx.c @@ -0,0 +1,444 @@ +/** + ****************************************************************************** + * @file system_stm32f0xx.c + * @author MCD Application Team + * @version V2.0.0 + * @date 28-May-2014 + * @brief CMSIS Cortex-M0 Device Peripheral Access Layer System Source File. + * + * 1. This file provides two functions and one global variable to be called from + * user application: + * - SystemInit(): This function is called at startup just after reset and + * before branch to main program. This call is made inside + * the "startup_stm32f0xx.s" file. + * + * - SystemCoreClock variable: Contains the core clock (HCLK), it can be used + * by the user application to setup the SysTick + * timer or configure other parameters. + * + * - SystemCoreClockUpdate(): Updates the variable SystemCoreClock and must + * be called whenever the core clock is changed + * during program execution. + * + * 2. After each device reset the HSI (8 MHz) is used as system clock source. + * Then SystemInit() function is called, in "startup_stm32f0xx.s" file, to + * configure the system clock before to branch to main program. + * + * 3. This file configures the system clock as follows: + *============================================================================= + * System clock source | 1- PLL_HSE_EXTC | 3- PLL_HSI + * | (external 8 MHz clock) | (internal 48 MHz) + * | 2- PLL_HSE_XTAL | + * | (external 8 MHz xtal) | + *----------------------------------------------------------------------------- + * SYSCLK(MHz) | 48 | 48 + *----------------------------------------------------------------------------- + * AHBCLK (MHz) | 48 | 48 + *----------------------------------------------------------------------------- + * APB1CLK (MHz) | 48 | 48 + *----------------------------------------------------------------------------- + * USB capable (48 MHz precise clock) | YES | YES + *============================================================================= + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/** @addtogroup CMSIS + * @{ + */ + +/** @addtogroup stm32f0xx_system + * @{ + */ + +/** @addtogroup STM32F0xx_System_Private_Includes + * @{ + */ + +#include "stm32f0xx.h" + +/** + * @} + */ + +/** @addtogroup STM32F0xx_System_Private_TypesDefinitions + * @{ + */ + +/** + * @} + */ + +/** @addtogroup STM32F0xx_System_Private_Defines + * @{ + */ +#if !defined (HSE_VALUE) + #define HSE_VALUE ((uint32_t)8000000) /*!< Default value of the External oscillator in Hz. + This value can be provided and adapted by the user application. */ +#endif /* HSE_VALUE */ + +#if !defined (HSI_VALUE) + #define HSI_VALUE ((uint32_t)8000000) /*!< Default value of the Internal oscillator in Hz. + This value can be provided and adapted by the user application. */ +#endif /* HSI_VALUE */ +/** + * @} + */ + +/** @addtogroup STM32F0xx_System_Private_Macros + * @{ + */ + +/* Select the clock sources (other than HSI) to start with (0=OFF, 1=ON) */ +#define USE_PLL_HSE_EXTC (1) /* Use external clock */ +#define USE_PLL_HSE_XTAL (1) /* Use external xtal */ + +/** + * @} + */ + +/** @addtogroup STM32F0xx_System_Private_Variables + * @{ + */ + /* This variable is updated in three ways: + 1) by calling CMSIS function SystemCoreClockUpdate() + 2) by calling HAL API function HAL_RCC_GetHCLKFreq() + 3) each time HAL_RCC_ClockConfig() is called to configure the system clock frequency + Note: If you use this function to configure the system clock; then there + is no need to call the 2 first functions listed above, since SystemCoreClock + variable is updated automatically. + */ +uint32_t SystemCoreClock = 48000000; +const uint8_t AHBPrescTable[16] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 6, 7, 8, 9}; + +/** + * @} + */ + +/** @addtogroup STM32F0xx_System_Private_FunctionPrototypes + * @{ + */ + +#if (USE_PLL_HSE_XTAL != 0) || (USE_PLL_HSE_EXTC != 0) +uint8_t SetSysClock_PLL_HSE(uint8_t bypass); +#endif + +uint8_t SetSysClock_PLL_HSI(void); + +/** + * @} + */ + +/** @addtogroup STM32F0xx_System_Private_Functions + * @{ + */ + +/** + * @brief Setup the microcontroller system. + * Initialize the default HSI clock source, vector table location and the PLL configuration is reset. + * @param None + * @retval None + */ +void SystemInit(void) +{ + /* Reset the RCC clock configuration to the default reset state ------------*/ + /* Set HSION bit */ + RCC->CR |= (uint32_t)0x00000001; + +#if defined (STM32F051x8) || defined (STM32F058x8) + /* Reset SW[1:0], HPRE[3:0], PPRE[2:0], ADCPRE and MCOSEL[2:0] bits */ + RCC->CFGR &= (uint32_t)0xF8FFB80C; +#else + /* Reset SW[1:0], HPRE[3:0], PPRE[2:0], ADCPRE, MCOSEL[2:0], MCOPRE[2:0] and PLLNODIV bits */ + RCC->CFGR &= (uint32_t)0x08FFB80C; +#endif /* STM32F051x8 or STM32F058x8 */ + + /* Reset HSEON, CSSON and PLLON bits */ + RCC->CR &= (uint32_t)0xFEF6FFFF; + + /* Reset HSEBYP bit */ + RCC->CR &= (uint32_t)0xFFFBFFFF; + + /* Reset PLLSRC, PLLXTPRE and PLLMUL[3:0] bits */ + RCC->CFGR &= (uint32_t)0xFFC0FFFF; + + /* Reset PREDIV[3:0] bits */ + RCC->CFGR2 &= (uint32_t)0xFFFFFFF0; + +#if defined (STM32F071xB) || defined (STM32F072xB) || defined (STM32F078xB) + /* Reset USART2SW[1:0] USART1SW[1:0], I2C1SW, CECSW, USBSW and ADCSW bits */ + RCC->CFGR3 &= (uint32_t)0xFFFCFE2C; +#elif defined (STM32F091xC) + /* Reset USART3SW[1:0], USART2SW[1:0], USART1SW[1:0], I2C1SW, CECSW bits */ + RCC->CFGR3 &= (uint32_t)0xFFF0FFAC; +#else + /* Reset USART1SW[1:0], I2C1SW, CECSW, USBSW and ADCSW bits */ + RCC->CFGR3 &= (uint32_t)0xFFFFFE2C; +#endif + + /* Reset HSI14 bit */ + RCC->CR2 &= (uint32_t)0xFFFFFFFE; + + /* Disable all interrupts */ + RCC->CIR = 0x00000000; + + /* Configure the Cube driver */ + HAL_Init(); + + /* Configure the System clock source, PLL Multiplier and Divider factors, + AHB/APBx prescalers and Flash settings */ + SetSysClock(); +} + +/** + * @brief Update SystemCoreClock variable according to Clock Register Values. + * The SystemCoreClock variable contains the core clock (HCLK), it can + * be used by the user application to setup the SysTick timer or configure + * other parameters. + * + * @note Each time the core clock (HCLK) changes, this function must be called + * to update SystemCoreClock variable value. Otherwise, any configuration + * based on this variable will be incorrect. + * + * @note - The system frequency computed by this function is not the real + * frequency in the chip. It is calculated based on the predefined + * constant and the selected clock source: + * + * - If SYSCLK source is HSI, SystemCoreClock will contain the HSI_VALUE(*) + * + * - If SYSCLK source is HSE, SystemCoreClock will contain the HSE_VALUE(**) + * + * - If SYSCLK source is PLL, SystemCoreClock will contain the HSE_VALUE(**) + * or HSI_VALUE(*) multiplied/divided by the PLL factors. + * + * (*) HSI_VALUE is a constant defined in stm32f0xx_hal.h file (default value + * 8 MHz) but the real value may vary depending on the variations + * in voltage and temperature. + * + * (**) HSE_VALUE is a constant defined in stm32f0xx_hal.h file (default value + * 8 MHz), user has to ensure that HSE_VALUE is same as the real + * frequency of the crystal used. Otherwise, this function may + * have wrong result. + * + * - The result of this function could be not correct when using fractional + * value for HSE crystal. + * + * @param None + * @retval None + */ +void SystemCoreClockUpdate (void) +{ + uint32_t tmp = 0, pllmull = 0, pllsource = 0, predivfactor = 0; + + /* Get SYSCLK source -------------------------------------------------------*/ + tmp = RCC->CFGR & RCC_CFGR_SWS; + + switch (tmp) + { + case RCC_CFGR_SWS_HSI: /* HSI used as system clock */ + SystemCoreClock = HSI_VALUE; + break; + case RCC_CFGR_SWS_HSE: /* HSE used as system clock */ + SystemCoreClock = HSE_VALUE; + break; + case RCC_CFGR_SWS_PLL: /* PLL used as system clock */ + /* Get PLL clock source and multiplication factor ----------------------*/ + pllmull = RCC->CFGR & RCC_CFGR_PLLMUL; + pllsource = RCC->CFGR & RCC_CFGR_PLLSRC; + pllmull = ( pllmull >> 18) + 2; + predivfactor = (RCC->CFGR2 & RCC_CFGR2_PREDIV) + 1; + + if (pllsource == RCC_CFGR_PLLSRC_HSE_PREDIV) + { + /* HSE used as PLL clock source : SystemCoreClock = HSE/PREDIV * PLLMUL */ + SystemCoreClock = (HSE_VALUE/predivfactor) * pllmull; + } +#if defined(STM32F042x6) || defined(STM32F048xx) || defined(STM32F072xB) || defined(STM32F078xx) + else if (pllsource == RCC_CFGR_PLLSRC_HSI48_PREDIV) + { + /* HSI48 used as PLL clock source : SystemCoreClock = HSI48/PREDIV * PLLMUL */ + SystemCoreClock = (HSI48_VALUE/predivfactor) * pllmull; + } +#endif /* STM32F042x6 || STM32F048xx || STM32F072xB || STM32F078xx */ + else + { +#if defined(STM32F042x6) || defined(STM32F048xx) || \ + defined(STM32F071xB) || defined(STM32F072xB) || defined(STM32F078xx) + /* HSI used as PLL clock source : SystemCoreClock = HSI/PREDIV * PLLMUL */ + SystemCoreClock = (HSI_VALUE/predivfactor) * pllmull; +#else + /* HSI used as PLL clock source : SystemCoreClock = HSI/2 * PLLMUL */ + SystemCoreClock = (HSI_VALUE >> 1) * pllmull; +#endif /* STM32F042x6 || STM32F048xx || STM32F071xB || STM32F072xB || STM32F078xx */ + } + break; + default: /* HSI used as system clock */ + SystemCoreClock = HSI_VALUE; + break; + } + /* Compute HCLK clock frequency ----------------*/ + /* Get HCLK prescaler */ + tmp = AHBPrescTable[((RCC->CFGR & RCC_CFGR_HPRE) >> 4)]; + /* HCLK clock frequency */ + SystemCoreClock >>= tmp; +} + +/** + * @brief Configures the System clock source, PLL Multiplier and Divider factors, + * AHB/APBx prescalers and Flash settings + * @note This function should be called only once the RCC clock configuration + * is reset to the default reset state (done in SystemInit() function). + * @param None + * @retval None + */ +void SetSysClock(void) +{ + /* 1- Try to start with HSE and external clock */ +#if USE_PLL_HSE_EXTC != 0 + if (SetSysClock_PLL_HSE(1) == 0) +#endif + { + /* 2- If fail try to start with HSE and external xtal */ + #if USE_PLL_HSE_XTAL != 0 + if (SetSysClock_PLL_HSE(0) == 0) + #endif + { + /* 3- If fail start with HSI clock */ + if (SetSysClock_PLL_HSI() == 0) + { + while(1) + { + // [TODO] Put something here to tell the user that a problem occured... + } + } + } + } + + // Output clock on MCO pin(PA8) for debugging purpose + //HAL_RCC_MCOConfig(RCC_MCO, RCC_MCOSOURCE_SYSCLK, RCC_MCO_DIV1); // 48 MHz +} + +#if (USE_PLL_HSE_XTAL != 0) || (USE_PLL_HSE_EXTC != 0) +/******************************************************************************/ +/* PLL (clocked by HSE) used as System clock source */ +/******************************************************************************/ +uint8_t SetSysClock_PLL_HSE(uint8_t bypass) +{ + RCC_ClkInitTypeDef RCC_ClkInitStruct; + RCC_OscInitTypeDef RCC_OscInitStruct; + + // Select HSE oscillator as PLL source + RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE | RCC_OSCILLATORTYPE_HSI48; + if (bypass == 0) { + RCC_OscInitStruct.HSEState = RCC_HSE_ON; // External 8 MHz xtal on OSC_IN/OSC_OUT + } else { + RCC_OscInitStruct.HSEState = RCC_HSE_BYPASS; // External 8 MHz clock on OSC_IN only + } + RCC_OscInitStruct.HSI48State = RCC_HSI48_ON; + RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; + RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE; + RCC_OscInitStruct.PLL.PREDIV = RCC_PREDIV_DIV2; + RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL12; + if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { + return 0; // FAIL + } + + // 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; // 48 MHz + RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; // 48 MHz + RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1; // 48 MHz + if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_1) != HAL_OK) { + return 0; // FAIL + } + + // Output clock on MCO pin(PA8) for debugging purpose + //if (bypass == 0) + // HAL_RCC_MCOConfig(RCC_MCO, RCC_MCOSOURCE_HSE, RCC_MCO_DIV2); // 4 MHz with xtal + //else + // HAL_RCC_MCOConfig(RCC_MCO, RCC_MCOSOURCE_HSE, RCC_MCO_DIV4); // 2 MHz with ST-Link MCO + + return 1; // OK +} +#endif + +/******************************************************************************/ +/* PLL (clocked by HSI) used as System clock source */ +/******************************************************************************/ +uint8_t SetSysClock_PLL_HSI(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) { + return 0; // FAIL + } + + // 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; // 48 MHz + RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; // 48 MHz + RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1; // 48 MHz + if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_1) != HAL_OK) { + return 0; // FAIL + } + + // Output clock on MCO1 pin(PA8) for debugging purpose + //HAL_RCC_MCOConfig(RCC_MCO, RCC_MCOSOURCE_HSI48, RCC_MCO_DIV1); // 48 MHz + + return 1; // OK +} + +/* Used for the different timeouts in the HAL */ +void SysTick_Handler(void) +{ + HAL_IncTick(); +} + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ + diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/system_stm32f0xx.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/system_stm32f0xx.h new file mode 100644 index 0000000000..03bfed0948 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F072RB/system_stm32f0xx.h @@ -0,0 +1,123 @@ +/** + ****************************************************************************** + * @file system_stm32f0xx.h + * @author MCD Application Team + * @version V2.0.0 + * @date 28-May-2014 + * @brief CMSIS Cortex-M0 Device System Source File for STM32F0xx devices. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/** @addtogroup CMSIS + * @{ + */ + +/** @addtogroup stm32f0xx_system + * @{ + */ + +/** + * @brief Define to prevent recursive inclusion + */ +#ifndef __SYSTEM_STM32F0XX_H +#define __SYSTEM_STM32F0XX_H + +#ifdef __cplusplus + extern "C" { +#endif + +/** @addtogroup STM32F0xx_System_Includes + * @{ + */ + +/** + * @} + */ + + +/** @addtogroup STM32F0xx_System_Exported_types + * @{ + */ + /* This variable is updated in three ways: + 1) by calling CMSIS function SystemCoreClockUpdate() + 3) by calling HAL API function HAL_RCC_GetHCLKFreq() + 3) by calling HAL API function HAL_RCC_ClockConfig() + Note: If you use this function to configure the system clock; then there + is no need to call the 2 first functions listed above, since SystemCoreClock + variable is updated automatically. + */ +extern uint32_t SystemCoreClock; /*!< System Clock Frequency (Core Clock) */ + +/** + * @} + */ + +/** @addtogroup STM32F0xx_System_Exported_Constants + * @{ + */ + +/** + * @} + */ + +/** @addtogroup STM32F0xx_System_Exported_Macros + * @{ + */ + +/** + * @} + */ + +/** @addtogroup STM32F0xx_System_Exported_Functions + * @{ + */ + +extern void SystemInit(void); +extern void SystemCoreClockUpdate(void); +extern void SetSysClock(void); + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /*__SYSTEM_STM32F0XX_H */ + +/** + * @} + */ + +/** + * @} + */ +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F103RB/TOOLCHAIN_GCC_ARM/STM32F10X.ld b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F103RB/TOOLCHAIN_GCC_ARM/STM32F10X.ld new file mode 100755 index 0000000000..fcf5013d5f --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F103RB/TOOLCHAIN_GCC_ARM/STM32F10X.ld @@ -0,0 +1,149 @@ +/* Linker script for STM32F103XXX */ + +/* Linker script to configure memory regions. */ +MEMORY +{ + FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 128K + RAM (rwx) : ORIGIN = 0x200000EC, LENGTH = 0x5000-0xEC /* First 236 bytes (0xEC) of RAM are reserved for ISR Vectors */ +} +/* Linker script to place sections and symbol values. Should be used together + * with other linker script that defines memory regions FLASH and RAM. + * It references following symbols, which must be defined in code: + * Reset_Handler : Entry of reset handler + * + * It defines following symbols, which code can use without definition: + * __exidx_start + * __exidx_end + * __etext + * __data_start__ + * __preinit_array_start + * __preinit_array_end + * __init_array_start + * __init_array_end + * __fini_array_start + * __fini_array_end + * __data_end__ + * __bss_start__ + * __bss_end__ + * __end__ + * end + * __HeapLimit + * __StackLimit + * __StackTop + * __stack + */ +ENTRY(Reset_Handler) + +SECTIONS +{ + .text : + { + KEEP(*(.isr_vector)) + *(.text*) + + KEEP(*(.init)) + KEEP(*(.fini)) + + /* .ctors */ + *crtbegin.o(.ctors) + *crtbegin?.o(.ctors) + *(EXCLUDE_FILE(*crtend?.o *crtend.o) .ctors) + *(SORT(.ctors.*)) + *(.ctors) + + /* .dtors */ + *crtbegin.o(.dtors) + *crtbegin?.o(.dtors) + *(EXCLUDE_FILE(*crtend?.o *crtend.o) .dtors) + *(SORT(.dtors.*)) + *(.dtors) + + *(.rodata*) + + KEEP(*(.eh_frame*)) + } > FLASH + + .ARM.extab : + { + *(.ARM.extab* .gnu.linkonce.armextab.*) + } > FLASH + + __exidx_start = .; + .ARM.exidx : + { + *(.ARM.exidx* .gnu.linkonce.armexidx.*) + } > FLASH + __exidx_end = .; + + __etext = .; + + .data : AT (__etext) + { + __data_start__ = .; + *(vtable) + *(.data*) + + . = ALIGN(4); + /* preinit data */ + PROVIDE_HIDDEN (__preinit_array_start = .); + KEEP(*(.preinit_array)) + PROVIDE_HIDDEN (__preinit_array_end = .); + + . = ALIGN(4); + /* init data */ + PROVIDE_HIDDEN (__init_array_start = .); + KEEP(*(SORT(.init_array.*))) + KEEP(*(.init_array)) + PROVIDE_HIDDEN (__init_array_end = .); + + + . = ALIGN(4); + /* finit data */ + PROVIDE_HIDDEN (__fini_array_start = .); + KEEP(*(SORT(.fini_array.*))) + KEEP(*(.fini_array)) + PROVIDE_HIDDEN (__fini_array_end = .); + + KEEP(*(.jcr*)) + . = ALIGN(4); + /* All data end */ + __data_end__ = .; + + } > RAM + + .bss : + { + . = ALIGN(4); + __bss_start__ = .; + *(.bss*) + *(COMMON) + . = ALIGN(4); + __bss_end__ = .; + } > RAM + + .heap (COPY): + { + __end__ = .; + end = __end__; + *(.heap*) + __HeapLimit = .; + } > RAM + + /* .stack_dummy section doesn't contains any symbols. It is only + * used for linker to calculate size of stack sections, and assign + * values to stack symbols later */ + .stack_dummy (COPY): + { + *(.stack*) + } > RAM + + /* Set stack top to end of RAM, and stack limit move down by + * size of stack_dummy section */ + __StackTop = ORIGIN(RAM) + LENGTH(RAM); + __StackLimit = __StackTop - SIZEOF(.stack_dummy); + PROVIDE(__stack = __StackTop); + + /* Check if data + heap + stack exceeds RAM limit */ + ASSERT(__StackLimit >= __HeapLimit, "region RAM overflowed with stack") +} + diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F103RB/TOOLCHAIN_GCC_ARM/startup_stm32f10x.S b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F103RB/TOOLCHAIN_GCC_ARM/startup_stm32f10x.S new file mode 100755 index 0000000000..587e27ab29 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F103RB/TOOLCHAIN_GCC_ARM/startup_stm32f10x.S @@ -0,0 +1,243 @@ +/* File: startup_ARMCM3.s + * Purpose: startup file for Cortex-M3/M4 devices. Should use with + * GNU Tools for ARM Embedded Processors + * Version: V1.1 + * Date: 17 June 2011 + * + * Copyright (c) 2011, 2012, ARM Limited + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + * Neither the name of the ARM Limited nor the + names of its contributors may be used to endorse or promote products + derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL ARM LIMITED BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + .syntax unified + .arch armv7-m + + .section .stack + .align 3 +#ifdef __STACK_SIZE + .equ Stack_Size, __STACK_SIZE +#else + .equ Stack_Size, 0xc00 +#endif + .globl __StackTop + .globl __StackLimit +__StackLimit: + .space Stack_Size + .size __StackLimit, . - __StackLimit +__StackTop: + .size __StackTop, . - __StackTop + + .section .heap + .align 3 +#ifdef __HEAP_SIZE + .equ Heap_Size, __HEAP_SIZE +#else + .equ Heap_Size, 0 +#endif + .globl __HeapBase + .globl __HeapLimit +__HeapBase: + .if Heap_Size + .space Heap_Size + .endif + .size __HeapBase, . - __HeapBase +__HeapLimit: + .size __HeapLimit, . - __HeapLimit + + .section .isr_vector + .align 2 + .globl __isr_vector +__isr_vector: + .long __StackTop /* Top of Stack */ + .long Reset_Handler /* Reset Handler */ + .long NMI_Handler /* NMI Handler */ + .long HardFault_Handler /* Hard Fault Handler */ + .long MemManage_Handler /* MPU Fault Handler */ + .long BusFault_Handler /* Bus Fault Handler */ + .long UsageFault_Handler /* Usage Fault Handler */ + .long 0 /* Reserved */ + .long 0 /* Reserved */ + .long 0 /* Reserved */ + .long 0 /* Reserved */ + .long SVC_Handler /* SVCall Handler */ + .long DebugMon_Handler /* Debug Monitor Handler */ + .long 0 /* Reserved */ + .long PendSV_Handler /* PendSV Handler */ + .long SysTick_Handler /* SysTick Handler */ + .long WWDG_IRQHandler /* Window Watchdog */ + + /* External interrupts */ + .long PVD_IRQHandler /* PVD through EXTI Line detect */ + .long TAMPER_IRQHandler /* Tamper */ + .long RTC_IRQHandler /* RTC */ + .long FLASH_IRQHandler /* Flash */ + .long RCC_IRQHandler /* RCC */ + .long EXTI0_IRQHandler /* EXTI Line 0 */ + .long EXTI1_IRQHandler /* EXTI Line 1 */ + .long EXTI2_IRQHandler /* EXTI Line 2 */ + .long EXTI3_IRQHandler /* EXTI Line 3 */ + .long EXTI4_IRQHandler /* EXTI Line 4 */ + .long DMA1_Channel1_IRQHandler /* DMA1 Channel 1 */ + .long DMA1_Channel2_IRQHandler /* DMA1 Channel 2 */ + .long DMA1_Channel3_IRQHandler /* DMA1 Channel 3 */ + .long DMA1_Channel4_IRQHandler /* DMA1 Channel 4 */ + .long DMA1_Channel5_IRQHandler /* DMA1 Channel 5 */ + .long DMA1_Channel6_IRQHandler /* DMA1 Channel 6 */ + .long DMA1_Channel7_IRQHandler /* DMA1 Channel 7 */ + .long ADC1_2_IRQHandler /* ADC1_2 */ + .long USB_HP_CAN1_TX_IRQHandler /* USB High Priority or CAN1 TX */ + .long USB_LP_CAN1_RX0_IRQHandler /* USB Low Priority or CAN1 RX0 */ + .long CAN1_RX1_IRQHandler /* CAN1 RX1 */ + .long CAN1_SCE_IRQHandler /* CAN1 SCE */ + .long EXTI9_5_IRQHandler /* EXTI Line 9..5 */ + .long TIM1_BRK_IRQHandler /* TIM1 Break */ + .long TIM1_UP_IRQHandler /* TIM1 Update */ + .long TIM1_TRG_COM_IRQHandler /* TIM1 Trigger and Commutation */ + .long TIM1_CC_IRQHandler /* TIM1 Capture Compare */ + .long TIM2_IRQHandler /* TIM2 */ + .long TIM3_IRQHandler /* TIM3 */ + .long TIM4_IRQHandler /* TIM4 */ + .long I2C1_EV_IRQHandler /* I2C1 Event */ + .long I2C1_ER_IRQHandler /* I2C1 Error */ + .long I2C2_EV_IRQHandler /* I2C2 Event */ + .long I2C2_ER_IRQHandler /* I2C2 Error */ + .long SPI1_IRQHandler /* SPI1 */ + .long SPI2_IRQHandler /* SPI2 */ + .long USART1_IRQHandler /* USART1 */ + .long USART2_IRQHandler /* USART2 */ + .long USART3_IRQHandler /* USART3 */ + .long EXTI15_10_IRQHandler /* EXTI Line 15..10 */ + .long RTCAlarm_IRQHandler /* RTC Alarm through EXTI Line */ + .long USBWakeUp_IRQHandler /* USB Wakeup from suspend */ + + .size __isr_vector, . - __isr_vector + + .text + .thumb + .thumb_func + .align 2 + .globl Reset_Handler + .type Reset_Handler, %function +Reset_Handler: +/* Loop to copy data from read only memory to RAM. The ranges + * of copy from/to are specified by following symbols evaluated in + * linker script. + * __etext: End of code section, i.e., begin of data sections to copy from. + * __data_start__/__data_end__: RAM address range that data should be + * copied to. Both must be aligned to 4 bytes boundary. */ + + ldr r1, =__etext + ldr r2, =__data_start__ + ldr r3, =__data_end__ + +.LC0: + cmp r2, r3 + ittt lt + ldrlt r0, [r1], #4 + strlt r0, [r2], #4 + blt .LC0 + + ldr r0, =SystemInit + blx r0 + ldr r0, =_start + bx r0 + .pool + .size Reset_Handler, . - Reset_Handler + + .text +/* Macro to define default handlers. Default handler + * will be weak symbol and just dead loops. They can be + * overwritten by other handlers */ + .macro def_default_handler handler_name + .align 1 + .thumb_func + .weak \handler_name + .type \handler_name, %function +\handler_name : + b . + .size \handler_name, . - \handler_name + .endm + + def_default_handler NMI_Handler + def_default_handler HardFault_Handler + def_default_handler MemManage_Handler + def_default_handler BusFault_Handler + def_default_handler UsageFault_Handler + def_default_handler SVC_Handler + def_default_handler DebugMon_Handler + def_default_handler PendSV_Handler + def_default_handler SysTick_Handler + def_default_handler Default_Handler + + .macro def_irq_default_handler handler_name + .weak \handler_name + .set \handler_name, Default_Handler + .endm + + def_irq_default_handler WWDG_IRQHandler + def_irq_default_handler PVD_IRQHandler + def_irq_default_handler TAMPER_IRQHandler + def_irq_default_handler RTC_IRQHandler + def_irq_default_handler FLASH_IRQHandler + def_irq_default_handler RCC_IRQHandler + def_irq_default_handler EXTI0_IRQHandler + def_irq_default_handler EXTI1_IRQHandler + def_irq_default_handler EXTI2_IRQHandler + def_irq_default_handler EXTI3_IRQHandler + def_irq_default_handler EXTI4_IRQHandler + def_irq_default_handler DMA1_Channel1_IRQHandler + def_irq_default_handler DMA1_Channel2_IRQHandler + def_irq_default_handler DMA1_Channel3_IRQHandler + def_irq_default_handler DMA1_Channel4_IRQHandler + def_irq_default_handler DMA1_Channel5_IRQHandler + def_irq_default_handler DMA1_Channel6_IRQHandler + def_irq_default_handler DMA1_Channel7_IRQHandler + + def_irq_default_handler ADC1_2_IRQHandler + def_irq_default_handler USB_HP_CAN1_TX_IRQHandler + def_irq_default_handler USB_LP_CAN1_RX0_IRQHandler + def_irq_default_handler CAN1_RX1_IRQHandler + def_irq_default_handler CAN1_SCE_IRQHandler + def_irq_default_handler EXTI9_5_IRQHandler + def_irq_default_handler TIM1_BRK_IRQHandler + def_irq_default_handler TIM1_UP_IRQHandler + def_irq_default_handler TIM1_TRG_COM_IRQHandler + def_irq_default_handler TIM1_CC_IRQHandler + def_irq_default_handler TIM2_IRQHandler + def_irq_default_handler TIM3_IRQHandler + def_irq_default_handler TIM4_IRQHandler + def_irq_default_handler I2C1_EV_IRQHandler + def_irq_default_handler I2C1_ER_IRQHandler + def_irq_default_handler I2C2_EV_IRQHandler + def_irq_default_handler I2C2_ER_IRQHandler + def_irq_default_handler SPI1_IRQHandler + def_irq_default_handler SPI2_IRQHandler + def_irq_default_handler USART1_IRQHandler + def_irq_default_handler USART2_IRQHandler + def_irq_default_handler USART3_IRQHandler + def_irq_default_handler EXTI15_10_IRQHandler + def_irq_default_handler RTCAlarm_IRQHandler + def_irq_default_handler USBWakeUp_IRQHandler + + .end + diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F401RE/stm32f4xx_hal_conf.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F401RE/stm32f4xx_hal_conf.h index 111c19651f..e91593d200 100644 --- a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F401RE/stm32f4xx_hal_conf.h +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F401RE/stm32f4xx_hal_conf.h @@ -103,7 +103,7 @@ #endif /* HSE_VALUE */ #if !defined (HSE_STARTUP_TIMEOUT) - #define HSE_STARTUP_TIMEOUT ((uint32_t)50) /*!< Time out for HSE start up, in ms */ + #define HSE_STARTUP_TIMEOUT ((uint32_t)100) /*!< Time out for HSE start up, in ms */ #endif /* HSE_STARTUP_TIMEOUT */ /** @@ -129,7 +129,7 @@ * frequency, this source is inserted directly through I2S_CKIN pad. */ #if !defined (EXTERNAL_CLOCK_VALUE) - #define EXTERNAL_CLOCK_VALUE ((uint32_t)12288000) /*!< Value of the Internal oscillator in Hz*/ + #define EXTERNAL_CLOCK_VALUE ((uint32_t)12288000) /*!< Value of the external oscillator in Hz*/ #endif /* EXTERNAL_CLOCK_VALUE */ /* Tip: To avoid modifying this file each time you need to use different HSE, diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F401RE/system_stm32f4xx.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F401RE/system_stm32f4xx.c index 7e06c7d938..463794abff 100644 --- a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F401RE/system_stm32f4xx.c +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F401RE/system_stm32f4xx.c @@ -2,7 +2,7 @@ ****************************************************************************** * @file system_stm32f4xx.c * @author MCD Application Team - * @version V1.0.0 + * @version V2.0.0 * @date 18-February-2014 * @brief CMSIS Cortex-M4 Device Peripheral Access Layer System Source File. * @@ -20,7 +20,23 @@ * be called whenever the core clock is changed * during program execution. * - * + * This file configures the system clock as follows: + *----------------------------------------------------------------------------- + * System clock source | 1- PLL_HSE_EXTC | 3- PLL_HSI + * | (external 8 MHz clock) | (internal 16 MHz) + * | 2- PLL_HSE_XTAL | + * | (external 8 MHz xtal) | + *----------------------------------------------------------------------------- + * SYSCLK(MHz) | 84 | 84 + *----------------------------------------------------------------------------- + * AHBCLK (MHz) | 84 | 84 + *----------------------------------------------------------------------------- + * APB1CLK (MHz) | 42 | 42 + *----------------------------------------------------------------------------- + * APB2CLK (MHz) | 84 | 84 + *----------------------------------------------------------------------------- + * USB capable (48 MHz precise clock) | YES | NO + *----------------------------------------------------------------------------- ****************************************************************************** * @attention * @@ -82,6 +98,19 @@ */ /************************* Miscellaneous Configuration ************************/ +/*!< Uncomment the following line if you need to use external SRAM or SDRAM mounted + on STM324xG_EVAL/STM324x9I_EVAL boards as data memory */ +#if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) || defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) +/* #define DATA_IN_ExtSRAM */ +#endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx */ + +#if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) +/* #define DATA_IN_ExtSDRAM */ +#endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx */ + +#if defined(DATA_IN_ExtSRAM) && defined(DATA_IN_ExtSDRAM) + #error "Please select DATA_IN_ExtSRAM or DATA_IN_ExtSDRAM " +#endif /* DATA_IN_ExtSRAM && DATA_IN_ExtSDRAM */ /*!< Uncomment the following line if you need to relocate your vector Table in Internal SRAM. */ @@ -98,6 +127,10 @@ * @{ */ +/* Select the clock sources (other than HSI) to start with (0=OFF, 1=ON) */ +#define USE_PLL_HSE_EXTC (1) /* Use external clock */ +#define USE_PLL_HSE_XTAL (1) /* Use external xtal */ + /** * @} */ @@ -113,8 +146,8 @@ is no need to call the 2 first functions listed above, since SystemCoreClock variable is updated automatically. */ - uint32_t SystemCoreClock = 84000000; /* [CHANGED FOR MBED] */ - __I uint8_t AHBPrescTable[16] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 6, 7, 8, 9}; +uint32_t SystemCoreClock = 84000000; +const uint8_t AHBPrescTable[16] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 6, 7, 8, 9}; /** * @} @@ -124,9 +157,16 @@ * @{ */ -/* [ADDED FOR MBED] */ -void SystemClock_Config(void); - +#if defined (DATA_IN_ExtSRAM) || defined (DATA_IN_ExtSDRAM) + static void SystemInit_ExtMemCtl(void); +#endif /* DATA_IN_ExtSRAM || DATA_IN_ExtSDRAM */ + +#if (USE_PLL_HSE_XTAL != 0) || (USE_PLL_HSE_EXTC != 0) +uint8_t SetSysClock_PLL_HSE(uint8_t bypass); +#endif + +uint8_t SetSysClock_PLL_HSI(void); + /** * @} */ @@ -167,6 +207,10 @@ void SystemInit(void) /* Disable all interrupts */ RCC->CIR = 0x00000000; +#if defined (DATA_IN_ExtSRAM) || defined (DATA_IN_ExtSDRAM) + SystemInit_ExtMemCtl(); +#endif /* DATA_IN_ExtSRAM || DATA_IN_ExtSDRAM */ + /* Configure the Vector Table location add offset address ------------------*/ #ifdef VECT_TAB_SRAM SCB->VTOR = SRAM_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal SRAM */ @@ -174,9 +218,12 @@ void SystemInit(void) SCB->VTOR = FLASH_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal FLASH */ #endif - /* [ADDED FOR MBED] */ + /* Configure the Cube driver */ HAL_Init(); - SystemClock_Config(); + + /* Configure the System clock source, PLL Multiplier and Divider factors, + AHB/APBx prescalers and Flash settings */ + SetSysClock(); } /** @@ -263,9 +310,269 @@ void SystemCoreClockUpdate(void) SystemCoreClock >>= tmp; } -/* [ADDED FOR MBED] - Configure the System clock to 84 MHz (max value) using the internal HSI 16 MHz clock */ -void SystemClock_Config(void) +#if defined (DATA_IN_ExtSRAM) || defined (DATA_IN_ExtSDRAM) +/** + * @brief Setup the external memory controller. + * Called in startup_stm32f4xx.s before jump to main. + * This function configures the external memories (SRAM/SDRAM) + * This SRAM/SDRAM will be used as program data memory (including heap and stack). + * @param None + * @retval None + */ +void SystemInit_ExtMemCtl(void) +{ +#if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) +#if defined (DATA_IN_ExtSDRAM) + register uint32_t tmpreg = 0, timeout = 0xFFFF; + register uint32_t index; + + /* Enable GPIOC, GPIOD, GPIOE, GPIOF, GPIOG, GPIOH and GPIOI interface + clock */ + RCC->AHB1ENR |= 0x000001F8; + + /* Connect PDx pins to FMC Alternate function */ + GPIOD->AFR[0] = 0x000000CC; + GPIOD->AFR[1] = 0xCC000CCC; + /* Configure PDx pins in Alternate function mode */ + GPIOD->MODER = 0xA02A000A; + /* Configure PDx pins speed to 50 MHz */ + GPIOD->OSPEEDR = 0xA02A000A; + /* Configure PDx pins Output type to push-pull */ + GPIOD->OTYPER = 0x00000000; + /* No pull-up, pull-down for PDx pins */ + GPIOD->PUPDR = 0x00000000; + + /* Connect PEx pins to FMC Alternate function */ + GPIOE->AFR[0] = 0xC00000CC; + GPIOE->AFR[1] = 0xCCCCCCCC; + /* Configure PEx pins in Alternate function mode */ + GPIOE->MODER = 0xAAAA800A; + /* Configure PEx pins speed to 50 MHz */ + GPIOE->OSPEEDR = 0xAAAA800A; + /* Configure PEx pins Output type to push-pull */ + GPIOE->OTYPER = 0x00000000; + /* No pull-up, pull-down for PEx pins */ + GPIOE->PUPDR = 0x00000000; + + /* Connect PFx pins to FMC Alternate function */ + GPIOF->AFR[0] = 0xCCCCCCCC; + GPIOF->AFR[1] = 0xCCCCCCCC; + /* Configure PFx pins in Alternate function mode */ + GPIOF->MODER = 0xAA800AAA; + /* Configure PFx pins speed to 50 MHz */ + GPIOF->OSPEEDR = 0xAA800AAA; + /* Configure PFx pins Output type to push-pull */ + GPIOF->OTYPER = 0x00000000; + /* No pull-up, pull-down for PFx pins */ + GPIOF->PUPDR = 0x00000000; + + /* Connect PGx pins to FMC Alternate function */ + GPIOG->AFR[0] = 0xCCCCCCCC; + GPIOG->AFR[1] = 0xCCCCCCCC; + /* Configure PGx pins in Alternate function mode */ + GPIOG->MODER = 0xAAAAAAAA; + /* Configure PGx pins speed to 50 MHz */ + GPIOG->OSPEEDR = 0xAAAAAAAA; + /* Configure PGx pins Output type to push-pull */ + GPIOG->OTYPER = 0x00000000; + /* No pull-up, pull-down for PGx pins */ + GPIOG->PUPDR = 0x00000000; + + /* Connect PHx pins to FMC Alternate function */ + GPIOH->AFR[0] = 0x00C0CC00; + GPIOH->AFR[1] = 0xCCCCCCCC; + /* Configure PHx pins in Alternate function mode */ + GPIOH->MODER = 0xAAAA08A0; + /* Configure PHx pins speed to 50 MHz */ + GPIOH->OSPEEDR = 0xAAAA08A0; + /* Configure PHx pins Output type to push-pull */ + GPIOH->OTYPER = 0x00000000; + /* No pull-up, pull-down for PHx pins */ + GPIOH->PUPDR = 0x00000000; + + /* Connect PIx pins to FMC Alternate function */ + GPIOI->AFR[0] = 0xCCCCCCCC; + GPIOI->AFR[1] = 0x00000CC0; + /* Configure PIx pins in Alternate function mode */ + GPIOI->MODER = 0x0028AAAA; + /* Configure PIx pins speed to 50 MHz */ + GPIOI->OSPEEDR = 0x0028AAAA; + /* Configure PIx pins Output type to push-pull */ + GPIOI->OTYPER = 0x00000000; + /* No pull-up, pull-down for PIx pins */ + GPIOI->PUPDR = 0x00000000; + +/*-- FMC Configuration ------------------------------------------------------*/ + /* Enable the FMC interface clock */ + RCC->AHB3ENR |= 0x00000001; + + /* Configure and enable SDRAM bank1 */ + FMC_Bank5_6->SDCR[0] = 0x000019E0; + FMC_Bank5_6->SDTR[0] = 0x01115351; + + /* SDRAM initialization sequence */ + /* Clock enable command */ + FMC_Bank5_6->SDCMR = 0x00000011; + tmpreg = FMC_Bank5_6->SDSR & 0x00000020; + while((tmpreg != 0) && (timeout-- > 0)) + { + tmpreg = FMC_Bank5_6->SDSR & 0x00000020; + } + + /* Delay */ + for (index = 0; index<1000; index++); + + /* PALL command */ + FMC_Bank5_6->SDCMR = 0x00000012; + timeout = 0xFFFF; + while((tmpreg != 0) && (timeout-- > 0)) + { + tmpreg = FMC_Bank5_6->SDSR & 0x00000020; + } + + /* Auto refresh command */ + FMC_Bank5_6->SDCMR = 0x00000073; + timeout = 0xFFFF; + while((tmpreg != 0) && (timeout-- > 0)) + { + tmpreg = FMC_Bank5_6->SDSR & 0x00000020; + } + + /* MRD register program */ + FMC_Bank5_6->SDCMR = 0x00046014; + timeout = 0xFFFF; + while((tmpreg != 0) && (timeout-- > 0)) + { + tmpreg = FMC_Bank5_6->SDSR & 0x00000020; + } + + /* Set refresh count */ + tmpreg = FMC_Bank5_6->SDRTR; + FMC_Bank5_6->SDRTR = (tmpreg | (0x0000027C<<1)); + + /* Disable write protection */ + tmpreg = FMC_Bank5_6->SDCR[0]; + FMC_Bank5_6->SDCR[0] = (tmpreg & 0xFFFFFDFF); +#endif /* DATA_IN_ExtSDRAM */ +#endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx */ + +#if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) || defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) +#if defined(DATA_IN_ExtSRAM) +/*-- GPIOs Configuration -----------------------------------------------------*/ + /* Enable GPIOD, GPIOE, GPIOF and GPIOG interface clock */ + RCC->AHB1ENR |= 0x00000078; + + /* Connect PDx pins to FMC Alternate function */ + GPIOD->AFR[0] = 0x00CCC0CC; + GPIOD->AFR[1] = 0xCCCCCCCC; + /* Configure PDx pins in Alternate function mode */ + GPIOD->MODER = 0xAAAA0A8A; + /* Configure PDx pins speed to 100 MHz */ + GPIOD->OSPEEDR = 0xFFFF0FCF; + /* Configure PDx pins Output type to push-pull */ + GPIOD->OTYPER = 0x00000000; + /* No pull-up, pull-down for PDx pins */ + GPIOD->PUPDR = 0x00000000; + + /* Connect PEx pins to FMC Alternate function */ + GPIOE->AFR[0] = 0xC00CC0CC; + GPIOE->AFR[1] = 0xCCCCCCCC; + /* Configure PEx pins in Alternate function mode */ + GPIOE->MODER = 0xAAAA828A; + /* Configure PEx pins speed to 100 MHz */ + GPIOE->OSPEEDR = 0xFFFFC3CF; + /* Configure PEx pins Output type to push-pull */ + GPIOE->OTYPER = 0x00000000; + /* No pull-up, pull-down for PEx pins */ + GPIOE->PUPDR = 0x00000000; + + /* Connect PFx pins to FMC Alternate function */ + GPIOF->AFR[0] = 0x00CCCCCC; + GPIOF->AFR[1] = 0xCCCC0000; + /* Configure PFx pins in Alternate function mode */ + GPIOF->MODER = 0xAA000AAA; + /* Configure PFx pins speed to 100 MHz */ + GPIOF->OSPEEDR = 0xFF000FFF; + /* Configure PFx pins Output type to push-pull */ + GPIOF->OTYPER = 0x00000000; + /* No pull-up, pull-down for PFx pins */ + GPIOF->PUPDR = 0x00000000; + + /* Connect PGx pins to FMC Alternate function */ + GPIOG->AFR[0] = 0x00CCCCCC; + GPIOG->AFR[1] = 0x000000C0; + /* Configure PGx pins in Alternate function mode */ + GPIOG->MODER = 0x00085AAA; + /* Configure PGx pins speed to 100 MHz */ + GPIOG->OSPEEDR = 0x000CAFFF; + /* Configure PGx pins Output type to push-pull */ + GPIOG->OTYPER = 0x00000000; + /* No pull-up, pull-down for PGx pins */ + GPIOG->PUPDR = 0x00000000; + +/*-- FMC/FSMC Configuration --------------------------------------------------*/ + /* Enable the FMC/FSMC interface clock */ + RCC->AHB3ENR |= 0x00000001; + +#if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx)|| defined(STM32F439xx) + /* Configure and enable Bank1_SRAM2 */ + FMC_Bank1->BTCR[2] = 0x00001011; + FMC_Bank1->BTCR[3] = 0x00000201; + FMC_Bank1E->BWTR[2] = 0x0fffffff; +#endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx */ + +#if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx)|| defined(STM32F417xx) + /* Configure and enable Bank1_SRAM2 */ + FSMC_Bank1->BTCR[2] = 0x00001011; + FSMC_Bank1->BTCR[3] = 0x00000201; + FSMC_Bank1E->BWTR[2] = 0x0FFFFFFF; +#endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx */ + +#endif /* DATA_IN_ExtSRAM */ +#endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx */ +} +#endif /* DATA_IN_ExtSRAM || DATA_IN_ExtSDRAM */ + +/** + * @brief Configures the System clock source, PLL Multiplier and Divider factors, + * AHB/APBx prescalers and Flash settings + * @note This function should be called only once the RCC clock configuration + * is reset to the default reset state (done in SystemInit() function). + * @param None + * @retval None + */ +void SetSysClock(void) +{ + /* 1- Try to start with HSE and external clock */ +#if USE_PLL_HSE_EXTC != 0 + if (SetSysClock_PLL_HSE(1) == 0) +#endif + { + /* 2- If fail try to start with HSE and external xtal */ + #if USE_PLL_HSE_XTAL != 0 + if (SetSysClock_PLL_HSE(0) == 0) + #endif + { + /* 3- If fail start with HSI clock */ + if (SetSysClock_PLL_HSI() == 0) + { + while(1) + { + // [TODO] Put something here to tell the user that a problem occured... + } + } + } + } + + /* Output clock on MCO2 pin(PC9) for debugging purpose */ + //HAL_RCC_MCOConfig(RCC_MCO2, RCC_MCO2SOURCE_SYSCLK, RCC_MCODIV_1); // 84 MHz +} + +#if (USE_PLL_HSE_XTAL != 0) || (USE_PLL_HSE_EXTC != 0) +/******************************************************************************/ +/* PLL (clocked by HSE) used as System clock source */ +/******************************************************************************/ +uint8_t SetSysClock_PLL_HSE(uint8_t bypass) { RCC_ClkInitTypeDef RCC_ClkInitStruct; RCC_OscInitTypeDef RCC_OscInitStruct; @@ -276,54 +583,98 @@ void SystemClock_Config(void) __PWR_CLK_ENABLE(); __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE2); - /* Enable HSI Oscillator and activate PLL with HSI as source */ - RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI; - RCC_OscInitStruct.HSEState = RCC_HSE_OFF; - RCC_OscInitStruct.HSIState = RCC_HSI_ON; - RCC_OscInitStruct.LSEState = RCC_LSE_OFF; - RCC_OscInitStruct.LSIState = RCC_LSI_OFF; - RCC_OscInitStruct.HSICalibrationValue = 16; + /* Enable HSE oscillator and activate PLL with HSE as source */ + RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE; + if (bypass == 0) + { + RCC_OscInitStruct.HSEState = RCC_HSE_ON; /* External 8 MHz xtal on OSC_IN/OSC_OUT */ + } + else + { + RCC_OscInitStruct.HSEState = RCC_HSE_BYPASS; /* External 8 MHz clock on OSC_IN */ + } RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; - RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI; - RCC_OscInitStruct.PLL.PLLM = 16; - RCC_OscInitStruct.PLL.PLLN = 336; - RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV4; - RCC_OscInitStruct.PLL.PLLQ = 7; + RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE; + RCC_OscInitStruct.PLL.PLLM = 8; // VCO input clock = 1 MHz (8 MHz / 8) + RCC_OscInitStruct.PLL.PLLN = 336; // VCO output clock = 336 MHz (1 MHz * 336) + RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV4; // PLLCLK = 84 MHz (336 MHz / 4) + RCC_OscInitStruct.PLL.PLLQ = 7; // USB clock = 48 MHz (336 MHz / 7) --> OK for USB if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { - // System clock initialization failed - while(1) - { - // [TODO] Put something here to tell the user that a problem occured... - } + return 0; // FAIL } /* Select PLL as system clock source and configure the HCLK, PCLK1 and PCLK2 clocks dividers */ RCC_ClkInitStruct.ClockType = (RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2); - RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; - RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; // 84 MHz - RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2; // 42 MHz - RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1; // 84 MHz (SPI1 clock...) + RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; // 84 MHz + RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; // 84 MHz + RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2; // 42 MHz + RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1; // 84 MHz if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK) { - // System clock initialization failed - while(1) - { - // [TODO] Put something here to tell the user that a problem occured... - } + return 0; // FAIL } - /* Update the SystemCoreClock variable - - Not needed because the variable is already set on top of this file. - - Warning: this function call is removed by the compiler with -O3/-Otime options. */ - //SystemCoreClockUpdate(); + /* Output clock on MCO1 pin(PA8) for debugging purpose */ + /* + if (bypass == 0) + HAL_RCC_MCOConfig(RCC_MCO1, RCC_MCO1SOURCE_HSE, RCC_MCODIV_2); // 4 MHz + else + HAL_RCC_MCOConfig(RCC_MCO1, RCC_MCO1SOURCE_HSE, RCC_MCODIV_1); // 8 MHz + */ + + return 1; // OK +} +#endif - /* Output SYSCLK on MCO2 pin(PC9) for debugging purpose */ - //HAL_RCC_MCOConfig(RCC_MCO2, RCC_MCO2SOURCE_SYSCLK, RCC_MCODIV_4); // 84 MHz / 4 = 21 MHz +/******************************************************************************/ +/* PLL (clocked by HSI) used as System clock source */ +/******************************************************************************/ +uint8_t SetSysClock_PLL_HSI(void) +{ + RCC_ClkInitTypeDef RCC_ClkInitStruct; + RCC_OscInitTypeDef RCC_OscInitStruct; + + /* The voltage scaling allows optimizing the power consumption when the device is + clocked below the maximum system frequency, to update the voltage scaling value + regarding system frequency refer to product datasheet. */ + __PWR_CLK_ENABLE(); + __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE2); + + /* Enable HSI oscillator and activate PLL with HSI as source */ + RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI | RCC_OSCILLATORTYPE_HSE; + RCC_OscInitStruct.HSIState = RCC_HSI_ON; + RCC_OscInitStruct.HSEState = RCC_HSE_OFF; + RCC_OscInitStruct.HSICalibrationValue = 16; + RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; + RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI; + RCC_OscInitStruct.PLL.PLLM = 16; // VCO input clock = 1 MHz (16 MHz / 16) + RCC_OscInitStruct.PLL.PLLN = 336; // VCO output clock = 336 MHz (1 MHz * 336) + RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV4; // PLLCLK = 84 MHz (336 MHz / 4) + RCC_OscInitStruct.PLL.PLLQ = 7; // USB clock = 48 MHz (336 MHz / 7) --> freq is ok but not precise enough + if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) + { + return 0; // FAIL + } + + /* Select PLL as system clock source and configure the HCLK, PCLK1 and PCLK2 clocks dividers */ + RCC_ClkInitStruct.ClockType = (RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2); + RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; // 84 MHz + RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; // 84 MHz + RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2; // 42 MHz + RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1; // 84 MHz + if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK) + { + return 0; // FAIL + } + + /* Output clock on MCO1 pin(PA8) for debugging purpose */ + //HAL_RCC_MCOConfig(RCC_MCO1, RCC_MCO1SOURCE_HSI, RCC_MCODIV_1); // 16 MHz + + return 1; // OK } -/* [ADDED FOR MBED] - Used for the different timeouts in the HAL */ +/* Used for the different timeouts in the HAL */ void SysTick_Handler(void) { HAL_IncTick(); diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F401RE/system_stm32f4xx.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F401RE/system_stm32f4xx.h index cbbd1b16a4..e3a3b0d34a 100644 --- a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F401RE/system_stm32f4xx.h +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_F401RE/system_stm32f4xx.h @@ -102,6 +102,8 @@ extern uint32_t SystemCoreClock; /*!< System Clock Frequency (Core Cloc extern void SystemInit(void); extern void SystemCoreClockUpdate(void); +extern void SetSysClock(void); + /** * @} */ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/TOOLCHAIN_ARM_MICRO/startup_stm32l053xx.s b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/TOOLCHAIN_ARM_MICRO/startup_stm32l053xx.s new file mode 100644 index 0000000000..d3752c6119 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/TOOLCHAIN_ARM_MICRO/startup_stm32l053xx.s @@ -0,0 +1,242 @@ +;******************** (C) COPYRIGHT 2014 STMicroelectronics ******************** +;* File Name : startup_stm32l053xx.s +;* Author : MCD Application Team +;* Version : V1.0.0 +;* Date : 22-April-2014 +;* Description : STM32l053xx Devices vector table for MDK-ARM toolchain. +;* This module performs: +;* - Set the initial SP +;* - Set the initial PC == Reset_Handler +;* - Set the vector table entries with the exceptions ISR address +;* - Branches to __main in the C library (which eventually +;* calls main()). +;* After Reset the Cortex-M0+ processor is in Thread mode, +;* priority is Privileged, and the Stack is set to Main. +;* <<< Use Configuration Wizard in Context Menu >>> +;******************************************************************************* +;* +;* Redistribution and use in source and binary forms, with or without modification, +;* are permitted provided that the following conditions are met: +;* 1. Redistributions of source code must retain the above copyright notice, +;* this list of conditions and the following disclaimer. +;* 2. Redistributions in binary form must reproduce the above copyright notice, +;* this list of conditions and the following disclaimer in the documentation +;* and/or other materials provided with the distribution. +;* 3. Neither the name of STMicroelectronics nor the names of its contributors +;* may be used to endorse or promote products derived from this software +;* without specific prior written permission. +;* +;* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +;* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +;* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +;* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +;* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +;* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +;* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +;* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +;* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +;* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +;* +;******************************************************************************* +; +; Amount of memory (in bytes) allocated for Stack +; Tailor this value to your application needs +; Stack Configuration +; Stack Size (in Bytes) <0x0-0xFFFFFFFF:8> +; + +Stack_Size EQU 0x00000400 + + AREA STACK, NOINIT, READWRITE, ALIGN=3 + EXPORT __initial_sp + +Stack_Mem SPACE Stack_Size +__initial_sp EQU 0x20002000 ; Top of RAM + + +; Heap Configuration +; Heap Size (in Bytes) <0x0-0xFFFFFFFF:8> +; + +Heap_Size EQU 0x00000000 + + AREA HEAP, NOINIT, READWRITE, ALIGN=3 + EXPORT __heap_base + EXPORT __heap_limit + +__heap_base +Heap_Mem SPACE Heap_Size +__heap_limit + + PRESERVE8 + THUMB + + +; Vector Table Mapped to Address 0 at Reset + AREA RESET, DATA, READONLY + EXPORT __Vectors + EXPORT __Vectors_End + EXPORT __Vectors_Size + +__Vectors DCD __initial_sp ; Top of Stack + DCD Reset_Handler ; Reset Handler + DCD NMI_Handler ; NMI Handler + DCD HardFault_Handler ; Hard Fault Handler + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD SVC_Handler ; SVCall Handler + DCD DebugMon_Handler ; Debug Monitor Handler + DCD 0 ; Reserved + DCD PendSV_Handler ; PendSV Handler + DCD SysTick_Handler ; SysTick Handler + + ; External Interrupts + DCD WWDG_IRQHandler ; Window Watchdog + DCD PVD_IRQHandler ; PVD through EXTI Line detect + DCD RTC_IRQHandler ; RTC through EXTI Line + DCD FLASH_IRQHandler ; FLASH + DCD RCC_CRS_IRQHandler ; RCC and CRS + DCD EXTI0_1_IRQHandler ; EXTI Line 0 and 1 + DCD EXTI2_3_IRQHandler ; EXTI Line 2 and 3 + DCD EXTI4_15_IRQHandler ; EXTI Line 4 to 15 + DCD TSC_IRQHandler ; TSC + DCD DMA1_Channel1_IRQHandler ; DMA1 Channel 1 + DCD DMA1_Channel2_3_IRQHandler ; DMA1 Channel 2 and Channel 3 + DCD DMA1_Channel4_5_6_7_IRQHandler ; DMA1 Channel 4, Channel 5, Channel 6 and Channel 7 + DCD ADC1_COMP_IRQHandler ; ADC1, COMP1 and COMP2 + DCD LPTIM1_IRQHandler ; LPTIM1 + DCD 0 ; Reserved + DCD TIM2_IRQHandler ; TIM2 + DCD 0 ; Reserved + DCD TIM6_DAC_IRQHandler ; TIM6 and DAC + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD TIM21_IRQHandler ; TIM21 + DCD 0 ; Reserved + DCD TIM22_IRQHandler ; TIM22 + DCD I2C1_IRQHandler ; I2C1 + DCD I2C2_IRQHandler ; I2C2 + DCD SPI1_IRQHandler ; SPI1 + DCD SPI2_IRQHandler ; SPI2 + DCD USART1_IRQHandler ; USART1 + DCD USART2_IRQHandler ; USART2 + DCD RNG_LPUART1_IRQHandler ; RNG and LPUART1 + DCD LCD_IRQHandler ; LCD + DCD USB_IRQHandler ; USB + +__Vectors_End + +__Vectors_Size EQU __Vectors_End - __Vectors + + AREA |.text|, CODE, READONLY + +; Reset handler routine +Reset_Handler PROC + EXPORT Reset_Handler [WEAK] + IMPORT __main + IMPORT SystemInit + LDR R0, =SystemInit + BLX R0 + LDR R0, =__main + BX R0 + ENDP + +; Dummy Exception Handlers (infinite loops which can be modified) + +NMI_Handler PROC + EXPORT NMI_Handler [WEAK] + B . + ENDP +HardFault_Handler\ + PROC + EXPORT HardFault_Handler [WEAK] + B . + ENDP +SVC_Handler PROC + EXPORT SVC_Handler [WEAK] + B . + ENDP +DebugMon_Handler\ + PROC + EXPORT DebugMon_Handler [WEAK] + B . + ENDP +PendSV_Handler PROC + EXPORT PendSV_Handler [WEAK] + B . + ENDP +SysTick_Handler PROC + EXPORT SysTick_Handler [WEAK] + B . + ENDP + +Default_Handler PROC + + EXPORT WWDG_IRQHandler [WEAK] + EXPORT PVD_IRQHandler [WEAK] + EXPORT RTC_IRQHandler [WEAK] + EXPORT FLASH_IRQHandler [WEAK] + EXPORT RCC_CRS_IRQHandler [WEAK] + EXPORT EXTI0_1_IRQHandler [WEAK] + EXPORT EXTI2_3_IRQHandler [WEAK] + EXPORT EXTI4_15_IRQHandler [WEAK] + EXPORT TSC_IRQHandler [WEAK] + EXPORT DMA1_Channel1_IRQHandler [WEAK] + EXPORT DMA1_Channel2_3_IRQHandler [WEAK] + EXPORT DMA1_Channel4_5_6_7_IRQHandler [WEAK] + EXPORT ADC1_COMP_IRQHandler [WEAK] + EXPORT LPTIM1_IRQHandler [WEAK] + EXPORT TIM2_IRQHandler [WEAK] + EXPORT TIM6_DAC_IRQHandler [WEAK] + EXPORT TIM21_IRQHandler [WEAK] + EXPORT TIM22_IRQHandler [WEAK] + EXPORT I2C1_IRQHandler [WEAK] + EXPORT I2C2_IRQHandler [WEAK] + EXPORT SPI1_IRQHandler [WEAK] + EXPORT SPI2_IRQHandler [WEAK] + EXPORT USART1_IRQHandler [WEAK] + EXPORT USART2_IRQHandler [WEAK] + EXPORT RNG_LPUART1_IRQHandler [WEAK] + EXPORT LCD_IRQHandler [WEAK] + EXPORT USB_IRQHandler [WEAK] + + +WWDG_IRQHandler +PVD_IRQHandler +RTC_IRQHandler +FLASH_IRQHandler +RCC_CRS_IRQHandler +EXTI0_1_IRQHandler +EXTI2_3_IRQHandler +EXTI4_15_IRQHandler +TSC_IRQHandler +DMA1_Channel1_IRQHandler +DMA1_Channel2_3_IRQHandler +DMA1_Channel4_5_6_7_IRQHandler +ADC1_COMP_IRQHandler +LPTIM1_IRQHandler +TIM2_IRQHandler +TIM6_DAC_IRQHandler +TIM21_IRQHandler +TIM22_IRQHandler +I2C1_IRQHandler +I2C2_IRQHandler +SPI1_IRQHandler +SPI2_IRQHandler +USART1_IRQHandler +USART2_IRQHandler +RNG_LPUART1_IRQHandler +LCD_IRQHandler +USB_IRQHandler + + B . + + ENDP + + ALIGN + END diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/TOOLCHAIN_ARM_MICRO/stm32l053r8.sct b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/TOOLCHAIN_ARM_MICRO/stm32l053r8.sct new file mode 100644 index 0000000000..f6d3c32f8a --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/TOOLCHAIN_ARM_MICRO/stm32l053r8.sct @@ -0,0 +1,45 @@ +; Scatter-Loading Description File +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +; Copyright (c) 2014, STMicroelectronics +; All rights reserved. +; +; Redistribution and use in source and binary forms, with or without +; modification, are permitted provided that the following conditions are met: +; +; 1. Redistributions of source code must retain the above copyright notice, +; this list of conditions and the following disclaimer. +; 2. Redistributions in binary form must reproduce the above copyright notice, +; this list of conditions and the following disclaimer in the documentation +; and/or other materials provided with the distribution. +; 3. Neither the name of STMicroelectronics nor the names of its contributors +; may be used to endorse or promote products derived from this software +; without specific prior written permission. +; +; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +; FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +; OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +; STM32L053R8: 64KB FLASH (0x10000) + 8KB RAM (0x2000) +LR_IROM1 0x08000000 0x10000 { ; load region size_region + + ER_IROM1 0x08000000 0x10000 { ; load address = execution address + *.o (RESET, +First) + *(InRoot$$Sections) + .ANY (+RO) + } + + ; Total: 48 vectors = 192 bytes (0xC0) to be reserved in RAM + RW_IRAM1 (0x20000000+0xC0) (0x2000-0xC0) { ; RW data + .ANY (+RW +ZI) + } + +} + diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/TOOLCHAIN_ARM_MICRO/sys.cpp b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/TOOLCHAIN_ARM_MICRO/sys.cpp new file mode 100644 index 0000000000..bb665909b9 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/TOOLCHAIN_ARM_MICRO/sys.cpp @@ -0,0 +1,56 @@ +/* mbed Microcontroller Library - stackheap + * Setup a fixed single stack/heap memory model, + * between the top of the RW/ZI region and the stackpointer + ******************************************************************************* + * Copyright (c) 2014, STMicroelectronics + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ******************************************************************************* + */ + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include + +extern char Image$$RW_IRAM1$$ZI$$Limit[]; + +extern __value_in_regs struct __initial_stackheap __user_setup_stackheap(uint32_t R0, uint32_t R1, uint32_t R2, uint32_t R3) { + uint32_t zi_limit = (uint32_t)Image$$RW_IRAM1$$ZI$$Limit; + uint32_t sp_limit = __current_sp(); + + zi_limit = (zi_limit + 7) & ~0x7; // ensure zi_limit is 8-byte aligned + + struct __initial_stackheap r; + r.heap_base = zi_limit; + r.heap_limit = sp_limit; + return r; +} + +#ifdef __cplusplus +} +#endif diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/TOOLCHAIN_ARM_STD/startup_stm32l053xx.s b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/TOOLCHAIN_ARM_STD/startup_stm32l053xx.s new file mode 100644 index 0000000000..4c1b6c7ffd --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/TOOLCHAIN_ARM_STD/startup_stm32l053xx.s @@ -0,0 +1,215 @@ +;******************** (C) COPYRIGHT 2014 STMicroelectronics ******************** +;* File Name : startup_stm32l053xx.s +;* Author : MCD Application Team +;* Version : V1.0.0 +;* Date : 22-April-2014 +;* Description : STM32l053xx Devices vector table for MDK-ARM toolchain. +;* This module performs: +;* - Set the initial SP +;* - Set the initial PC == Reset_Handler +;* - Set the vector table entries with the exceptions ISR address +;* - Branches to __main in the C library (which eventually +;* calls main()). +;* After Reset the Cortex-M0+ processor is in Thread mode, +;* priority is Privileged, and the Stack is set to Main. +;* <<< Use Configuration Wizard in Context Menu >>> +;******************************************************************************* +;* +;* Redistribution and use in source and binary forms, with or without modification, +;* are permitted provided that the following conditions are met: +;* 1. Redistributions of source code must retain the above copyright notice, +;* this list of conditions and the following disclaimer. +;* 2. Redistributions in binary form must reproduce the above copyright notice, +;* this list of conditions and the following disclaimer in the documentation +;* and/or other materials provided with the distribution. +;* 3. Neither the name of STMicroelectronics nor the names of its contributors +;* may be used to endorse or promote products derived from this software +;* without specific prior written permission. +;* +;* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +;* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +;* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +;* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +;* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +;* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +;* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +;* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +;* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +;* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +;* +;******************************************************************************* + +__initial_sp EQU 0x20002000 ; Top of RAM + + PRESERVE8 + THUMB + + +; Vector Table Mapped to Address 0 at Reset + AREA RESET, DATA, READONLY + EXPORT __Vectors + EXPORT __Vectors_End + EXPORT __Vectors_Size + +__Vectors DCD __initial_sp ; Top of Stack + DCD Reset_Handler ; Reset Handler + DCD NMI_Handler ; NMI Handler + DCD HardFault_Handler ; Hard Fault Handler + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD SVC_Handler ; SVCall Handler + DCD DebugMon_Handler ; Debug Monitor Handler + DCD 0 ; Reserved + DCD PendSV_Handler ; PendSV Handler + DCD SysTick_Handler ; SysTick Handler + + ; External Interrupts + DCD WWDG_IRQHandler ; Window Watchdog + DCD PVD_IRQHandler ; PVD through EXTI Line detect + DCD RTC_IRQHandler ; RTC through EXTI Line + DCD FLASH_IRQHandler ; FLASH + DCD RCC_CRS_IRQHandler ; RCC and CRS + DCD EXTI0_1_IRQHandler ; EXTI Line 0 and 1 + DCD EXTI2_3_IRQHandler ; EXTI Line 2 and 3 + DCD EXTI4_15_IRQHandler ; EXTI Line 4 to 15 + DCD TSC_IRQHandler ; TSC + DCD DMA1_Channel1_IRQHandler ; DMA1 Channel 1 + DCD DMA1_Channel2_3_IRQHandler ; DMA1 Channel 2 and Channel 3 + DCD DMA1_Channel4_5_6_7_IRQHandler ; DMA1 Channel 4, Channel 5, Channel 6 and Channel 7 + DCD ADC1_COMP_IRQHandler ; ADC1, COMP1 and COMP2 + DCD LPTIM1_IRQHandler ; LPTIM1 + DCD 0 ; Reserved + DCD TIM2_IRQHandler ; TIM2 + DCD 0 ; Reserved + DCD TIM6_DAC_IRQHandler ; TIM6 and DAC + DCD 0 ; Reserved + DCD 0 ; Reserved + DCD TIM21_IRQHandler ; TIM21 + DCD 0 ; Reserved + DCD TIM22_IRQHandler ; TIM22 + DCD I2C1_IRQHandler ; I2C1 + DCD I2C2_IRQHandler ; I2C2 + DCD SPI1_IRQHandler ; SPI1 + DCD SPI2_IRQHandler ; SPI2 + DCD USART1_IRQHandler ; USART1 + DCD USART2_IRQHandler ; USART2 + DCD RNG_LPUART1_IRQHandler ; RNG and LPUART1 + DCD LCD_IRQHandler ; LCD + DCD USB_IRQHandler ; USB + +__Vectors_End + +__Vectors_Size EQU __Vectors_End - __Vectors + + AREA |.text|, CODE, READONLY + +; Reset handler routine +Reset_Handler PROC + EXPORT Reset_Handler [WEAK] + IMPORT __main + IMPORT SystemInit + LDR R0, =SystemInit + BLX R0 + LDR R0, =__main + BX R0 + ENDP + +; Dummy Exception Handlers (infinite loops which can be modified) + +NMI_Handler PROC + EXPORT NMI_Handler [WEAK] + B . + ENDP +HardFault_Handler\ + PROC + EXPORT HardFault_Handler [WEAK] + B . + ENDP +SVC_Handler PROC + EXPORT SVC_Handler [WEAK] + B . + ENDP +DebugMon_Handler\ + PROC + EXPORT DebugMon_Handler [WEAK] + B . + ENDP +PendSV_Handler PROC + EXPORT PendSV_Handler [WEAK] + B . + ENDP +SysTick_Handler PROC + EXPORT SysTick_Handler [WEAK] + B . + ENDP + +Default_Handler PROC + + EXPORT WWDG_IRQHandler [WEAK] + EXPORT PVD_IRQHandler [WEAK] + EXPORT RTC_IRQHandler [WEAK] + EXPORT FLASH_IRQHandler [WEAK] + EXPORT RCC_CRS_IRQHandler [WEAK] + EXPORT EXTI0_1_IRQHandler [WEAK] + EXPORT EXTI2_3_IRQHandler [WEAK] + EXPORT EXTI4_15_IRQHandler [WEAK] + EXPORT TSC_IRQHandler [WEAK] + EXPORT DMA1_Channel1_IRQHandler [WEAK] + EXPORT DMA1_Channel2_3_IRQHandler [WEAK] + EXPORT DMA1_Channel4_5_6_7_IRQHandler [WEAK] + EXPORT ADC1_COMP_IRQHandler [WEAK] + EXPORT LPTIM1_IRQHandler [WEAK] + EXPORT TIM2_IRQHandler [WEAK] + EXPORT TIM6_DAC_IRQHandler [WEAK] + EXPORT TIM21_IRQHandler [WEAK] + EXPORT TIM22_IRQHandler [WEAK] + EXPORT I2C1_IRQHandler [WEAK] + EXPORT I2C2_IRQHandler [WEAK] + EXPORT SPI1_IRQHandler [WEAK] + EXPORT SPI2_IRQHandler [WEAK] + EXPORT USART1_IRQHandler [WEAK] + EXPORT USART2_IRQHandler [WEAK] + EXPORT RNG_LPUART1_IRQHandler [WEAK] + EXPORT LCD_IRQHandler [WEAK] + EXPORT USB_IRQHandler [WEAK] + + +WWDG_IRQHandler +PVD_IRQHandler +RTC_IRQHandler +FLASH_IRQHandler +RCC_CRS_IRQHandler +EXTI0_1_IRQHandler +EXTI2_3_IRQHandler +EXTI4_15_IRQHandler +TSC_IRQHandler +DMA1_Channel1_IRQHandler +DMA1_Channel2_3_IRQHandler +DMA1_Channel4_5_6_7_IRQHandler +ADC1_COMP_IRQHandler +LPTIM1_IRQHandler +TIM2_IRQHandler +TIM6_DAC_IRQHandler +TIM21_IRQHandler +TIM22_IRQHandler +I2C1_IRQHandler +I2C2_IRQHandler +SPI1_IRQHandler +SPI2_IRQHandler +USART1_IRQHandler +USART2_IRQHandler +RNG_LPUART1_IRQHandler +LCD_IRQHandler +USB_IRQHandler + + B . + + ENDP + + ALIGN + END diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/TOOLCHAIN_ARM_STD/stm32l053r8.sct b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/TOOLCHAIN_ARM_STD/stm32l053r8.sct new file mode 100644 index 0000000000..f6d3c32f8a --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/TOOLCHAIN_ARM_STD/stm32l053r8.sct @@ -0,0 +1,45 @@ +; Scatter-Loading Description File +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; +; Copyright (c) 2014, STMicroelectronics +; All rights reserved. +; +; Redistribution and use in source and binary forms, with or without +; modification, are permitted provided that the following conditions are met: +; +; 1. Redistributions of source code must retain the above copyright notice, +; this list of conditions and the following disclaimer. +; 2. Redistributions in binary form must reproduce the above copyright notice, +; this list of conditions and the following disclaimer in the documentation +; and/or other materials provided with the distribution. +; 3. Neither the name of STMicroelectronics nor the names of its contributors +; may be used to endorse or promote products derived from this software +; without specific prior written permission. +; +; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +; AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +; IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +; DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +; FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +; DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +; CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +; OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; + +; STM32L053R8: 64KB FLASH (0x10000) + 8KB RAM (0x2000) +LR_IROM1 0x08000000 0x10000 { ; load region size_region + + ER_IROM1 0x08000000 0x10000 { ; load address = execution address + *.o (RESET, +First) + *(InRoot$$Sections) + .ANY (+RO) + } + + ; Total: 48 vectors = 192 bytes (0xC0) to be reserved in RAM + RW_IRAM1 (0x20000000+0xC0) (0x2000-0xC0) { ; RW data + .ANY (+RW +ZI) + } + +} + diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/TOOLCHAIN_ARM_STD/sys.cpp b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/TOOLCHAIN_ARM_STD/sys.cpp new file mode 100644 index 0000000000..bb665909b9 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/TOOLCHAIN_ARM_STD/sys.cpp @@ -0,0 +1,56 @@ +/* mbed Microcontroller Library - stackheap + * Setup a fixed single stack/heap memory model, + * between the top of the RW/ZI region and the stackpointer + ******************************************************************************* + * Copyright (c) 2014, STMicroelectronics + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ******************************************************************************* + */ + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include + +extern char Image$$RW_IRAM1$$ZI$$Limit[]; + +extern __value_in_regs struct __initial_stackheap __user_setup_stackheap(uint32_t R0, uint32_t R1, uint32_t R2, uint32_t R3) { + uint32_t zi_limit = (uint32_t)Image$$RW_IRAM1$$ZI$$Limit; + uint32_t sp_limit = __current_sp(); + + zi_limit = (zi_limit + 7) & ~0x7; // ensure zi_limit is 8-byte aligned + + struct __initial_stackheap r; + r.heap_base = zi_limit; + r.heap_limit = sp_limit; + return r; +} + +#ifdef __cplusplus +} +#endif diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/cmsis.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/cmsis.h new file mode 100644 index 0000000000..eaecefae59 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/cmsis.h @@ -0,0 +1,38 @@ +/* mbed Microcontroller Library + * A generic CMSIS include header + ******************************************************************************* + * Copyright (c) 2014, STMicroelectronics + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ******************************************************************************* + */ + +#ifndef MBED_CMSIS_H +#define MBED_CMSIS_H + +#include "stm32l0xx.h" +#include "cmsis_nvic.h" + +#endif diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/cmsis_nvic.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/cmsis_nvic.c new file mode 100644 index 0000000000..2da63fc9af --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/cmsis_nvic.c @@ -0,0 +1,55 @@ +/* mbed Microcontroller Library + * CMSIS-style functionality to support dynamic vectors + ******************************************************************************* + * Copyright (c) 2014, STMicroelectronics + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ******************************************************************************* + */ +#include "cmsis_nvic.h" + +#define NVIC_RAM_VECTOR_ADDRESS (0x20000000) // Vectors positioned at start of RAM +#define NVIC_FLASH_VECTOR_ADDRESS (0x08000000) // Initial vector position in flash + +void NVIC_SetVector(IRQn_Type IRQn, uint32_t vector) { + uint32_t *vectors = (uint32_t *)SCB->VTOR; + uint32_t i; + + // Copy and switch to dynamic vectors if the first time called + if (SCB->VTOR == NVIC_FLASH_VECTOR_ADDRESS) { + uint32_t *old_vectors = vectors; + vectors = (uint32_t*)NVIC_RAM_VECTOR_ADDRESS; + for (i=0; iVTOR = (uint32_t)NVIC_RAM_VECTOR_ADDRESS; + } + vectors[IRQn + NVIC_USER_IRQ_OFFSET] = vector; +} + +uint32_t NVIC_GetVector(IRQn_Type IRQn) { + uint32_t *vectors = (uint32_t*)SCB->VTOR; + return vectors[IRQn + NVIC_USER_IRQ_OFFSET]; +} diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/cmsis_nvic.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/cmsis_nvic.h new file mode 100644 index 0000000000..0e0ab96f82 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/cmsis_nvic.h @@ -0,0 +1,55 @@ +/* mbed Microcontroller Library + * CMSIS-style functionality to support dynamic vectors + ******************************************************************************* + * Copyright (c) 2014, STMicroelectronics + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ******************************************************************************* + */ + +#ifndef MBED_CMSIS_NVIC_H +#define MBED_CMSIS_NVIC_H + +// STM32L053R8 +// CORE: 16 vectors = 64 bytes from 0x00 to 0x3F +// MCU Peripherals: 32 vectors = 128 bytes from 0x40 to 0xBF +// Total: 48 vectors = 192 bytes (0xC0) to be reserved in RAM +#define NVIC_NUM_VECTORS 48 +#define NVIC_USER_IRQ_OFFSET 16 + +#include "cmsis.h" + +#ifdef __cplusplus +extern "C" { +#endif + +void NVIC_SetVector(IRQn_Type IRQn, uint32_t vector); +uint32_t NVIC_GetVector(IRQn_Type IRQn); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l053xx.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l053xx.h new file mode 100644 index 0000000000..9e91dbf656 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l053xx.h @@ -0,0 +1,4168 @@ +/** + ****************************************************************************** + * @file stm32l053xx.h + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief CMSIS Cortex-M0+ Device Peripheral Access Layer Header File. + * This file contains all the peripheral register's definitions, bits + * definitions and memory mapping for STM32L0xx devices. + * + * This file contains: + * - Data structures and the address mapping for all peripherals + * - Peripheral's registers declarations and bits definition + * - Macros to access peripheral’s registers hardware + * + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/** @addtogroup CMSIS + * @{ + */ + +/** @addtogroup stm32l053xx + * @{ + */ + +#ifndef __STM32L053xx_H +#define __STM32L053xx_H + +#ifdef __cplusplus + extern "C" { +#endif + + +/** @addtogroup Configuration_section_for_CMSIS + * @{ + */ +/** + * @brief Configuration of the Cortex-M0+ Processor and Core Peripherals + */ +#define __CM0PLUS_REV 0 /*!< Core Revision r0p0 */ +#define __MPU_PRESENT 1 /*!< STM32L0xx provides an MPU */ +#define __VTOR_PRESENT 1 /*!< Vector Table Register supported */ +#define __NVIC_PRIO_BITS 2 /*!< STM32L0xx uses 2 Bits for the Priority Levels */ +#define __Vendor_SysTickConfig 0 /*!< Set to 1 if different SysTick Config is used */ + + +/** + * @} + */ + +/** @addtogroup Peripheral_interrupt_number_definition + * @{ + */ + +/** + * @brief STM32L0xx Interrupt Number Definition, according to the selected device + * in @ref Library_configuration_section + */ + +/*!< Interrupt Number Definition */ +typedef enum +{ +/****** Cortex-M0 Processor Exceptions Numbers ******************************************************/ + NonMaskableInt_IRQn = -14, /*!< 2 Non Maskable Interrupt */ + HardFault_IRQn = -13, /*!< 3 Cortex-M0+ Hard Fault Interrupt */ + SVC_IRQn = -5, /*!< 11 Cortex-M0+ SV Call Interrupt */ + PendSV_IRQn = -2, /*!< 14 Cortex-M0+ Pend SV Interrupt */ + SysTick_IRQn = -1, /*!< 15 Cortex-M0+ System Tick Interrupt */ + +/****** STM32L-0 specific Interrupt Numbers *********************************************************/ + WWDG_IRQn = 0, /*!< Window WatchDog Interrupt */ + PVD_IRQn = 1, /*!< PVD through EXTI Line detect Interrupt */ + RTC_IRQn = 2, /*!< RTC through EXTI Line Interrupt */ + FLASH_IRQn = 3, /*!< FLASH Interrupt */ + RCC_CRS_IRQn = 4, /*!< RCC and CRS Interrupts */ + EXTI0_1_IRQn = 5, /*!< EXTI Line 0 and 1 Interrupts */ + EXTI2_3_IRQn = 6, /*!< EXTI Line 2 and 3 Interrupts */ + EXTI4_15_IRQn = 7, /*!< EXTI Line 4 to 15 Interrupts */ + TSC_IRQn = 8, /*!< TSC Interrupt */ + DMA1_Channel1_IRQn = 9, /*!< DMA1 Channel 1 Interrupt */ + DMA1_Channel2_3_IRQn = 10, /*!< DMA1 Channel 2 and Channel 3 Interrupts */ + DMA1_Channel4_5_6_7_IRQn = 11, /*!< DMA1 Channel 4, Channel 5, Channel 6 and Channel 7 Interrupts */ + ADC1_COMP_IRQn = 12, /*!< ADC1, COMP1 and COMP2 Interrupts */ + LPTIM1_IRQn = 13, /*!< LPTIM1 Interrupt */ + TIM2_IRQn = 15, /*!< TIM2 Interrupt */ + TIM6_DAC_IRQn = 17, /*!< TIM6 and DAC Interrupts */ + TIM21_IRQn = 20, /*!< TIM21 Interrupt */ + TIM22_IRQn = 22, /*!< TIM22 Interrupt */ + I2C1_IRQn = 23, /*!< I2C1 Interrupt */ + I2C2_IRQn = 24, /*!< I2C2 Interrupt */ + SPI1_IRQn = 25, /*!< SPI1 Interrupt */ + SPI2_IRQn = 26, /*!< SPI2 Interrupt */ + USART1_IRQn = 27, /*!< USART1 Interrupt */ + USART2_IRQn = 28, /*!< USART2 Interrupt */ + RNG_LPUART1_IRQn = 29, /*!< RNG and LPUART1 Interrupts */ + LCD_IRQn = 30, /*!< LCD Interrupts */ + USB_IRQn = 31 /*!< USB global Interrupt */ +} IRQn_Type; + +/** + * @} + */ + +#include "core_cm0plus.h" +#include "system_stm32l0xx.h" +#include + +/** @addtogroup Peripheral_registers_structures + * @{ + */ + +/** + * @brief Analog to Digital Converter + */ + +typedef struct +{ + __IO uint32_t ISR; /*!< ADC Interrupt and Status register, Address offset:0x00 */ + __IO uint32_t IER; /*!< ADC Interrupt Enable register, Address offset:0x04 */ + __IO uint32_t CR; /*!< ADC Control register, Address offset:0x08 */ + __IO uint32_t CFGR1; /*!< ADC Configuration register 1, Address offset:0x0C */ + __IO uint32_t CFGR2; /*!< ADC Configuration register 2, Address offset:0x10 */ + __IO uint32_t SMPR; /*!< ADC Sampling time register, Address offset:0x14 */ + uint32_t RESERVED1; /*!< Reserved, 0x18 */ + uint32_t RESERVED2; /*!< Reserved, 0x1C */ + __IO uint32_t TR; /*!< ADC watchdog threshold register, Address offset:0x20 */ + uint32_t RESERVED3; /*!< Reserved, 0x24 */ + __IO uint32_t CHSELR; /*!< ADC channel selection register, Address offset:0x28 */ + uint32_t RESERVED4[5]; /*!< Reserved, 0x2C */ + __IO uint32_t DR; /*!< ADC data register, Address offset:0x40 */ + uint32_t RESERVED5[28]; /*!< Reserved, 0x44 - 0xB0 */ + __IO uint32_t CALFACT; /*!< ADC data register, Address offset:0xB4 */ +} ADC_TypeDef; + +typedef struct +{ + __IO uint32_t CCR; +} ADC_Common_TypeDef; + + +/** + * @brief Comparator + */ + +typedef struct +{ + __IO uint32_t CSR; /*!< COMP comparator control and status register, Address offset: 0x18 */ +} COMP_TypeDef; + + +/** + * @brief CRC calculation unit + */ + +typedef struct +{ + __IO uint32_t DR; /*!< CRC Data register, Address offset: 0x00 */ + __IO uint8_t IDR; /*!< CRC Independent data register, Address offset: 0x04 */ + uint8_t RESERVED0; /*!< Reserved, 0x05 */ + uint16_t RESERVED1; /*!< Reserved, 0x06 */ + __IO uint32_t CR; /*!< CRC Control register, Address offset: 0x08 */ + uint32_t RESERVED2; /*!< Reserved, 0x0C */ + __IO uint32_t INIT; /*!< Initial CRC value register, Address offset: 0x10 */ + __IO uint32_t POL; /*!< CRC polynomial register, Address offset: 0x14 */ +} CRC_TypeDef; + +/** + * @brief Clock Recovery System + */ +typedef struct +{ +__IO uint32_t CR; /*!< CRS ccontrol register, Address offset: 0x00 */ +__IO uint32_t CFGR; /*!< CRS configuration register, Address offset: 0x04 */ +__IO uint32_t ISR; /*!< CRS interrupt and status register, Address offset: 0x08 */ +__IO uint32_t ICR; /*!< CRS interrupt flag clear register, Address offset: 0x0C */ +} CRS_TypeDef; + +/** + * @brief Digital to Analog Converter + */ + +typedef struct +{ + __IO uint32_t CR; /*!< DAC control register, Address offset: 0x00 */ + __IO uint32_t SWTRIGR; /*!< DAC software trigger register, Address offset: 0x04 */ + __IO uint32_t DHR12R1; /*!< DAC channel1 12-bit right-aligned data holding register, Address offset: 0x08 */ + __IO uint32_t DHR12L1; /*!< DAC channel1 12-bit left aligned data holding register, Address offset: 0x0C */ + __IO uint32_t DHR8R1; /*!< DAC channel1 8-bit right aligned data holding register, Address offset: 0x10 */ + uint32_t RESERVED0[6]; /*!< 0x14-0x28 */ + __IO uint32_t DOR1; /*!< DAC channel1 data output register, Address offset: 0x2C */ + uint32_t RESERVED1; /*!< 0x30 */ + __IO uint32_t SR; /*!< DAC status register, Address offset: 0x34 */ +} DAC_TypeDef; + +/** + * @brief Debug MCU + */ + +typedef struct +{ + __IO uint32_t IDCODE; /*!< MCU device ID code, Address offset: 0x00 */ + __IO uint32_t CR; /*!< Debug MCU configuration register, Address offset: 0x04 */ + __IO uint32_t APB1FZ; /*!< Debug MCU APB1 freeze register, Address offset: 0x08 */ + __IO uint32_t APB2FZ; /*!< Debug MCU APB2 freeze register, Address offset: 0x0C */ +}DBGMCU_TypeDef; + +/** + * @brief DMA Controller + */ + +typedef struct +{ + __IO uint32_t CCR; /*!< DMA channel x configuration register */ + __IO uint32_t CNDTR; /*!< DMA channel x number of data register */ + __IO uint32_t CPAR; /*!< DMA channel x peripheral address register */ + __IO uint32_t CMAR; /*!< DMA channel x memory address register */ +} DMA_Channel_TypeDef; + +typedef struct +{ + __IO uint32_t ISR; /*!< DMA interrupt status register, Address offset: 0x00 */ + __IO uint32_t IFCR; /*!< DMA interrupt flag clear register, Address offset: 0x04 */ +} DMA_TypeDef; + +typedef struct +{ + __IO uint32_t CSELR; /*!< DMA channel selection register, Address offset: 0xA8 */ +} DMA_Request_TypeDef; + +/** + * @brief External Interrupt/Event Controller + */ + +typedef struct +{ + __IO uint32_t IMR; /*!
© COPYRIGHT(c) 2014 STMicroelectronics
+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/** @addtogroup CMSIS + * @{ + */ + +/** @addtogroup stm32l0xx + * @{ + */ + +#ifndef __STM32L0xx_H +#define __STM32L0xx_H + +#ifdef __cplusplus + extern "C" { +#endif /* __cplusplus */ + +/** @addtogroup Library_configuration_section + * @{ + */ + +/* Uncomment the line below according to the target STM32 device used in your + application + */ + +#if !defined (STM32L051xx) && !defined (STM32L052xx) && !defined (STM32L053xx) && !defined (STM32L062xx) && \ + !defined (STM32L063xx) && !defined (STM32L061xx) + /* #define STM32L051xx */ /*!< STM32L051K8, STM32L051C6,STM32L051C8,STM32L051R6 and STM32L051R8 Devices */ + /* #define STM32L052xx */ /*!< STM32L052K6, STM32L052K8,STM32L052C6,STM32L052C8,STM32L052R6 and STM32L052R8 Devices */ +#define STM32L053xx /*!< STM32L053C6, STM32L053C8, STM32L053R6, and STM32L053R8 Devices */ + /* #define STM32L062xx */ /*!< STM32L062K8 */ + /* #define STM32L063xx */ /*!< STM32L063C8, STM32L063R8 */ + /* #define STM32L061xx */ +#endif + +/* Tip: To avoid modifying this file each time you need to switch between these + devices, you can define the device in your toolchain compiler preprocessor. + */ +#if !defined (USE_HAL_DRIVER) +/** + * @brief Comment the line below if you will not use the peripherals drivers. + In this case, these drivers will not be included and the application code will + be based on direct access to peripherals registers + */ +#define USE_HAL_DRIVER +#endif /* USE_HAL_DRIVER */ + +/** + * @brief CMSIS Device version number V1.0.0 + */ +#define __STM32L0xx_CMSIS_DEVICE_VERSION_MAIN (0x01) /*!< [31:24] main version */ +#define __STM32L0xx_CMSIS_DEVICE_VERSION_SUB1 (0x00) /*!< [23:16] sub1 version */ +#define __STM32L0xx_CMSIS_DEVICE_VERSION_SUB2 (0x00) /*!< [15:8] sub2 version */ +#define __STM32L0xx_CMSIS_DEVICE_VERSION_RC (0x00) /*!< [7:0] release candidate */ +#define __STM32L0xx_CMSIS_DEVICE_VERSION ((__CMSIS_DEVICE_VERSION_MAIN << 24)\ + |(__CMSIS_DEVICE_HAL_VERSION_SUB1 << 16)\ + |(__CMSIS_DEVICE_HAL_VERSION_SUB2 << 8 )\ + |(__CMSIS_DEVICE_HAL_VERSION_RC)) + +/** + * @} + */ + +/** @addtogroup Device_Included + * @{ + */ + +#if defined(STM32L051xx) + #include "stm32l051xx.h" +#elif defined(STM32L052xx) + #include "stm32l052xx.h" +#elif defined(STM32L053xx) + #include "stm32l053xx.h" +#elif defined(STM32L062xx) + #include "stm32l062xx.h" +#elif defined(STM32L063xx) + #include "stm32l063xx.h" +#elif defined(STM32L061xx) + #include "stm32l061xx.h" +#else + #error "Please select first the target STM32L0xx device used in your application (in stm32l0xx.h file)" +#endif + +/** + * @} + */ + +/** @addtogroup Exported_types + * @{ + */ +typedef enum +{ + RESET = 0, + SET = !RESET +} FlagStatus, ITStatus; + +typedef enum +{ + DISABLE = 0, + ENABLE = !DISABLE +} FunctionalState; +#define IS_FUNCTIONAL_STATE(STATE) (((STATE) == DISABLE) || ((STATE) == ENABLE)) + +typedef enum +{ + ERROR = 0, + SUCCESS = !ERROR +} ErrorStatus; + +/** + * @} + */ + + +/** @addtogroup Exported_macro + * @{ + */ +#define SET_BIT(REG, BIT) ((REG) |= (BIT)) + +#define CLEAR_BIT(REG, BIT) ((REG) &= ~(BIT)) + +#define READ_BIT(REG, BIT) ((REG) & (BIT)) + +#define CLEAR_REG(REG) ((REG) = (0x0)) + +#define WRITE_REG(REG, VAL) ((REG) = (VAL)) + +#define READ_REG(REG) ((REG)) + +#define MODIFY_REG(REG, CLEARMASK, SETMASK) WRITE_REG((REG), (((READ_REG(REG)) & (~(CLEARMASK))) | (SETMASK))) + + + +/** + * @} + */ + +#if defined (USE_HAL_DRIVER) + #include "stm32l0xx_hal.h" +#endif /* USE_HAL_DRIVER */ + + +#ifdef __cplusplus +} +#endif /* __cplusplus */ + +#endif /* __STM32L0xx_H */ +/** + * @} + */ + +/** + * @} + */ + + + + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal.c new file mode 100644 index 0000000000..fb30a498d2 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal.c @@ -0,0 +1,642 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal.c + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief HAL module driver. + * This is the common part of the HAL initialization + * + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + The common HAL driver contains a set of generic and common APIs that can be + used by the PPP peripheral drivers and the user to start using the HAL. + [..] + The HAL contains two APIs' categories: + (+) Common HAL APIs + (+) Services HAL APIs + + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @defgroup HAL + * @brief HAL module driver. + * @{ + */ + +#ifdef HAL_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/** + * @brief STM32L0xx HAL Driver version number V1.0.0 + */ +#define __STM32L0xx_HAL_VERSION_MAIN (0x01) /*!< [31:24] main version */ +#define __STM32L0xx_HAL_VERSION_SUB1 (0x00) /*!< [23:16] sub1 version */ +#define __STM32L0xx_HAL_VERSION_SUB2 (0x00) /*!< [15:8] sub2 version */ +#define __STM32L0xx_HAL_VERSION_RC (0x00) /*!< [7:0] release candidate */ +#define __STM32L0xx_HAL_VERSION ((__STM32L0xx_HAL_VERSION_MAIN << 24)\ + |(__STM32L0xx_HAL_VERSION_SUB1 << 16)\ + |(__STM32L0xx_HAL_VERSION_SUB2 << 8 )\ + |(__STM32L0xx_HAL_VERSION_RC)) + +#define IDCODE_DEVID_MASK ((uint32_t)0x00000FFF) +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +static __IO uint32_t uwTick; +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup HAL_Private_Functions + * @{ + */ + +/** @defgroup HAL_Group1 Initialization and de-initialization Functions + * @brief Initialization and de-initialization functions + * +@verbatim + =============================================================================== + ##### Initialization and de-initialization functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Initializes the Flash interface, the NVIC allocation and initial clock + configuration. It initializes the source of time base also when timeout + is needed and the backup domain when enabled. + (+) de-Initializes common part of the HAL. + (+) Configure The time base source to have 1ms time base with a dedicated + Tick interrupt priority. + (++) Systick timer is used by default as source of time base, but user + can eventually implement his proper time base source (a general purpose + timer for example or other time source), keeping in mind that Time base + duration should be kept 1ms since PPP_TIMEOUT_VALUEs are defined and + handled in milliseconds basis. + (++) Time base configuration function (HAL_InitTick ()) is called automatically + at the beginning of the program after reset by HAL_Init() or at any time + when clock is configured, by HAL_RCC_ClockConfig(). + (++) Source of time base is configured to generate interrupts at regular + time intervals. Care must be taken if HAL_Delay() is called from a + peripheral ISR process, the Tick interrupt line must have higher priority + (numerically lower) than the peripheral interrupt. Otherwise the caller + ISR process will be blocked. + (++) functions affecting time base configurations are declared as __Weak + to make override possible in case of other implementations in user file. + +@endverbatim + * @{ + */ + +/** + * @brief This function configures the Flash prefetch, Flash preread and Buffer cache, + * Configures time base source, NVIC and Low level hardware + * @note This function is called at the beginning of program after reset and before + * the clock configuration + * @note The time base configuration is based on MSI clock when exiting from Reset. + * Once done, time base tick start incrementing. + * In the default implementation,Systick is used as source of time base. + * the tick variable is incremented each 1ms in its ISR. + * @param None + * @retval HAL status + */ +HAL_StatusTypeDef HAL_Init(void) +{ + /* Configure Buffer cache, Flash prefetch, Flash preread */ +#if (BUFFER_CACHE_DISABLE != 0) + __HAL_FLASH_BUFFER_CACHE_DISABLE(); +#endif /* BUFFER_CACHE_DISABLE */ + +#if (PREREAD_ENABLE != 0) + __HAL_FLASH_PREREAD_BUFFER_ENABLE(); +#endif /* PREREAD_ENABLE */ + +#if (PREFETCH_ENABLE != 0) + __HAL_FLASH_PREFETCH_BUFFER_ENABLE(); +#endif /* PREFETCH_ENABLE */ + + /* Use systick as time base source and configure 1ms tick (default clock after Reset is MSI) */ + + HAL_InitTick(TICK_INT_PRIORITY); + + /* Init the low level hardware */ + HAL_MspInit(); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief This function de-Initializes common part of the HAL and stops the source + * of time base. + * @note This function is optional. + * @param None + * @retval HAL status + */ +HAL_StatusTypeDef HAL_DeInit(void) +{ + /* Reset of all peripherals */ + __APB1_FORCE_RESET(); + __APB1_RELEASE_RESET(); + + __APB2_FORCE_RESET(); + __APB2_RELEASE_RESET(); + + __AHB_FORCE_RESET(); + __AHB_RELEASE_RESET(); + + __IOP_FORCE_RESET(); + __IOP_RELEASE_RESET(); + + /* De-Init the low level hardware */ + HAL_MspDeInit(); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Initializes the MSP. + * @param None + * @retval None + */ +__weak void HAL_MspInit(void) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_MspInit could be implemented in the user file + */ +} + +/** + * @brief DeInitializes the MSP. + * @param None + * @retval None + */ +__weak void HAL_MspDeInit(void) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_MspDeInit could be implemented in the user file + */ +} + +/** + * @} + */ + +/** + * @brief This function configures the source of the time base. + * The time source is configured to have 1ms time base with a dedicated + * Tick interrupt priority. + * @note This function is called automatically at the beginning of program after + * reset by HAL_Init() or at any time when clock is reconfigured by HAL_RCC_ClockConfig(). + * @note In the default implementation, SysTick timer is the source of time base. + * It is used to generate interrupts at regular time intervals. + * Care must be taken if HAL_Delay() is called from a peripheral ISR process, + * The the SysTick interrupt must have higher priority (numerically lower) + * than the peripheral interrupt. Otherwise the caller ISR process will be blocked. + * The function is declared as __Weak to be overwritten in case of other + * implementation in user file. + * @param TickPriority: Tick interrupt priority. + * @retval HAL status + */ +__weak HAL_StatusTypeDef HAL_InitTick(uint32_t TickPriority) +{ + /*Configure the SysTick to have interrupt in 1ms time basis*/ + HAL_SYSTICK_Config(HAL_RCC_GetHCLKFreq()/1000); + + /*Configure the SysTick IRQ priority */ + HAL_NVIC_SetPriority(SysTick_IRQn, TickPriority ,0); + + /* Return function status */ + return HAL_OK; +} + +/** @defgroup HAL_Group2 HAL Control functions + * @brief HAL Control functions + * +@verbatim + =============================================================================== + ##### HAL Control functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Provide a tick value in millisecond + (+) Provide a blocking delay in millisecond + (+) Suspend the time base source interrupt + (+) Resume the time base source interrupt + (+) Get the HAL API driver version + (+) Get the device identifier + (+) Get the device revision identifier + (+) Configures low power mode behavior when the MCU is in Debug mode + +@endverbatim + * @{ + */ + +/** + * @brief This function is called to increment a global variable "uwTick" + * used as application time base. + * @note In the default implementation, this variable is incremented each 1ms + * in Systick ISR. + * @note This function is declared as __weak to be overwritten in case of other + * implementations in user file. + * @param None + * @retval None + */ +__weak void HAL_IncTick(void) +{ + uwTick++; +} + +/** + * @brief Provides a tick value in millisecond. + * @note This function is declared as __weak to be overwritten in case of other + * implementations in user file. + * @param None + * @retval tick value + */ +__weak uint32_t HAL_GetTick(void) +{ + return uwTick; +} + +/** + * @brief This function provides accurate delay (in milliseconds) based + * on variable incremented. + * @note In the default implementation , SysTick timer is the source of time base. + * It is used to generate interrupts at regular time intervals where uwTick + * is incremented. + * @note ThiS function is declared as __weak to be overwritten in case of other + * implementations in user file. + * @param Delay: specifies the delay time length, in milliseconds. + * @retval None + */ +__weak void HAL_Delay(__IO uint32_t Delay) +{ + uint32_t tickstart = 0; + tickstart = HAL_GetTick(); + while((HAL_GetTick() - tickstart) < Delay) + { + } +} + +/** + * @brief Suspend Tick increment. + * @note In the default implementation , SysTick timer is the source of time base. It is + * used to generate interrupts at regular time intervals. Once HAL_SuspendTick() + * is called, the the SysTick interrupt will be disabled and so Tick increment + * is suspended. + * @note This function is declared as __weak to be overwritten in case of other + * implementations in user file. + * @param None + * @retval None + */ +__weak void HAL_SuspendTick(void) +{ + /* Disable SysTick Interrupt */ + SysTick->CTRL &= ~SysTick_CTRL_TICKINT_Msk; +} + +/** + * @brief Resume Tick increment. + * @note In the default implementation , SysTick timer is the source of time base. It is + * used to generate interrupts at regular time intervals. Once HAL_ResumeTick() + * is called, the the SysTick interrupt will be enabled and so Tick increment + * is resumed. + * @note This function is declared as __weak to be overwritten in case of other + * implementations in user file. + * @param None + * @retval None + */ +__weak void HAL_ResumeTick(void) +{ + /* Enable SysTick Interrupt */ + SysTick->CTRL |= SysTick_CTRL_TICKINT_Msk; +} + +/** + * @brief Returns the HAL revision + * @param None + * @retval version: 0xXYZR (8bits for each decimal, R for RC) + */ +uint32_t HAL_GetHalVersion(void) +{ + return __STM32L0xx_HAL_VERSION; +} + +/** + * @brief Returns the device revision identifier. + * @param None + * @retval Device revision identifier + */ +uint32_t HAL_GetREVID(void) +{ + return((DBGMCU->IDCODE) >> 16); +} + +/** + * @brief Returns the device identifier. + * @param None + * @retval Device identifier + */ +uint32_t HAL_GetDEVID(void) +{ + return((DBGMCU->IDCODE) & IDCODE_DEVID_MASK); +} + +/** + * @brief Configures low power mode behavior when the MCU is in Debug mode. + * @param Periph: specifies the low power mode. + * This parameter can be any combination of the following values: + * @arg DBGMCU_SLEEP: Keep debugger connection during SLEEP mode + * @arg DBGMCU_STOP: Keep debugger connection during STOP mode + * @arg DBGMCU_STANDBY: Keep debugger connection during STANDBY mode + * @param NewState: new state of the specified low power mode in Debug mode. + * This parameter can be: ENABLE or DISABLE. + * @retval None + */ +void HAL_DBG_LowPowerConfig(uint32_t Periph, FunctionalState NewState) +{ + /* Check the parameters */ + assert_param(IS_DBGMCU_PERIPH(Periph)); + assert_param(IS_FUNCTIONAL_STATE(NewState)); + if (NewState != DISABLE) + { + DBGMCU->CR |= Periph; + } + else + { + DBGMCU->CR &= ~Periph; + } +} + +/** + * @brief Returns the boot mode as configured by user. + * @param None. + * @retval The boot mode as configured by user. The returned value can be one + * of the following values: + * - 0x00000000: Boot is configured in Main Flash memory + * - 0x00000100: Boot is configured in System Flash memory + * - 0x00000300: Boot is configured in Embedded SRAM memory + */ +uint32_t HAL_GetBootMode(void) +{ + return (SYSCFG->CFGR1 & SYSCFG_CFGR1_BOOT_MODE); +} + +/** + * @brief Configures the I2C fast mode plus driving capability. + * @param SYSCFG_I2CFastModePlus: selects the pin. + * This parameter can be one of the following values: + * @arg SYSCFG_I2CFastModePlus_PB6: Configure fast mode plus driving capability for PB6 + * @arg SYSCFG_I2CFastModePlus_PB7: Configure fast mode plus driving capability for PB7 + * @arg SYSCFG_I2CFastModePlus_PB8: Configure fast mode plus driving capability for PB8 + * @arg SYSCFG_I2CFastModePlus_PB9: Configure fast mode plus driving capability for PB9 + * @arg SYSCFG_I2CFastModePlus_I2C1: Configure fast mode plus driving capability for I2C1 pins + * @arg SYSCFG_I2CFastModePlus_I2C2: Configure fast mode plus driving capability for I2C2 pins + * @param NewState: This parameter can be: + * @arg ENABLE: Enable fast mode plus driving capability for selected I2C pin + * @arg DISABLE: Disable fast mode plus driving capability for selected I2C pin + * @note For I2C1, fast mode plus driving capability can be enabled on all selected + * I2C1 pins using SYSCFG_I2CFastModePlus_I2C1 parameter or independently + * on each one of the following pins PB6, PB7, PB8 and PB9. + * @note For remaining I2C1 pins (PA14, PA15...) fast mode plus driving capability + * can be enabled only by using SYSCFG_I2CFastModePlus_I2C1 parameter. + * @note For all I2C2 pins fast mode plus driving capability can be enabled + * only by using SYSCFG_I2CFastModePlus_I2C2 parameter. + * @retval None + */ +void HAL_I2CFastModePlusConfig(uint32_t SYSCFG_I2CFastModePlus, FunctionalState NewState) +{ + /* Check the parameters */ + assert_param(IS_SYSCFG_I2C_FMP(SYSCFG_I2CFastModePlus)); + assert_param(IS_FUNCTIONAL_STATE(NewState)); + + if (NewState != DISABLE) + { + /* Enable fast mode plus driving capability for selected pin */ + SYSCFG->CFGR2 |= (uint32_t)SYSCFG_I2CFastModePlus; + } + else + { + /* Disable fast mode plus driving capability for selected pin */ + SYSCFG->CFGR2 &= (uint32_t)(~SYSCFG_I2CFastModePlus); + } +} + +/** + * @brief Enables or disables the VREFINT. + * @param NewState: new state of the Vrefint. + * This parameter can be: ENABLE or DISABLE. + * @retval None + */ +void HAL_VREFINT_Cmd(FunctionalState NewState) +{ + /* Check the parameters */ + assert_param(IS_FUNCTIONAL_STATE(NewState)); + + if (NewState != DISABLE) + { + /* Enable the VREFINT by setting EN_VREFINT bit in the CFGR3 register */ + SYSCFG->CFGR3 |= SYSCFG_CFGR3_EN_VREFINT; + } + else + { + /* Disable the VREFINT by setting EN_VREFINT bit in the CFGR3 register */ + SYSCFG->CFGR3 &= (uint32_t)~((uint32_t)SYSCFG_CFGR3_EN_VREFINT); + } +} + +/** + * @brief Selects the output of internal reference voltage (VREFINT). + * The VREFINT output can be routed to(PB0) or + * (PB1) or both. + * @param SYSCFG_Vrefint_OUTPUT: new state of the Vrefint output. + * This parameter can be one of the following values: + * @arg SYSCFG_VREFINT_OUT_NONE + * @arg SYSCFG_VREFINT_OUT_PB0 + * @arg SYSCFG_VREFINT_OUT_PB1 + * @arg SYSCFG_VREFINT_OUT_PB0_PB1 + * @retval None + */ +void HAL_VREFINT_OutputSelect(uint32_t SYSCFG_Vrefint_OUTPUT) +{ + /* Check the parameters */ + assert_param(IS_SYSCFG_VREFINT_OUT_SELECT(SYSCFG_Vrefint_OUTPUT)); + + /* Set the output Vrefint pin */ + SYSCFG->CFGR3 &= ~(SYSCFG_CFGR3_VREF_OUT); + SYSCFG->CFGR3 |= (uint32_t)(SYSCFG_Vrefint_OUTPUT); +} + +/** + * @brief Enables or disables the Buffer Vrefint for the ADC. + * @param NewState: new state of the Vrefint. + * This parameter can be: ENABLE or DISABLE. + * @note This is functional only if the LOCK is not set + * @retval None + */ +void HAL_ADC_EnableBuffer_Cmd(FunctionalState NewState) +{ + /* Check the parameters */ + assert_param(IS_FUNCTIONAL_STATE(NewState)); + + if (NewState != DISABLE) + { + /* Enable the Buffer for the ADC by setting EN_VREFINT bit and the ENBUF_VREFINT_ADC in the CFGR3 register */ + SYSCFG->CFGR3 |= (SYSCFG_CFGR3_ENBUF_VREFINT_ADC | SYSCFG_CFGR3_EN_VREFINT); + } + else + { + /* Disable the Vrefint by resetting ENBUF_BGAP_ADC bit and the EN_VREFINT bit in the CFGR3 register */ + SYSCFG->CFGR3 &= (uint32_t)~((uint32_t)(SYSCFG_CFGR3_ENBUF_VREFINT_ADC | SYSCFG_CFGR3_EN_VREFINT)); + } +} + +/** + * @brief Enables or disables the Buffer Sensor for the ADC. + * @param NewState: new state of the Vrefint. + * This parameter can be: ENABLE or DISABLE. + * @note This is functional only if the LOCK is not set. + * @retval None + */ +void HAL_ADC_EnableBufferSensor_Cmd(FunctionalState NewState) +{ + /* Check the parameters */ + assert_param(IS_FUNCTIONAL_STATE(NewState)); + + if (NewState != DISABLE) + { + /* Enable the Buffer for the ADC by setting EN_VREFINT bit and the ENBUF_SENSOR_ADC in the CFGR3 register */ + SYSCFG->CFGR3 |= (SYSCFG_CFGR3_ENBUF_SENSOR_ADC | SYSCFG_CFGR3_EN_VREFINT); + } + else + { + /* Disable the Vrefint by resetting EN_VREFINT bit and the ENBUF_SENSOR_ADC in the CFGR3 register */ + SYSCFG->CFGR3 &= (uint32_t)~((uint32_t)(SYSCFG_CFGR3_ENBUF_SENSOR_ADC | SYSCFG_CFGR3_EN_VREFINT)); + } +} + +/** + * @brief Enables or disables the Buffer Vrefint for the COMP. + * @param NewState: new state of the Vrefint. + * This parameter can be: ENABLE or DISABLE. + * @note This is functional only if the LOCK is not set + * @retval None + */ +void HAL_COMP_EnableBuffer_Cmd(FunctionalState NewState) +{ + /* Check the parameters */ + assert_param(IS_FUNCTIONAL_STATE(NewState)); + + if (NewState != DISABLE) + { + /* Enable the Buffer for the COMP by setting EN_VREFINT bit and the ENBUFLP_VREFINT_COMP in the CFGR3 register */ + SYSCFG->CFGR3 |= (SYSCFG_CFGR3_ENBUFLP_VREFINT_COMP | SYSCFG_CFGR3_EN_VREFINT); + } + else + { + /* Disable the Vrefint by resetting ENBUFLP_BGAP_COMP bit and the EN_VREFINT bit in the CFGR3 register */ + SYSCFG->CFGR3 &= (uint32_t)~((uint32_t)(SYSCFG_CFGR3_ENBUFLP_VREFINT_COMP | SYSCFG_CFGR3_EN_VREFINT)); + } +} + +/** + * @brief Enables or disables the Buffer Vrefint for the RC48. + * @param NewState: new state of the Vrefint. + * This parameter can be: ENABLE or DISABLE. + * @note This is functional only if the LOCK is not set + * @retval None + */ +void HAL_RC48_EnableBuffer_Cmd(FunctionalState NewState) +{ + /* Check the parameters */ + assert_param(IS_FUNCTIONAL_STATE(NewState)); + + if (NewState != DISABLE) + { + /* Enable the Buffer for the ADC by setting EN_VREFINT bit and the SYSCFG_CFGR3_ENREF_HSI48 in the CFGR3 register */ + SYSCFG->CFGR3 |= (SYSCFG_CFGR3_ENREF_HSI48 | SYSCFG_CFGR3_EN_VREFINT); + } + else + { + /* Disable the Vrefint by resetting SYSCFG_CFGR3_ENREF_HSI48 bit and the EN_VREFINT bit in the CFGR3 register */ + SYSCFG->CFGR3 &= (uint32_t)~((uint32_t)(SYSCFG_CFGR3_ENREF_HSI48 | SYSCFG_CFGR3_EN_VREFINT)); + } +} + +/** + * @brief Enables or disables the Lock. + * @param NewState: new state of the Lock. + * This parameter can be: ENABLE or DISABLE. + * @retval None + */ +void HAL_Lock_Cmd(FunctionalState NewState) +{ + /* Check the parameters */ + assert_param(IS_FUNCTIONAL_STATE(NewState)); + + if (NewState != DISABLE) + { + /* Enable the LOCK by setting REF_LOCK bit in the CFGR3 register */ + SYSCFG->CFGR3 |= SYSCFG_CFGR3_REF_LOCK; + } + else + { + /* Disable the LOCK by setting REF_LOCK bit in the CFGR3 register */ + SYSCFG->CFGR3 &= (uint32_t)~((uint32_t)SYSCFG_CFGR3_REF_LOCK); + } +} + +/** + * @} + */ + +/** + * @} + */ + +#endif /* HAL_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal.h new file mode 100644 index 0000000000..851730cb55 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal.h @@ -0,0 +1,235 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal.h + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief This file contains all the functions prototypes for the HAL + * module driver. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32L0xx_HAL_H +#define __STM32L0xx_HAL_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal_conf.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @addtogroup HAL + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/* Exported constants --------------------------------------------------------*/ +/** @defgroup HAL_Exported_Constants + * @{ + */ + +/** @defgroup DBGMCU_Low_Power_Config + * @{ + */ +#define DBGMCU_SLEEP DBGMCU_CR_DBG_SLEEP +#define DBGMCU_STOP DBGMCU_CR_DBG_STOP +#define DBGMCU_STANDBY DBGMCU_CR_DBG_STANDBY +#define IS_DBGMCU_PERIPH(PERIPH) ((((PERIPH) & 0xFFFFFFF8) == 0x00) && ((PERIPH) != 0x00)) + +/** + * @} + */ + + +/** @defgroup SYSCFG_I2C_FastModePlus_Config + * @{ + */ +#define SYSCFG_I2CFastModePlus_PB6 SYSCFG_CFGR2_I2C_PB6_FMP /* Enable Fast Mode Plus on PB6 */ +#define SYSCFG_I2CFastModePlus_PB7 SYSCFG_CFGR2_I2C_PB7_FMP /* Enable Fast Mode Plus on PB7 */ +#define SYSCFG_I2CFastModePlus_PB8 SYSCFG_CFGR2_I2C_PB8_FMP /* Enable Fast Mode Plus on PB8 */ +#define SYSCFG_I2CFastModePlus_PB9 SYSCFG_CFGR2_I2C_PB9_FMP /* Enable Fast Mode Plus on PB9 */ +#define SYSCFG_I2CFastModePlus_I2C1 SYSCFG_CFGR2_I2C1_FMP /*!< Enable Fast Mode Plus on I2C1 pins */ +#define SYSCFG_I2CFastModePlus_I2C2 SYSCFG_CFGR2_I2C2_FMP /*!< Enable Fast Mode Plus on I2C2 pins */ + +#define IS_SYSCFG_I2C_FMP(PIN) (((PIN) == SYSCFG_I2CFastModePlus_PB6) || \ + ((PIN) == SYSCFG_I2CFastModePlus_PB7) || \ + ((PIN) == SYSCFG_I2CFastModePlus_PB8) || \ + ((PIN) == SYSCFG_I2CFastModePlus_PB9) || \ + ((PIN) == SYSCFG_I2CFastModePlus_I2C1) || \ + ((PIN) == SYSCFG_I2CFastModePlus_I2C2)) + +/** + * @} + */ + +/** @defgroup SYSCFG_VREFINT_OUT_SELECT + * @{ + */ +#define SYSCFG_VREFINT_OUT_NONE ((uint32_t)0x00000000) /* no pad connected */ +#define SYSCFG_VREFINT_OUT_PB0 SYSCFG_CFGR3_VREF_OUT_0 /* Selects PBO as output for the Vrefint */ +#define SYSCFG_VREFINT_OUT_PB1 SYSCFG_CFGR3_VREF_OUT_1 /* Selects PB1 as output for the Vrefint */ +#define SYSCFG_VREFINT_OUT_PB0_PB1 SYSCFG_CFGR3_VREF_OUT /* Selects PBO and PB1 as output for the Vrefint */ + +#define IS_SYSCFG_VREFINT_OUT_SELECT(OUTPUT) (((OUTPUT) == SYSCFG_VREFINT_OUT_PB0) || \ + ((OUTPUT) == SYSCFG_VREFINT_OUT_PB1) || \ + ((OUTPUT) == SYSCFG_VREFINT_OUT_PB0_PB1)) + +/** + * @} + */ + +/** @defgroup SYSCFG_flags_definition + * @{ + */ + +#define SYSCFG_FLAG_RC48 SYSCFG_CFGR3_REF_HSI48_RDYF +#define SYSCFG_FLAG_SENSOR_ADC SYSCFG_CFGR3_SENSOR_ADC_RDYF +#define SYSCFG_FLAG_VREF_ADC SYSCFG_VREFINT_ADC_RDYF +#define SYSCFG_FLAG_VREF_COMP SYSCFG_CFGR3_VREFINT_COMP_RDYF +#define SYSCFG_FLAG_VREF_READY SYSCFG_CFGR3_VREFINT_RDYF + +#define IS_SYSCFG_FLAG(FLAG) (((FLAG) == SYSCFG_FLAG_RC48) || \ + ((FLAG) == SYSCFG_FLAG_SENSOR_ADC) || \ + ((FLAG) == SYSCFG_FLAG_VREF_ADC) || \ + ((FLAG) == SYSCFG_FLAG_VREF_COMP) || \ + ((FLAG) == SYSCFG_FLAG_VREF_READY)) + +/** + * @} + */ +/* Exported macro ------------------------------------------------------------*/ + +/** @brief Freeze/Unfreeze Peripherals in Debug mode + */ +#define __HAL_FREEZE_TIM2_DBGMCU() (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_TIM2_STOP)) +#define __HAL_FREEZE_TIM6_DBGMCU() (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_TIM6_STOP)) +#define __HAL_FREEZE_RTC_DBGMCU() (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_RTC_STOP)) +#define __HAL_FREEZE_WWDG_DBGMCU() (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_WWDG_STOP)) +#define __HAL_FREEZE_IWDG_DBGMCU() (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_IWDG_STOP)) +#define __HAL_FREEZE_I2C1_TIMEOUT_DBGMCU() (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_I2C1_STOP)) +#define __HAL_FREEZE_I2C2_TIMEOUT_DBGMCU() (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_I2C2_STOP)) +#define __HAL_FREEZE_LPTIMER_DBGMCU() (DBGMCU->APB1FZ |= (DBGMCU_APB1_FZ_DBG_LPTIMER_STOP)) +#define __HAL_FREEZE_TIM22_DBGMCU() (DBGMCU->APB2FZ |= (DBGMCU_APB2_FZ_DBG_TIM22_STOP)) +#define __HAL_FREEZE_TIM21_DBGMCU() (DBGMCU->APB2FZ |= (DBGMCU_APB2_FZ_DBG_TIM21_STOP)) + +#define __HAL_UNFREEZE_TIM2_DBGMCU() (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_TIM2_STOP)) +#define __HAL_UNFREEZE_TIM6_DBGMCU() (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_TIM6_STOP)) +#define __HAL_UNFREEZE_RTC_DBGMCU() (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_RTC_STOP)) +#define __HAL_UNFREEZE_WWDG_DBGMCU() (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_WWDG_STOP)) +#define __HAL_UNFREEZE_IWDG_DBGMCU() (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_IWDG_STOP)) +#define __HAL_UNFREEZE_I2C1_TIMEOUT_DBGMCU() (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_I2C1_STOP)) +#define __HAL_UNFREEZE_I2C2_TIMEOUT_DBGMCU() (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_I2C2_STOP)) +#define __HAL_UNFREEZE_LPTIMER_DBGMCU() (DBGMCU->APB1FZ &= ~(DBGMCU_APB1_FZ_DBG_LPTIMER_STOP)) +#define __HAL_UNFREEZE_TIM22_DBGMCU() (DBGMCU->APB2FZ &= ~(DBGMCU_APB2_FZ_DBG_TIM22_STOP)) +#define __HAL_UNFREEZE_TIM21_DBGMCU() (DBGMCU->APB2FZ &= ~(DBGMCU_APB2_FZ_DBG_TIM21_STOP)) + +/** @brief Main Flash memory mapped at 0x00000000 + */ +#define __HAL_REMAPMEMORY_FLASH (SYSCFG->CFGR1 &= ~(SYSCFG_CFGR1_MEM_MODE)) + +/** @brief System Flash memory mapped at 0x00000000 + */ +#define __HAL_REMAPMEMORY_SYSTEMFLASH do {SYSCFG->MEMRMP &= ~(SYSCFG_CFGR1_MEM_MODE);\ + SYSCFG->MEMRMP |= SYSCFG_CFGR1_MEM_MODE_0;\ + }while(0); + +/** @brief Embedded SRAM mapped at 0x00000000 + */ +#define __HAL_REMAPMEMORY_SRAM do {SYSCFG->CFGR1 &= ~(SYSCFG_CFGR1_MEM_MODE);\ + SYSCFG->CFGR1 |= (SYSCFG_CFGR1_MEM_MODE_0 | SYSCFG_CFGR1_MEM_MODE_1);\ + }while(0); + +/** @brief Check whether the specified SYSCFG flag is set or not. + * @param __FLAG__: specifies the flag to check. + * This parameter can be one of the following values: + * SYSCFG_FLAG_PE: SRAM parity error flag. + * @arg SYSCFG_FLAG_RC48 + * @arg SYSCFG_FLAG_SENSOR_ADC + * @arg SYSCFG_FLAG_VREF_ADC + * @arg SYSCFG_FLAG_VREF_COMP + * @arg SYSCFG_FLAG_VREF_READY + * @retval The new state of __FLAG__ (TRUE or FALSE). + */ +#define __HAL_SYSCFG_GET_FLAG(__FLAG__) (((SYSCFG->CFGR3) & (__FLAG__)) == (__FLAG__)) + +/** + * @} + */ +/* Exported functions --------------------------------------------------------*/ + +/* Initialization and de-initialization functions ******************************/ +HAL_StatusTypeDef HAL_Init(void); +HAL_StatusTypeDef HAL_DeInit(void); +void HAL_MspInit(void); +void HAL_MspDeInit(void); +HAL_StatusTypeDef HAL_InitTick (uint32_t TickPriority); + +/* Peripheral Control functions ************************************************/ +void HAL_IncTick(void); +void HAL_Delay(__IO uint32_t Delay); +uint32_t HAL_GetTick(void); +void HAL_SuspendTick(void); +void HAL_ResumeTick(void); +uint32_t HAL_GetHalVersion(void); +uint32_t HAL_GetREVID(void); +uint32_t HAL_GetDEVID(void); + +void HAL_DBG_LowPowerConfig(uint32_t Periph, FunctionalState NewState); +uint32_t HAL_GetBootMode(void); +void HAL_I2CFastModePlusConfig(uint32_t SYSCFG_I2CFastModePlus, FunctionalState NewState); +void HAL_VREFINT_Cmd(FunctionalState NewState); +void HAL_VREFINT_OutputSelect(uint32_t SYSCFG_Vrefint_OUTPUT); +void HAL_ADC_EnableBuffer_Cmd(FunctionalState NewState); +void HAL_ADC_EnableBufferSensor_Cmd(FunctionalState NewState); +void HAL_COMP_EnableBuffer_Cmd(FunctionalState NewState); +void HAL_RC48_EnableBuffer_Cmd(FunctionalState NewState); +void HAL_Lock_Cmd(FunctionalState NewState); + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __STM32L0xx_HAL_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_adc.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_adc.c new file mode 100644 index 0000000000..a16421993c --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_adc.c @@ -0,0 +1,1605 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_adc.c + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief This file provides firmware functions to manage the following + * functionalities of the Analog to Digital Convertor (ADC) + * peripheral: + * + Initialization and de-initialization functions + * ++ Initialization and Configuration of ADC + * + Operation functions + * ++ Start, stop, get result of conversions of regular + * groups, using 3 possible modes : polling, interruption or DMA. + * ++ Calibration feature + * + Control functions + * ++ Analog Watchdog configuration + * ++ Regular Channels Configuration + * + State functions + * ++ ADC state machine management + * ++ Interrupts and flags management + * + @verbatim + ============================================================================== + ##### ADC specific features ##### + ============================================================================== + [..] + (#) 12-bit, 10-bit, 8-bit or 6-bit configurable resolution. + + (#) A built-in hardware oversampler allows to improve analog performances + while off-loading the related computational burden from the CPU. + + (#) Interrupt generation at the end of conversionand in case of analog + watchdog or overrun events. + + (#) Single and continuous conversion modes. + + (#) Scan or dicontinuous mode conversion of channel 0 to channel 18. + + (#) Configurable scan direction (Upward from channel 0 to 18 or Backward from + channel 18 to channel 0) + + (#) Data alignment with in-built data coherency. + + (#) Channel-wise programmable sampling time. + + (#) External trigger option with configurable polarity. + + (#) DMA request generation during regular channel conversion. + + (#) ADC supply requirements: 2.4 V to 3.6 V at full speed and down to 1.8 V at + slower speed. + + (#) ADC input range: VREF–=VIN =VREF+. + + (#) ADC self-calibration. + + (#) ADC is automatically powered off (AutoOff mode) except during the active + conversion phase. This dramatically reduces the power consumption of the + ADC. + + (#) Wait mode to prevent ADC overrun in applications with low frequency. + + + ##### How to use this driver ##### + ============================================================================== + [..] + + (#) Enable the ADC interface + As prerequisite, into HAL_ADC_MspInit(), ADC clock must be configured + at RCC top level. + + Depending on both possible clock sources: PCLK clock or ADC asynchronous + clock. + __ADC1_CLK_ENABLE(); + + + (#) ADC pins configuration + (++) Enable the clock for the ADC GPIOs using the following function: + __GPIOx_CLK_ENABLE(); + (++) Configure these ADC pins in analog mode using HAL_GPIO_Init(); + + (#) Configure the ADC parameters (conversion resolution, oversampler, + data alignment, continuous mode,...) using the HAL_ADC_Init() function. + + (#) Activate the ADC peripheral using one of the start functions: + HAL_ADC_Start(), HAL_ADC_Start_IT() or HAL_ADC_Start_DMA() + + *** Channels configuration *** + =============================== + [..] + (+) To configure the ADC channels group, use HAL_ADC_ConfigChannel() function. + (+) To read the ADC converted values, use the HAL_ADC_GetValue() function. + + *** DMA feature configuration *** + ================================= + [..] + (+) To enable the DMA mode, use the HAL_ADC_Start_DMA() function. + (+) To enable the generation of DMA requests continuously at the end of + the last DMA transfer, set .Init.DMAContinuousRequests to ENABLE and + call HAL_ADC_Init() function. + + + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @addtogroup ADC + * @brief ADC driver modules + * @{ + */ + +#ifdef HAL_ADC_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +static HAL_StatusTypeDef ADC_Enable(ADC_HandleTypeDef* hadc); +static void ADC_DMAConvCplt(DMA_HandleTypeDef *hdma); +static void ADC_DMAHalfConvCplt(DMA_HandleTypeDef *hdma); +static void ADC_DMAError(DMA_HandleTypeDef *hdma); +static HAL_StatusTypeDef ADC_ConversionStop(ADC_HandleTypeDef* hadc, uint32_t ConversionGroup); +static HAL_StatusTypeDef ADC_Disable(ADC_HandleTypeDef* hadc); + +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup ADC_Private_Functions + * @{ + */ + +/** @defgroup ADC_Group1 Initialization/de-initialization functions + * @brief Initialization and Configuration functions + * +@verbatim + =============================================================================== + ##### Initialization and de-initialization functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Initialize and configure the ADC. + (+) De-initialize the ADC. + +@endverbatim + * @{ + */ + + +/** + * @brief Initializes the ADCx peripheral according to the specified parameters + * in the ADC_InitStruct. + * @note This function is used to configure the global features of the ADC + * (ClockPrescaler, Resolution, Data Alignment and number of conversion), however, + * the rest of the configuration parameters are specific to the regular + * channels group (scan mode activation, continuous mode activation, + * External trigger source and edge, DMA continuous request after the + * last transfer and End of conversion selection). + * + * As prerequisite, into HAL_ADC_MspInit(), ADC clock must be + * configured at RCC top level. + * See commented example code below that can be copied + * and uncommented into HAL_ADC_MspInit(). + * + * @param hadc: pointer to a ADC_HandleTypeDef structure that contains + * the configuration information for the specified ADC. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_ADC_Init(ADC_HandleTypeDef* hadc) +{ + uint32_t tickstart = 0x00; + + /* Check ADC handle */ + if(hadc == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance)); + assert_param(IS_ADC_CLOCKPRESCALER(hadc->Init.ClockPrescaler)); + assert_param(IS_ADC_RESOLUTION(hadc->Init.Resolution)); + assert_param(IS_ADC_SAMPLE_TIME(hadc->Init.SamplingTime)); + assert_param(IS_ADC_SCAN_DIRECTION(hadc->Init.ScanDirection)); + assert_param(IS_ADC_DATA_ALIGN(hadc->Init.DataAlign)); + assert_param(IS_FUNCTIONAL_STATE(hadc->Init.ContinuousConvMode)); + assert_param(IS_FUNCTIONAL_STATE(hadc->Init.DiscontinuousConvMode)); + assert_param(IS_ADC_EXTTRIG_EDGE(hadc->Init.ExternalTrigConvEdge)); + assert_param(IS_ADC_EXTERNAL_TRIG_CONV(hadc->Init.ExternalTrigConv)); + assert_param(IS_FUNCTIONAL_STATE(hadc->Init.DMAContinuousRequests)); + assert_param(IS_ADC_EOC_SELECTION(hadc->Init.EOCSelection)); + assert_param(IS_ADC_OVERRUN(hadc->Init.Overrun)); + assert_param(IS_FUNCTIONAL_STATE(hadc->Init.LowPowerAutoWait)); + assert_param(IS_FUNCTIONAL_STATE(hadc->Init.LowPowerFrequencyMode)); + assert_param(IS_FUNCTIONAL_STATE(hadc->Init.LowPowerAutoOff)); + assert_param(IS_FUNCTIONAL_STATE(hadc->Init.OversamplingMode)); + + if(hadc->State == HAL_ADC_STATE_RESET) + { + /* Init the low level hardware */ + HAL_ADC_MspInit(hadc); + } + + /* Initialize the ADC state */ + hadc->State = HAL_ADC_STATE_BUSY; + + /* Configuration of ADC clock: clock source PCLK or asynchronous with + selectable prescaler */ + __HAL_ADC_CLOCK_PRESCALER(hadc); + + /* Set the Low Frequency mode */ + ADC->CCR &= (uint32_t)~ADC_CCR_LFMEN; + ADC->CCR |=__HAL_ADC_CCR_LOWFREQUENCY(hadc->Init.LowPowerFrequencyMode); + + /* Enable voltage regulator (if disabled at this step) */ + if (HAL_IS_BIT_CLR(hadc->Instance->CR, ADC_CR_ADVREGEN)) + { + /* Note: The software must wait for the startup time of the ADC voltage */ + /* regulator before launching a calibration or enabling the ADC. */ + /* This temporization must be implemented by software and is equal */ + /* to 10 µs in the worst case process/temperature/power supply. */ + + /* Disable the ADC (if not already disabled) */ + if (__HAL_ADC_IS_ENABLED(hadc) != RESET ) + { + /* Check if conditions to disable the ADC are fulfilled */ + if (__HAL_ADC_DISABLING_CONDITIONS(hadc) != RESET) + { + __HAL_ADC_DISABLE(hadc); + } + else + { + hadc->State= HAL_ADC_STATE_ERROR; + + /* Process unlocked */ + __HAL_UNLOCK(hadc); + + return HAL_ERROR; + } + + /* Get timeout */ + tickstart = HAL_GetTick(); + + /* Wait for disabling completion */ + while(HAL_IS_BIT_SET(hadc->Instance->CR, ADC_CR_ADEN)) + { + /* Check for the Timeout */ + if(ADC_ENABLE_TIMEOUT != HAL_MAX_DELAY) + { + if((HAL_GetTick() - tickstart ) > ADC_DISABLE_TIMEOUT) + { + hadc->State= HAL_ADC_STATE_TIMEOUT; + + /* Process unlocked */ + __HAL_UNLOCK(hadc); + + return HAL_TIMEOUT; + } + } + } + + } + + /* Set ADVREGEN bit */ + hadc->Instance->CR |= ADC_CR_ADVREGEN; + /* Delay of 10 µs minimum (value from design, cf reference manual) */ + /* Delay fixed to worst case: maximum CPU frequency */ + HAL_Delay(10); + } + + /* Configuration of ADC: */ + /* - Resolution */ + /* - Data alignment */ + /* - Scan directio */ + /* - External trigger to start conversion */ + /* - External trigger polarity */ + /* - Continuous conversion mode */ + /* - DMA continuous request */ + /* - Overrun */ + /* - AutoDelay feature */ + /* - Discontinuous mode */ + hadc->Instance->CFGR1 &= ~( ADC_CFGR1_RES | + ADC_CFGR1_ALIGN | + ADC_CFGR1_SCANDIR | + ADC_CFGR1_EXTSEL | + ADC_CFGR1_EXTEN | + ADC_CFGR1_CONT | + ADC_CFGR1_DMACFG | + ADC_CFGR1_OVRMOD | + ADC_CFGR1_AUTDLY | + ADC_CFGR1_AUTOFF | + ADC_CFGR1_DISCEN); + + hadc->Instance->CFGR1 |= ( hadc->Init.Resolution | + hadc->Init.DataAlign | + hadc->Init.ScanDirection | + hadc->Init.ExternalTrigConvEdge | + __HAL_ADC_CFGR1_CONTINUOUS(hadc->Init.ContinuousConvMode) | + __HAL_ADC_CFGR1_DMAContReq(hadc->Init.DMAContinuousRequests) | + hadc->Init.Overrun | + __HAL_ADC_CFGR1_AutoDelay(hadc->Init.LowPowerAutoWait) | + __HAL_ADC_CFGR1_AUTOFF(hadc->Init.LowPowerAutoOff)); + + /* Configure the external trigger only if Conversion edge is not "NONE" */ + if (hadc->Init.ExternalTrigConvEdge != ADC_EXTERNALTRIG_EDGE_NONE) + { + hadc->Instance->CFGR1 |= hadc->Init.ExternalTrigConv; + } + + /* Enable discontinuous mode only if continuous mode is disabled */ + if ((hadc->Init.DiscontinuousConvMode == ENABLE) && (hadc->Init.ContinuousConvMode == DISABLE)) + { + /* Enable the selected ADC discontinuous mode */ + hadc->Instance->CFGR1 |= ( ADC_CFGR1_DISCEN); + } + + if (hadc->Init.OversamplingMode == ENABLE) + { + assert_param(IS_ADC_OVERSAMPLING_RATIO(hadc->Init.Oversample.Ratio)); + assert_param(IS_ADC_RIGHT_BIT_SHIFT(hadc->Init.Oversample.RightBitShift)); + assert_param(IS_ADC_TRIGGERED_OVERSAMPLING_MODE(hadc->Init.Oversample.TriggeredMode)); + + /* Configuration of Oversampler: */ + /* - Oversampling Ratio */ + /* - Right bit shift */ + /* - Triggered mode */ + + hadc->Instance->CFGR2 &= ~( ADC_CFGR2_OVSR | + ADC_CFGR2_OVSS | + ADC_CFGR2_TOVS ); + + hadc->Instance->CFGR2 |= ( hadc->Init.Oversample.Ratio | + hadc->Init.Oversample.RightBitShift | + hadc->Init.Oversample.TriggeredMode ); + + /* Enable OverSampling mode */ + hadc->Instance->CFGR2 |= ADC_CFGR2_OVSE; + } + else + { + /* Disable OverSampling mode */ + hadc->Instance->CFGR2 &= ~ADC_CFGR2_OVSE; + } + + /* Clear the old sampling time */ + hadc->Instance->SMPR &= (uint32_t)(~ADC_SMPR_SMPR); + + /* Set the new sample time */ + hadc->Instance->SMPR |= hadc->Init.SamplingTime; + + + /* Set ADC error code to none */ + hadc->ErrorCode = HAL_ADC_ERROR_NONE; + + /* Initialize the ADC state */ + hadc->State = HAL_ADC_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Deinitialize the ADC peripheral registers to its default reset values. + * @note To not impact other ADCs, reset of common ADC registers have been + * left commented below. + * If needed, the example code can be copied and uncommented into + * function HAL_ADC_MspDeInit(). + * @param hadc: pointer to a ADC_HandleTypeDef structure that contains + * the configuration information for the specified ADC. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_ADC_DeInit(ADC_HandleTypeDef* hadc) +{ + uint32_t tickstart = 0; + + /* Check ADC handle */ + if(hadc == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance)); + + /* Change ADC state */ + hadc->State = HAL_ADC_STATE_BUSY; + + /* Stop potential conversion ongoing */ + if (HAL_IS_BIT_SET(hadc->Instance->CR, ADC_CR_ADSTART) && HAL_IS_BIT_CLR(hadc->Instance->CR, ADC_CR_ADDIS)) + { + /* Stop regular conversion */ + hadc->Instance->CR |= ADC_CR_ADSTP; + } + + /* Disable ADC: Solution to recover from an unknown ADC state (for example, */ + /* in case of forbidden action on register bits) */ + /* Procedure to disable the ADC peripheral: wait for conversions */ + /* effectively stopped, then disable ADC */ + /* 1. Wait until ADSTART = 0 */ + + /* Get timeout */ + tickstart = HAL_GetTick(); + + while(HAL_IS_BIT_SET(hadc->Instance->CR, ADC_CR_ADSTART)) + { + /* Check for the Timeout */ + if(ADC_STOP_CONVERSION_TIMEOUT != HAL_MAX_DELAY) + { + if((HAL_GetTick() - tickstart ) > ADC_STOP_CONVERSION_TIMEOUT) + { + hadc->State= HAL_ADC_STATE_TIMEOUT; + + /* Process unlocked */ + __HAL_UNLOCK(hadc); + + return HAL_TIMEOUT; + } + } + } + + /* 2. Disable the ADC peripheral */ + __HAL_ADC_DISABLE(hadc); + + + /* Reset ADC registers****************/ + /* Reset register IER */ + __HAL_ADC_DISABLE_IT(hadc, (ADC_IT_AWD | ADC_IT_OVR | ADC_IT_EOCAL | ADC_IT_EOS | \ + ADC_IT_EOC | ADC_IT_RDY | ADC_IT_EOSMP )); + + /* Reset register ISR */ + __HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_AWD | ADC_FLAG_EOCAL | ADC_FLAG_OVR | ADC_FLAG_EOS | \ + ADC_FLAG_EOC | ADC_FLAG_EOSMP | ADC_FLAG_RDY)); + + /* Reset register CR */ + /* Disable voltage regulator */ + /* Note: Regulator disable useful for power saving */ + /* Reset ADVREGEN bit */ + hadc->Instance->CR &= ~ADC_CR_ADVREGEN; + + /* Bits ADC_CR_ADSTP, ADC_CR_ADSTART are in access mode "read-set": no direct reset applicable */ + /* No action */ + + /* Reset register CFGR1 */ + hadc->Instance->CFGR1 &= ~(ADC_CFGR1_AWDCH | ADC_CFGR1_AWDEN | ADC_CFGR1_AWDSGL | \ + ADC_CFGR1_DISCEN | ADC_CFGR1_AUTOFF | ADC_CFGR1_AUTDLY | \ + ADC_CFGR1_CONT | ADC_CFGR1_OVRMOD | ADC_CFGR1_EXTEN | \ + ADC_CFGR1_EXTSEL | ADC_CFGR1_ALIGN | ADC_CFGR1_RES | \ + ADC_CFGR1_SCANDIR| ADC_CFGR1_DMACFG | ADC_CFGR1_DMAEN); + + /* Reset register CFGR2 */ + hadc->Instance->CFGR2 &= ~(ADC_CFGR2_TOVS | ADC_CFGR2_OVSS | ADC_CFGR2_OVSR | \ + ADC_CFGR2_OVSE | ADC_CFGR2_CKMODE ); + + /* Reset register SMPR */ + hadc->Instance->SMPR &= ~(ADC_SMPR_SMPR); + + /* Reset register TR */ + hadc->Instance->TR &= ~(ADC_TR_LT | ADC_TR_HT); + + /* Reset register CALFACT */ + hadc->Instance->CALFACT &= ~(ADC_CALFACT_CALFACT); + + /* Reset register DR */ + /* bits in access mode read only, no direct reset applicable*/ + + /* Reset register CALFACT */ + hadc->Instance->CALFACT &= ~(ADC_CALFACT_CALFACT); + + + /* DeInit the low level hardware */ + HAL_ADC_MspDeInit(hadc); + + /* Set ADC error code to none */ + hadc->ErrorCode = HAL_ADC_ERROR_NONE; + + /* Change ADC state */ + hadc->State = HAL_ADC_STATE_RESET; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Initializes the ADC MSP. + * @param hadc: pointer to a ADC_HandleTypeDef structure that contains + * the configuration information for the specified ADC. + * @retval None + */ +__weak void HAL_ADC_MspInit(ADC_HandleTypeDef* hadc) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_ADC_MspInit could be implemented in the user file + */ +} + +/** + * @brief DeInitializes the ADC MSP. + * @param hadc: pointer to a ADC_HandleTypeDef structure that contains + * the configuration information for the specified ADC. + * @retval None + */ +__weak void HAL_ADC_MspDeInit(ADC_HandleTypeDef* hadc) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_ADC_MspDeInit could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup ADC_Group2 I/O operation functions + * @brief I/O operation functions + * +@verbatim + =============================================================================== + ##### IO operation functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Start conversion. + (+) Stop conversion. + (+) poll for conversion complete. + (+) poll for conversion event. + (+) Start conversion and enable interrupt. + (+) Stop conversion and disable interrupt. + (+) handle ADC interrupt request. + (+) Start conversion of regular channel and enable DMA transfer. + (+) Stop conversion of regular channel and disable DMA transfer. + (+) Get result of regular channel conversion. + (+) Handle ADC interrupt request. + +@endverbatim + * @{ + */ + + +/** + * @brief Enables ADC and starts conversion of the regular channels. + * @param hadc: pointer to a ADC_HandleTypeDef structure that contains + * the configuration information for the specified ADC. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_ADC_Start(ADC_HandleTypeDef* hadc) +{ + HAL_StatusTypeDef tmpHALStatus = HAL_OK; + + /* Check the parameters */ + assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance)); + + /* Process locked */ + __HAL_LOCK(hadc); + + /* Change ADC state */ + hadc->State = HAL_ADC_STATE_BUSY_REG; + + /* Set ADC error code to none */ + hadc->ErrorCode = HAL_ADC_ERROR_NONE; + + /* Enable ADC */ + tmpHALStatus = ADC_Enable(hadc); + + /* Start conversion if ADC is effectively enabled */ + if (tmpHALStatus != HAL_ERROR) + { + /* ADC start conversion command */ + hadc->Instance->CR |= ADC_CR_ADSTART; + } + + /* Process unlocked */ + __HAL_UNLOCK(hadc); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stop ADC conversion of regular channels, disable ADC peripheral. + * @param hadc: pointer to a ADC_HandleTypeDef structure that contains + * the configuration information for the specified ADC. + * @retval None + */ +HAL_StatusTypeDef HAL_ADC_Stop(ADC_HandleTypeDef* hadc) +{ + HAL_StatusTypeDef tmpHALStatus = HAL_OK; + + /* Process locked */ + __HAL_LOCK(hadc); + + /* 1. Stop potential conversion ongoing (regular conversion) */ + tmpHALStatus = ADC_ConversionStop(hadc, REGULAR_GROUP); + + /* 2. Disable ADC peripheral if conversions are effectively stopped */ + if (tmpHALStatus != HAL_ERROR) + { + /* Disable the ADC peripheral */ + ADC_Disable(hadc); + + /* Check if ADC is effectively disabled */ + if (hadc->State != HAL_ADC_STATE_ERROR) + { + /* Change ADC state */ + hadc->State = HAL_ADC_STATE_READY; + } + else + { + return HAL_ERROR; + } + } + else + { + return HAL_ERROR; + } + + /* Process unlocked */ + __HAL_UNLOCK(hadc); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Poll for conversion complete. + * @param hadc: pointer to a ADC_HandleTypeDef structure that contains + * the configuration information for the specified ADC. + * @param Timeout: Timeout value in millisecond. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_ADC_PollForConversion(ADC_HandleTypeDef* hadc, uint32_t Timeout) +{ + uint32_t tickstart = 0; + uint32_t tmp_Flag_EOC; + + /* Check the parameters */ + assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance)); + + /* If interruption after each sequence */ + if (hadc->Init.EOCSelection == EOC_SEQ_CONV) + { + tmp_Flag_EOC = ADC_FLAG_EOS; + } + /* If interruption after each conversion */ + else /* EOC_SINGLE_CONV */ + { + tmp_Flag_EOC = (ADC_FLAG_EOC | ADC_FLAG_EOS); + } + + /* Get timeout */ + tickstart = HAL_GetTick(); + + /* Wait until End of Conversion flag is raised */ + while(HAL_IS_BIT_CLR(hadc->Instance->ISR, tmp_Flag_EOC)) + { + /* Check for the Timeout */ + if(Timeout != HAL_MAX_DELAY) + { + if((int32_t) (HAL_GetTick() - tickstart ) > Timeout) + { + hadc->State= HAL_ADC_STATE_TIMEOUT; + + /* Process unlocked */ + __HAL_UNLOCK(hadc); + + return HAL_TIMEOUT; + } + } + } + + /* Clear end of conversion flag of regular group if low power feature */ + /* "LowPowerAutoWait " is disabled, to not interfere with this feature */ + /* until data register is read using function HAL_ADC_GetValue(). */ + if (hadc->Init.LowPowerAutoWait == DISABLE) + { + /* Clear regular group conversion flag */ + __HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_EOC | ADC_FLAG_EOS)); + } + + /* Change ADC state */ + hadc->State = HAL_ADC_STATE_EOC; + + /* Return ADC state */ + return HAL_OK; +} + +/** + * @brief Poll for conversion event. + * @param hadc: ADC handle. + * @param EventType: the ADC event type. + * This parameter can be one of the following values: + * @arg AWD_EVENT: ADC Analog watchdog event. + * @arg OVR_EVENT: ADC Overrun event. + * @param Timeout: Timeout value in millisecond. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_ADC_PollForEvent(ADC_HandleTypeDef* hadc, uint32_t EventType, uint32_t Timeout) +{ + uint32_t tickstart = 0; + + /* Check the parameters */ + assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance)); + assert_param(IS_ADC_EVENT_TYPE(EventType)); + + /* Get timeout */ + tickstart = HAL_GetTick(); + + /* Check selected event flag */ + while(!(__HAL_ADC_GET_FLAG(hadc,EventType))) + { + /* Check if timeout is disabled (set to infinite wait) */ + if(Timeout != HAL_MAX_DELAY) + { + if((HAL_GetTick() - tickstart ) > Timeout) + { + /* Update ADC state machine to timeout */ + hadc->State = HAL_ADC_STATE_TIMEOUT; + + /* Process unlocked */ + __HAL_UNLOCK(hadc); + + return HAL_TIMEOUT; + } + } + } + + switch(EventType) + { + /* Check analog watchdog flag */ + case AWD_EVENT: + /* Change ADC state */ + hadc->State = HAL_ADC_STATE_AWD; + + /* Clear ADC analog watchdog flag */ + __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_AWD); + break; + + /* Case OVR_EVENT */ + default: + /* Change ADC state */ + hadc->State = HAL_ADC_STATE_ERROR; + + /* Clear ADC Overrun flag */ + __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_OVR); + break; + } + + /* Return ADC state */ + return HAL_OK; +} + +/** + * @brief Enables the interrupt and starts ADC conversion of regular channels. + * @param hadc: pointer to a ADC_HandleTypeDef structure that contains + * the configuration information for the specified ADC. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_ADC_Start_IT(ADC_HandleTypeDef* hadc) +{ + HAL_StatusTypeDef tmpHALStatus = HAL_OK; + + /* Check the parameters */ + assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance)); + + /* Process locked */ + __HAL_LOCK(hadc); + + /* State machine update: Change ADC state */ + hadc->State = HAL_ADC_STATE_BUSY_REG; + + /* Set ADC error code to none */ + hadc->ErrorCode = HAL_ADC_ERROR_NONE; + + /* Enable the ADC peripheral */ + tmpHALStatus = ADC_Enable(hadc); + + /* Start conversion if ADC is effectively enabled */ + if (tmpHALStatus != HAL_ERROR) + { + /* Enable ADC overrun interrupt */ + __HAL_ADC_ENABLE_IT(hadc, ADC_IT_OVR); + + /* Enable ADC end of conversion interrupt */ + switch(hadc->Init.EOCSelection) + { + case EOC_SEQ_CONV: + __HAL_ADC_DISABLE_IT(hadc, ADC_IT_EOC); + __HAL_ADC_ENABLE_IT(hadc, ADC_IT_EOS); + break; + /* case EOC_SINGLE_CONV */ + default: + __HAL_ADC_DISABLE_IT(hadc, ADC_IT_EOS); + __HAL_ADC_ENABLE_IT(hadc, ADC_IT_EOC); + break; + } + + /* ADC start conversion command */ + hadc->Instance->CR |= ADC_CR_ADSTART; + } + + else + { + return HAL_ERROR; + } + + /* Process unlocked */ + __HAL_UNLOCK(hadc); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stop ADC conversion of regular channels, disable interruptions + * EOC/EOS/OVR, disable ADC peripheral. + * @param hadc: pointer to a ADC_HandleTypeDef structure that contains + * the configuration information for the specified ADC. + * @retval None + */ +HAL_StatusTypeDef HAL_ADC_Stop_IT(ADC_HandleTypeDef* hadc) +{ + HAL_StatusTypeDef tmpHALStatus = HAL_OK; + + /* Process locked */ + __HAL_LOCK(hadc); + + /* 1. Stop potential conversion ongoing (regular conversion) */ + tmpHALStatus = ADC_ConversionStop(hadc, REGULAR_GROUP); + + /* 2. Disable ADC peripheral if conversions are effectively stopped */ + if (tmpHALStatus != HAL_ERROR) + { + /* Disable ADC interrupts */ + __HAL_ADC_DISABLE_IT(hadc, (ADC_IT_EOC | ADC_IT_EOS | ADC_IT_OVR)); + + /* Disable the ADC peripheral */ + ADC_Disable(hadc); + + /* Check if ADC is effectively disabled */ + if (hadc->State != HAL_ADC_STATE_ERROR) + { + /* Change ADC state */ + hadc->State = HAL_ADC_STATE_READY; + } + else + { + return HAL_ERROR; + } + } + else + { + return HAL_ERROR; + } + + + /* Process unlocked */ + __HAL_UNLOCK(hadc); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Handles ADC interrupt request + * @param hadc: pointer to a ADC_HandleTypeDef structure that contains + * the configuration information for the specified ADC. + * @retval None + */ +void HAL_ADC_IRQHandler(ADC_HandleTypeDef* hadc) +{ + /* Check the parameters */ + assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance)); + assert_param(IS_ADC_EOC_SELECTION(hadc->Init.EOCSelection)); + + + /* Check End of Conversion flag for regular channels */ + if( (__HAL_ADC_GET_FLAG(hadc, ADC_FLAG_EOC) && __HAL_ADC_GET_IT_SOURCE(hadc, ADC_IT_EOC)) || \ + (__HAL_ADC_GET_FLAG(hadc, ADC_FLAG_EOS) && __HAL_ADC_GET_IT_SOURCE(hadc, ADC_IT_EOS)) ) + { + /* Change ADC state */ + hadc->State = HAL_ADC_STATE_EOC; + + + /* Disable interruption if no further conversion upcoming by continuous mode or external trigger */ + if((hadc->Init.ContinuousConvMode == DISABLE) && \ + (hadc->Init.ExternalTrigConvEdge == ADC_EXTERNALTRIG_EDGE_NONE) + ) + { + /* Allowed to modify bits ADC_IT_EOC/ADC_IT_EOS only if bit ADSTART==0 (no conversion on going) */ + if (HAL_IS_BIT_CLR(hadc->Instance->CR, ADC_CR_ADSTART)) + { + /* Cases of interruption after each conversion or after each sequence */ + /* If interruption after each sequence */ + if (hadc->Init.EOCSelection == EOC_SEQ_CONV) + { + /* If End of Sequence is reached, disable interrupts */ + if( __HAL_ADC_GET_FLAG(hadc, ADC_FLAG_EOS) ) + { + /* DISABLE ADC end of sequence conversion interrupt */ + /* DISABLE ADC overrun interrupt */ + __HAL_ADC_DISABLE_IT(hadc, ADC_IT_EOC | ADC_IT_EOS | ADC_IT_OVR); + } + } + /* If interruption after each conversion */ + else + { + /* DISABLE ADC end of single conversion interrupt */ + /* DISABLE ADC overrun interrupt */ + __HAL_ADC_DISABLE_IT(hadc, ADC_IT_EOC | ADC_IT_OVR); + } + } + else + { + /* Change ADC state to error state */ + hadc->State = HAL_ADC_STATE_ERROR; + } + } + + /* Conversion complete callback */ + /* Note: into callback, to determine if callback has been triggered from EOC or EOS, */ + /* it is possible to use: if( __HAL_ADC_GET_FLAG(hadc, ADC_FLAG_EOS)) */ + HAL_ADC_ConvCpltCallback(hadc); + + /* Clear regular channels conversion flag */ + if (hadc->Init.LowPowerAutoWait != ENABLE) + { + __HAL_ADC_CLEAR_FLAG(hadc, (ADC_FLAG_EOC | ADC_FLAG_EOS) ); + } + } + + + /* Check Analog watchdog flags */ + if( (__HAL_ADC_GET_FLAG(hadc, ADC_FLAG_AWD) && __HAL_ADC_GET_IT_SOURCE(hadc, ADC_IT_AWD))) + { + /* Change ADC state */ + hadc->State = HAL_ADC_STATE_AWD; + + /* Level out of window callback */ + HAL_ADC_LevelOutOfWindowCallback(hadc); + + /* Clear ADC Analog watchdog flag */ + __HAL_ADC_CLEAR_FLAG(hadc, ADC_FLAG_AWD); + } + + /* Check Overrun flag */ + if(__HAL_ADC_GET_FLAG(hadc, ADC_FLAG_OVR) && __HAL_ADC_GET_IT_SOURCE(hadc, ADC_IT_OVR)) + { + /* Change ADC state to overrun state */ + hadc->State = HAL_ADC_STATE_ERROR; + + /* Set ADC error code to overrun */ + hadc->ErrorCode |= HAL_ADC_ERROR_OVR; + + /* Clear the Overrun flag */ + __HAL_ADC_CLEAR_FLAG(hadc,ADC_FLAG_OVR); + + /* Error callback */ + HAL_ADC_ErrorCallback(hadc); + } +} + +/** + * @brief Enables ADC DMA request after last transfer (Single-ADC mode) and enables ADC peripheral + * @param hadc: pointer to a ADC_HandleTypeDef structure that contains + * the configuration information for the specified ADC. + * @param pData: The destination Buffer address. + * @param Length: The length of data to be transferred from ADC peripheral to memory. + * @retval None + */ +HAL_StatusTypeDef HAL_ADC_Start_DMA(ADC_HandleTypeDef* hadc, uint32_t* pData, uint32_t Length) +{ + HAL_StatusTypeDef tmpHALStatus = HAL_OK; + + /* Check the parameters */ + assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance)); + + /* Process locked */ + __HAL_LOCK(hadc); + + /* Change ADC state */ + hadc->State = HAL_ADC_STATE_BUSY_REG; + + /* Set ADC error code to none */ + hadc->ErrorCode = HAL_ADC_ERROR_NONE; + + /* Enable ADC */ + tmpHALStatus = ADC_Enable(hadc); + + /* Start conversion if ADC is effectively enabled */ + if (tmpHALStatus != HAL_ERROR) + { + /* Enable ADC DMA mode */ + hadc->Instance->CFGR1 |= ADC_CFGR1_DMAEN; + + /* Set the DMA transfer complete callback */ + hadc->DMA_Handle->XferCpltCallback = ADC_DMAConvCplt; + + /* Set the DMA half transfer complete callback */ + hadc->DMA_Handle->XferHalfCpltCallback = ADC_DMAHalfConvCplt; + + /* Set the DMA error callback */ + hadc->DMA_Handle->XferErrorCallback = ADC_DMAError; + + /* Manage ADC and DMA start: ADC overrun interruption, DMA start, + ADC start (in case of SW start) */ + + /* Enable ADC overrun interrupt */ + __HAL_ADC_ENABLE_IT(hadc, ADC_IT_OVR); + + /* Enable the DMA Stream */ + HAL_DMA_Start_IT(hadc->DMA_Handle, (uint32_t)&hadc->Instance->DR, (uint32_t)pData, Length); + + + /* ADC start conversion command */ + hadc->Instance->CR |= ADC_CR_ADSTART; + } + + /* Process unlocked */ + __HAL_UNLOCK(hadc); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Disable ADC DMA (Single-ADC mode), disable ADC peripheral + * @param hadc: pointer to a ADC_HandleTypeDef structure that contains + * the configuration information for the specified ADC. + * @retval None + */ +HAL_StatusTypeDef HAL_ADC_Stop_DMA(ADC_HandleTypeDef* hadc) +{ + HAL_StatusTypeDef tmpHALStatus = HAL_OK; + + /* Process locked */ + __HAL_LOCK(hadc); + + /* 1. Stop potential conversion ongoing (regular conversion) */ + tmpHALStatus = ADC_ConversionStop(hadc, REGULAR_GROUP); + + /* 2. Disable ADC peripheral if conversions are effectively stopped */ + if (tmpHALStatus != HAL_ERROR) + { + /* Disable ADC DMA (ADC DMA configuration ADC_CFGR_DMACFG is kept) */ + hadc->Instance->CFGR1 &= ~ADC_CFGR1_DMAEN; + + /* Disable the DMA Stream */ + if (HAL_DMA_Abort(hadc->DMA_Handle) != HAL_OK) + { + /* Update ADC state machine to error */ + hadc->State = HAL_ADC_STATE_ERROR; + + /* Process unlocked */ + __HAL_UNLOCK(hadc); + + return HAL_ERROR; + } + + /* Disable ADC overrun interrupt */ + __HAL_ADC_DISABLE_IT(hadc, ADC_IT_OVR); + + /* Disable the ADC peripheral */ + ADC_Disable(hadc); + + /* Check if ADC is effectively disabled */ + if (hadc->State != HAL_ADC_STATE_ERROR) + { + /* Change ADC state */ + hadc->State = HAL_ADC_STATE_READY; + } + else + { + return HAL_ERROR; + } + } + else + { + return HAL_ERROR; + } + + /* Process unlocked */ + __HAL_UNLOCK(hadc); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Gets the converted value from data register of regular channel. + * @param hadc: pointer to a ADC_HandleTypeDef structure that contains + * the configuration information for the specified ADC. + * @retval Converted value + */ +uint32_t HAL_ADC_GetValue(ADC_HandleTypeDef* hadc) +{ + /* Return the selected ADC converted value */ + return hadc->Instance->DR; +} + +/** + * @brief Regular conversion complete callback in non blocking mode + * @param hadc: pointer to a ADC_HandleTypeDef structure that contains + * the configuration information for the specified ADC. + * @retval None + */ +__weak void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef* hadc) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_ADC_ConvCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Regular conversion half DMA transfer callback in non blocking mode + * @param hadc: pointer to a ADC_HandleTypeDef structure that contains + * the configuration information for the specified ADC. + * @retval None + */ +__weak void HAL_ADC_ConvHalfCpltCallback(ADC_HandleTypeDef* hadc) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_ADC_ConvHalfCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Analog watchdog callback in non blocking mode + * @param hadc: pointer to a ADC_HandleTypeDef structure that contains + * the configuration information for the specified ADC. + * @retval None + */ +__weak void HAL_ADC_LevelOutOfWindowCallback(ADC_HandleTypeDef* hadc) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_ADC_LevelOoutOfWindowCallback could be implemented in the user file + */ +} + +/** + * @brief Error ADC callback. + * @param hadc: pointer to a ADC_HandleTypeDef structure that contains + * the configuration information for the specified ADC. + * @retval None + */ +__weak void HAL_ADC_ErrorCallback(ADC_HandleTypeDef *hadc) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_ADC_ErrorCallback could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup ADC_Group3 Peripheral Control functions + * @brief Peripheral Control functions + * +@verbatim + =============================================================================== + ##### Peripheral Control functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Configure channels. + (+) Configure the analog watch dog. + +@endverbatim + * @{ + */ + + +/** + * @brief Configures the selected ADC regular channel: sampling time, + * offset,. + * @param hadc: pointer to a ADC_HandleTypeDef structure that contains + * the configuration information for the specified ADC. + * @param sConfig: ADC regular channel configuration structure. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_ADC_ConfigChannel(ADC_HandleTypeDef* hadc, ADC_ChannelConfTypeDef* sConfig) +{ + + /* Check the parameters */ + assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance)); + assert_param(IS_ADC_CHANNEL(sConfig->Channel)); + + /* Process locked */ + __HAL_LOCK(hadc); + + /* Enable selected channels */ + hadc->Instance->CHSELR |= (uint32_t)(sConfig->Channel & ADC_CHANNEL_MASK); + + /* Management of internal measurement channels: Vlcd/VrefInt/TempSensor */ + /* internal measurement paths enable: If internal channel selected, enable */ + /* dedicated internal buffers and path. */ + + /* If Temperature sensor channel is selected, then enable the internal */ + /* buffers and path */ + if (((sConfig->Channel & ADC_CHANNEL_MASK) & ADC_CHANNEL_TEMPSENSOR ) == (ADC_CHANNEL_TEMPSENSOR & ADC_CHANNEL_MASK)) + { + ADC->CCR |= ADC_CCR_TSEN; + } + + /* If VRefInt channel is selected, then enable the internal buffers and path */ + if (((sConfig->Channel & ADC_CHANNEL_MASK) & ADC_CHANNEL_VREFINT) == (ADC_CHANNEL_VREFINT & ADC_CHANNEL_MASK)) + { + ADC->CCR |= ADC_CCR_VREFEN; + } + + /* If Vlcd channel is selected, then enable the internal buffers and path */ + if (((sConfig->Channel & ADC_CHANNEL_MASK) & ADC_CHANNEL_VLCD) == (ADC_CHANNEL_VLCD & ADC_CHANNEL_MASK)) + { + ADC->CCR |= ADC_CCR_VLCDEN; + } + + /* Process unlocked */ + __HAL_UNLOCK(hadc); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Configures the analog watchdog. + * @param hadc: pointer to a ADC_HandleTypeDef structure that contains + * the configuration information for the specified ADC. + * @param AnalogWDGConfig : pointer to an ADC_AnalogWDGConfTypeDef structure + * that contains the configuration information of ADC analog watchdog. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_ADC_AnalogWDGConfig(ADC_HandleTypeDef* hadc, ADC_AnalogWDGConfTypeDef* AnalogWDGConfig) +{ + uint32_t tmpAWDHighThresholdShifted; + uint32_t tmpAWDLowThresholdShifted; + + /* Check the parameters */ + assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance)); + assert_param(IS_ADC_ANALOG_WATCHDOG_MODE(AnalogWDGConfig->WatchdogMode)); + assert_param(IS_ADC_CHANNEL(AnalogWDGConfig->Channel)); + assert_param(IS_FUNCTIONAL_STATE(AnalogWDGConfig->ITMode)); + + assert_param(IS_ADC_RANGE(__HAL_ADC_GET_RESOLUTION(hadc), AnalogWDGConfig->HighThreshold)); + assert_param(IS_ADC_RANGE(__HAL_ADC_GET_RESOLUTION(hadc), AnalogWDGConfig->LowThreshold)); + + /* Process locked */ + __HAL_LOCK(hadc); + + /* Configure ADC Analog watchdog interrupt */ + if(AnalogWDGConfig->ITMode == ENABLE) + { + /* Enable the ADC Analog watchdog interrupt */ + __HAL_ADC_ENABLE_IT(hadc, ADC_IT_AWD); + } + else + { + /* Disable the ADC Analog watchdog interrupt */ + __HAL_ADC_DISABLE_IT(hadc, ADC_IT_AWD); + } + + /* Configuration of analog watchdog: */ + /* - Set the analog watchdog mode */ + /* - Set the Analog watchdog channel (is not used if watchdog */ + /* mode "all channels": ADC_CFGR1_AWD1SGL=0) */ + hadc->Instance->CFGR1 &= ~( ADC_CFGR1_AWDSGL | + ADC_CFGR1_AWDEN | + ADC_CFGR1_AWDCH ); + + hadc->Instance->CFGR1 |= ( AnalogWDGConfig->WatchdogMode | + (AnalogWDGConfig->Channel & ADC_CHANNEL_AWD_MASK)); + + + /* Shift the offset in function of the selected ADC resolution: Thresholds */ + /* have to be left-aligned on bit 11, the LSB (right bits) are set to 0 */ + tmpAWDHighThresholdShifted = __HAL_ADC_AWD1Threshold_shift_resolution(hadc, AnalogWDGConfig->HighThreshold); + tmpAWDLowThresholdShifted = __HAL_ADC_AWD1Threshold_shift_resolution(hadc, AnalogWDGConfig->LowThreshold); + + /* Clear High & Low high thresholds */ + hadc->Instance->TR &= (uint32_t) ~ (ADC_TR_HT | ADC_TR_LT); + + /* Set the high threshold */ + hadc->Instance->TR = __HAL_ADC_TRx_HighThreshold (tmpAWDHighThresholdShifted); + /* Set the low threshold */ + hadc->Instance->TR |= tmpAWDLowThresholdShifted; + + /* Process unlocked */ + __HAL_UNLOCK(hadc); + + /* Return function status */ + return HAL_OK; +} + +/** + * @} + */ + +/** @defgroup ADC_Group4 ADC Peripheral State functions + * @brief ADC Peripheral State functions + * +@verbatim + =============================================================================== + ##### ADC Peripheral State functions ##### + =============================================================================== + [..] + This subsection provides functions allowing to + (+) Check the ADC state. + (+) handle ADC interrupt request. + +@endverbatim + * @{ + */ + +/** + * @brief return the ADC state + * @param hadc: pointer to a ADC_HandleTypeDef structure that contains + * the configuration information for the specified ADC. + * @retval HAL state + */ +HAL_ADC_StateTypeDef HAL_ADC_GetState(ADC_HandleTypeDef* hadc) +{ + /* Return ADC state */ + return hadc->State; +} + +/** + * @brief Return the ADC error code + * @param hadc: pointer to a ADC_HandleTypeDef structure that contains + * the configuration information for the specified ADC. + * @retval ADC Error Code + */ +uint32_t HAL_ADC_GetError(ADC_HandleTypeDef *hadc) +{ + return hadc->ErrorCode; +} + + +/** + * @} + */ + +/** + * @brief Enable the selected ADC. + * @note Prerequisite condition to use this function: ADC must be disabled + * and voltage regulator must be enabled (done into HAL_ADC_Init()). + * @param hadc: ADC handle + * @retval HAL status. + */ +static HAL_StatusTypeDef ADC_Enable(ADC_HandleTypeDef* hadc) +{ + uint32_t tickstart = 0; + + /* ADC enable and wait for ADC ready (in case of ADC is disabled or */ + /* enabling phase not yet completed: flag ADC ready not yet set). */ + /* Timeout implemented to not be stuck if ADC cannot be enabled (possible */ + /* causes: ADC clock not running, ...). */ + if (__HAL_ADC_IS_ENABLED(hadc) == RESET) + { + /* Check if conditions to enable the ADC are fulfilled */ + if (__HAL_ADC_ENABLING_CONDITIONS(hadc) == RESET) + { + /* Update ADC state machine to error */ + hadc->State = HAL_ADC_STATE_ERROR; + + /* Set ADC error code to ADC IP internal error */ + hadc->ErrorCode |= HAL_ADC_ERROR_INTERNAL; + + return HAL_ERROR; + } + + /* Enable the ADC peripheral */ + __HAL_ADC_ENABLE(hadc); + + /* Wait for ADC effectively enabled */ + /* Get timeout */ + tickstart = HAL_GetTick(); + + while(__HAL_ADC_GET_FLAG(hadc, ADC_FLAG_RDY) == RESET) + { + /* Check for the Timeout */ + if(ADC_ENABLE_TIMEOUT != HAL_MAX_DELAY) + { + if((HAL_GetTick() - tickstart ) > ADC_ENABLE_TIMEOUT) + { + /* Update ADC state machine to error */ + hadc->State = HAL_ADC_STATE_ERROR; + + /* Set ADC error code to ADC IP internal error */ + hadc->ErrorCode |= HAL_ADC_ERROR_INTERNAL; + + return HAL_ERROR; + } + } + } + } + + /* Return HAL status */ + return HAL_OK; +} + +/** + * @brief Disable the selected ADC. + * @note Prerequisite condition to use this function: ADC conversions must be + * stopped to disable the ADC. + * @param hadc: ADC handle + * @retval HAL status. + */ +static HAL_StatusTypeDef ADC_Disable(ADC_HandleTypeDef* hadc) +{ + uint32_t tickstart = 0; + + /* Verification if ADC is not already disabled: */ + /* forbidden to disable ADC (set bit ADC_CR_ADDIS) if ADC is already */ + /* disabled. */ + if (__HAL_ADC_IS_ENABLED(hadc) != RESET ) + { + /* Check if conditions to disable the ADC are fulfilled */ + if (__HAL_ADC_DISABLING_CONDITIONS(hadc) != RESET) + { + /* Disable the ADC peripheral */ + __HAL_ADC_DISABLE(hadc); + } + else + { + /* Update ADC state machine to error */ + hadc->State = HAL_ADC_STATE_ERROR; + + /* Set ADC error code to ADC internal error */ + hadc->ErrorCode |= HAL_ADC_ERROR_INTERNAL; + + return HAL_ERROR; + } + + /* Wait for ADC effectively disabled */ + /* Get timeout */ + tickstart = HAL_GetTick(); + + while(HAL_IS_BIT_SET(hadc->Instance->CR, ADC_CR_ADEN)) + { + /* Check for the Timeout */ + if(ADC_ENABLE_TIMEOUT != HAL_MAX_DELAY) + { + if((HAL_GetTick() - tickstart ) > ADC_DISABLE_TIMEOUT) + { + /* Update ADC state machine to error */ + hadc->State = HAL_ADC_STATE_ERROR; + + /* Set ADC error code to ADC internal error */ + hadc->ErrorCode |= HAL_ADC_ERROR_INTERNAL; + + return HAL_ERROR; + } + } + } + } + + /* Return HAL status */ + return HAL_OK; +} + +/** + * @brief Stop ADC conversion. + * @note Prerequisite condition to use this function: ADC conversions must be + * stopped to disable the ADC. + * @param hadc: ADC handle + * @param ConversionGroup: Only ADC group regular. + * This parameter can be one of the following values: + * @arg REGULAR_GROUP: ADC regular conversion type. + * @retval HAL status. + */ +static HAL_StatusTypeDef ADC_ConversionStop(ADC_HandleTypeDef* hadc, uint32_t ConversionGroup) +{ + uint32_t tickstart = 0 ; + + /* Check the parameters */ + assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance)); + assert_param(IS_ADC_CONVERSION_GROUP(ConversionGroup)); + + /* Verification: if ADC is not already stopped, bypass this function */ + if (HAL_IS_BIT_SET(hadc->Instance->CR, ADC_CR_ADSTART)) + { + /* Stop potential conversion on regular group */ + if (ConversionGroup == REGULAR_GROUP) + { + /* Software is allowed to set ADSTP only when ADSTART=1 and ADDIS=0 */ + if (HAL_IS_BIT_SET(hadc->Instance->CR, ADC_CR_ADSTART) && \ + HAL_IS_BIT_CLR(hadc->Instance->CR, ADC_CR_ADDIS) ) + { + /* Stop conversions on regular group */ + hadc->Instance->CR |= ADC_CR_ADSTP; + } + } + + /* Wait for conversion effectively stopped */ + /* Get timeout */ + tickstart = HAL_GetTick(); + + while((hadc->Instance->CR & ADC_CR_ADSTART) != RESET) + { + /* Check for the Timeout */ + if(ADC_STOP_CONVERSION_TIMEOUT != HAL_MAX_DELAY) + { + if((HAL_GetTick() - tickstart ) > ADC_STOP_CONVERSION_TIMEOUT) + { + /* Update ADC state machine to error */ + hadc->State = HAL_ADC_STATE_ERROR; + + /* Set ADC error code to ADC IP internal error */ + hadc->ErrorCode |= HAL_ADC_ERROR_INTERNAL; + + return HAL_ERROR; + } + } + } + } + + /* Return HAL status */ + return HAL_OK; +} + +/** + * @brief DMA transfer complete callback. + * @param hdma: pointer to DMA handle. + * @retval None + */ +static void ADC_DMAConvCplt(DMA_HandleTypeDef *hdma) +{ + ADC_HandleTypeDef* hadc = ( ADC_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + + /* Change ADC state */ + hadc->State = HAL_ADC_STATE_EOC; + + HAL_ADC_ConvCpltCallback(hadc); +} + +/** + * @brief DMA half transfer complete callback. + * @param hdma: pointer to DMA handle. + * @retval None + */ +static void ADC_DMAHalfConvCplt(DMA_HandleTypeDef *hdma) +{ + ADC_HandleTypeDef* hadc = ( ADC_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + + /* Conversion complete callback */ + HAL_ADC_ConvHalfCpltCallback(hadc); +} + +/** + * @brief DMA error callback + * @param hdma: pointer to DMA handle. + * @retval None + */ +static void ADC_DMAError(DMA_HandleTypeDef *hdma) +{ + ADC_HandleTypeDef* hadc = ( ADC_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + hadc->State= HAL_ADC_STATE_ERROR; + /* Set ADC error code to DMA error */ + hadc->ErrorCode |= HAL_ADC_ERROR_DMA; + HAL_ADC_ErrorCallback(hadc); +} + +/** + * @} + */ + +#endif /* HAL_ADC_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_adc.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_adc.h new file mode 100644 index 0000000000..df0e09669a --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_adc.h @@ -0,0 +1,939 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_adc.h + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief This file contains all the functions prototypes for the ADC firmware + * library. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32L0xx_ADC_H +#define __STM32L0xx_ADC_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal_def.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @addtogroup ADC + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/** + * @brief HAL State structures definition + */ +typedef enum +{ + HAL_ADC_STATE_RESET = 0x00, /*!< ADC not yet initialized or disabled */ + HAL_ADC_STATE_READY = 0x01, /*!< ADC peripheral ready for use */ + HAL_ADC_STATE_BUSY = 0x02, /*!< An internal process is ongoing */ + HAL_ADC_STATE_BUSY_REG = 0x12, /*!< Regular conversion is ongoing */ + HAL_ADC_STATE_TIMEOUT = 0x03, /*!< Timeout state */ + HAL_ADC_STATE_ERROR = 0x04, /*!< ADC state error */ + HAL_ADC_STATE_EOC = 0x05, /*!< Conversion is completed */ + HAL_ADC_STATE_AWD = 0x06, /*!< ADC state analog watchdog */ +}HAL_ADC_StateTypeDef; + + +/** + * @brief ADC Oversampler structure definition + */ +typedef struct +{ + uint32_t Ratio; /*!< Configures the oversampling ratio. + This parameter can be a value of @ref ADC_Oversampling_Ratio */ + uint32_t RightBitShift; /*!< Configures the division coefficient for the Oversampler. + This parameter can be a value of @ref ADC_Right_Bit_Shift */ + uint32_t TriggeredMode; /*!< Selects the regular triggered oversampling mode + This parameter can be a value of @ref ADC_Triggered_Oversampling_Mode */ + +}ADC_OversamplingTypeDef; + +/** + * @brief ADC Init structure definition + * @note The setting of these parameters with function HAL_ADC_Init() is conditioned by the ADC state. + * If ADC is not in the appropriate state to modify some parameters, these parameters setting is bypassed + * without error reporting (as it can be the expected behaviour in case of intended action to update antother parameter (which fullfills the ADC state condition) on the fly). + */ +typedef struct +{ + uint32_t OversamplingMode; /*!< Specifies whether the oversampling feature is enabled or disabled + This parameter can be set to ENABLE or DISABLE. + Note: This parameter can be modified only if there is no conversion is ongoing. */ + ADC_OversamplingTypeDef Oversample; /*!< Specifies the Oversampling parameters + Note: This parameter can be modified only if there is no conversion is ongoing. */ + uint32_t ClockPrescaler; /*!< Selects the ADC clock frequency. + This parameter can be a value of @ref ADC_ClockPrescaler + Note: This parameter can be modified only if ADC is disabled. */ + uint32_t Resolution; /*!< Configures the ADC resolution mode. + This parameter can be a value of @ref ADC_Resolution + Note: This parameter can be modified only if ADC is disabled. */ + uint32_t SamplingTime; /*!< The sample time value to be set for all channels. + This parameter can be a value of @ref ADC_sampling_times. + Note: This parameter can be modified only if there is no conversion is ongoing. */ + uint32_t ScanDirection; /*!< The scan sequence direction. + This parameter can be a value of @ref ADC_scan_direction. + Note: This parameter can be modified only if there is no conversion is ongoing. */ + uint32_t DataAlign; /*!< Specifies whether the ADC data alignment is left or right. + This parameter can be a value of @ref ADC_data_align. + Note: This parameter can be modified only if there is no conversion is ongoing. */ + uint32_t ContinuousConvMode; /*!< Specifies whether the conversion is performed in Continuous or Single mode. + This parameter can be set to ENABLE or DISABLE. + Note: This parameter can be modified only if there is no conversion is ongoing. */ + uint32_t DiscontinuousConvMode; /*!< Specifies whether the conversion is performed + in Complete-sequence/Discontinuous-sequence. + Discontinuous mode can be enabled only if continuous mode is disabled. + This parameter can be set to ENABLE or DISABLE. + Note: This parameter can be modified only if there is no conversion is ongoing. */ + uint32_t ExternalTrigConvEdge; /*!< Select the external trigger edge and enable the trigger. + This parameter can be a value of @ref ADC_External_trigger_Edge. + Note: This parameter can be modified only if there is no conversion is ongoing. */ + uint32_t ExternalTrigConv; /*!< Select the external event used to trigger the start of conversion. + This parameter can be a value of @ref ADC_External_trigger_Source. + Note: This parameter can be modified only if there is no conversion is ongoing. */ + uint32_t DMAContinuousRequests; /*!< Specifies whether the DMA requests are performed in one shot mode (DMA transfer stop when number of conversions is reached) + or in Continuous mode (DMA transfer unlimited, whatever number of conversions). + Note: In continuous mode, DMA must be configured in circular mode. Otherwise an overrun will be triggered when DMA buffer max pointer is reached. + This parameter can be set to ENABLE or DISABLE. + Note: This parameter can be modified only if there is no conversion is ongoing. */ + uint32_t EOCSelection; /*!< Specifies what EOC (End Of Conversion) flag is used for conversion polling and interruption: + end of single channel conversion or end of channels conversions sequence. + This parameter can be a value of @ref ADC_EOCSelection. */ + uint32_t Overrun; /*!< Select the behaviour in case of overrun: data preserved or overwritten + This parameter has an effect on regular channels only, including in DMA mode. + This parameter can be a value of @ref ADC_Overrun. + Note: This parameter can be modified only if there is no conversion is ongoing. */ + uint32_t LowPowerAutoWait; /*!< Specifies the usage of dynamic low power Auto Delay: new conversion start only + when the previous conversion (for regular channel) is completed. + This avoids risk of overrun for low frequency application. + This parameter can be set to ENABLE or DISABLE. + Note: This parameter can be modified only if there is no conversion is ongoing. */ + uint32_t LowPowerFrequencyMode; /*!< When selecting an analog ADC clock frequency lower than 2.8MHz, + it is mandatory to first enable the Low Frequency Mode. + This parameter can be set to ENABLE or DISABLE. + Note: This parameter can be modified only if there is no conversion is ongoing. */ + uint32_t LowPowerAutoOff; /*!< When setting the AutoOff feature, the ADC is always powered off when not converting and automatically + wakes-up when a conversion is started (by software or hardware trigger). + This parameter can be set to ENABLE or DISABLE. + Note: This parameter can be modified only if there is no conversion is ongoing. */ +}ADC_InitTypeDef; + +/** + * @brief ADC handle Structure definition + */ +typedef struct __ADC_HandleTypeDef +{ + ADC_TypeDef *Instance; /*!< Register base address */ + + ADC_InitTypeDef Init; /*!< ADC required parameters */ + + DMA_HandleTypeDef *DMA_Handle; /*!< Pointer DMA Handler */ + + HAL_LockTypeDef Lock; /*!< ADC locking object */ + + __IO HAL_ADC_StateTypeDef State; /*!< ADC communication state */ + + __IO uint32_t ErrorCode; /*!< ADC Error code */ +}ADC_HandleTypeDef; + +/** + * @brief ADC Configuration regular Channel structure definition + */ +typedef struct +{ + uint32_t Channel; /*!< the ADC channel to configure + This parameter can be a value of @ref ADC_channels */ +}ADC_ChannelConfTypeDef; + + +/** + * @brief ADC Configuration analog watchdog definition + */ +typedef struct +{ + uint32_t WatchdogMode; /*!< Configures the ADC analog watchdog mode: single/all channels. + This parameter can be a value of @ref ADC_analog_watchdog_mode. */ + uint32_t Channel; /*!< Selects which ADC channel to monitor by analog watchdog. + This parameter has an effect only if watchdog mode is configured on single channel (parameter WatchdogMode) + This parameter can be a value of @ref ADC_channels. */ + uint32_t ITMode; /*!< Specifies whether the analog watchdog is configured in interrupt or polling mode. + This parameter can be set to ENABLE or DISABLE */ + uint32_t HighThreshold; /*!< Configures the ADC analog watchdog High threshold value. + Depending of ADC resolution selected (12, 10, 8 or 6 bits), + this parameter must be a number between Min_Data = 0x000 and Max_Data = 0xFFF, 0x3FF, 0xFF or 0x3F respectively. */ + uint32_t LowThreshold; /*!< Configures the ADC analog watchdog High threshold value. + Depending of ADC resolution selected (12, 10, 8 or 6 bits), + this parameter must be a number between Min_Data = 0x000 and Max_Data = 0xFFF, 0x3FF, 0xFF or 0x3F respectively. */ +}ADC_AnalogWDGConfTypeDef; + + +/* Exported constants --------------------------------------------------------*/ + +/** @defgroup ADC_Exported_Constants + * @{ + */ + +/** @defgroup ADC_Error_Code + * @{ + */ +#define HAL_ADC_ERROR_NONE ((uint32_t)0x00) /*!< No error */ +#define HAL_ADC_ERROR_INTERNAL ((uint32_t)0x01) /*!< ADC IP internal error: if problem of clocking, + enable/disable, erroneous state */ +#define HAL_ADC_ERROR_OVR ((uint32_t)0x01) /*!< OVR error */ +#define HAL_ADC_ERROR_DMA ((uint32_t)0x02) /*!< DMA transfer error */ +/** + * @} + */ + +/** @defgroup ADC_TimeOut_Values + * @{ + */ + + /* Fixed timeout values for ADC calibration, enable settling time, disable */ + /* settling time. */ + /* Values defined to be higher than worst cases: low clocks freq, */ + /* maximum prescalers. */ + /* Unit: ms */ +#define ADC_ENABLE_TIMEOUT 10 +#define ADC_DISABLE_TIMEOUT 10 +#define ADC_STOP_CONVERSION_TIMEOUT 10 + + /* Delay of 10us fixed to worst case: maximum CPU frequency 180MHz to have */ + /* the minimum number of CPU cycles to fulfill this delay */ + #define ADC_DELAY_10US_MIN_CPU_CYCLES 1800 +/** + * @} + */ + +/** @defgroup ADC_ClockPrescaler + * @{ + */ +#define ADC_CLOCK_ASYNC_DIV1 ((uint32_t)0x00000000) /*!< ADC Asynchronous clock mode divided by 1 */ +#define ADC_CLOCK_ASYNC_DIV2 (ADC_CCR_PRESC_0) /*!< ADC Asynchronous clock mode divided by 2 */ +#define ADC_CLOCK_ASYNC_DIV4 (ADC_CCR_PRESC_1) /*!< ADC Asynchronous clock mode divided by 2 */ +#define ADC_CLOCK_ASYNC_DIV6 (ADC_CCR_PRESC_1 | ADC_CCR_PRESC_0) /*!< ADC Asynchronous clock mode divided by 2 */ +#define ADC_CLOCK_ASYNC_DIV8 (ADC_CCR_PRESC_2) /*!< ADC Asynchronous clock mode divided by 2 */ +#define ADC_CLOCK_ASYNC_DIV10 (ADC_CCR_PRESC_2 | ADC_CCR_PRESC_0) /*!< ADC Asynchronous clock mode divided by 2 */ +#define ADC_CLOCK_ASYNC_DIV12 (ADC_CCR_PRESC_2 | ADC_CCR_PRESC_1) /*!< ADC Asynchronous clock mode divided by 2 */ +#define ADC_CLOCK_ASYNC_DIV16 (ADC_CCR_PRESC_2 | ADC_CCR_PRESC_1 | ADC_CCR_PRESC_0) /*!< ADC Asynchronous clock mode divided by 2 */ +#define ADC_CLOCK_ASYNC_DIV32 (ADC_CCR_PRESC_3) /*!< ADC Asynchronous clock mode divided by 2 */ +#define ADC_CLOCK_ASYNC_DIV64 (ADC_CCR_PRESC_3 | ADC_CCR_PRESC_0) /*!< ADC Asynchronous clock mode divided by 2 */ +#define ADC_CLOCK_ASYNC_DIV128 (ADC_CCR_PRESC_3 | ADC_CCR_PRESC_1) /*!< ADC Asynchronous clock mode divided by 2 */ +#define ADC_CLOCK_ASYNC_DIV256 (ADC_CCR_PRESC_3 | ADC_CCR_PRESC_1 | ADC_CCR_PRESC_0) /*!< ADC Asynchronous clock mode divided by 2 */ + +#define ADC_CLOCKPRESCALER_PCLK_DIV1 ((uint32_t)ADC_CFGR2_CKMODE_0) /*!< Synchronous clock mode divided by 1 */ +#define ADC_CLOCKPRESCALER_PCLK_DIV2 ((uint32_t)ADC_CFGR2_CKMODE_1) /*!< Synchronous clock mode divided by 2 */ +#define ADC_CLOCKPRESCALER_PCLK_DIV4 ((uint32_t)ADC_CFGR2_CKMODE) /*!< Synchronous clock mode divided by 4 */ + +#define IS_ADC_CLOCKPRESCALER(ADC_CLOCK) (((ADC_CLOCK) == ADC_CLOCK_ASYNC_DIV1) ||\ + ((ADC_CLOCK) == ADC_CLOCKPRESCALER_PCLK_DIV1) ||\ + ((ADC_CLOCK) == ADC_CLOCKPRESCALER_PCLK_DIV2) ||\ + ((ADC_CLOCK) == ADC_CLOCKPRESCALER_PCLK_DIV4) ||\ + ((ADC_CLOCK) == ADC_CLOCK_ASYNC_DIV1 ) ||\ + ((ADC_CLOCK) == ADC_CLOCK_ASYNC_DIV2 ) ||\ + ((ADC_CLOCK) == ADC_CLOCK_ASYNC_DIV4 ) ||\ + ((ADC_CLOCK) == ADC_CLOCK_ASYNC_DIV6 ) ||\ + ((ADC_CLOCK) == ADC_CLOCK_ASYNC_DIV8 ) ||\ + ((ADC_CLOCK) == ADC_CLOCK_ASYNC_DIV10 ) ||\ + ((ADC_CLOCK) == ADC_CLOCK_ASYNC_DIV12 ) ||\ + ((ADC_CLOCK) == ADC_CLOCK_ASYNC_DIV16 ) ||\ + ((ADC_CLOCK) == ADC_CLOCK_ASYNC_DIV32 ) ||\ + ((ADC_CLOCK) == ADC_CLOCK_ASYNC_DIV64 ) ||\ + ((ADC_CLOCK) == ADC_CLOCK_ASYNC_DIV128 ) ||\ + ((ADC_CLOCK) == ADC_CLOCK_ASYNC_DIV256)) +/** + * @} + */ + +/** @defgroup ADC_Resolution + * @{ + */ +#define ADC_RESOLUTION12b ((uint32_t)0x00000000) /*!< ADC 12-bit resolution */ +#define ADC_RESOLUTION10b ((uint32_t)ADC_CFGR1_RES_0) /*!< ADC 10-bit resolution */ +#define ADC_RESOLUTION8b ((uint32_t)ADC_CFGR1_RES_1) /*!< ADC 8-bit resolution */ +#define ADC_RESOLUTION6b ((uint32_t)ADC_CFGR1_RES) /*!< ADC 6-bit resolution */ + +#define IS_ADC_RESOLUTION(RESOLUTION) (((RESOLUTION) == ADC_RESOLUTION12b) || \ + ((RESOLUTION) == ADC_RESOLUTION10b) || \ + ((RESOLUTION) == ADC_RESOLUTION8b) || \ + ((RESOLUTION) == ADC_RESOLUTION6b)) + +#define IS_ADC_RESOLUTION_8_6_BITS(RESOLUTION) (((RESOLUTION) == ADC_RESOLUTION8b) || \ + ((RESOLUTION) == ADC_RESOLUTION6b)) +/** + * @} + */ + +/** @defgroup ADC_data_align + * @{ + */ +#define ADC_DATAALIGN_RIGHT ((uint32_t)0x00000000) +#define ADC_DATAALIGN_LEFT ((uint32_t)ADC_CFGR1_ALIGN) + +#define IS_ADC_DATA_ALIGN(ALIGN) (((ALIGN) == ADC_DATAALIGN_RIGHT) || \ + ((ALIGN) == ADC_DATAALIGN_LEFT)) +/** + * @} + */ + +/** @defgroup ADC_External_trigger_Edge + * @{ + */ +#define ADC_EXTERNALTRIG_EDGE_NONE ((uint32_t)0x00000000) +#define ADC_EXTERNALTRIG_EDGE_RISING ((uint32_t)ADC_CFGR1_EXTEN_0) +#define ADC_EXTERNALTRIG_EDGE_FALLING ((uint32_t)ADC_CFGR1_EXTEN_1) +#define ADC_EXTERNALTRIG_EDGE_RISINGFALLING ((uint32_t)ADC_CFGR1_EXTEN) + +#define IS_ADC_EXTTRIG_EDGE(EDGE) (((EDGE) == ADC_EXTERNALTRIG_EDGE_NONE) || \ + ((EDGE) == ADC_EXTERNALTRIG_EDGE_RISING) || \ + ((EDGE) == ADC_EXTERNALTRIG_EDGE_FALLING) || \ + ((EDGE) == ADC_EXTERNALTRIG_EDGE_RISINGFALLING)) +/** + * @} + */ + +/** @defgroup ADC_External_trigger_Source + * @{ + */ +#define ADC_EXTERNALTRIG0_T6_TRGO ((uint32_t)0x00000000) +#define ADC_EXTERNALTRIG1_T21_CC2 ADC_CFGR1_EXTSEL_0 +#define ADC_EXTERNALTRIG2_T2_TRGO ADC_CFGR1_EXTSEL_1 +#define ADC_EXTERNALTRIG3_T2_CC4 ((uint32_t)0x000000C0) +#define ADC_EXTERNALTRIG4_T22_TRGO ADC_CFGR1_EXTSEL_2 +#define ADC_EXTERNALTRIG7_EXT_IT11 ADC_CFGR1_EXTSEL + +#define IS_ADC_EXTERNAL_TRIG_CONV(CONV) (((CONV) == ADC_EXTERNALTRIG0_T6_TRGO ) || \ + ((CONV) == ADC_EXTERNALTRIG1_T21_CC2 ) || \ + ((CONV) == ADC_EXTERNALTRIG2_T2_TRGO ) || \ + ((CONV) == ADC_EXTERNALTRIG3_T2_CC4 ) || \ + ((CONV) == ADC_EXTERNALTRIG4_T22_TRGO ) || \ + ((CONV) == ADC_EXTERNALTRIG7_EXT_IT11 )) + +/** + * @} + */ + +/** @defgroup ADC_EOCSelection + * @{ + */ +#define EOC_SINGLE_CONV ((uint32_t) ADC_ISR_EOC) +#define EOC_SEQ_CONV ((uint32_t) ADC_ISR_EOS) +#define EOC_SINGLE_SEQ_CONV ((uint32_t)(ADC_ISR_EOC | ADC_ISR_EOS)) /*!< reserved for future use */ + +#define IS_ADC_EOC_SELECTION(EOC_SELECTION) (((EOC_SELECTION) == EOC_SINGLE_CONV) || \ + ((EOC_SELECTION) == EOC_SEQ_CONV) || \ + ((EOC_SELECTION) == EOC_SINGLE_SEQ_CONV)) +/** + * @} + */ + +/** @defgroup ADC_Overrun + * @{ + */ +#define OVR_DATA_PRESERVED ((uint32_t)0x00000000) +#define OVR_DATA_OVERWRITTEN ((uint32_t)ADC_CFGR1_OVRMOD) + +#define IS_ADC_OVERRUN(OVR) (((OVR) == OVR_DATA_PRESERVED) || \ + ((OVR) == OVR_DATA_OVERWRITTEN)) +/** + * @} + */ + +/** @defgroup ADC_channels + * @{ + */ +#define ADC_CHANNEL_0 ((uint32_t)(ADC_CHSELR_CHSEL0)) +#define ADC_CHANNEL_1 ((uint32_t)(ADC_CHSELR_CHSEL1) | ADC_CFGR1_AWDCH_0) +#define ADC_CHANNEL_2 ((uint32_t)(ADC_CHSELR_CHSEL2) | ADC_CFGR1_AWDCH_1) +#define ADC_CHANNEL_3 ((uint32_t)(ADC_CHSELR_CHSEL3)| ADC_CFGR1_AWDCH_1 | ADC_CFGR1_AWDCH_0) +#define ADC_CHANNEL_4 ((uint32_t)(ADC_CHSELR_CHSEL4)| ADC_CFGR1_AWDCH_2) +#define ADC_CHANNEL_5 ((uint32_t)(ADC_CHSELR_CHSEL5)| ADC_CFGR1_AWDCH_2| ADC_CFGR1_AWDCH_0) +#define ADC_CHANNEL_6 ((uint32_t)(ADC_CHSELR_CHSEL6)| ADC_CFGR1_AWDCH_2| ADC_CFGR1_AWDCH_1) +#define ADC_CHANNEL_7 ((uint32_t)(ADC_CHSELR_CHSEL7)| ADC_CFGR1_AWDCH_2| ADC_CFGR1_AWDCH_1 | ADC_CFGR1_AWDCH_0) +#define ADC_CHANNEL_8 ((uint32_t)(ADC_CHSELR_CHSEL8)| ADC_CFGR1_AWDCH_3) +#define ADC_CHANNEL_9 ((uint32_t)(ADC_CHSELR_CHSEL9)| ADC_CFGR1_AWDCH_3| ADC_CFGR1_AWDCH_0) +#define ADC_CHANNEL_10 ((uint32_t)(ADC_CHSELR_CHSEL10)| ADC_CFGR1_AWDCH_3| ADC_CFGR1_AWDCH_1) +#define ADC_CHANNEL_11 ((uint32_t)(ADC_CHSELR_CHSEL11)| ADC_CFGR1_AWDCH_3| ADC_CFGR1_AWDCH_1| ADC_CFGR1_AWDCH_0) +#define ADC_CHANNEL_12 ((uint32_t)(ADC_CHSELR_CHSEL12)| ADC_CFGR1_AWDCH_3| ADC_CFGR1_AWDCH_2) +#define ADC_CHANNEL_13 ((uint32_t)(ADC_CHSELR_CHSEL13)| ADC_CFGR1_AWDCH_3| ADC_CFGR1_AWDCH_2| ADC_CFGR1_AWDCH_0) +#define ADC_CHANNEL_14 ((uint32_t)(ADC_CHSELR_CHSEL14)| ADC_CFGR1_AWDCH_3| ADC_CFGR1_AWDCH_2| ADC_CFGR1_AWDCH_1) +#define ADC_CHANNEL_15 ((uint32_t)(ADC_CHSELR_CHSEL15)| ADC_CFGR1_AWDCH_3| ADC_CFGR1_AWDCH_2| ADC_CFGR1_AWDCH_1| ADC_CFGR1_AWDCH_0) +#define ADC_CHANNEL_16 ((uint32_t)(ADC_CHSELR_CHSEL16)| ADC_CFGR1_AWDCH_4) +#define ADC_CHANNEL_17 ((uint32_t)(ADC_CHSELR_CHSEL17)| ADC_CFGR1_AWDCH_4| ADC_CFGR1_AWDCH_0) +#define ADC_CHANNEL_18 ((uint32_t)(ADC_CHSELR_CHSEL18)| ADC_CFGR1_AWDCH_4| ADC_CFGR1_AWDCH_1) + +/* Internal channels */ +#define ADC_CHANNEL_TEMPSENSOR ADC_CHANNEL_16 +#define ADC_CHANNEL_VREFINT ADC_CHANNEL_17 +#define ADC_CHANNEL_VLCD ADC_CHANNEL_18 + + +#define IS_ADC_CHANNEL(CHANNEL) (((CHANNEL) == ADC_CHANNEL_0) || \ + ((CHANNEL) == ADC_CHANNEL_1) || \ + ((CHANNEL) == ADC_CHANNEL_2) || \ + ((CHANNEL) == ADC_CHANNEL_3) || \ + ((CHANNEL) == ADC_CHANNEL_4) || \ + ((CHANNEL) == ADC_CHANNEL_5) || \ + ((CHANNEL) == ADC_CHANNEL_6) || \ + ((CHANNEL) == ADC_CHANNEL_7) || \ + ((CHANNEL) == ADC_CHANNEL_8) || \ + ((CHANNEL) == ADC_CHANNEL_9) || \ + ((CHANNEL) == ADC_CHANNEL_10) || \ + ((CHANNEL) == ADC_CHANNEL_11) || \ + ((CHANNEL) == ADC_CHANNEL_12) || \ + ((CHANNEL) == ADC_CHANNEL_13) || \ + ((CHANNEL) == ADC_CHANNEL_14) || \ + ((CHANNEL) == ADC_CHANNEL_15) || \ + ((CHANNEL) == ADC_CHANNEL_TEMPSENSOR) || \ + ((CHANNEL) == ADC_CHANNEL_VREFINT) || \ + ((CHANNEL) == ADC_CHANNEL_VLCD)) + +/** + * @} + */ + +/** @defgroup ADC_Channel_AWD_Masks + * @{ + */ +#define ADC_CHANNEL_MASK ((uint32_t)0x0007FFFF) +#define ADC_CHANNEL_AWD_MASK ((uint32_t)0x7C000000) +/** + * @} + */ + + +/** @defgroup ADC_sampling_times + * @{ + */ + +#define ADC_SAMPLETIME_1CYCLE_5 ((uint32_t)0x00000000) /*!< ADC sampling time 1.5 cycle */ +#define ADC_SAMPLETIME_7CYCLES_5 ((uint32_t)ADC_SMPR_SMPR_0) /*!< ADC sampling time 7.5 CYCLES */ +#define ADC_SAMPLETIME_13CYCLES_5 ((uint32_t)ADC_SMPR_SMPR_1) /*!< ADC sampling time 13.5 CYCLES */ +#define ADC_SAMPLETIME_28CYCLES_5 ((uint32_t)(ADC_SMPR_SMPR_1 | ADC_SMPR_SMPR_0)) /*!< ADC sampling time 28.5 CYCLES */ +#define ADC_SAMPLETIME_41CYCLES_5 ((uint32_t)ADC_SMPR_SMPR_2) /*!< ADC sampling time 41.5 CYCLES */ +#define ADC_SAMPLETIME_55CYCLES_5 ((uint32_t)(ADC_SMPR_SMPR_2 | ADC_SMPR_SMPR_0)) /*!< ADC sampling time 55.5 CYCLES */ +#define ADC_SAMPLETIME_71CYCLES_5 ((uint32_t)(ADC_SMPR_SMPR_2 | ADC_SMPR_SMPR_1)) /*!< ADC sampling time 71.5 CYCLES */ +#define ADC_SAMPLETIME_239CYCLES_5 ((uint32_t)ADC_SMPR_SMPR) /*!< ADC sampling time 239.5 CYCLES */ + +#define IS_ADC_SAMPLE_TIME(TIME) (((TIME) == ADC_SAMPLETIME_1CYCLE_5 ) || \ + ((TIME) == ADC_SAMPLETIME_7CYCLES_5 ) || \ + ((TIME) == ADC_SAMPLETIME_13CYCLES_5 ) || \ + ((TIME) == ADC_SAMPLETIME_28CYCLES_5 ) || \ + ((TIME) == ADC_SAMPLETIME_41CYCLES_5 ) || \ + ((TIME) == ADC_SAMPLETIME_55CYCLES_5 ) || \ + ((TIME) == ADC_SAMPLETIME_71CYCLES_5 ) || \ + ((TIME) == ADC_SAMPLETIME_239CYCLES_5)) +/** + * @} + */ + + /** @defgroup ADC_scan_direction + * @{ + */ +#define ADC_SCAN_DIRECTION_UPWARD ((uint32_t)0x00000000) +#define ADC_SCAN_DIRECTION_BACKWARD ADC_CFGR1_SCANDIR + + +#define IS_ADC_SCAN_DIRECTION(DIRECTION) (((DIRECTION) == ADC_SCAN_DIRECTION_UPWARD) || \ + ((DIRECTION) == ADC_SCAN_DIRECTION_BACKWARD)) +/** + * @} + */ + +/** @defgroup ADC_Oversampling_Ratio + * @{ + */ + +#define ADC_OVERSAMPLING_RATIO_2 ((uint32_t)0x00000000) /*!< ADC Oversampling ratio 2x */ +#define ADC_OVERSAMPLING_RATIO_4 ((uint32_t)0x00000004) /*!< ADC Oversampling ratio 4x */ +#define ADC_OVERSAMPLING_RATIO_8 ((uint32_t)0x00000008) /*!< ADC Oversampling ratio 8x */ +#define ADC_OVERSAMPLING_RATIO_16 ((uint32_t)0x0000000C) /*!< ADC Oversampling ratio 16x */ +#define ADC_OVERSAMPLING_RATIO_32 ((uint32_t)0x00000010) /*!< ADC Oversampling ratio 32x */ +#define ADC_OVERSAMPLING_RATIO_64 ((uint32_t)0x00000014) /*!< ADC Oversampling ratio 64x */ +#define ADC_OVERSAMPLING_RATIO_128 ((uint32_t)0x00000018) /*!< ADC Oversampling ratio 128x */ +#define ADC_OVERSAMPLING_RATIO_256 ((uint32_t)0x0000001C) /*!< ADC Oversampling ratio 256x */ +#define IS_ADC_OVERSAMPLING_RATIO(RATIO) (((RATIO) == ADC_OVERSAMPLING_RATIO_2 ) || \ + ((RATIO) == ADC_OVERSAMPLING_RATIO_4 ) || \ + ((RATIO) == ADC_OVERSAMPLING_RATIO_8 ) || \ + ((RATIO) == ADC_OVERSAMPLING_RATIO_16 ) || \ + ((RATIO) == ADC_OVERSAMPLING_RATIO_32 ) || \ + ((RATIO) == ADC_OVERSAMPLING_RATIO_64 ) || \ + ((RATIO) == ADC_OVERSAMPLING_RATIO_128 ) || \ + ((RATIO) == ADC_OVERSAMPLING_RATIO_256 )) +/** + * @} + */ + +/** @defgroup ADC_Right_Bit_Shift + * @{ + */ +#define ADC_RIGHTBITSHIFT_NONE ((uint32_t)0x00000000) /*!< ADC No bit shift for oversampling */ +#define ADC_RIGHTBITSHIFT_1 ((uint32_t)0x00000020) /*!< ADC 1 bit shift for oversampling */ +#define ADC_RIGHTBITSHIFT_2 ((uint32_t)0x00000040) /*!< ADC 2 bits shift for oversampling */ +#define ADC_RIGHTBITSHIFT_3 ((uint32_t)0x00000060) /*!< ADC 3 bits shift for oversampling */ +#define ADC_RIGHTBITSHIFT_4 ((uint32_t)0x00000080) /*!< ADC 4 bits shift for oversampling */ +#define ADC_RIGHTBITSHIFT_5 ((uint32_t)0x000000A0) /*!< ADC 5 bits shift for oversampling */ +#define ADC_RIGHTBITSHIFT_6 ((uint32_t)0x000000C0) /*!< ADC 6 bits shift for oversampling */ +#define ADC_RIGHTBITSHIFT_7 ((uint32_t)0x000000E0) /*!< ADC 7 bits shift for oversampling */ +#define ADC_RIGHTBITSHIFT_8 ((uint32_t)0x00000100) /*!< ADC 8 bits shift for oversampling */ +#define IS_ADC_RIGHT_BIT_SHIFT(SHIFT) (((SHIFT) == ADC_RIGHTBITSHIFT_NONE) || \ + ((SHIFT) == ADC_RIGHTBITSHIFT_1 ) || \ + ((SHIFT) == ADC_RIGHTBITSHIFT_2 ) || \ + ((SHIFT) == ADC_RIGHTBITSHIFT_3 ) || \ + ((SHIFT) == ADC_RIGHTBITSHIFT_4 ) || \ + ((SHIFT) == ADC_RIGHTBITSHIFT_5 ) || \ + ((SHIFT) == ADC_RIGHTBITSHIFT_6 ) || \ + ((SHIFT) == ADC_RIGHTBITSHIFT_7 ) || \ + ((SHIFT) == ADC_RIGHTBITSHIFT_8 )) +/** + * @} + */ + +/** @defgroup ADC_Triggered_Oversampling_Mode + * @{ + */ +#define ADC_TRIGGEREDMODE_SINGLE_TRIGGER ((uint32_t)0x00000000) /*!< ADC No bit shift for oversampling */ +#define ADC_TRIGGEREDMODE_MULTI_TRIGGER ((uint32_t)0x00000200) /*!< ADC No bit shift for oversampling */ +#define IS_ADC_TRIGGERED_OVERSAMPLING_MODE(MODE) (((MODE) == ADC_TRIGGEREDMODE_SINGLE_TRIGGER) || \ + ((MODE) == ADC_TRIGGEREDMODE_MULTI_TRIGGER) ) +/** + * @} + */ + +/** @defgroup ADC_analog_watchdog_mode + * @{ + */ +#define ADC_ANALOGWATCHDOG_NONE ((uint32_t) 0x00000000) +#define ADC_ANALOGWATCHDOG_SINGLE_REG ((uint32_t)(ADC_CFGR1_AWDSGL | ADC_CFGR1_AWDEN)) +#define ADC_ANALOGWATCHDOG_ALL_REG ((uint32_t) ADC_CFGR1_AWDEN) + + +#define IS_ADC_ANALOG_WATCHDOG_MODE(WATCHDOG) (((WATCHDOG) == ADC_ANALOGWATCHDOG_NONE ) || \ + ((WATCHDOG) == ADC_ANALOGWATCHDOG_SINGLE_REG) || \ + ((WATCHDOG) == ADC_ANALOGWATCHDOG_ALL_REG )) +/** + * @} + */ + +/** @defgroup ADC_conversion_type + * @{ + */ +#define REGULAR_GROUP ((uint32_t)(ADC_FLAG_EOC | ADC_FLAG_EOS)) +#define IS_ADC_CONVERSION_GROUP(CONVERSION) ((CONVERSION) == REGULAR_GROUP) +/** + * @} + */ + +/** @defgroup ADC_Event_type + * @{ + */ +#define AWD_EVENT ((uint32_t)ADC_FLAG_AWD) +#define OVR_EVENT ((uint32_t)ADC_FLAG_OVR) + +#define IS_ADC_EVENT_TYPE(EVENT) (((EVENT) == AWD_EVENT) || \ + ((EVENT) == OVR_EVENT)) +/** + * @} + */ + +/** @defgroup ADC_interrupts_definition + * @{ + */ +#define ADC_IT_RDY ADC_IER_ADRDYIE /*!< ADC Ready (ADRDY) interrupt source */ +#define ADC_IT_EOSMP ADC_IER_EOSMPIE /*!< ADC End of Sampling interrupt source */ +#define ADC_IT_EOC ADC_IER_EOCIE /*!< ADC End of Regular Conversion interrupt source */ +#define ADC_IT_EOS ADC_IER_EOSEQIE /*!< ADC End of Regular sequence of Conversions interrupt source */ +#define ADC_IT_OVR ADC_IER_OVRIE /*!< ADC overrun interrupt source */ +#define ADC_IT_AWD ADC_IER_AWDIE /*!< ADC Analog watchdog 1 interrupt source */ +#define ADC_IT_EOCAL ADC_IER_EOCALIE /*!< ADC End of Calibration interrupt source */ + +/* Check of single flag */ +#define IS_ADC_IT(IT) (((IT) == ADC_IT_AWD) || ((IT) == ADC_IT_RDY) || \ + ((IT) == ADC_IT_EOSMP) || ((IT) == ADC_IT_EOC) || \ + ((IT) == ADC_IT_EOS) || ((IT) == ADC_IT_OVR)) +/** + * @} + */ + + + +/** @defgroup ADC_flags_definition + * @{ + */ +#define ADC_FLAG_RDY ADC_ISR_ADRDY /*!< ADC Ready (ADRDY) flag */ +#define ADC_FLAG_EOSMP ADC_ISR_EOSMP /*!< ADC End of Sampling flag */ +#define ADC_FLAG_EOC ADC_ISR_EOC /*!< ADC End of Regular Conversion flag */ +#define ADC_FLAG_EOS ADC_ISR_EOSEQ /*!< ADC End of Regular sequence of Conversions flag */ +#define ADC_FLAG_OVR ADC_ISR_OVR /*!< ADC overrun flag */ +#define ADC_FLAG_AWD ADC_ISR_AWD /*!< ADC Analog watchdog flag */ +#define ADC_FLAG_EOCAL ADC_ISR_EOCAL /*!< ADC Enf Of Calibration flag */ + + +#define ADC_FLAG_ALL (ADC_FLAG_RDY | ADC_FLAG_EOSMP | ADC_FLAG_EOC | ADC_FLAG_EOS | \ + ADC_FLAG_OVR | ADC_FLAG_AWD | ADC_FLAG_EOCAL) + +/* Check of single flag */ +#define IS_ADC_FLAG(FLAG) (((FLAG) == ADC_FLAG_RDY) || ((FLAG) == ADC_FLAG_EOSMP) || \ + ((FLAG) == ADC_FLAG_EOC) || ((FLAG) == ADC_FLAG_EOS) || \ + ((FLAG) == ADC_FLAG_OVR) || ((FLAG) == ADC_FLAG_AWD) || \ + ((FLAG) == ADC_FLAG_EOCAL)) +/** + * @} + */ + + +/** @defgroup ADC_range_verification + * in function of ADC resolution selected (12, 10, 8 or 6 bits) + * @{ + */ +#define IS_ADC_RANGE(RESOLUTION, ADC_VALUE) \ + ((((RESOLUTION) == ADC_RESOLUTION12b) && ((ADC_VALUE) <= ((uint32_t)0x0FFF))) || \ + (((RESOLUTION) == ADC_RESOLUTION10b) && ((ADC_VALUE) <= ((uint32_t)0x03FF))) || \ + (((RESOLUTION) == ADC_RESOLUTION8b) && ((ADC_VALUE) <= ((uint32_t)0x00FF))) || \ + (((RESOLUTION) == ADC_RESOLUTION6b) && ((ADC_VALUE) <= ((uint32_t)0x003F)))) +/** + * @} + */ + +/** @defgroup ADC_regular_nb_conv_verification + * @{ + */ +#define IS_ADC_REGULAR_NB_CONV(LENGTH) (((LENGTH) >= ((uint32_t)1)) && ((LENGTH) <= ((uint32_t)16))) +/** + * @} + */ + +/** + * @} + */ +/* Exported macro ------------------------------------------------------------*/ + +/** @defgroup ADC_Exported_Macro + * @{ + */ +/** @brief Reset ADC handle state + * @param __HANDLE__: ADC handle + * @retval None + */ +#define __HAL_ADC_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_ADC_STATE_RESET) + +/** + * @brief Enable the ADC peripheral + * @param __HANDLE__: ADC handle + * @retval None + */ +#define __HAL_ADC_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= ADC_CR_ADEN) + +/** + * @brief Verification of hardware constraints before ADC can be enabled + * @param __HANDLE__: ADC handle + * @retval SET (ADC can be enabled) or RESET (ADC cannot be enabled) + */ +#define __HAL_ADC_ENABLING_CONDITIONS(__HANDLE__) \ + (( ( ((__HANDLE__)->Instance->CR) & \ + (ADC_CR_ADCAL | ADC_CR_ADSTP | ADC_CR_ADSTART | \ + ADC_CR_ADDIS | ADC_CR_ADEN ) \ + ) == RESET \ + ) ? SET : RESET) + +/** + * @brief Disable the ADC peripheral + * @param __HANDLE__: ADC handle + * @retval None + */ +#define __HAL_ADC_DISABLE(__HANDLE__) \ + do{ \ + (__HANDLE__)->Instance->CR |= ADC_CR_ADDIS; \ + __HAL_ADC_CLEAR_FLAG((__HANDLE__), (ADC_FLAG_EOSMP | ADC_FLAG_RDY)); \ + } while(0) + +/** + * @brief Verification of hardware constraints before ADC can be disabled + * @param __HANDLE__: ADC handle + * @retval SET (ADC can be disabled) or RESET (ADC cannot be disabled) + */ +#define __HAL_ADC_DISABLING_CONDITIONS(__HANDLE__) \ + (( ( ((__HANDLE__)->Instance->CR) & \ + (ADC_CR_ADSTART | ADC_CR_ADEN)) == ADC_CR_ADEN \ + ) ? SET : RESET) + +/** + * @brief Verification of ADC state: enabled or disabled + * @param __HANDLE__: ADC handle + * @retval SET (ADC enabled) or RESET (ADC disabled) + */ +#define __HAL_ADC_IS_ENABLED(__HANDLE__) \ + (( ((((__HANDLE__)->Instance->CR) & (ADC_CR_ADEN | ADC_CR_ADDIS)) == ADC_CR_ADEN) && \ + ((((__HANDLE__)->Instance->ISR) & ADC_FLAG_RDY) == ADC_FLAG_RDY) \ + ) ? SET : RESET) + +/** + * @brief Returns resolution bits in CFGR register: RES[1:0]. Return value among parameter to @ref ADC_Resolution. + * @param __HANDLE__: ADC handle + * @retval None + */ +#define __HAL_ADC_GET_RESOLUTION(__HANDLE__) (((__HANDLE__)->Instance->CFGR1) & ADC_CFGR1_RES) + +/** + * @brief Check if no conversion is ongoing on regular groups + * @param __HANDLE__: ADC handle + * @retval SET (conversion is on going) or RESET (no conversion is on going) + */ +#define __HAL_ADC_IS_CONVERSION_ONGOING(__HANDLE__) \ + (( (((__HANDLE__)->Instance->CR) & (ADC_CR_ADSTART)) == RESET ) ? RESET : SET) + +/** + * @brief Enable ADC continuous conversion mode. + * @param _CONTINUOUS_MODE_: Continuous mode. + * @retval None + */ +#define __HAL_ADC_CFGR1_CONTINUOUS(_CONTINUOUS_MODE_) ((_CONTINUOUS_MODE_) << 13) + +/** + * @brief Configures the number of discontinuous conversions for the regular group channels. + * @param _NBR_DISCONTINUOUS_CONV_: Number of discontinuous conversions. + * @retval None + */ +#define __HAL_ADC_CFGR1_DISCONTINUOUS_NUM(_NBR_DISCONTINUOUS_CONV_) (((_NBR_DISCONTINUOUS_CONV_) - 1) << 17) + +/** + * @brief Enable the ADC DMA continuous request. + * @param _DMAContReq_MODE_: DMA continuous request mode. + * @retval None + */ +#define __HAL_ADC_CFGR1_DMAContReq(_DMAContReq_MODE_) ((_DMAContReq_MODE_) << 1) + +/** + * @brief Enable the ADC Auto Delay. + * @param _AutoDelay_: Auto delay bit enable or disable. + * @retval None + */ +#define __HAL_ADC_CFGR1_AutoDelay(_AutoDelay_) ((_AutoDelay_) << 14) + +/** + * @brief Enable the ADC LowPowerAutoOff. + * @param _AUTOFF_: AutoOff bit enable or disable. + * @retval None + */ +#define __HAL_ADC_CFGR1_AUTOFF(_AUTOFF_) ((_AUTOFF_) << 15) + +/** + * @brief Configure the analog watchdog high threshold into registers TR1, TR2 or TR3. + * @param _Threshold_: Threshold value + * @retval None + */ +#define __HAL_ADC_TRx_HighThreshold(_Threshold_) ((_Threshold_) << 16) + + /** + * @brief Enable the ADC Low Frequency mode. + * @param _LOW_FREQUENCY_MODE_: Low Frequency mode. + * @retval None + */ +#define __HAL_ADC_CCR_LOWFREQUENCY(_LOW_FREQUENCY_MODE_) ((_LOW_FREQUENCY_MODE_) << 25) + +/** + * @brief Shift the offset in function of the selected ADC resolution. + * Offset has to be left-aligned on bit 11, the LSB (right bits) are set to 0 + * If resolution 12 bits, no shift. + * If resolution 10 bits, shift of 2 ranks on the right. + * If resolution 8 bits, shift of 4 ranks on the right. + * If resolution 6 bits, shift of 6 ranks on the right. + * therefore, shift = (12 - resolution) = 12 - (12- (((RES[1:0]) >> 3)*2)) + * @param __HANDLE__: ADC handle. + * @param _Offset_: Value to be shifted + * @retval None + */ +#define __HAL_ADC_Offset_shift_resolution(__HANDLE__, _Offset_) \ + ((_Offset_) << ((((__HANDLE__)->Instance->CFGR & ADC_CFGR1_RES) >> 3)*2)) + +/** + * @brief Shift the AWD1 threshold in function of the selected ADC resolution. + * Thresholds have to be left-aligned on bit 11, the LSB (right bits) are set to 0 + * If resolution 12 bits, no shift. + * If resolution 10 bits, shift of 2 ranks on the right. + * If resolution 8 bits, shift of 4 ranks on the right. + * If resolution 6 bits, shift of 6 ranks on the right. + * therefore, shift = (12 - resolution) = 12 - (12- (((RES[1:0]) >> 3)*2)) + * @param __HANDLE__: ADC handle. + * @param _Threshold_: Value to be shifted + * @retval None + */ +#define __HAL_ADC_AWD1Threshold_shift_resolution(__HANDLE__, _Threshold_) \ + ((_Threshold_) << ((((__HANDLE__)->Instance->CFGR1 & ADC_CFGR1_RES) >> 3)*2)) + +/** + * @brief Shift the value on the left, less significant are set to 0. + * @param _Value_: Value to be shifted + * @param _Shift_: Number of shift to be done + * @retval None + */ +#define __HAL_ADC_Value_Shift_left(_Value_, _Shift_) ((_Value_) << (_Shift_)) + + +/** + * @brief Enable the ADC end of conversion interrupt. + * @param __HANDLE__: ADC handle. + * @param __INTERRUPT__: ADC Interrupt. + * @retval None + */ +#define __HAL_ADC_ENABLE_IT(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->IER) |= (__INTERRUPT__)) + +/** + * @brief Disable the ADC end of conversion interrupt. + * @param __HANDLE__: ADC handle. + * @param __INTERRUPT__: ADC interrupt. + * @retval None + */ +#define __HAL_ADC_DISABLE_IT(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->IER) &= ~(__INTERRUPT__)) + +/** @brief Checks if the specified ADC interrupt source is enabled or disabled. + * @param __HANDLE__: specifies the ADC Handle. + * @param __INTERRUPT__: specifies the ADC interrupt source to check. + * @retval The new state of __IT__ (TRUE or FALSE). + */ +#define __HAL_ADC_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((((__HANDLE__)->Instance->IER & (__INTERRUPT__)) == (__INTERRUPT__)) ? SET : RESET) + +/** + * @brief Clear the ADC's pending flags + * @param __HANDLE__: ADC handle. + * @param __FLAG__: ADC flag. + * @retval None + */ +/* Note: bit cleared bit by writing 1 */ +#define __HAL_ADC_CLEAR_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->ISR) &= (__FLAG__)) + +/** + * @brief Get the selected ADC's flag status. + * @param __HANDLE__: ADC handle. + * @param __FLAG__: ADC flag. + * @retval None + */ +#define __HAL_ADC_GET_FLAG(__HANDLE__, __FLAG__) ((((__HANDLE__)->Instance->ISR) & (__FLAG__)) == (__FLAG__)) + + + +/** + * @brief Configuration of ADC clock & prescaler: clock source PCLK or Asynchronous with selectable prescaler + * @param __HANDLE__: ADC handle + * @retval None + */ + +#define __HAL_ADC_CLOCK_PRESCALER(__HANDLE__) \ + do{ \ + if ((((__HANDLE__)->Init.ClockPrescaler) == ADC_CLOCKPRESCALER_PCLK_DIV1) || \ + (((__HANDLE__)->Init.ClockPrescaler) == ADC_CLOCKPRESCALER_PCLK_DIV2) || \ + (((__HANDLE__)->Init.ClockPrescaler) == ADC_CLOCKPRESCALER_PCLK_DIV2)) \ + { \ + (__HANDLE__)->Instance->CFGR2 &= ~(ADC_CFGR2_CKMODE); \ + (__HANDLE__)->Instance->CFGR2 |= (__HANDLE__)->Init.ClockPrescaler; \ + } \ + else \ + { \ + /* CKMOD bits must be reset */ \ + (__HANDLE__)->Instance->CFGR2 &= ~(ADC_CFGR2_CKMODE); \ + ADC->CCR &= ~(ADC_CCR_PRESC); \ + ADC->CCR |= (__HANDLE__)->Init.ClockPrescaler; \ + } \ + } while(0) + + /** + * @} + */ + +/* Include ADC HAL Extension module */ +#include "stm32l0xx_hal_adc_ex.h" + +/* Exported functions --------------------------------------------------------*/ +/* Initialization and de-initialization functions **********************************/ +HAL_StatusTypeDef HAL_ADC_Init(ADC_HandleTypeDef* hadc); +HAL_StatusTypeDef HAL_ADC_DeInit(ADC_HandleTypeDef *hadc); +void HAL_ADC_MspInit(ADC_HandleTypeDef* hadc); +void HAL_ADC_MspDeInit(ADC_HandleTypeDef* hadc); + +/* IO operation functions *****************************************************/ +/* Blocking mode: Polling */ +HAL_StatusTypeDef HAL_ADC_Start(ADC_HandleTypeDef* hadc); +HAL_StatusTypeDef HAL_ADC_Stop(ADC_HandleTypeDef* hadc); +HAL_StatusTypeDef HAL_ADC_PollForConversion(ADC_HandleTypeDef* hadc, uint32_t Timeout); +HAL_StatusTypeDef HAL_ADC_PollForEvent(ADC_HandleTypeDef* hadc, uint32_t EventType, uint32_t Timeout); + +/* Non-blocking mode: Interruption */ +HAL_StatusTypeDef HAL_ADC_Start_IT(ADC_HandleTypeDef* hadc); +HAL_StatusTypeDef HAL_ADC_Stop_IT(ADC_HandleTypeDef* hadc); + +/* Non-blocking mode: DMA */ +HAL_StatusTypeDef HAL_ADC_Start_DMA(ADC_HandleTypeDef* hadc, uint32_t* pData, uint32_t Length); +HAL_StatusTypeDef HAL_ADC_Stop_DMA(ADC_HandleTypeDef* hadc); + +/* ADC retrieve conversion value intended to be used with polling or interruption */ +uint32_t HAL_ADC_GetValue(ADC_HandleTypeDef* hadc); + +/* ADC IRQHandler and Callbacks used in non-blocking modes (Interruption and DMA) */ +void HAL_ADC_IRQHandler(ADC_HandleTypeDef* hadc); +void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef* hadc); +void HAL_ADC_ConvHalfCpltCallback(ADC_HandleTypeDef* hadc); +void HAL_ADC_LevelOutOfWindowCallback(ADC_HandleTypeDef* hadc); +void HAL_ADC_ErrorCallback(ADC_HandleTypeDef *hadc); + +/* Peripheral Control functions ***********************************************/ +HAL_StatusTypeDef HAL_ADC_ConfigChannel(ADC_HandleTypeDef* hadc, ADC_ChannelConfTypeDef* sConfig); +HAL_StatusTypeDef HAL_ADC_AnalogWDGConfig(ADC_HandleTypeDef* hadc, ADC_AnalogWDGConfTypeDef* AnalogWDGConfig); + +/* Peripheral State functions *************************************************/ +HAL_ADC_StateTypeDef HAL_ADC_GetState(ADC_HandleTypeDef* hadc); +uint32_t HAL_ADC_GetError(ADC_HandleTypeDef *hadc); + + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /*__STM32L0xx_ADC_H */ + + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_adc_ex.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_adc_ex.c new file mode 100644 index 0000000000..585f250b5e --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_adc_ex.c @@ -0,0 +1,273 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_adc_ex.c + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief This file provides firmware functions to manage the following + * functionalities of the Analog to Digital Convertor (ADC) + * peripheral: + * + Start calibration. + * + Read the calibration factor. + * + Set a calibration factor. + * + @verbatim + ============================================================================== + ##### ADC specific features ##### + ============================================================================== + [..] + (#) Self calibration. + + + ##### How to use this driver ##### + ============================================================================== + [..] + + (#) Call HAL_ADCEx_Calibration_Start() to start calibration + + (#) Read the calibration factor using HAL_ADCEx_Calibration_GetValue() + + (#) User can set a his calibration factor using HAL_ADCEx_Calibration_SetValue() + + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @addtogroup ADCEx + * @brief ADC driver modules + * @{ + */ + +#ifdef HAL_ADC_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ + + +/** @defgroup ADCEx_Group ADC Extended features functions + * @brief ADC Extended features functions + * +@verbatim + =============================================================================== + ##### ADC Extended features functions ##### + =============================================================================== + [..] +This subsection provides functions allowing to: + (+) Start calibration. + (+) Get calibration factor. + (+) Set calibration factor. + +@endverbatim + * @{ + */ + + +/** + * @brief Start an automatic calibration + * @param hadc: pointer to a ADC_HandleTypeDef structure that contains + * the configuration information for the specified ADC. + * @param SingleDiff: Selection of single-ended or differential input + * This parameter can be only of the following values: + * @arg ADC_SINGLE_ENDED: Channel in mode input single ended + * @retval HAL status + */ +HAL_StatusTypeDef HAL_ADCEx_Calibration_Start(ADC_HandleTypeDef* hadc, uint32_t SingleDiff) +{ + uint32_t tickstart = 0; + + /* Check the parameters */ + assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance)); + assert_param(IS_ADC_SINGLE_DIFFERENTIAL(SingleDiff)); + + /* Process locked */ + __HAL_LOCK(hadc); + + /* Disable the ADC (if not already disabled) */ + if (__HAL_ADC_IS_ENABLED(hadc) != RESET ) + { + /* Check if conditions to disable the ADC are fulfilled */ + if (__HAL_ADC_DISABLING_CONDITIONS(hadc) != RESET) + { + __HAL_ADC_DISABLE(hadc); + } + else + { + hadc->State= HAL_ADC_STATE_ERROR; + + /* Process unlocked */ + __HAL_UNLOCK(hadc); + + return HAL_ERROR; + } + + /* Wait for ADC effectively disabled */ + /* Get timeout */ + tickstart = HAL_GetTick(); + + /* Wait for disabling completion */ + while(HAL_IS_BIT_SET(hadc->Instance->CR, ADC_CR_ADEN)) + { + /* Check for the Timeout */ + if(ADC_DISABLE_TIMEOUT != HAL_MAX_DELAY) + { + if((HAL_GetTick() - tickstart ) > ADC_DISABLE_TIMEOUT) + { + hadc->State= HAL_ADC_STATE_TIMEOUT; + + /* Process unlocked */ + __HAL_UNLOCK(hadc); + + return HAL_TIMEOUT; + } + } + } + } + + /* Start ADC calibration */ + hadc->Instance->CR |= ADC_CR_ADCAL; + + /* Get timeout */ + tickstart = HAL_GetTick(); + + /* Wait for calibration completion */ + while(HAL_IS_BIT_SET(hadc->Instance->CR, ADC_CR_ADCAL)) + { + /* Check for the Timeout */ + if(ADC_CALIBRATION_TIMEOUT != HAL_MAX_DELAY) + { + if((HAL_GetTick() - tickstart ) > ADC_CALIBRATION_TIMEOUT) + { + hadc->State= HAL_ADC_STATE_TIMEOUT; + + /* Process unlocked */ + __HAL_UNLOCK(hadc); + + return HAL_TIMEOUT; + } + } + } + + /* Process unlocked */ + __HAL_UNLOCK(hadc); + + /* Return function status */ + return HAL_OK; + +} + +/** + * @brief Get the calibration factor. + * @param hadc: ADC handle. + * @param SingleDiff: This parameter can be only: + * @arg ADC_SINGLE_ENDED: Channel in mode input single ended. + * @retval Calibration value. + */ +uint32_t HAL_ADCEx_Calibration_GetValue(ADC_HandleTypeDef* hadc, uint32_t SingleDiff) +{ + /* Check the parameters */ + assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance)); + assert_param(IS_ADC_SINGLE_DIFFERENTIAL(SingleDiff)); + + /* Return the ADC calibration value */ + return ((hadc->Instance->CALFACT) & 0x0000007F); +} + +/** + * @brief Set the calibration factor to overwrite automatic conversion result. + * ADC must be enabled and no conversion is ongoing. + * @param hadc: ADC handle + * @param SingleDiff: This parameter can be only: + * @arg ADC_SINGLE_ENDED: Channel in mode input single ended. + * @param CalibrationFactor: Calibration factor (coded on 7 bits maximum) + * @retval HAL state + */ +HAL_StatusTypeDef HAL_ADCEx_Calibration_SetValue(ADC_HandleTypeDef* hadc, uint32_t SingleDiff, uint32_t CalibrationFactor) +{ + HAL_StatusTypeDef tmpHALStatus = HAL_OK; + + /* Check the parameters */ + assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance)); + assert_param(IS_ADC_SINGLE_DIFFERENTIAL(SingleDiff)); + assert_param(IS_ADC_CALFACT(CalibrationFactor)); + + /* Process locked */ + __HAL_LOCK(hadc); + + /* Verification of hardware constraints before modifying the calibration */ + /* factors register: ADC must be enabled, no conversion on going. */ + if ( (__HAL_ADC_IS_ENABLED(hadc) != RESET) && + (__HAL_ADC_IS_CONVERSION_ONGOING(hadc) == RESET) ) + { + /* Set the selected ADC calibration value */ + hadc->Instance->CALFACT &= ~ADC_CALFACT_CALFACT; + hadc->Instance->CALFACT |= CalibrationFactor; + } + else + { + /* Update ADC state machine to error */ + hadc->State = HAL_ADC_STATE_ERROR; + + /* Update ADC state machine to error */ + tmpHALStatus = HAL_ERROR; + } + + /* Process unlocked */ + __HAL_UNLOCK(hadc); + + /* Return function status */ + return tmpHALStatus; +} + +/** + * @} + */ + + +#endif /* HAL_ADC_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_adc_ex.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_adc_ex.h new file mode 100644 index 0000000000..1d51ff497c --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_adc_ex.h @@ -0,0 +1,121 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_adc_ex.h + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief This file contains all the functions prototypes for the ADC firmware + * library. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32L0xx_ADC_EX_H +#define __STM32L0xx_ADC_EX_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal_def.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @addtogroup ADCEx + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/* Exported constants --------------------------------------------------------*/ +/** @defgroup ADCEx_Exported_Constants + * @{ + */ + + /** @defgroup ADCEx_TimeOut_Values + * @{ + */ +#define ADC_CALIBRATION_TIMEOUT 10 +/** + * @} + */ + + +/** @defgroup ADCEx_Channel_Mode + * @{ + */ +#define ADC_SINGLE_ENDED (uint32_t)0x00000000 /* dummy value */ +#define IS_ADC_SINGLE_DIFFERENTIAL(SING_DIFF) ((SING_DIFF) == ADC_SINGLE_ENDED) +/** + * @} + */ + +/** @defgroup ADCEx_calibration_factor_length_verification + * @{ + */ +/** + * @brief Calibration factor lenght verification (7 bits maximum) + * @param _Calibration_Factor_: Calibration factor value + * @retval None + */ +#define IS_ADC_CALFACT(_Calibration_Factor_) ((_Calibration_Factor_) <= ((uint32_t)0x7F)) +/** + * @} + */ + +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/* Peripheral Control functions ***********************************************/ +HAL_StatusTypeDef HAL_ADCEx_Calibration_Start(ADC_HandleTypeDef* hadc, uint32_t SingleDiff); +uint32_t HAL_ADCEx_Calibration_GetValue(ADC_HandleTypeDef* hadc, uint32_t SingleDiff); +HAL_StatusTypeDef HAL_ADCEx_Calibration_SetValue(ADC_HandleTypeDef* hadc, uint32_t SingleDiff, uint32_t CalibrationFactor); + + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /*__STM32L0xx_ADC_H */ + + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_comp.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_comp.c new file mode 100644 index 0000000000..4be7b5f3e5 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_comp.c @@ -0,0 +1,609 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_comp.c + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief COMP HAL module driver. + * + * This file provides firmware functions to manage the following + * functionalities of the COMP peripheral: + * + Initialization/de-initialization functions + * + I/O operation functions + * + Peripheral Control functions + * + Peripheral State functions + * + @verbatim +================================================================================ + ##### COMP Peripheral features ##### +================================================================================ + + [..] + The STM32L0xx device family integrates 2 analog comparators COMP1 and COMP2: + (#) The non inverting input and inverting input can be set to GPIO pins + as shown in table1. COMP Inputs below. + + (#) The COMP output is available using HAL_COMP_GetOutputLevel() + and can be set on GPIO pins. Refer to table 2. COMP Outputs below. + + (#) The COMP output can be redirected to embedded timers (TIM2, TIM21, TIM22...) and LPTIM + Refer to TIM and LPTIM drivers. + + (#) The comparators COMP1 and COMP2 can be combined in window mode and only COMP2 non inverting input can be used as non-inverting input. + + (#) The 2 comparators have interrupt capability with wake-up + from Sleep and Stop modes (through the EXTI controller): + (++) COMP1 is internally connected to EXTI Line 21 + (++) COMP2 is internally connected to EXTI Line 22 + + From the corresponding IRQ handler, the right interrupt source can be retrieved with the + macro __HAL_COMP_EXTI_GET_FLAG(). Possible values are: + (++) COMP_EXTI_LINE_COMP1_EVENT + (++) COMP_EXTI_LINE_COMP2_EVENT + + +[..] Table 1. COMP Inputs for the STM32L0xx devices + +--------------------------------------------------+ + | | | COMP1 | COMP2 | + |-----------------|----------------|---------------| + | | 1/4 VREFINT | -- | OK | + | | 1/2 VREFINT | -- | OK | + | | 3/4 VREFINT | -- | OK | + | Inverting Input | VREFINT | OK | OK | + | | DAC OUT (PA4) | OK | OK | + | | IO1 | PA0 | PA2 | + | | IO2 | PA5 | PA5 | + | | IO3 | --- | PB3 | + |-----------------|----------------|-------|-------| + | Non Inverting | IO1 | PA1 | PA3 | + | Input | IO2 | --- | PB4 | + | | IO3 | --- | PB5 | + | | IO4 | --- | PB6 | + | | IO5 | --- | PB7 | + +--------------------------------------------------+ + + [..] Table 2. COMP Outputs for the STM32L0xx devices + +---------------+ + | COMP1 | COMP2 | + |-------|-------| + | PA0 | PA2 | + | PA6 | PA7 | + | PA11 | PA12 | + +---------------+ + + + ##### How to use this driver ##### +================================================================================ + [..] + This driver provides functions to configure and program the Comparators of all STM32L0xx devices. + + To use the comparator, perform the following steps: + + (#) Initialize the COMP low level resources by implementing the HAL_COMP_MspInit(). + (++) Enable the SYSCFG APB clock to get write access to comparator register using __SYSCFG_CLK_ENABLE(). + (++) Configure the comparator input in analog mode using HAL_GPIO_Init(). + (++) Configure the comparator output in alternate function mode using HAL_GPIO_Init() to map the comparator + output to the GPIO pin. + (++) If required enable the VREFINT reference using HAL_VREFINT_Cmd() and HAL_COMP_EnableBuffer_Cmd(). + (++) If required enable the COMP interrupt by configuring and enabling EXTI line in Interrupt mode and + selecting the desired sensitivity level using HAL_GPIO_Init() function. After that enable the comparator + interrupt vector using HAL_NVIC_EnableIRQ() function. + + (#) Configure the comparator using HAL_COMP_Init() function: + (++) Select the inverting input + (++) Select the non-inverting input + (++) Select the output polarity + (++) Select the power mode + (++) Select the window mode + + (#) Enable the comparator using HAL_COMP_Start() function + + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @defgroup COMP + * @brief COMP HAL module driver + * @{ + */ + +#ifdef HAL_COMP_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* CSR register reset value */ +#define COMP_CSR_RESET_VALUE ((uint32_t)0x00000000) + +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup COMP_Private_Functions + * @{ + */ + +/** @defgroup HAL_COMP_Group1 Initialization/de-initialization functions + * @brief Initialization and Configuration functions + * +@verbatim + =============================================================================== + ##### Initialization/de-initialization functions ##### + =============================================================================== + [..] This section provides functions to initialize and de-initialize comparators + +@endverbatim + * @{ + */ + +/** + * @brief Initializes the COMP according to the specified + * parameters in the COMP_InitTypeDef and create the associated handle. + * @note If the selected comparator is locked, initialization can't be performed. + * To unlock the configuration, perform a system reset. + * @param hcomp: COMP handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_COMP_Init(COMP_HandleTypeDef *hcomp) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check the COMP handle allocation and lock status */ + if((hcomp == NULL) || ((hcomp->State & COMP_STATE_BIT_LOCK) != 0x00)) + { + status = HAL_ERROR; + } + else + { + /* Check the parameter */ + assert_param(IS_COMP_ALL_INSTANCE(hcomp->Instance)); + assert_param(IS_COMP_INVERTINGINPUT(hcomp->Init.InvertingInput)); + assert_param(IS_COMP_NONINVERTINGINPUT(hcomp->Init.NonInvertingInput)); + assert_param(IS_COMP_OUTPUTPOL(hcomp->Init.OutputPol)); + assert_param(IS_COMP_MODE(hcomp->Init.Mode)); + + if(hcomp->Init.WindowMode != COMP_WINDOWMODE_DISABLED) + { + assert_param(IS_COMP_WINDOWMODE_INSTANCE(hcomp->Instance)); + assert_param(IS_COMP_WINDOWMODE(hcomp->Init.WindowMode)); + } + + if(hcomp->State == HAL_COMP_STATE_RESET) + { + /* Init the low level hardware : SYSCFG to access comparators */ + HAL_COMP_MspInit(hcomp); + } + + /* Change COMP peripheral state */ + hcomp->State = HAL_COMP_STATE_BUSY; + + /* Set COMP parameters */ + /* Set COMPxINSEL bits according to hcomp->Init.InvertingInput value */ + /* Set COMPxNONINSEL bits according to hcomp->Init.NonInvertingInput value */ + /* Set COMPxPOL bit according to hcomp->Init.OutputPol value */ + /* Set COMPxMODE bits according to hcomp->Init.Mode value */ + /* Set COMP1WM bit according to hcomp->Init.WindowMode value */ + MODIFY_REG(hcomp->Instance->CSR, COMP_CSR_UPDATE_PARAMETERS_MASK, \ + hcomp->Init.InvertingInput | \ + hcomp->Init.NonInvertingInput | \ + hcomp->Init.OutputPol | \ + hcomp->Init.Mode | \ + hcomp->Init.WindowMode); + + + /* Initialize the COMP state*/ + hcomp->State = HAL_COMP_STATE_READY; + + } + + return status; +} + +/** + * @brief DeInitializes the COMP peripheral + * @note Deinitialization can't be performed if the COMP configuration is locked. + * To unlock the configuration, perform a system reset. + * @param hcomp: COMP handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_COMP_DeInit(COMP_HandleTypeDef *hcomp) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check the COMP handle allocation and lock status */ + if((hcomp == NULL) || ((hcomp->State & COMP_STATE_BIT_LOCK) != 0x00)) + { + status = HAL_ERROR; + } + else + { + /* Check the parameter */ + assert_param(IS_COMP_ALL_INSTANCE(hcomp->Instance)); + + /* Set COMP_CSR register to reset value */ + WRITE_REG(hcomp->Instance->CSR, COMP_CSR_RESET_VALUE); + + /* DeInit the low level hardware: SYSCFG, GPIO, CLOCK and NVIC */ + HAL_COMP_MspDeInit(hcomp); + + hcomp->State = HAL_COMP_STATE_RESET; + + /* Release Lock */ + __HAL_UNLOCK(hcomp); + } + + return status; +} + +/** + * @brief Initializes the COMP MSP. + * @param hcomp: COMP handle + * @retval None + */ +__weak void HAL_COMP_MspInit(COMP_HandleTypeDef *hcomp) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_COMP_MspInit could be implenetd in the user file + */ +} + +/** + * @brief DeInitializes COMP MSP. + * @param hcomp: COMP handle + * @retval None + */ +__weak void HAL_COMP_MspDeInit(COMP_HandleTypeDef *hcomp) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_COMP_MspDeInit could be implenetd in the user file + */ +} + +/** + * @} + */ + +/** @defgroup HAL_COMP_Group2 I/O operation functions + * @brief Data transfers functions + * +@verbatim + =============================================================================== + ##### IO operation functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to manage the COMP data + transfers. + +@endverbatim + * @{ + */ + +/** + * @brief Start the comparator + * @param hcomp: COMP handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_COMP_Start(COMP_HandleTypeDef *hcomp) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check the COMP handle allocation and lock status */ + if((hcomp == NULL) || ((hcomp->State & COMP_STATE_BIT_LOCK) != 0x00)) + { + status = HAL_ERROR; + } + else + { + /* Check the parameter */ + assert_param(IS_COMP_ALL_INSTANCE(hcomp->Instance)); + + if(hcomp->State == HAL_COMP_STATE_READY) + { + /* Enable the selected comparator */ + __HAL_COMP_ENABLE(hcomp); + + hcomp->State = HAL_COMP_STATE_BUSY; + } + else + { + status = HAL_ERROR; + } + } + + return status; +} + +/** + * @brief Stop the comparator + * @param hcomp: COMP handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_COMP_Stop(COMP_HandleTypeDef *hcomp) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check the COMP handle allocation and lock status */ + if((hcomp == NULL) || ((hcomp->State & COMP_STATE_BIT_LOCK) != 0x00)) + { + status = HAL_ERROR; + } + else + { + /* Check the parameter */ + assert_param(IS_COMP_ALL_INSTANCE(hcomp->Instance)); + + if(hcomp->State == HAL_COMP_STATE_BUSY) + { + /* Disable the selected comparator */ + __HAL_COMP_DISABLE(hcomp); + + hcomp->State = HAL_COMP_STATE_READY; + } + else + { + status = HAL_ERROR; + } + } + + return status; +} + +/** + * @brief Enables the interrupt and starts the comparator + * @param hcomp: COMP handle + * @param mode: IT trigger mode: a value of @ref COMP_TriggerMode + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_COMP_Start_IT(COMP_HandleTypeDef *hcomp) +{ + HAL_StatusTypeDef status = HAL_OK; + uint32_t extiline = 0; + + status = HAL_COMP_Start(hcomp); + if(status == HAL_OK) + { + /* Check the Exti Line output configuration */ + extiline = __HAL_COMP_GET_EXTI_LINE(hcomp->Instance); + + /* Configure the rising edge */ + if((hcomp->Init.TriggerMode & COMP_TRIGGERMODE_IT_RISING) != 0x00) + { + __HAL_COMP_EXTI_RISING_IT_ENABLE(extiline); + } + else + { + __HAL_COMP_EXTI_RISING_IT_DISABLE(extiline); + } + + /* Configure the falling edge */ + if((hcomp->Init.TriggerMode & COMP_TRIGGERMODE_IT_FALLING) != 0x00) + { + __HAL_COMP_EXTI_FALLING_IT_ENABLE(extiline); + } + else + { + __HAL_COMP_EXTI_FALLING_IT_DISABLE(extiline); + } + + /* Enable Exti interrupt mode */ + __HAL_COMP_EXTI_ENABLE_IT(extiline); + + /* Clear COMP Exti pending bit */ + __HAL_COMP_EXTI_CLEAR_FLAG(extiline); + } + + return status; +} + +/** + * @brief Disable the interrupt and Stop the comparator + * @param hcomp: COMP handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_COMP_Stop_IT(COMP_HandleTypeDef *hcomp) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Disable the Exti Line interrupt mode */ + __HAL_COMP_EXTI_DISABLE_IT(__HAL_COMP_GET_EXTI_LINE(hcomp->Instance)); + + status = HAL_COMP_Stop(hcomp); + + return status; +} + +/** + * @brief Comparator IRQ Handler + * @param hcomp: COMP handle + * @retval HAL status + */ +void HAL_COMP_IRQHandler(COMP_HandleTypeDef *hcomp) +{ + uint32_t extiline = __HAL_COMP_GET_EXTI_LINE(hcomp->Instance); + + /* Check COMP Exti flag */ + if(__HAL_COMP_EXTI_GET_FLAG(extiline) != RESET) + { + /* Clear COMP Exti pending bit */ + __HAL_COMP_EXTI_CLEAR_FLAG(extiline); + } + + /* COMP trigger user callback */ + HAL_COMP_TriggerCallback(hcomp); +} + +/** + * @} + */ + +/** @defgroup HAL_COMP_Group3 Peripheral Control functions + * @brief management functions + * +@verbatim + =============================================================================== + ##### Peripheral Control functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to control the COMP data + transfers. + +@endverbatim + * @{ + */ + +/** + * @brief Lock the selected comparator configuration. + * @param hcomp: COMP handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_COMP_Lock(COMP_HandleTypeDef *hcomp) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check the COMP handle allocation and lock status */ + if((hcomp == NULL) || ((hcomp->State & COMP_STATE_BIT_LOCK) != 0x00)) + { + status = HAL_ERROR; + } + else + { + /* Check the parameter */ + assert_param(IS_COMP_ALL_INSTANCE(hcomp->Instance)); + + /* Set lock flag */ + hcomp->State |= COMP_STATE_BIT_LOCK; + + /* Set the lock bit corresponding to selected comparator */ + __HAL_COMP_LOCK(hcomp); + } + + return status; +} + +/** + * @brief Return the output level (high or low) of the selected comparator. + * The output level depends on the selected polarity. + * If the polarity is not inverted: + * - Comparator output is low when the non-inverting input is at a lower + * voltage than the inverting input + * - Comparator output is high when the non-inverting input is at a higher + * voltage than the inverting input + * If the polarity is inverted: + * - Comparator output is high when the non-inverting input is at a lower + * voltage than the inverting input + * - Comparator output is low when the non-inverting input is at a higher + * voltage than the inverting input + * @param hcomp: COMP handle + * @retval Returns the selected comparator output level: COMP_OUTPUTLEVEL_LOW or COMP_OUTPUTLEVEL_HIGH. + * + */ +uint32_t HAL_COMP_GetOutputLevel(COMP_HandleTypeDef *hcomp) +{ + /* Check the parameter */ + assert_param(IS_COMP_ALL_INSTANCE(hcomp->Instance)); + + return((uint32_t)(hcomp->Instance->CSR & COMP_OUTPUTLEVEL_HIGH)); +} + +/** + * @brief Comparator callback. + * @param hcomp: COMP handle + * @retval None + */ +__weak void HAL_COMP_TriggerCallback(COMP_HandleTypeDef *hcomp) +{ + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_COMP_TriggerCallback should be implemented in the user file + */ +} + + +/** + * @} + */ + +/** @defgroup HAL_COMP_Group4 Peripheral State functions + * @brief Peripheral State functions + * +@verbatim + =============================================================================== + ##### Peripheral State functions ##### + =============================================================================== + [..] + This subsection permit to get in run-time the status of the peripheral + and the data flow. + +@endverbatim + * @{ + */ + +/** + * @brief Return the COMP state + * @param hcomp : COMP handle + * @retval HAL state + */ +HAL_COMP_StateTypeDef HAL_COMP_GetState(COMP_HandleTypeDef *hcomp) +{ + /* Check the COMP handle allocation */ + if(hcomp == NULL) + { + return HAL_COMP_STATE_RESET; + } + + /* Check the parameter */ + assert_param(IS_COMP_ALL_INSTANCE(hcomp->Instance)); + + return hcomp->State; +} +/** + * @} + */ + +/** + * @} + */ + +#endif /* HAL_COMP_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_comp.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_comp.h new file mode 100644 index 0000000000..e0ce932e9f --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_comp.h @@ -0,0 +1,411 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_comp.h + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief Header file of COMP HAL module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32L0xx_HAL_COMP_H +#define __STM32L0xx_HAL_COMP_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal_def.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @addtogroup COMP + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ + +/** + * @brief COMP Init structure definition + */ + +typedef struct +{ + + uint32_t InvertingInput; /*!< Selects the inverting input of the comparator. + This parameter can be a value of @ref COMP_InvertingInput */ + + uint32_t NonInvertingInput; /*!< Selects the non inverting input of the comparator. + This parameter can be a value of @ref COMP_NonInvertingInput */ + + uint32_t OutputPol; /*!< Selects the output polarity of the comparator. + This parameter can be a value of @ref COMP_OutputPolarity */ + + uint32_t Mode; /*!< Selects the operating comsumption mode of the comparator + to adjust the speed/consumption. + This parameter can be a value of @ref COMP_Mode */ + + uint32_t WindowMode; /*!< Selects the window mode of the comparator 2. + This parameter can be a value of @ref COMP_WindowMode */ + + uint32_t TriggerMode; /*!< Selects the trigger mode of the comparator (interrupt mode). + This parameter can be a value of @ref COMP_TriggerMode */ + +}COMP_InitTypeDef; + +/** + * @brief HAL State structures definition + */ +typedef enum +{ + HAL_COMP_STATE_RESET = 0x00, /*!< COMP not yet initialized or disabled */ + HAL_COMP_STATE_READY = 0x01, /*!< COMP initialized and ready for use */ + HAL_COMP_STATE_READY_LOCKED = 0x11, /*!< COMP initialized but the configuration is locked */ + HAL_COMP_STATE_BUSY = 0x02, /*!< COMP is running */ + HAL_COMP_STATE_BUSY_LOCKED = 0x12 /*!< COMP is running and the configuration is locked */ +}HAL_COMP_StateTypeDef; + +/** + * @brief PPP Handle Structure definition + */ +typedef struct +{ + COMP_TypeDef *Instance; /*!< Register base address */ + COMP_InitTypeDef Init; /*!< COMP required parameters */ + HAL_LockTypeDef Lock; /*!< Locking object */ + __IO HAL_COMP_StateTypeDef State; /*!< COMP communication state */ +} COMP_HandleTypeDef; + +/* Exported constants --------------------------------------------------------*/ +/** @defgroup COMP_Exported_Constants + * @{ + */ + +/** @defgroup COMP_OutputPolarity + * @{ + */ +#define COMP_OUTPUTPOL_NONINVERTED ((uint32_t)0x00000000) /*!< COMP output on GPIO isn't inverted */ +#define COMP_OUTPUTPOL_INVERTED COMP_CSR_COMPxPOLARITY /*!< COMP output on GPIO is inverted */ +#define IS_COMP_OUTPUTPOL(POL) (((POL) == COMP_OUTPUTPOL_NONINVERTED) || \ + ((POL) == COMP_OUTPUTPOL_INVERTED)) +/** + * @} + */ + + +/** @defgroup COMP_InvertingInput + * @{ + */ + +/* Inverting Input specific to COMP1 */ +#define COMP_INVERTINGINPUT_VREFINT ((uint32_t)0x00000000) /*!< VREFINT connected to comparator1 inverting input */ +#define COMP_INVERTINGINPUT_IO1 ((uint32_t)0x00000010) /*!< I/O1 connected to comparator inverting input (PA0) for COMP1 and (PA2) for COMP2*/ +#define COMP_INVERTINGINPUT_DAC1 ((uint32_t)0x00000020) /*!< DAC1_OUT (PA4) connected to comparator inverting input */ +#define COMP_INVERTINGINPUT_IO2 ((uint32_t)0x00000030) /*!< I/O2 (PA5) connected to comparator inverting input */ + +/* Inverting Input specific to COMP2 */ +#define COMP_INVERTINGINPUT_1_4VREFINT ((uint32_t)0x00000040) /*!< 1/4 VREFINT connected to comparator inverting input */ +#define COMP_INVERTINGINPUT_1_2VREFINT ((uint32_t)0x00000050) /*!< 1/2 VREFINT connected to comparator inverting input */ +#define COMP_INVERTINGINPUT_3_4VREFINT ((uint32_t)0x00000060) /*!< 3/4 VREFINT connected to comparator inverting input */ +#define COMP_INVERTINGINPUT_IO3 ((uint32_t)0x00000070) /*!< I/O3 (PB3) for COMP2 connected to comparator inverting input */ + + +#define IS_COMP_INVERTINGINPUT(INPUT) (((INPUT) == COMP_INVERTINGINPUT_VREFINT) || \ + ((INPUT) == COMP_INVERTINGINPUT_IO1) || \ + ((INPUT) == COMP_INVERTINGINPUT_DAC1) || \ + ((INPUT) == COMP_INVERTINGINPUT_IO2) || \ + ((INPUT) == COMP_INVERTINGINPUT_1_4VREFINT) || \ + ((INPUT) == COMP_INVERTINGINPUT_1_2VREFINT) || \ + ((INPUT) == COMP_INVERTINGINPUT_3_4VREFINT) || \ + ((INPUT) == COMP_INVERTINGINPUT_IO3)) + +/** + * @} + */ + + +/** @defgroup COMP_NonInvertingInput + * @{ + */ + +#define COMP_NONINVERTINGINPUT_IO1 ((uint32_t)0x00000000) /*!< I/O1 (PA3) connected to comparator non inverting input */ +#define COMP_NONINVERTINGINPUT_IO2 ((uint32_t)0x00000100) /*!< I/O2 (PB4) connected to comparator non inverting input */ +#define COMP_NONINVERTINGINPUT_IO3 ((uint32_t)0x00000200) /*!< I/O3 (PB5) connected to comparator non inverting input */ +#define COMP_NONINVERTINGINPUT_IO4 ((uint32_t)0x00000300) /*!< I/O1 (PB6) connected to comparator non inverting input */ +#define COMP_NONINVERTINGINPUT_IO5 ((uint32_t)0x00000400) /*!< I/O3 (PB7) connected to comparator non inverting input */ +#define COMP_NONINVERTINGINPUT_IO6 ((uint32_t)0x00000500) /*!< I/O3 (PB7) connected to comparator non inverting input */ +#define COMP_NONINVERTINGINPUT_IO7 ((uint32_t)0x00000600) /*!< I/O3 (PB7) connected to comparator non inverting input */ +#define COMP_NONINVERTINGINPUT_IO8 ((uint32_t)0x00000700) /*!< I/O3 (PB7) connected to comparator non inverting input */ + +#define IS_COMP_NONINVERTINGINPUT(INPUT) (((INPUT) == COMP_NONINVERTINGINPUT_IO1) || \ + ((INPUT) == COMP_NONINVERTINGINPUT_IO2) || \ + ((INPUT) == COMP_NONINVERTINGINPUT_IO3) || \ + ((INPUT) == COMP_NONINVERTINGINPUT_IO4) || \ + ((INPUT) == COMP_NONINVERTINGINPUT_IO5) || \ + ((INPUT) == COMP_NONINVERTINGINPUT_IO6) || \ + ((INPUT) == COMP_NONINVERTINGINPUT_IO7) || \ + ((INPUT) == COMP_NONINVERTINGINPUT_IO8)) +/** + * @} + */ + + +/** @defgroup COMP_Mode + * @{ + */ +/* Please refer to the electrical characteristics in the device datasheet for + the power consumption values */ +#define COMP_MODE_HIGHSPEED COMP_CSR_COMP2SPEED /*!< High Speed */ +#define COMP_MODE_LOWSPEED ((uint32_t)0x00000000) /*!< Low Speed */ + +#define IS_COMP_MODE(SPEED) (((SPEED) == COMP_MODE_HIGHSPEED) || \ + ((SPEED) == COMP_MODE_LOWSPEED)) +/** + * @} + */ + +/** @defgroup COMP_WindowMode + * @{ + */ +#define COMP_WINDOWMODE_DISABLED ((uint32_t)0x00000000) /*!< Window mode disabled (Plus input of comparator 1 connected to PA1)*/ +#define COMP_WINDOWMODE_ENABLED COMP_CSR_COMP1WM /*!< Window mode enabled: Plus input of comparator 1 shorted with Plus input of comparator 2 */ +#define IS_COMP_WINDOWMODE(WINDOWMODE) (((WINDOWMODE) == COMP_WINDOWMODE_DISABLED) || \ + ((WINDOWMODE) == COMP_WINDOWMODE_ENABLED)) + +#define IS_COMP_WINDOWMODE_INSTANCE(INSTANCE) ((INSTANCE) == COMP1) +/** + * @} + */ + + +/** @defgroup COMP_OutputLevel + * @{ + */ +/* When output polarity is not inverted, comparator output is low when + the non-inverting input is at a lower voltage than the inverting input*/ +#define COMP_OUTPUTLEVEL_LOW ((uint32_t)0x00000000) +/* When output polarity is not inverted, comparator output is high when + the non-inverting input is at a higher voltage than the inverting input */ +#define COMP_OUTPUTLEVEL_HIGH COMP_CSR_COMPxOUTVALUE +/** + * @} + */ + +/* CSR register Mask */ +#define COMP_CSR_UPDATE_PARAMETERS_MASK ((uint32_t)0xC0008779) + +#define COMP_LOCK_DISABLE ((uint32_t)0x00000000) +#define COMP_LOCK_ENABLE COMP_CSR_COMPxLOCK + +#define COMP_STATE_BIT_LOCK ((uint32_t)0x10) + +/** @defgroup COMP_TriggerMode + * @{ + */ +#define COMP_TRIGGERMODE_IT_RISING ((uint32_t)0x00000001) /*!< External Interrupt Mode with Rising edge trigger detection */ +#define COMP_TRIGGERMODE_IT_FALLING ((uint32_t)0x00000002) /*!< External Interrupt Mode with Falling edge trigger detection */ +#define COMP_TRIGGERMODE_IT_RISING_FALLING ((uint32_t)0x00000003) /*!< External Interrupt Mode with Rising/Falling edge trigger detection */ +#define IS_COMP_TRIGGERMODE(MODE) (((MODE) == COMP_TRIGGERMODE_IT_RISING) || \ + ((MODE) == COMP_TRIGGERMODE_IT_FALLING) || \ + ((MODE) == COMP_TRIGGERMODE_IT_RISING_FALLING)) +/** + * @} + */ + +/** @defgroup COMP_ExtiLineEvent + * @{ + */ + +#define COMP_EXTI_LINE_COMP2_EVENT ((uint32_t)0x00400000) /*!< External interrupt line 22 Connected to COMP2 */ +#define COMP_EXTI_LINE_COMP1_EVENT ((uint32_t)0x00200000) /*!< External interrupt line 21 Connected to COMP1 */ + +/** + * @} + */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ +/** @brief Reset COMP handle state + * @param __HANDLE__: COMP handle. + * @retval None + */ +#define __HAL_COMP_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_COMP_STATE_RESET) + +/** + * @brief Enables the specified comparator + * @param __HANDLE__: COMP handle. + * @retval None. + */ +#define __HAL_COMP_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CSR |= (COMP_CSR_COMPxEN)) + +/** + * @brief Disables the specified comparator + * @param __HANDLE__: COMP handle. + * @retval None. + */ +#define __HAL_COMP_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CSR &= ~(COMP_CSR_COMPxEN)) + +/** + * @brief Lock the specified comparator configuration + * @param __HANDLE__: COMP handle. + * @retval None. + */ +#define __HAL_COMP_LOCK(__HANDLE__) ((__HANDLE__)->Instance->CSR |= COMP_CSR_COMPxLOCK) + +/** @brief Checks whether the specified COMP flag is set or not. + * @param __HANDLE__: specifies the COMP Handle. + * @param __FLAG__: specifies the flag to check. + * This parameter can be one of the following values: + * @arg COMP_FLAG_LOCK: lock flag + * @retval The new state of __FLAG__ (TRUE or FALSE). + */ +#define __HAL_COMP_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->CSR & (__FLAG__)) == (__FLAG__)) + + +/** + * @brief Enable the Exti Line rising edge trigger. + * @param __EXTILINE__: specifies the COMP Exti sources to be enabled. + * This parameter can be a value of @ref COMP_ExtiLineEvent + * @retval None. + */ +#define __HAL_COMP_EXTI_RISING_IT_ENABLE(__EXTILINE__) (EXTI->RTSR |= (__EXTILINE__)) + +/** + * @brief Disable the Exti Line rising edge trigger. + * @param __EXTILINE__: specifies the COMP Exti sources to be disabled. + * This parameter can be a value of @ref COMP_ExtiLineEvent + * @retval None. + */ +#define __HAL_COMP_EXTI_RISING_IT_DISABLE(__EXTILINE__) (EXTI->RTSR &= ~(__EXTILINE__)) + +/** + * @brief Enable the Exti Line falling edge trigger. + * @param __EXTILINE__: specifies the COMP Exti sources to be enabled. + * This parameter can be a value of @ref COMP_ExtiLineEvent + * @retval None. + */ +#define __HAL_COMP_EXTI_FALLING_IT_ENABLE(__EXTILINE__) (EXTI->FTSR |= (__EXTILINE__)) + +/** + * @brief Disable the Exti Line falling edge trigger. + * @param __EXTILINE__: specifies the COMP Exti sources to be disabled. + * This parameter can be a value of @ref COMP_ExtiLineEvent + * @retval None. + */ +#define __HAL_COMP_EXTI_FALLING_IT_DISABLE(__EXTILINE__) (EXTI->FTSR &= ~(__EXTILINE__)) + +/** + * @brief Get the specified EXTI line for a comparator instance + * @param __INSTANCE__: specifies the COMP instance. + * @retval value of @ref COMP_ExtiLineEvent + */ +#define __HAL_COMP_GET_EXTI_LINE(__INSTANCE__) (((__INSTANCE__) == COMP1) ? COMP_EXTI_LINE_COMP1_EVENT : \ + COMP_EXTI_LINE_COMP2_EVENT) + +/** + * @brief Enable the COMP Exti Line. + * @param __EXTILINE__: specifies the COMP Exti sources to be enabled. + * This parameter can be a value of @ref COMP_ExtiLineEvent + * @retval None. + */ +#define __HAL_COMP_EXTI_ENABLE_IT(__EXTILINE__) (EXTI->IMR |= (__EXTILINE__)) + +/** + * @brief Disable the COMP Exti Line. + * @param __EXTILINE__: specifies the COMP Exti sources to be disabled. + * This parameter can be a value of @ref COMP_ExtiLineEvent + * @retval None. + */ +#define __HAL_COMP_EXTI_DISABLE_IT(__EXTILINE__) (EXTI->IMR &= ~(__EXTILINE__)) + +/** + * @brief Checks whether the specified EXTI line flag is set or not. + * @param __FLAG__: specifies the COMP Exti sources to be checked. + * This parameter can be a value of @ref COMP_ExtiLineEvent + * @retval The state of __FLAG__ (SET or RESET). + */ +#define __HAL_COMP_EXTI_GET_FLAG(__FLAG__) (EXTI->PR & (__FLAG__)) + +/** + * @brief Clear the COMP Exti flags. + * @param __FLAG__: specifies the COMP Exti sources to be cleared. + * This parameter can be a value of @ref COMP_ExtiLineEvent + * @retval None. + */ +#define __HAL_COMP_EXTI_CLEAR_FLAG(__FLAG__) (EXTI->PR |= (__FLAG__)) + + +/* Exported functions --------------------------------------------------------*/ + +/* Initialization/de-initialization functions **********************************/ +HAL_StatusTypeDef HAL_COMP_Init(COMP_HandleTypeDef *hcomp); +HAL_StatusTypeDef HAL_COMP_DeInit (COMP_HandleTypeDef *hcomp); +void HAL_COMP_MspInit(COMP_HandleTypeDef *hcomp); +void HAL_COMP_MspDeInit(COMP_HandleTypeDef *hcomp); + +/* I/O operation functions *****************************************************/ +HAL_StatusTypeDef HAL_COMP_Start(COMP_HandleTypeDef *hcomp); +HAL_StatusTypeDef HAL_COMP_Stop(COMP_HandleTypeDef *hcomp); +HAL_StatusTypeDef HAL_COMP_Start_IT(COMP_HandleTypeDef *hcomp); +HAL_StatusTypeDef HAL_COMP_Stop_IT(COMP_HandleTypeDef *hcomp); +void HAL_COMP_IRQHandler(COMP_HandleTypeDef *hcomp); + +/* Peripheral Control functions ************************************************/ +HAL_StatusTypeDef HAL_COMP_Lock(COMP_HandleTypeDef *hcomp); +uint32_t HAL_COMP_GetOutputLevel(COMP_HandleTypeDef *hcomp); + +/* Callback in Interrupt mode */ +void HAL_COMP_TriggerCallback(COMP_HandleTypeDef *hcomp); + +/* Peripheral State functions **************************************************/ +HAL_COMP_StateTypeDef HAL_COMP_GetState(COMP_HandleTypeDef *hcomp); + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __STM32L0xx_HAL_COMP_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_conf.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_conf.h new file mode 100644 index 0000000000..1025fb65db --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_conf.h @@ -0,0 +1,292 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_conf.h + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief HAL configuration file. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32L0xx_HAL_CONF_H +#define __STM32L0xx_HAL_CONF_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Exported types ------------------------------------------------------------*/ +/* Exported constants --------------------------------------------------------*/ + +/* ########################## Module Selection ############################## */ +/** + * @brief This is the list of modules to be used in the HAL driver + */ +#define HAL_MODULE_ENABLED +#define HAL_ADC_MODULE_ENABLED +#define HAL_COMP_MODULE_ENABLED +#define HAL_CRC_MODULE_ENABLED +#define HAL_CRYP_MODULE_ENABLED +#define HAL_DAC_MODULE_ENABLED +#define HAL_DMA_MODULE_ENABLED +#define HAL_FLASH_MODULE_ENABLED +#define HAL_GPIO_MODULE_ENABLED +#define HAL_I2C_MODULE_ENABLED +#define HAL_I2S_MODULE_ENABLED +#define HAL_IWDG_MODULE_ENABLED +#define HAL_LCD_MODULE_ENABLED +#define HAL_LPTIM_MODULE_ENABLED +#define HAL_PWR_MODULE_ENABLED +#define HAL_RCC_MODULE_ENABLED +#define HAL_RNG_MODULE_ENABLED +#define HAL_RTC_MODULE_ENABLED +#define HAL_SPI_MODULE_ENABLED +#define HAL_TIM_MODULE_ENABLED +#define HAL_TSC_MODULE_ENABLED +#define HAL_UART_MODULE_ENABLED +#define HAL_USART_MODULE_ENABLED +#define HAL_IRDA_MODULE_ENABLED +#define HAL_SMARTCARD_MODULE_ENABLED +#define HAL_SMBUS_MODULE_ENABLED +#define HAL_WWDG_MODULE_ENABLED +#define HAL_CORTEX_MODULE_ENABLED +#define HAL_PCD_MODULE_ENABLED + + +/* ########################## Oscillator Values adaptation ####################*/ +/** + * @brief Adjust the value of External High Speed oscillator (HSE) used in your application. + * This value is used by the RCC HAL module to compute the system frequency + * (when HSE is used as system clock source, directly or through the PLL). + */ +#if !defined (HSE_VALUE) + #define HSE_VALUE ((uint32_t)8000000) /*!< Value of the External oscillator in Hz */ +#endif /* HSE_VALUE */ + +#if !defined (HSE_STARTUP_TIMEOUT) + #define HSE_STARTUP_TIMEOUT ((uint32_t)50) /*!< Time out for HSE start up, in ms */ +#endif /* HSE_STARTUP_TIMEOUT */ + +/** + * @brief Internal Multiple Speed oscillator (MSI) default value. + * This value is the default MSI range value after Reset. + */ +#if !defined (MSI_VALUE) + #define MSI_VALUE ((uint32_t)2000000) /*!< Value of the Internal oscillator in Hz*/ +#endif /* MSI_VALUE */ + +/** + * @brief Internal High Speed oscillator (HSI) value. + * This value is used by the RCC HAL module to compute the system frequency + * (when HSI is used as system clock source, directly or through the PLL). + */ +#if !defined (HSI_VALUE) + #define HSI_VALUE ((uint32_t)16000000) /*!< Value of the Internal oscillator in Hz*/ +#endif /* HSI_VALUE */ + +/** + * @brief External Low Speed oscillator (LSE) value. + * This value is used by the UART, RTC HAL module to compute the system frequency + */ +#if !defined (LSE_VALUE) + #define LSE_VALUE ((uint32_t)32768) /*!< Value of the External oscillator in Hz*/ +#endif /* LSE_VALUE */ + + +#if !defined (LSE_STARTUP_TIMEOUT) + #define LSE_STARTUP_TIMEOUT ((uint32_t)500) /*!< Time out for LSE start up, in ms */ +#endif /* HSE_STARTUP_TIMEOUT */ + + +/* Tip: To avoid modifying this file each time you need to use different HSE, + === you can define the HSE value in your toolchain compiler preprocessor. */ + +/* ########################### System Configuration ######################### */ +/** + * @brief This is the HAL system configuration section + */ +#define VDD_VALUE ((uint32_t)3300) /*!< Value of VDD in mv */ +#define TICK_INT_PRIORITY ((uint32_t)3) /*!< tick interrupt priority */ +#define USE_RTOS 0 +#define PREFETCH_ENABLE 1 +#define PREREAD_ENABLE 1 +#define BUFFER_CACHE_DISABLE 0 + +/* ########################## Assert Selection ############################## */ +/** + * @brief Uncomment the line below to expanse the "assert_param" macro in the + * HAL drivers code + */ +/* #define USE_FULL_ASSERT 1 */ + +/* Includes ------------------------------------------------------------------*/ +/** + * @brief Include module's header file + */ + +#ifdef HAL_RCC_MODULE_ENABLED + #include "stm32l0xx_hal_rcc.h" +#endif /* HAL_RCC_MODULE_ENABLED */ + +#ifdef HAL_GPIO_MODULE_ENABLED + #include "stm32l0xx_hal_gpio.h" +#endif /* HAL_GPIO_MODULE_ENABLED */ + +#ifdef HAL_DMA_MODULE_ENABLED + #include "stm32l0xx_hal_dma.h" +#endif /* HAL_DMA_MODULE_ENABLED */ + +#ifdef HAL_CORTEX_MODULE_ENABLED + #include "stm32l0xx_hal_cortex.h" +#endif /* HAL_CORTEX_MODULE_ENABLED */ + +#ifdef HAL_ADC_MODULE_ENABLED + #include "stm32l0xx_hal_adc.h" +#endif /* HAL_ADC_MODULE_ENABLED */ + +#ifdef HAL_COMP_MODULE_ENABLED + #include "stm32l0xx_hal_comp.h" +#endif /* HAL_COMP_MODULE_ENABLED */ + +#ifdef HAL_CRC_MODULE_ENABLED + #include "stm32l0xx_hal_crc.h" +#endif /* HAL_CRC_MODULE_ENABLED */ + +#ifdef HAL_CRYP_MODULE_ENABLED + #include "stm32l0xx_hal_cryp.h" +#endif /* HAL_CRYP_MODULE_ENABLED */ + +#ifdef HAL_DAC_MODULE_ENABLED + #include "stm32l0xx_hal_dac.h" +#endif /* HAL_DAC_MODULE_ENABLED */ + +#ifdef HAL_FLASH_MODULE_ENABLED + #include "stm32l0xx_hal_flash.h" +#endif /* HAL_FLASH_MODULE_ENABLED */ + +#ifdef HAL_I2C_MODULE_ENABLED + #include "stm32l0xx_hal_i2c.h" +#endif /* HAL_I2C_MODULE_ENABLED */ + +#ifdef HAL_I2S_MODULE_ENABLED + #include "stm32l0xx_hal_i2s.h" +#endif /* HAL_I2S_MODULE_ENABLED */ + +#ifdef HAL_IWDG_MODULE_ENABLED + #include "stm32l0xx_hal_iwdg.h" +#endif /* HAL_IWDG_MODULE_ENABLED */ + +#ifdef HAL_LCD_MODULE_ENABLED + #include "stm32l0xx_hal_lcd.h" +#endif /* HAL_LCD_MODULE_ENABLED */ + +#ifdef HAL_LPTIM_MODULE_ENABLED +#include "stm32l0xx_hal_lptim.h" +#endif /* HAL_LPTIM_MODULE_ENABLED */ + +#ifdef HAL_PWR_MODULE_ENABLED + #include "stm32l0xx_hal_pwr.h" +#endif /* HAL_PWR_MODULE_ENABLED */ + +#ifdef HAL_RNG_MODULE_ENABLED + #include "stm32l0xx_hal_rng.h" +#endif /* HAL_RNG_MODULE_ENABLED */ + +#ifdef HAL_RTC_MODULE_ENABLED + #include "stm32l0xx_hal_rtc.h" + +#endif /* HAL_RTC_MODULE_ENABLED */ + +#ifdef HAL_SPI_MODULE_ENABLED + #include "stm32l0xx_hal_spi.h" +#endif /* HAL_SPI_MODULE_ENABLED */ + +#ifdef HAL_TIM_MODULE_ENABLED + #include "stm32l0xx_hal_tim.h" +#endif /* HAL_TIM_MODULE_ENABLED */ + +#ifdef HAL_TSC_MODULE_ENABLED + #include "stm32l0xx_hal_tsc.h" +#endif /* HAL_TSC_MODULE_ENABLED */ + +#ifdef HAL_UART_MODULE_ENABLED + #include "stm32l0xx_hal_uart.h" +#endif /* HAL_UART_MODULE_ENABLED */ + +#ifdef HAL_USART_MODULE_ENABLED + #include "stm32l0xx_hal_usart.h" +#endif /* HAL_USART_MODULE_ENABLED */ + +#ifdef HAL_IRDA_MODULE_ENABLED + #include "stm32l0xx_hal_irda.h" +#endif /* HAL_IRDA_MODULE_ENABLED */ + +#ifdef HAL_SMARTCARD_MODULE_ENABLED + #include "stm32l0xx_hal_smartcard.h" +#endif /* HAL_SMARTCARD_MODULE_ENABLED */ + +#ifdef HAL_SMBUS_MODULE_ENABLED + #include "stm32l0xx_hal_smbus.h" +#endif /* HAL_SMBUS_MODULE_ENABLED */ + +#ifdef HAL_WWDG_MODULE_ENABLED + #include "stm32l0xx_hal_wwdg.h" +#endif /* HAL_WWDG_MODULE_ENABLED */ + +#ifdef HAL_PCD_MODULE_ENABLED + #include "stm32l0xx_hal_pcd.h" +#endif /* HAL_PCD_MODULE_ENABLED */ + +/* Exported macro ------------------------------------------------------------*/ +#ifdef USE_FULL_ASSERT +/** + * @brief The assert_param macro is used for function's parameters check. + * @param expr: If expr is false, it calls assert_failed function + * which reports the name of the source file and the source + * line number of the call that failed. + * If expr is true, it returns no value. + * @retval None + */ + #define assert_param(expr) ((expr) ? (void)0 : assert_failed((uint8_t *)__FILE__, __LINE__)) +/* Exported functions ------------------------------------------------------- */ + void assert_failed(uint8_t* file, uint32_t line); +#else + #define assert_param(expr) ((void)0) +#endif /* USE_FULL_ASSERT */ + +#ifdef __cplusplus +} +#endif + +#endif /* __STM32L0xx_HAL_CONF_H */ + + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_cortex.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_cortex.c new file mode 100644 index 0000000000..fc5c0aa1dd --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_cortex.c @@ -0,0 +1,333 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_cortex.c + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief CORTEX HAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the CORTEX: + * + Initialization and de-initialization functions + * + Peripheral Control functions + * + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + + [..] + *** How to configure Interrupts using CORTEX HAL driver *** + =========================================================== + [..] + This section provide functions allowing to configure the NVIC interrupts (IRQ). + The Cortex-M0+ exceptions are managed by CMSIS functions. + (#) Enable and Configure the priority of the selected IRQ Channels. + The priority can be 0..3. + + -@- Lower priority values gives higher priority. + -@- Priority Order: + (#@) Lowest priority. + (#@) Lowest hardware priority (IRQn position). + + (#) Configure the priority of the selected IRQ Channels using HAL_NVIC_SetPriority() + + (#) Enable the selected IRQ Channels using HAL_NVIC_EnableIRQ() + + [..] + *** How to configure Systick using CORTEX HAL driver *** + ======================================================== + [..] + Setup SysTick Timer for time base + + (+) The HAL_SYSTICK_Config()function calls the SysTick_Config() function which + is a CMSIS function that: + (++) Configures the SysTick Reload register with value passed as function parameter. + (++) Configures the SysTick IRQ priority to the lowest value (0x03). + (++) Resets the SysTick Counter register. + (++) Configures the SysTick Counter clock source to be Core Clock Source (HCLK). + (++) Enables the SysTick Interrupt. + (++) Starts the SysTick Counter. + + (+) You can change the SysTick Clock source to be HCLK_Div8 by calling the macro + __HAL_CORTEX_SYSTICKCLK_CONFIG(SYSTICK_CLKSOURCE_HCLK_DIV8) just after the + HAL_SYSTICK_Config() function call. The __HAL_CORTEX_SYSTICKCLK_CONFIG() macro is defined + inside the stm32l0xx_hal_cortex.h file. + + (+) You can change the SysTick IRQ priority by calling the + HAL_NVIC_SetPriority(SysTick_IRQn,...) function just after the HAL_SYSTICK_Config() function + call. The HAL_NVIC_SetPriority() call the NVIC_SetPriority() function which is a CMSIS function. + + (+) To adjust the SysTick time base, use the following formula: + + Reload Value = SysTick Counter Clock (Hz) x Desired Time base (s) + (++) Reload Value is the parameter to be passed for HAL_SYSTICK_Config() function + (++) Reload Value should not exceed 0xFFFFFF + + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @defgroup CORTEX + * @brief CORTEX HAL module driver + * @{ + */ + +#ifdef HAL_CORTEX_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup CORTEX_Private_Functions + * @{ + */ + + +/** @defgroup CORTEX_Group1 Initialization and de-initialization functions + * @brief Initialization and Configuration functions + * +@verbatim + ============================================================================== + ##### Initialization and de-initialization functions ##### + ============================================================================== + [..] + This section provides the CORTEX HAL driver functions allowing to configure Interrupts + Systick functionalities + +@endverbatim + * @{ + */ + +/** + * @brief Sets the priority of an interrupt. + * @param IRQn: External interrupt number . + * This parameter can be an enumerator of IRQn_Type enumeration + * (For the complete STM32 Devices IRQ Channels list, please refer to stm32l0xx.h file) + * @param PreemptPriority: The pre-emption priority for the IRQn channel. + * This parameter can be a value between 0 and 3. + * A lower priority value indicates a higher priority + * @param SubPriority: The subpriority level for the IRQ channel. + * with stm32l0xx devices, this parameter is a dummy value and it is ignored, because + * no subpriority supported in Cortex M0+ based products. + * @retval None + */ +void HAL_NVIC_SetPriority(IRQn_Type IRQn, uint32_t PreemptPriority, uint32_t SubPriority) +{ + /* Check the parameters */ + assert_param(IS_NVIC_PREEMPTION_PRIORITY(PreemptPriority)); + NVIC_SetPriority(IRQn,PreemptPriority); +} + +/** + * @brief Enables a device specific interrupt in the NVIC interrupt controller. + * @note To configure interrupts priority correctly, the NVIC_PriorityGroupConfig() + * function should be called before. + * @param IRQn External interrupt number . + * This parameter can be an enumerator of IRQn_Type enumeration + * (For the complete STM32 Devices IRQ Channels list, please refer to stm32l0xx.h file) + * @retval None + */ +void HAL_NVIC_EnableIRQ(IRQn_Type IRQn) +{ + /* Enable interrupt */ + NVIC_EnableIRQ(IRQn); +} + +/** + * @brief Disables a device specific interrupt in the NVIC interrupt controller. + * @param IRQn External interrupt number . + * This parameter can be an enumerator of IRQn_Type enumeration + * (For the complete STM32 Devices IRQ Channels list, please refer to stm32l0xx.h file) + * @retval None + */ +void HAL_NVIC_DisableIRQ(IRQn_Type IRQn) +{ + /* Disable interrupt */ + NVIC_DisableIRQ(IRQn); +} + +/** + * @brief Initiates a system reset request to reset the MCU. + * @param None + * @retval None + */ +void HAL_NVIC_SystemReset(void) +{ + /* System Reset */ + NVIC_SystemReset(); +} + +/** + * @brief Initializes the System Timer and its interrupt, and starts the System Tick Timer. + * Counter is in free running mode to generate periodic interrupts. + * @param TicksNumb: Specifies the ticks Number of ticks between two interrupts. + * @retval status: - 0 Function succeeded. + * - 1 Function failed. + */ +uint32_t HAL_SYSTICK_Config(uint32_t TicksNumb) +{ + return SysTick_Config(TicksNumb); +} +/** + * @} + */ + +/** @defgroup CORTEX_Group2 Peripheral Control functions + * @brief Cortex control functions + * +@verbatim + ============================================================================== + ##### Peripheral Control functions ##### + ============================================================================== + [..] + This subsection provides a set of functions allowing to control the CORTEX + (NVIC, SYSTICK) functionalities. + + +@endverbatim + * @{ + */ + + + +/** + * @brief Sets Pending bit of an external interrupt. + * @param IRQn External interrupt number + * This parameter can be an enumerator of @ref IRQn_Type enumeration + * (For the complete STM32 Devices IRQ Channels list, please refer to stm32l0xx.h file) + * @retval None + */ +void HAL_NVIC_SetPendingIRQ(IRQn_Type IRQn) +{ + /* Set interrupt pending */ + NVIC_SetPendingIRQ(IRQn); +} + +/** + * @brief Gets Pending Interrupt (reads the pending register in the NVIC + * and returns the pending bit for the specified interrupt). + * @param IRQn External interrupt number . + * This parameter can be an enumerator of IRQn_Type enumeration + * (For the complete STM32 Devices IRQ Channels list, please refer to stm32l0xx.h file) + * @retval status: - 0 Interrupt status is not pending. + * - 1 Interrupt status is pending. + */ +uint32_t HAL_NVIC_GetPendingIRQ(IRQn_Type IRQn) +{ + /* Return 1 if pending else 0 */ + return NVIC_GetPendingIRQ(IRQn); +} + +/** + * @brief Clears the pending bit of an external interrupt. + * @param IRQn External interrupt number . + * This parameter can be an enumerator of IRQn_Type enumeration + * (For the complete STM32 Devices IRQ Channels list, please refer to stm32l0xx.h file) + * @retval None + */ +void HAL_NVIC_ClearPendingIRQ(IRQn_Type IRQn) +{ + /* Clear pending interrupt */ + NVIC_ClearPendingIRQ(IRQn); +} + + +/** + * @brief Configures the SysTick clock source. + * @param CLKSource: specifies the SysTick clock source. + * This parameter can be one of the following values: + * @arg SYSTICK_CLKSOURCE_HCLK_DIV8: AHB clock divided by 8 selected as SysTick clock source. + * @arg SYSTICK_CLKSOURCE_HCLK: AHB clock selected as SysTick clock source. + * @retval None + */ +void HAL_SYSTICK_CLKSourceConfig(uint32_t CLKSource) +{ + /* Check the parameters */ + assert_param(IS_SYSTICK_CLK_SOURCE(CLKSource)); + if (CLKSource == SYSTICK_CLKSOURCE_HCLK) + { + SysTick->CTRL |= SYSTICK_CLKSOURCE_HCLK; + } + else + { + SysTick->CTRL &= ~SYSTICK_CLKSOURCE_HCLK; + } +} + +/** + * @brief This function handles SYSTICK interrupt request. + * @param None + * @retval None + */ +void HAL_SYSTICK_IRQHandler(void) +{ + HAL_SYSTICK_Callback(); +} + +/** + * @brief SYSTICK callback. + * @param None + * @retval None + */ +__weak void HAL_SYSTICK_Callback(void) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_SYSTICK_Callback could be implemented in the user file + */ +} + +/** + * @} + */ + +/** + * @} + */ + +#endif /* HAL_CORTEX_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_cortex.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_cortex.h new file mode 100644 index 0000000000..9dad2c67a6 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_cortex.h @@ -0,0 +1,132 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_cortex.h + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief Header file of CORTEX HAL module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32L0xx_HAL_CORTEX_H +#define __STM32L0xx_HAL_CORTEX_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal_def.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @addtogroup CORTEX + * @{ + */ +/* Exported types ------------------------------------------------------------*/ +/* Exported constants --------------------------------------------------------*/ + +/** @defgroup CORTEX_Exported_Constants + * @{ + */ + + +#define IS_NVIC_PREEMPTION_PRIORITY(PRIORITY) ((PRIORITY) < 0x4) + +/** @defgroup CORTEX_SysTick_clock_source + * @{ + */ +#define SYSTICK_CLKSOURCE_HCLK_DIV8 ((uint32_t)0x00000000) +#define SYSTICK_CLKSOURCE_HCLK ((uint32_t)0x00000004) +#define IS_SYSTICK_CLK_SOURCE(SOURCE) (((SOURCE) == SYSTICK_CLKSOURCE_HCLK) || \ + ((SOURCE) == SYSTICK_CLKSOURCE_HCLK_DIV8)) +/** + * @} + */ + +/* Exported Macros -----------------------------------------------------------*/ + +/** @brief Configures the SysTick clock source. + * @param __CLKSRC__: specifies the SysTick clock source. + * This parameter can be one of the following values: + * @arg SYSTICK_CLKSOURCE_HCLK_DIV8: AHB clock divided by 8 selected as SysTick clock source. + * @arg SYSTICK_CLKSOURCE_HCLK: AHB clock selected as SysTick clock source. + * @retval None + */ +#define __HAL_CORTEX_SYSTICKCLK_CONFIG(__CLKSRC__) \ + do { \ + if ((__CLKSRC__) == SYSTICK_CLKSOURCE_HCLK) \ + { \ + SysTick->CTRL |= SYSTICK_CLKSOURCE_HCLK; \ + } \ + else \ + SysTick->CTRL &= ~SYSTICK_CLKSOURCE_HCLK; \ + } while(0) + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ +/* Exported functions --------------------------------------------------------*/ +/* Initialization and de-initialization functions *******************************/ +void HAL_NVIC_SetPriority(IRQn_Type IRQn, uint32_t PreemptPriority, uint32_t SubPriority); +void HAL_NVIC_EnableIRQ(IRQn_Type IRQn); +void HAL_NVIC_DisableIRQ(IRQn_Type IRQn); +void HAL_NVIC_SystemReset(void); +uint32_t HAL_SYSTICK_Config(uint32_t TicksNumb); + +/* Peripheral Control functions *************************************************/ +uint32_t HAL_NVIC_GetPendingIRQ(IRQn_Type IRQn); +void HAL_NVIC_SetPendingIRQ(IRQn_Type IRQn); +void HAL_NVIC_ClearPendingIRQ(IRQn_Type IRQn); +void HAL_SYSTICK_CLKSourceConfig(uint32_t CLKSource); +void HAL_SYSTICK_IRQHandler(void); +void HAL_SYSTICK_Callback(void); + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __STM32L0xx_HAL_CORTEX_H */ + + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_crc.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_crc.c new file mode 100644 index 0000000000..ee749ea0cd --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_crc.c @@ -0,0 +1,558 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_crc.c + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief CRC HAL module driver. + * + * This file provides firmware functions to manage the following + * functionalities of the CRC peripheral: + * + Initialization and de-initialization functions + * + Peripheral Control functions + * + Peripheral State functions + * + @verbatim + =============================================================================== + ##### How to use this driver ##### + =============================================================================== + [..] + (+) Enable CRC AHB clock using __CRC_CLK_ENABLE(); + (+) Initialize CRC calculator + - specify generating polynomial (IP default or non-default one) + - specify initialization value (IP default or non-default one) + - specify input data format + - specify input or output data inversion mode if any + (+) Use HAL_CRC_Accumulate() function to compute the CRC value of the + input data buffer starting with the previously computed CRC as + initialization value + (+) Use HAL_CRC_Calculate() function to compute the CRC value of the + input data buffer starting with the defined initialization value + (default or non-default) to initiate CRC calculation + + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @defgroup CRC + * @brief CRC HAL module driver. + * @{ + */ + +#ifdef HAL_CRC_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ +static uint32_t CRC_Handle_8(CRC_HandleTypeDef *hcrc, uint8_t pBuffer[], uint32_t BufferLength); +static uint32_t CRC_Handle_16(CRC_HandleTypeDef *hcrc, uint16_t pBuffer[], uint32_t BufferLength); +/** @defgroup CRC_Private_Functions + * @{ + */ + +/** @defgroup HAL_CRC_Group1 Initialization/de-initialization functions + * @brief Initialization and Configuration functions. + * +@verbatim + =============================================================================== + ##### Initialization/de-initialization functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Initialize the CRC according to the specified parameters + in the CRC_InitTypeDef and create the associated handle + (+) DeInitialize the CRC peripheral + (+) Initialize the CRC MSP + (+) DeInitialize CRC MSP + +@endverbatim + * @{ + */ + +/** + * @brief Initializes the CRC according to the specified + * parameters in the CRC_InitTypeDef and creates the associated handle. + * @param hcrc: CRC handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_CRC_Init(CRC_HandleTypeDef *hcrc) +{ + /* Check the CRC handle allocation */ + if(hcrc == NULL) + { + return HAL_ERROR; + } + + assert_param(IS_CRC_INSTANCE(hcrc->Instance)); + + if(hcrc->State == HAL_CRC_STATE_RESET) + { + /* Init the low level hardware */ + HAL_CRC_MspInit(hcrc); + } + + /* Change CRC peripheral state */ + hcrc->State = HAL_CRC_STATE_BUSY; + + /* check whether or not non-default generating polynomial has been + * picked up by user */ + assert_param(IS_DEFAULT_POLYNOMIAL(hcrc->Init.DefaultPolynomialUse)); + if (hcrc->Init.DefaultPolynomialUse == DEFAULT_POLYNOMIAL_ENABLE) + { + /* initialize IP with default generating polynomial */ + WRITE_REG(hcrc->Instance->POL, DEFAULT_CRC32_POLY); + MODIFY_REG(hcrc->Instance->CR, CRC_CR_POLYSIZE, CRC_POLYLENGTH_32B); + } + else + { + /* initialize CRC IP with generating polynomial defined by user */ + if (HAL_CRCEx_Polynomial_Set(hcrc, hcrc->Init.GeneratingPolynomial, hcrc->Init.CRCLength) != HAL_OK) + { + return HAL_ERROR; + } + } + + /* check whether or not non-default CRC initial value has been + * picked up by user */ + assert_param(IS_DEFAULT_INIT_VALUE(hcrc->Init.DefaultInitValueUse)); + if (hcrc->Init.DefaultInitValueUse == DEFAULT_INIT_VALUE_ENABLE) + { + WRITE_REG(hcrc->Instance->INIT, DEFAULT_CRC_INITVALUE); + } + else + { + WRITE_REG(hcrc->Instance->INIT, hcrc->Init.InitValue); + } + + + /* set input data inversion mode */ + assert_param(IS_CRC_INPUTDATA_INVERSION_MODE(hcrc->Init.InputDataInversionMode)); + MODIFY_REG(hcrc->Instance->CR, CRC_CR_REV_IN, hcrc->Init.InputDataInversionMode); + + /* set output data inversion mode */ + assert_param(IS_CRC_OUTPUTDATA_INVERSION_MODE(hcrc->Init.OutputDataInversionMode)); + MODIFY_REG(hcrc->Instance->CR, CRC_CR_REV_OUT, hcrc->Init.OutputDataInversionMode); + + /* makes sure the input data format (bytes, halfwords or words stream) + * is properly specified by user */ + assert_param(IS_CRC_INPUTDATA_FORMAT(hcrc->InputDataFormat)); + + /* Change CRC peripheral state */ + hcrc->State = HAL_CRC_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief DeInitializes the CRC peripheral. + * @param hcrc: CRC handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_CRC_DeInit(CRC_HandleTypeDef *hcrc) +{ + /* Check the CRC handle allocation */ + if(hcrc == NULL) + { + return HAL_ERROR; + } + + assert_param(IS_CRC_INSTANCE(hcrc->Instance)); + + /* Check the CRC peripheral state */ + if(hcrc->State == HAL_CRC_STATE_BUSY) + { + return HAL_BUSY; + } + + /* Change CRC peripheral state */ + hcrc->State = HAL_CRC_STATE_BUSY; + + /* DeInit the low level hardware */ + HAL_CRC_MspDeInit(hcrc); + + /* Change CRC peripheral state */ + hcrc->State = HAL_CRC_STATE_RESET; + + /* Process unlocked */ + __HAL_UNLOCK(hcrc); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Initializes the CRC MSP. + * @param hcrc: CRC handle + * @retval None + */ +__weak void HAL_CRC_MspInit(CRC_HandleTypeDef *hcrc) +{ + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_CRC_MspInit can be implemented in the user file + */ +} + +/** + * @brief DeInitializes the CRC MSP. + * @param hcrc: CRC handle + * @retval None + */ +__weak void HAL_CRC_MspDeInit(CRC_HandleTypeDef *hcrc) +{ + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_CRC_MspDeInit can be implemented in the user file + */ +} + + + +/** + * @brief Set the Reverse Input data mode. + * @param hcrc: CRC handle + * @param InputReverseMode: Input Data inversion mode + * This parameter can be one of the following values: + * @arg CRC_INPUTDATA_NOINVERSION: no change in bit order (default value) + * @arg CRC_INPUTDATA_INVERSION_BYTE: Byte-wise bit reversal + * @arg CRC_INPUTDATA_INVERSION_HALFWORD: HalfWord-wise bit reversal + * @arg CRC_INPUTDATA_INVERSION_WORD: Word-wise bit reversal + * @retval HAL status + */ +HAL_StatusTypeDef HAL_CRC_Input_Data_Reverse(CRC_HandleTypeDef *hcrc, uint32_t InputReverseMode) +{ + /* Check the parameters */ + assert_param(IS_CRC_INPUTDATA_INVERSION_MODE(InputReverseMode)); + + /* Change CRC peripheral state */ + hcrc->State = HAL_CRC_STATE_BUSY; + + /* set input data inversion mode */ + MODIFY_REG(hcrc->Instance->CR, CRC_CR_REV_IN, InputReverseMode); + /* Change CRC peripheral state */ + hcrc->State = HAL_CRC_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Set the Reverse Output data mode. + * @param hcrc: CRC handle + * @param OutputReverseMode: Output Data inversion mode + * This parameter can be one of the following values: + * @arg CRC_OUTPUTDATA_INVERSION_DISABLED: no CRC inversion (default value) + * @arg CRC_OUTPUTDATA_INVERSION_ENABLED: bit-level inversion (e.g for a 8-bit CRC: 0xB5 becomes 0xAD) + * @retval HAL status + */ +HAL_StatusTypeDef HAL_CRC_Output_Data_Reverse(CRC_HandleTypeDef *hcrc, uint32_t OutputReverseMode) +{ + /* Check the parameters */ + assert_param(IS_CRC_OUTPUTDATA_INVERSION_MODE(OutputReverseMode)); + + /* Change CRC peripheral state */ + hcrc->State = HAL_CRC_STATE_BUSY; + + /* set output data inversion mode */ + MODIFY_REG(hcrc->Instance->CR, CRC_CR_REV_OUT, OutputReverseMode); + + /* Change CRC peripheral state */ + hcrc->State = HAL_CRC_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + + + + +/** + * @} + */ + +/** @defgroup HAL_CRC_Group2 Peripheral Control functions + * @brief management functions. + * +@verbatim + =============================================================================== + ##### Peripheral Control functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Compute the 7, 8, 16 or 32-bit CRC value of an 8, 16 or 32-bit data buffer + using combination of the previous CRC value and the new one. + + or + + (+) Compute the 7, 8, 16 or 32-bit CRC value of an 8, 16 or 32-bit data buffer + independently of the previous CRC value. + +@endverbatim + * @{ + */ + +/** + * @brief Compute the 7, 8, 16 or 32-bit CRC value of an 8, 16 or 32-bit data buffer + * starting with the previously computed CRC as initialization value. + * @param hcrc: CRC handle + * @param pBuffer: pointer to the input data buffer, exact input data format is + * provided by hcrc->InputDataFormat. + * @param BufferLength: input data buffer length + * @retval uint32_t CRC (returned value LSBs for CRC shorter than 32 bits) + */ +uint32_t HAL_CRC_Accumulate(CRC_HandleTypeDef *hcrc, uint32_t pBuffer[], uint32_t BufferLength) +{ + uint32_t index = 0; /* CRC input data buffer index */ + uint32_t temp = 0; /* CRC output (read from hcrc->Instance->DR register) */ + + /* Process locked */ + __HAL_LOCK(hcrc); + + /* Change CRC peripheral state */ + hcrc->State = HAL_CRC_STATE_BUSY; + + switch (hcrc->InputDataFormat) + { + case CRC_INPUTDATA_FORMAT_WORDS: + /* Enter Data to the CRC calculator */ + for(index = 0; index < BufferLength; index++) + { + hcrc->Instance->DR = pBuffer[index]; + } + temp = hcrc->Instance->DR; + break; + + case CRC_INPUTDATA_FORMAT_BYTES: + temp = CRC_Handle_8(hcrc, (uint8_t*)pBuffer, BufferLength); + break; + + case CRC_INPUTDATA_FORMAT_HALFWORDS: + temp = CRC_Handle_16(hcrc, (uint16_t*)pBuffer, BufferLength); + break; + default: + break; + } + + /* Change CRC peripheral state */ + hcrc->State = HAL_CRC_STATE_READY; + + /* Process unlocked */ + __HAL_UNLOCK(hcrc); + + /* Return the CRC computed value */ + return temp; +} + + +/** + * @brief Compute the 7, 8, 16 or 32-bit CRC value of an 8, 16 or 32-bit data buffer + * starting with hcrc->Instance->INIT as initialization value. + * @param hcrc: CRC handle + * @param pBuffer: pointer to the input data buffer, exact input data format is + * provided by hcrc->InputDataFormat. + * @param BufferLength: input data buffer length + * @retval uint32_t CRC (returned value LSBs for CRC shorter than 32 bits) + */ +uint32_t HAL_CRC_Calculate(CRC_HandleTypeDef *hcrc, uint32_t pBuffer[], uint32_t BufferLength) +{ + uint32_t index = 0; /* CRC input data buffer index */ + uint32_t temp = 0; /* CRC output (read from hcrc->Instance->DR register) */ + + /* Process locked */ + __HAL_LOCK(hcrc); + + /* Change CRC peripheral state */ + hcrc->State = HAL_CRC_STATE_BUSY; + + /* Reset CRC Calculation Unit (hcrc->Instance->INIT is + * written in hcrc->Instance->DR) */ + __HAL_CRC_DR_RESET(hcrc); + + switch (hcrc->InputDataFormat) + { + case CRC_INPUTDATA_FORMAT_WORDS: + /* Enter 32-bit input data to the CRC calculator */ + for(index = 0; index < BufferLength; index++) + { + hcrc->Instance->DR = pBuffer[index]; + } + temp = hcrc->Instance->DR; + break; + + case CRC_INPUTDATA_FORMAT_BYTES: + /* Specific 8-bit input data handling */ + temp = CRC_Handle_8(hcrc, (uint8_t*)pBuffer, BufferLength); + break; + + case CRC_INPUTDATA_FORMAT_HALFWORDS: + /* Specific 16-bit input data handling */ + temp = CRC_Handle_16(hcrc, (uint16_t*)pBuffer, BufferLength); + break; + default: + break; + } + + /* Change CRC peripheral state */ + hcrc->State = HAL_CRC_STATE_READY; + + /* Process unlocked */ + __HAL_UNLOCK(hcrc); + + /* Return the CRC computed value */ + return temp; +} + + + +/** + * @brief Enter 8-bit input data to the CRC calculator. + * Specific data handling to optimize processing time. + * @param hcrc: CRC handle + * @param pBuffer: pointer to the input data buffer + * @param BufferLength: input data buffer length + * @retval uint32_t CRC (returned value LSBs for CRC shorter than 32 bits) + */ +static uint32_t CRC_Handle_8(CRC_HandleTypeDef *hcrc, uint8_t pBuffer[], uint32_t BufferLength) +{ + uint32_t i = 0; /* input data buffer index */ + + /* Processing time optimization: 4 bytes are entered in a row with a single word write, + * last bytes must be carefully fed to the CRC calculator to ensure a correct type + * handling by the IP */ + for(i = 0; i < (BufferLength/4); i++) + { + hcrc->Instance->DR = (uint32_t)(((uint32_t)(pBuffer[4*i])<<24) | ((uint32_t)(pBuffer[4*i+1])<<16) | ((uint32_t)(pBuffer[4*i+2])<<8) | (uint32_t)(pBuffer[4*i+3])); + } + /* last bytes specific handling */ + if ((BufferLength%4) != 0) + { + if (BufferLength%4 == 1) + { + *(__IO uint8_t*) (&hcrc->Instance->DR) = pBuffer[4*i]; + } + if (BufferLength%4 == 2) + { + *(__IO uint16_t*) (&hcrc->Instance->DR) = (uint16_t)(((uint32_t)(pBuffer[4*i])<<8) | (uint32_t)(pBuffer[4*i+1])); + } + if (BufferLength%4 == 3) + { + *(__IO uint16_t*) (&hcrc->Instance->DR) = (uint16_t)(((uint32_t)(pBuffer[4*i])<<8) | (uint32_t)(pBuffer[4*i+1])); + *(__IO uint8_t*) (&hcrc->Instance->DR) = pBuffer[4*i+2]; + } + } + + /* Return the CRC computed value */ + return hcrc->Instance->DR; +} + + + +/** + * @brief Enter 16-bit input data to the CRC calculator. + * Specific data handling to optimize processing time. + * @param hcrc: CRC handle + * @param pBuffer: pointer to the input data buffer + * @param BufferLength: input data buffer length + * @retval uint32_t CRC (returned value LSBs for CRC shorter than 32 bits) + */ +static uint32_t CRC_Handle_16(CRC_HandleTypeDef *hcrc, uint16_t pBuffer[], uint32_t BufferLength) +{ + uint32_t i = 0; /* input data buffer index */ + + /* Processing time optimization: 2 HalfWords are entered in a row with a single word write, + * in case of odd length, last HalfWord must be carefully fed to the CRC calculator to ensure + * a correct type handling by the IP */ + for(i = 0; i < (BufferLength/2); i++) + { + hcrc->Instance->DR = (((uint32_t)(pBuffer[2*i])<<16) | (uint32_t)(pBuffer[2*i+1])); + } + if ((BufferLength%2) != 0) + { + *(__IO uint16_t*) (&hcrc->Instance->DR) = pBuffer[2*i]; + } + + /* Return the CRC computed value */ + return hcrc->Instance->DR; +} + +/** + * @} + */ + +/** @defgroup HAL_CRC_Group3 Peripheral State functions + * @brief Peripheral State functions. + * +@verbatim + =============================================================================== + ##### Peripheral State functions ##### + =============================================================================== + [..] + This subsection permits to get in run-time the status of the peripheral + and the data flow. + +@endverbatim + * @{ + */ + +/** + * @brief Returns the CRC state. + * @param hcrc: CRC handle + * @retval HAL state + */ +HAL_CRC_StateTypeDef HAL_CRC_GetState(CRC_HandleTypeDef *hcrc) +{ + return hcrc->State; +} + +/** + * @} + */ + +/** + * @} + */ + +#endif /* HAL_CRC_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_crc.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_crc.h new file mode 100644 index 0000000000..f6000eb55a --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_crc.h @@ -0,0 +1,343 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_crc.h + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief Header file of CRC HAL module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32L0xx_HAL_CRC_H +#define __STM32L0xx_HAL_CRC_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal_def.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @addtogroup CRC + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ + +/** + * @brief CRC HAL State Structure definition + */ +typedef enum +{ + HAL_CRC_STATE_RESET = 0x00, /*!< CRC Reset State */ + HAL_CRC_STATE_READY = 0x01, /*!< CRC Initialized and ready for use */ + HAL_CRC_STATE_BUSY = 0x02, /*!< CRC process is ongoing */ + HAL_CRC_STATE_TIMEOUT = 0x03, /*!< CRC Timeout State */ + HAL_CRC_STATE_ERROR = 0x04 /*!< CRC Error State */ +}HAL_CRC_StateTypeDef; + +/** + * @brief CRC Init Structure definition + */ +typedef struct +{ + uint8_t DefaultPolynomialUse; /*!< This parameter is a value of @ref CRC_Default_Polynomial and indicates if default polynomial is used. + If set to DEFAULT_POLYNOMIAL_ENABLE, resort to default + X^32 + X^26 + X^23 + X^22 + X^16 + X^12 + X^11 + X^10 +X^8 + X^7 + X^5 + X^4 + X^2+ X +1. + In that case, there is no need to set GeneratingPolynomial field. + If otherwise set to DEFAULT_POLYNOMIAL_DISABLE, GeneratingPolynomial and CRCLength fields must be set */ + + uint8_t DefaultInitValueUse; /*!< This parameter is a value of @ref CRC_Default_InitValue_Use and indicates if default init value is used. + If set to DEFAULT_INIT_VALUE_ENABLE, resort to default + 0xFFFFFFFF value. In that case, there is no need to set InitValue field. + If otherwise set to DEFAULT_INIT_VALUE_DISABLE, InitValue field must be set */ + + uint32_t GeneratingPolynomial; /*!< Set CRC generating polynomial. 7, 8, 16 or 32-bit long value for a polynomial degree + respectively equal to 7, 8, 16 or 32. This field is written in normal representation, + e.g., for a polynomial of degree 7, X^7 + X^6 + X^5 + X^2 + 1 is written 0x65. + No need to specify it if DefaultPolynomialUse is set to DEFAULT_POLYNOMIAL_ENABLE */ + + uint32_t CRCLength; /*!< This parameter is a value of @ref CRC_Polynomial_Size_Definitions and indicates CRC length. + Value can be either one of + CRC_POLYLENGTH_32B (32-bit CRC) + CRC_POLYLENGTH_16B (16-bit CRC) + CRC_POLYLENGTH_8B (8-bit CRC) + CRC_POLYLENGTH_7B (7-bit CRC) */ + + uint32_t InitValue; /*!< Init value to initiate CRC computation. No need to specify it if DefaultInitValueUse + is set to DEFAULT_INIT_VALUE_ENABLE */ + + uint32_t InputDataInversionMode; /*!< This parameter is a value of @ref Input_Data_Inversion and specifies input data inversion mode. + Can be either one of the following values + CRC_INPUTDATA_INVERSION_NONE no input data inversion + CRC_INPUTDATA_INVERSION_BYTE byte-wise inversion, 0x1A2B3C4D becomes 0x58D43CB2 + CRC_INPUTDATA_INVERSION_HALFWORD halfword-wise inversion, 0x1A2B3C4D becomes 0xD458B23C + CRC_INPUTDATA_INVERSION_WORD word-wise inversion, 0x1A2B3C4D becomes 0xB23CD458 */ + + uint32_t OutputDataInversionMode; /*!< This parameter is a value of @ref Output_Data_Inversion and specifies output data (i.e. CRC) inversion mode. + Can be either + CRC_OUTPUTDATA_INVERSION_DISABLED no CRC inversion, or + CRC_OUTPUTDATA_INVERSION_ENABLED CRC 0x11223344 is converted into 0x22CC4488 */ +}CRC_InitTypeDef; + + +/** + * @brief CRC Handle Structure definition + */ +typedef struct +{ + CRC_TypeDef *Instance; /*!< Register base address */ + + CRC_InitTypeDef Init; /*!< CRC configuration parameters */ + + HAL_LockTypeDef Lock; /*!< CRC Locking object */ + + __IO HAL_CRC_StateTypeDef State; /*!< CRC communication state */ + + uint32_t InputDataFormat; /*!< This parameter is a value of @ref Input_Buffer_Format and specifies input data format. + Can be either + CRC_INPUTDATA_FORMAT_BYTES input data is a stream of bytes (8-bit data) + CRC_INPUTDATA_FORMAT_HALFWORDS input data is a stream of half-words (16-bit data) + CRC_INPUTDATA_FORMAT_WORDS input data is a stream of words (32-bits data) + Note that constant CRC_INPUT_FORMAT_UNDEFINED is defined but an initialization error + must occur if InputBufferFormat is not one of the three values listed above */ +}CRC_HandleTypeDef; + +/* Exported constants --------------------------------------------------------*/ + +/** @defgroup CRC_Default_Polynomial_Value Default CRC generating polynomial + * @{ + */ +#define DEFAULT_CRC32_POLY 0x04C11DB7 + +/** + * @} + */ + +/** @defgroup CRC_Default_InitValue Default CRC computation initialization value + * @{ + */ +#define DEFAULT_CRC_INITVALUE 0xFFFFFFFF + +/** + * @} + */ + +/** @defgroup CRC_Default_Polynomial Indicates whether or not default polynomial is used + * @{ + */ +#define DEFAULT_POLYNOMIAL_ENABLE ((uint8_t)0x00) +#define DEFAULT_POLYNOMIAL_DISABLE ((uint8_t)0x01) +#define IS_DEFAULT_POLYNOMIAL(DEFAULT) (((DEFAULT) == DEFAULT_POLYNOMIAL_ENABLE) || \ + ((DEFAULT) == DEFAULT_POLYNOMIAL_DISABLE)) + +/** + * @} + */ + +/** @defgroup CRC_Default_InitValue_Use Indicates whether or not default init value is used + * @{ + */ +#define DEFAULT_INIT_VALUE_ENABLE ((uint8_t)0x00) +#define DEFAULT_INIT_VALUE_DISABLE ((uint8_t)0x01) +#define IS_DEFAULT_INIT_VALUE(VALUE) (((VALUE) == DEFAULT_INIT_VALUE_ENABLE) || \ + ((VALUE) == DEFAULT_INIT_VALUE_DISABLE)) + +/** + * @} + */ + +/** @defgroup CRC_Polynomial_Sizes Polynomial sizes to configure the IP + * @{ + */ +#define CRC_POLYLENGTH_32B ((uint32_t)0x00000000) +#define CRC_POLYLENGTH_16B ((uint32_t)CRC_CR_POLYSIZE_0) +#define CRC_POLYLENGTH_8B ((uint32_t)CRC_CR_POLYSIZE_1) +#define CRC_POLYLENGTH_7B ((uint32_t)CRC_CR_POLYSIZE) +#define IS_CRC_POL_LENGTH(LENGTH) (((LENGTH) == CRC_POLYLENGTH_32B) || \ + ((LENGTH) == CRC_POLYLENGTH_16B) || \ + ((LENGTH) == CRC_POLYLENGTH_8B) || \ + ((LENGTH) == CRC_POLYLENGTH_7B)) +/** + * @} + */ + +/** @defgroup CRC_Polynomial_Size_Definitions CRC polynomial possible sizes actual definitions + * @{ + */ +#define HAL_CRC_LENGTH_32B 32 +#define HAL_CRC_LENGTH_16B 16 +#define HAL_CRC_LENGTH_8B 8 +#define HAL_CRC_LENGTH_7B 7 + +/** + * @} + */ + +/** @defgroup Input_Data_Inversion Input Data Inversion Modes + * @{ + */ +#define CRC_INPUTDATA_INVERSION_NONE ((uint32_t)0x00000000) +#define CRC_INPUTDATA_INVERSION_BYTE ((uint32_t)CRC_CR_REV_IN_0) +#define CRC_INPUTDATA_INVERSION_HALFWORD ((uint32_t)CRC_CR_REV_IN_1) +#define CRC_INPUTDATA_INVERSION_WORD ((uint32_t)CRC_CR_REV_IN) +#define IS_CRC_INPUTDATA_INVERSION_MODE(MODE) (((MODE) == CRC_INPUTDATA_INVERSION_NONE) || \ + ((MODE) == CRC_INPUTDATA_INVERSION_BYTE) || \ + ((MODE) == CRC_INPUTDATA_INVERSION_HALFWORD) || \ + ((MODE) == CRC_INPUTDATA_INVERSION_WORD)) +/** + * @} + */ + +/** @defgroup Output_Data_Inversion Output Data Inversion Modes + * @{ + */ +#define CRC_OUTPUTDATA_INVERSION_DISABLED ((uint32_t)0x00000000) +#define CRC_OUTPUTDATA_INVERSION_ENABLED ((uint32_t)CRC_CR_REV_OUT) +#define IS_CRC_OUTPUTDATA_INVERSION_MODE(MODE) (((MODE) == CRC_OUTPUTDATA_INVERSION_DISABLED) || \ + ((MODE) == CRC_OUTPUTDATA_INVERSION_ENABLED)) +/** + * @} + */ + +/** @defgroup Input_Buffer_Format Input Buffer Format + * @{ + */ +/* WARNING: CRC_INPUT_FORMAT_UNDEFINED is created for reference purposes but + * an error is triggered in HAL_CRC_Init() if InputDataFormat field is set + * to CRC_INPUT_FORMAT_UNDEFINED: the format MUST be defined by the user for + * the CRC APIs to provide a correct result */ +#define CRC_INPUTDATA_FORMAT_UNDEFINED ((uint32_t)0x00000000) +#define CRC_INPUTDATA_FORMAT_BYTES ((uint32_t)0x00000001) +#define CRC_INPUTDATA_FORMAT_HALFWORDS ((uint32_t)0x00000002) +#define CRC_INPUTDATA_FORMAT_WORDS ((uint32_t)0x00000003) +#define IS_CRC_INPUTDATA_FORMAT(FORMAT) (((FORMAT) == CRC_INPUTDATA_FORMAT_BYTES) || \ + ((FORMAT) == CRC_INPUTDATA_FORMAT_HALFWORDS) || \ + ((FORMAT) == CRC_INPUTDATA_FORMAT_WORDS)) +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ + +/** @defgroup CRC_Exported_Macro + * @{ + */ + +/** @brief Reset CRC handle state + * @param __HANDLE__: CRC handle + * @retval None + */ +#define __HAL_CRC_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_CRC_STATE_RESET) + +/** + * @brief Check that instance is correctly set to CRC + * @param __PERIPH__: CRC handle instance + * @retval None. + */ +#define IS_CRC_INSTANCE(__PERIPH__) ((__PERIPH__) == CRC) + +/** + * @brief Reset CRC Data Register. + * @param __HANDLE__: CRC handle + * @retval None. + */ +#define __HAL_CRC_DR_RESET(__HANDLE__) ((__HANDLE__)->Instance->CR |= CRC_CR_RESET) + +/** + * @brief Set CRC INIT non-default value + * @param __HANDLE__ : CRC handle + * @param __INIT__ : 32-bit initial value + * @retval None. + */ +#define __HAL_CRC_INITIALCRCVALUE_CONFIG(__HANDLE__, __INIT__) ((__HANDLE__)->Instance->INIT = (__INIT__)) + + +/** + * @brief Set CRC output reversal + * @param __HANDLE__ : CRC handle + * @retval None. + */ +#define __HAL_CRC_OUTPUTREVERSAL_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= CRC_CR_REV_OUT) + + +/** + * @brief Unset CRC output reversal + * @param __HANDLE__ : CRC handle + * @retval None. + */ +#define __HAL_CRC_OUTPUTREVERSAL_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~(CRC_CR_REV_OUT)) + + +/** + * @} + */ + + +/* Include CRC HAL Extension module */ +#include "stm32l0xx_hal_crc_ex.h" + +/* Exported functions --------------------------------------------------------*/ + +/* Initialization and de-initialization functions ****************************/ +HAL_StatusTypeDef HAL_CRC_Init(CRC_HandleTypeDef *hcrc); +HAL_StatusTypeDef HAL_CRC_DeInit (CRC_HandleTypeDef *hcrc); +void HAL_CRC_MspInit(CRC_HandleTypeDef *hcrc); +void HAL_CRC_MspDeInit(CRC_HandleTypeDef *hcrc); +HAL_StatusTypeDef HAL_CRC_Input_Data_Reverse(CRC_HandleTypeDef *hcrc, uint32_t InputReverseMode); +HAL_StatusTypeDef HAL_CRC_Output_Data_Reverse(CRC_HandleTypeDef *hcrc, uint32_t OutputReverseMode); + +/* Peripheral Control functions ***********************************************/ +uint32_t HAL_CRC_Accumulate(CRC_HandleTypeDef *hcrc, uint32_t pBuffer[], uint32_t BufferLength); +uint32_t HAL_CRC_Calculate(CRC_HandleTypeDef *hcrc, uint32_t pBuffer[], uint32_t BufferLength); + +/* Peripheral State and Error functions ***************************************/ +HAL_CRC_StateTypeDef HAL_CRC_GetState(CRC_HandleTypeDef *hcrc); + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __STM32L0xx_HAL_CRC_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_crc_ex.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_crc_ex.c new file mode 100644 index 0000000000..c1d2876606 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_crc_ex.c @@ -0,0 +1,210 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_crc_ex.c + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief Extended CRC HAL module driver. + * + * This file provides firmware functions to manage the following + * functionalities of the CRC peripheral: + * + Initialization/de-initialization functions + * + @verbatim +================================================================================ + ##### ##### +================================================================================ + + [..] < This section can contain: + (#) Description of the product specific implementation; all features + that is specific to this IP: separate clock for RTC/LCD/IWDG/ADC, + power domain (backup domain for the RTC)... + (#) IP main features, only when needed and not mandatory for all IPs, + ex. for xWDG, GPIO, COMP... + > + + [..] < You can add as much sections as needed.> + + [..] < You can add as much sections as needed.> + + + ##### How to use this driver ##### +================================================================================ + [..] + (+) Enable CRC AHB clock using __CRC_CLK_ENABLE(); + (+) Initialize CRC calculator + - specify generating polynomial (IP default or non-default one) + - specify initialization value (IP default or non-default one) + - specify input data format + - specify input or output data inversion mode if any + (+) Use HAL_CRC_Accumulate() function to compute the CRC value of the + input data buffer starting with the previously computed CRC as + initialization value + (+) Use HAL_CRC_Calculate() function to compute the CRC value of the + input data buffer starting with the defined initialization value + (default or non-default) to initiate CRC calculation + + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @defgroup CRCEx + * @brief CRC Extended HAL module driver + * @{ + */ + +#ifdef HAL_CRC_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup CRCEx_Private_Functions + * @{ + */ + +/** @defgroup CRCEx_Group1 Extended Initialization/de-initialization functions + * @brief Extended Initialization and Configuration functions. + * +@verbatim + =============================================================================== + ##### Initialization/de-initialization functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Initialize the CRC according to the specified parameters + in the CRC_InitTypeDef and create the associated handle + (+) DeInitialize the CRC peripheral + (+) Initialize the CRC MSP + (+) DeInitialize CRC MSP + +@endverbatim + * @{ + */ + + +/** + * @brief Initializes the CRC polynomial if different from default one. + * @param hcrc: CRC handle + * @param Pol: CRC generating polynomial (7, 8, 16 or 32-bit long) + * This parameter is written in normal representation, e.g. + * for a polynomial of degree 7, X^7 + X^6 + X^5 + X^2 + 1 is written 0x65 + * for a polynomial of degree 16, X^16 + X^12 + X^5 + 1 is written 0x1021 + * @param PolyLength: CRC polynomial length + * This parameter can be one of the following values: + * @arg CRC_POLYLENGTH_7B: 7-bit long CRC (generating polynomial of degree 7) + * @arg CRC_POLYLENGTH_8B: 8-bit long CRC (generating polynomial of degree 8) + * @arg CRC_POLYLENGTH_16B: 16-bit long CRC (generating polynomial of degree 16) + * @arg CRC_POLYLENGTH_32B: 32-bit long CRC (generating polynomial of degree 32) + * @retval HAL status + */ +HAL_StatusTypeDef HAL_CRCEx_Polynomial_Set(CRC_HandleTypeDef *hcrc, uint32_t Pol, uint32_t PolyLength) +{ + uint32_t msb = 31; /* polynomial degree is 32 at most, so msb is initialized to max value */ + + /* Check the parameters */ + assert_param(IS_CRC_POL_LENGTH(PolyLength)); + + /* check polynomial definition vs polynomial size: + * polynomial length must be aligned with polynomial + * definition. HAL_ERROR is reported if Pol degree is + * larger than that indicated by PolyLength. + * Look for MSB position: msb will contain the degree of + * the second to the largest polynomial member. E.g., for + * X^7 + X^6 + X^5 + X^2 + 1, msb = 6. */ + while (((Pol & ((uint32_t)(0x1) << msb)) == 0) && (msb-- > 0)) + { + } + + switch (PolyLength) + { + case CRC_POLYLENGTH_7B: + if (msb >= HAL_CRC_LENGTH_7B) + { + return HAL_ERROR; + } + break; + case CRC_POLYLENGTH_8B: + if (msb >= HAL_CRC_LENGTH_8B) + { + return HAL_ERROR; + } + break; + case CRC_POLYLENGTH_16B: + if (msb >= HAL_CRC_LENGTH_16B) + { + return HAL_ERROR; + } + break; + case CRC_POLYLENGTH_32B: + /* no polynomial definition vs. polynomial length issue possible */ + break; + default: + break; + } + + /* set generating polynomial */ + WRITE_REG(hcrc->Instance->POL, Pol); + + /* set generating polynomial size */ + MODIFY_REG(hcrc->Instance->CR, CRC_CR_POLYSIZE, PolyLength); + + /* Return function status */ + return HAL_OK; +} +/** + * @} + */ + + +/** + * @} + */ + + +#endif /* HAL_CRC_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_crc_ex.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_crc_ex.h new file mode 100644 index 0000000000..9a1df59a98 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_crc_ex.h @@ -0,0 +1,105 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_crc_ex.h + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief Header file of CRC HAL module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32L0xx_HAL_CRC_EX_H +#define __STM32L0xx_HAL_CRC_EX_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal_def.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @addtogroup CRCEx + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ + + +/* Exported constants --------------------------------------------------------*/ + +/* Exported macro ------------------------------------------------------------*/ + +/** @defgroup CRCEx_Extended_Exported_Macro + * @{ + */ + + +/** + * @brief Set CRC non-default polynomial + * @param __HANDLE__ : CRC handle + * @param __POLYNOMIAL__: 7, 8, 16 or 32-bit polynomial + * @retval None. + */ +#define __HAL_CRC_POLYNOMIAL_CONFIG(__HANDLE__, __POLYNOMIAL__) ((__HANDLE__)->Instance->POL = (__POLYNOMIAL__)) + + +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ + +/* Initialization and de-initialization functions ****************************/ +HAL_StatusTypeDef HAL_CRCEx_Polynomial_Set(CRC_HandleTypeDef *hcrc, uint32_t Pol, uint32_t PolyLength); + +/* Peripheral Control functions ***********************************************/ +/* Peripheral State and Error functions ***************************************/ + + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __STM32L0xx_HAL_CRC_EX_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_cryp.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_cryp.c new file mode 100644 index 0000000000..1af697c46b --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_cryp.c @@ -0,0 +1,2090 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_cryp.c + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief CRYP HAL module driver. + * + * This file provides firmware functions to manage the following + * functionalities of the Cryptography (CRYP) peripheral: + * + Initialization and de-initialization functions + * + Processing functions by algorithm using polling mode + * + Processing functions by algorithm using interrupt mode + * + Processing functions by algorithm using DMA mode + * + Peripheral State functions + * + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + The CRYP HAL driver can be used as follows: + + (#)Initialize the CRYP low level resources by implementing the HAL_CRYP_MspInit(): + (##) Enable the CRYP interface clock using __CRYP_CLK_ENABLE() + (##) In case of using interrupts (e.g. HAL_AES_ECB_Encrypt_IT()) + (+) Configure the CRYP interrupt priority using HAL_NVIC_SetPriority() + (+) Enable the CRYP IRQ handler using HAL_NVIC_EnableIRQ() + (+) In CRYP IRQ handler, call HAL_CRYP_IRQHandler() + (##) In case of using DMA to control data transfer (e.g. HAL_AES_ECB_Encrypt_DMA()) + (+) Enable the DMA1 interface clock using + (++) __DMA1_CLK_ENABLE() + (+) Configure and enable two DMA Channels one for managing data transfer from + memory to peripheral (input channel) and another channel for managing data + transfer from peripheral to memory (output channel) + (+) Associate the initilalized DMA handle to the CRYP DMA handle + using __HAL_LINKDMA() + (+) Configure the priority and enable the NVIC for the transfer complete + interrupt on the two DMA Streams. The output stream should have higher + priority than the input stream. + (++) HAL_NVIC_SetPriority() + (++) HAL_NVIC_EnableIRQ() + + (#)Initialize the CRYP HAL using HAL_CRYP_Init(). This function configures mainly: + (##) The data type: 1-bit, 8-bit, 16-bit and 32-bit + (##) The encryption/decryption key. + (##) The initialization vector (counter). It is not used ECB mode. + + (#)Three processing (encryption/decryption) functions are available: + (##) Polling mode: encryption and decryption APIs are blocking functions + i.e. they process the data and wait till the processing is finished + e.g. HAL_CRYP_AESCBC_Encrypt() + (##) Interrupt mode: encryption and decryption APIs are not blocking functions + i.e. they process the data under interrupt + e.g. HAL_CRYP_AESCBC_Encrypt_IT() + (##) DMA mode: encryption and decryption APIs are not blocking functions + i.e. the data transfer is ensured by DMA + e.g. HAL_CRYP_AESCBC_Encrypt_DMA() + + (#)When the processing function is called at first time after HAL_CRYP_Init() + the CRYP peripheral is initialized and processes the buffer in input. + At second call, the processing function performs an append of the already + processed buffer. + When a new data block is to be processed, call HAL_CRYP_Init() then the + processing function. + + (#)Call HAL_CRYP_DeInit() to deinitialize the CRYP peripheral. + + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @defgroup CRYP + * @brief CRYP HAL module driver. + * @{ + */ + +#ifdef HAL_CRYP_MODULE_ENABLED +#if !defined (STM32L051xx) && !defined (STM32L052xx) && !defined (STM32L053xx) + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +#define CRYP_ALGO_CHAIN_MASK (AES_CR_MODE | AES_CR_CHMOD) +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +static void CRYP_SetInitVector(CRYP_HandleTypeDef *hcryp, uint8_t *InitVector); +static void CRYP_SetKey(CRYP_HandleTypeDef *hcryp, uint8_t *Key); +static HAL_StatusTypeDef CRYP_ProcessData(CRYP_HandleTypeDef *hcryp, uint8_t* Input, uint16_t Ilength, uint8_t* Output, uint32_t Timeout); +static void CRYP_DMAInCplt(DMA_HandleTypeDef *hdma); +static void CRYP_DMAOutCplt(DMA_HandleTypeDef *hdma); +static void CRYP_DMAError(DMA_HandleTypeDef *hdma); +static void CRYP_SetDMAConfig(CRYP_HandleTypeDef *hcryp, uint32_t inputaddr, uint16_t Size, uint32_t outputaddr); +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup CRYP_Private_Functions + * @{ + */ + +/** @defgroup CRYP_Group1 Initialization and de-initialization functions + * @brief Initialization and Configuration functions. + * +@verbatim + ============================================================================== + ##### Initialization and de-initialization functions ##### + ============================================================================== + [..] This section provides functions allowing to: + (+) Initialize the CRYP according to the specified parameters + in the CRYP_InitTypeDef and creates the associated handle + (+) DeInitialize the CRYP peripheral + (+) Initialize the CRYP MSP + (+) DeInitialize CRYP MSP + +@endverbatim + * @{ + */ + +/** + * @brief Initializes the CRYP according to the specified + * parameters in the CRYP_InitTypeDef and creates the associated handle. + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module + * @retval HAL status + */ +HAL_StatusTypeDef HAL_CRYP_Init(CRYP_HandleTypeDef *hcryp) +{ + /* Check the parameters */ + assert_param(IS_CRYP_DATATYPE(hcryp->Init.DataType)); + + /* Check the CRYP handle allocation */ + if(hcryp == NULL) + { + return HAL_ERROR; + } + + if(hcryp->State == HAL_CRYP_STATE_RESET) + { + /* Init the low level hardware */ + HAL_CRYP_MspInit(hcryp); + } + + /* Change the CRYP state */ + hcryp->State = HAL_CRYP_STATE_BUSY; + + /* Set the data type*/ + AES->CR = hcryp->Init.DataType; + + /* Reset CrypInCount and CrypOutCount */ + hcryp->CrypInCount = 0; + hcryp->CrypOutCount = 0; + + /* Change the CRYP state */ + hcryp->State = HAL_CRYP_STATE_READY; + + /* Set the default CRYP phase */ + hcryp->Phase = HAL_CRYP_PHASE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief DeInitializes the CRYP peripheral. + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module + * @retval HAL status + */ +HAL_StatusTypeDef HAL_CRYP_DeInit(CRYP_HandleTypeDef *hcryp) +{ + /* Check the CRYP handle allocation */ + if(hcryp == NULL) + { + return HAL_ERROR; + } + + /* Change the CRYP state */ + hcryp->State = HAL_CRYP_STATE_BUSY; + + /* Set the default CRYP phase */ + hcryp->Phase = HAL_CRYP_PHASE_READY; + + /* Reset CrypInCount and CrypOutCount */ + hcryp->CrypInCount = 0; + hcryp->CrypOutCount = 0; + + /* Disable the CRYP Peripheral Clock */ + __HAL_CRYP_DISABLE(); + + /* DeInit the low level hardware: CLOCK, NVIC.*/ + HAL_CRYP_MspDeInit(hcryp); + + /* Change the CRYP state */ + hcryp->State = HAL_CRYP_STATE_RESET; + + /* Release Lock */ + __HAL_UNLOCK(hcryp); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Initializes the CRYP MSP. + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module + * @retval None + */ +__weak void HAL_CRYP_MspInit(CRYP_HandleTypeDef *hcryp) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_CRYP_MspInit could be implemented in the user file + */ +} + +/** + * @brief DeInitializes CRYP MSP. + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module + * @retval None + */ +__weak void HAL_CRYP_MspDeInit(CRYP_HandleTypeDef *hcryp) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_CRYP_MspDeInit could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup CRYP_Group2 AES processing functions + * @brief processing functions. + * +@verbatim + ============================================================================== + ##### AES processing functions ##### + ============================================================================== + [..] This section provides functions allowing to: + (+) Encrypt plaintext using AES algorithm in different chaining modes + (+) Decrypt cyphertext using AES algorithm in different chaining modes + [..] Three processing functions are available: + (+) Polling mode + (+) Interrupt mode + (+) DMA mode + +@endverbatim + * @{ + */ + +/** + * @brief Initializes the CRYP peripheral in AES ECB encryption mode + * then encrypt pPlainData. The cypher data are available in pCypherData + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module + * @param pPlainData: Pointer to the plaintext buffer + * @param Size: Length of the plaintext buffer, must be a multiple of 16. + * @param pCypherData: Pointer to the cyphertext buffer + * @param Timeout: Specify Timeout value + * @retval HAL status + */ +HAL_StatusTypeDef HAL_CRYP_AESECB_Encrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData, uint32_t Timeout) +{ + /* Process Locked */ + __HAL_LOCK(hcryp); + + /* Change the CRYP state */ + hcryp->State = HAL_CRYP_STATE_BUSY; + + /* Check if initialization phase has already been performed */ + if(hcryp->Phase == HAL_CRYP_PHASE_READY) + { + /* Set the key */ + CRYP_SetKey(hcryp, hcryp->Init.pKey); + + /* Reset the CHMOD & MODE bits & */ + AES->CR &= (uint32_t)(~CRYP_ALGO_CHAIN_MASK); + + /* Set the CRYP peripheral in AES ECB mode */ + __HAL_CRYP_SET_MODE(CRYP_CR_ALGOMODE_AES_ECB_ENCRYPT); + + /* Enable CRYP */ + __HAL_CRYP_ENABLE(); + + /* Set the phase */ + hcryp->Phase = HAL_CRYP_PHASE_PROCESS; + } + + /* Write Plain Data and Get Cypher Data */ + if(CRYP_ProcessData(hcryp,pPlainData, Size, pCypherData, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + /* Change the CRYP state */ + hcryp->State = HAL_CRYP_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hcryp); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Initializes the CRYP peripheral in AES CBC encryption mode + * then encrypt pPlainData. The cypher data are available in pCypherData + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module + * @param pPlainData: Pointer to the plaintext buffer + * @param Size: Length of the plaintext buffer, must be a multiple of 16. + * @param pCypherData: Pointer to the cyphertext buffer + * @param Timeout: Specify Timeout value + * @retval HAL status + */ +HAL_StatusTypeDef HAL_CRYP_AESCBC_Encrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData, uint32_t Timeout) +{ + /* Process Locked */ + __HAL_LOCK(hcryp); + + /* Change the CRYP state */ + hcryp->State = HAL_CRYP_STATE_BUSY; + + /* Check if initialization phase has already been performed */ + if(hcryp->Phase == HAL_CRYP_PHASE_READY) + { + /* Set the key */ + CRYP_SetKey(hcryp, hcryp->Init.pKey); + + /* Reset the CHMOD & MODE bits & */ + AES->CR &= (uint32_t)(~CRYP_ALGO_CHAIN_MASK); + + /* Set the CRYP peripheral in AES ECB mode */ + __HAL_CRYP_SET_MODE(CRYP_CR_ALGOMODE_AES_CBC_ENCRYPT); + + /* Set the Initialization Vector */ + CRYP_SetInitVector(hcryp, hcryp->Init.pInitVect); + + /* Enable CRYP */ + __HAL_CRYP_ENABLE(); + + /* Set the phase */ + hcryp->Phase = HAL_CRYP_PHASE_PROCESS; + } + + /* Write Plain Data and Get Cypher Data */ + if(CRYP_ProcessData(hcryp,pPlainData, Size, pCypherData, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + /* Change the CRYP state */ + hcryp->State = HAL_CRYP_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hcryp); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Initializes the CRYP peripheral in AES CTR encryption mode + * then encrypt pPlainData. The cypher data are available in pCypherData + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module + * @param pPlainData: Pointer to the plaintext buffer + * @param Size: Length of the plaintext buffer, must be a multiple of 16. + * @param pCypherData: Pointer to the cyphertext buffer + * @param Timeout: Specify Timeout value + * @retval HAL status + */ +HAL_StatusTypeDef HAL_CRYP_AESCTR_Encrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData, uint32_t Timeout) +{ + /* Process Locked */ + __HAL_LOCK(hcryp); + + /* Change the CRYP state */ + hcryp->State = HAL_CRYP_STATE_BUSY; + + /* Check if initialization phase has already been performed */ + if(hcryp->Phase == HAL_CRYP_PHASE_READY) + { + /* Set the key */ + CRYP_SetKey(hcryp, hcryp->Init.pKey); + + /* Reset the CHMOD & MODE bits & */ + AES->CR &= (uint32_t)(~CRYP_ALGO_CHAIN_MASK); + + /* Set the CRYP peripheral in AES ECB mode */ + __HAL_CRYP_SET_MODE(CRYP_CR_ALGOMODE_AES_CTR_ENCRYPT); + + /* Set the Initialization Vector */ + CRYP_SetInitVector(hcryp, hcryp->Init.pInitVect); + + /* Enable CRYP */ + __HAL_CRYP_ENABLE(); + + /* Set the phase */ + hcryp->Phase = HAL_CRYP_PHASE_PROCESS; + } + + /* Write Plain Data and Get Cypher Data */ + if(CRYP_ProcessData(hcryp, pPlainData, Size, pCypherData, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + /* Change the CRYP state */ + hcryp->State = HAL_CRYP_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hcryp); + + /* Return function status */ + return HAL_OK; +} + + + +/** + * @brief Initializes the CRYP peripheral in AES ECB decryption mode + * then decrypted pCypherData. The cypher data are available in pPlainData + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module + * @param pCypherData: Pointer to the cyphertext buffer + * @param Size: Length of the plaintext buffer, must be a multiple of 16. + * @param pPlainData: Pointer to the plaintext buffer + * @param Timeout: Specify Timeout value + * @retval HAL status + */ +HAL_StatusTypeDef HAL_CRYP_AESECB_Decrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData, uint32_t Timeout) +{ + /* Process Locked */ + __HAL_LOCK(hcryp); + + /* Change the CRYP state */ + hcryp->State = HAL_CRYP_STATE_BUSY; + + /* Check if initialization phase has already been performed */ + if(hcryp->Phase == HAL_CRYP_PHASE_READY) + { + /* Set the key */ + CRYP_SetKey(hcryp, hcryp->Init.pKey); + + /* Reset the CHMOD & MODE bits & */ + AES->CR &= (uint32_t)(~CRYP_ALGO_CHAIN_MASK); + + /* Set the CRYP peripheral in AES ECB decryption mode (with key derivation) */ + __HAL_CRYP_SET_MODE(CRYP_CR_ALGOMODE_AES_ECB_KEYDERDECRYPT); + + /* Enable CRYP */ + __HAL_CRYP_ENABLE(); + + /* Set the phase */ + hcryp->Phase = HAL_CRYP_PHASE_PROCESS; + } + + /* Write Plain Data and Get Cypher Data */ + if(CRYP_ProcessData(hcryp, pCypherData, Size, pPlainData, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + /* Change the CRYP state */ + hcryp->State = HAL_CRYP_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hcryp); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Initializes the CRYP peripheral in AES ECB decryption mode + * then decrypted pCypherData. The cypher data are available in pPlainData + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module + * @param pCypherData: Pointer to the cyphertext buffer + * @param Size: Length of the plaintext buffer, must be a multiple of 16. + * @param pPlainData: Pointer to the plaintext buffer + * @param Timeout: Specify Timeout value + * @retval HAL status + */ +HAL_StatusTypeDef HAL_CRYP_AESCBC_Decrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData, uint32_t Timeout) +{ + /* Process Locked */ + __HAL_LOCK(hcryp); + + /* Change the CRYP state */ + hcryp->State = HAL_CRYP_STATE_BUSY; + + /* Check if initialization phase has already been performed */ + if(hcryp->Phase == HAL_CRYP_PHASE_READY) + { + /* Set the key */ + CRYP_SetKey(hcryp, hcryp->Init.pKey); + + /* Reset the CHMOD & MODE bits & */ + AES->CR &= (uint32_t)(~CRYP_ALGO_CHAIN_MASK); + + /* Set the CRYP peripheral in AES CBC decryption mode (with key derivation) */ + __HAL_CRYP_SET_MODE(CRYP_CR_ALGOMODE_AES_CBC_KEYDERDECRYPT); + + /* Set the Initialization Vector */ + CRYP_SetInitVector(hcryp, hcryp->Init.pInitVect); + + /* Enable CRYP */ + __HAL_CRYP_ENABLE(); + + /* Set the phase */ + hcryp->Phase = HAL_CRYP_PHASE_PROCESS; + } + + /* Write Plain Data and Get Cypher Data */ + if(CRYP_ProcessData(hcryp, pCypherData, Size, pPlainData, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + /* Change the CRYP state */ + hcryp->State = HAL_CRYP_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hcryp); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Initializes the CRYP peripheral in AES CTR decryption mode + * then decrypted pCypherData. The cypher data are available in pPlainData + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module + * @param pCypherData: Pointer to the cyphertext buffer + * @param Size: Length of the plaintext buffer, must be a multiple of 16. + * @param pPlainData: Pointer to the plaintext buffer + * @param Timeout: Specify Timeout value + * @retval HAL status + */ +HAL_StatusTypeDef HAL_CRYP_AESCTR_Decrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData, uint32_t Timeout) +{ + /* Process Locked */ + __HAL_LOCK(hcryp); + + /* Check if initialization phase has already been performed */ + if(hcryp->Phase == HAL_CRYP_PHASE_READY) + { + /* Change the CRYP state */ + hcryp->State = HAL_CRYP_STATE_BUSY; + + /* Set the key */ + CRYP_SetKey(hcryp, hcryp->Init.pKey); + + /* Reset the CHMOD & MODE bits & */ + AES->CR &= (uint32_t)(~CRYP_ALGO_CHAIN_MASK); + + /* Set the CRYP peripheral in AES CTR decryption mode */ + __HAL_CRYP_SET_MODE(CRYP_CR_ALGOMODE_AES_CTR_DECRYPT); + + /* Set the Initialization Vector */ + CRYP_SetInitVector(hcryp, hcryp->Init.pInitVect); + + /* Enable CRYP */ + __HAL_CRYP_ENABLE(); + + /* Set the phase */ + hcryp->Phase = HAL_CRYP_PHASE_PROCESS; + } + + /* Write Plain Data and Get Cypher Data */ + if(CRYP_ProcessData(hcryp, pCypherData, Size, pPlainData, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + /* Change the CRYP state */ + hcryp->State = HAL_CRYP_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hcryp); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Initializes the CRYP peripheral in AES ECB encryption mode using Interrupt. + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module + * @param pPlainData: Pointer to the plaintext buffer + * @param Size: Length of the plaintext buffer, must be a multiple of 16 bytes + * @param pCypherData: Pointer to the cyphertext buffer + * @retval HAL status + */ +HAL_StatusTypeDef HAL_CRYP_AESECB_Encrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData) +{ + uint32_t inputaddr; + uint32_t outputaddr; + + if(hcryp->State == HAL_CRYP_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hcryp); + + /* Get the buffer addresses and sizes */ + hcryp->CrypInCount = Size; + hcryp->pCrypInBuffPtr = pPlainData; + hcryp->pCrypOutBuffPtr = pCypherData; + hcryp->CrypOutCount = Size; + + /* Change the CRYP state */ + hcryp->State = HAL_CRYP_STATE_BUSY; + + /* Check if initialization phase has already been performed */ + if(hcryp->Phase == HAL_CRYP_PHASE_READY) + { + /* Set the key */ + CRYP_SetKey(hcryp, hcryp->Init.pKey); + + /* Reset the CHMOD & MODE bits & */ + AES->CR &= (uint32_t)(~CRYP_ALGO_CHAIN_MASK); + + /* Set the CRYP peripheral in AES ECB mode */ + __HAL_CRYP_SET_MODE(CRYP_CR_ALGOMODE_AES_ECB_ENCRYPT); + + /* Set the phase */ + hcryp->Phase = HAL_CRYP_PHASE_PROCESS; + } + + /* Enable Interrupts */ + __HAL_CRYP_ENABLE_IT(AES_IT_CC); + + /* Enable CRYP */ + __HAL_CRYP_ENABLE(); + + /* Get the last input data adress */ + inputaddr = (uint32_t)hcryp->pCrypInBuffPtr; + + /* Write the Input block in the Data Input register */ + AES->DINR = *(uint32_t*)(inputaddr); + inputaddr+=4; + AES->DINR = *(uint32_t*)(inputaddr); + inputaddr+=4; + AES->DINR = *(uint32_t*)(inputaddr); + inputaddr+=4; + AES->DINR = *(uint32_t*)(inputaddr); + hcryp->pCrypInBuffPtr += 16; + hcryp->CrypInCount -= 16; + + /* Return function status */ + return HAL_OK; + } + + else if(__HAL_CRYP_GET_FLAG(AES_FLAG_CCF)) + { + /* Clear CCF Flag */ + AES->CR |= AES_CR_CCFC; + + /* Get the last Output data adress */ + outputaddr = (uint32_t)hcryp->pCrypOutBuffPtr; + + /* Read the Output block from the Data Output Register */ + *(uint32_t*)(outputaddr) = AES->DOUTR; + outputaddr+=4; + *(uint32_t*)(outputaddr) = AES->DOUTR; + outputaddr+=4; + *(uint32_t*)(outputaddr) = AES->DOUTR; + outputaddr+=4; + *(uint32_t*)(outputaddr) = AES->DOUTR; + hcryp->pCrypOutBuffPtr += 16; + hcryp->CrypOutCount -= 16; + + /* Check if all input text is encrypted */ + if(hcryp->CrypOutCount == 0) + { + /* Disable Computation Complete Interrupt */ + __HAL_CRYP_DISABLE_IT(AES_IT_CC); + + /* Process Unlocked */ + __HAL_UNLOCK(hcryp); + + /* Change the CRYP state */ + hcryp->State = HAL_CRYP_STATE_READY; + + /* Call computation complete callback */ + HAL_CRYP_ComputationCpltCallback(hcryp); + } + else /* Process the rest of input text */ + { + /* Get the last Intput data adress */ + inputaddr = (uint32_t)hcryp->pCrypInBuffPtr; + + /* Write the Input block in the Data Input register */ + AES->DINR = *(uint32_t*)(inputaddr); + inputaddr+=4; + AES->DINR = *(uint32_t*)(inputaddr); + inputaddr+=4; + AES->DINR = *(uint32_t*)(inputaddr); + inputaddr+=4; + AES->DINR = *(uint32_t*)(inputaddr); + hcryp->pCrypInBuffPtr += 16; + hcryp->CrypInCount -= 16; + } + } + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Initializes the CRYP peripheral in AES CBC encryption mode using Interrupt. + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module + * @param pPlainData: Pointer to the plaintext buffer + * @param Size: Length of the plaintext buffer, must be a multiple of 16 bytes + * @param pCypherData: Pointer to the cyphertext buffer + * @retval HAL status + */ +HAL_StatusTypeDef HAL_CRYP_AESCBC_Encrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData) +{ + uint32_t inputaddr; + uint32_t outputaddr; + + if(hcryp->State == HAL_CRYP_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hcryp); + + /* Get the buffer addresses and sizes */ + hcryp->CrypInCount = Size; + hcryp->pCrypInBuffPtr = pPlainData; + hcryp->pCrypOutBuffPtr = pCypherData; + hcryp->CrypOutCount = Size; + + /* Change the CRYP state */ + hcryp->State = HAL_CRYP_STATE_BUSY; + + /* Check if initialization phase has already been performed */ + if(hcryp->Phase == HAL_CRYP_PHASE_READY) + { + /* Set the key */ + CRYP_SetKey(hcryp, hcryp->Init.pKey); + + /* Reset the CHMOD & MODE bits & */ + AES->CR &= (uint32_t)(~CRYP_ALGO_CHAIN_MASK); + + /* Set the CRYP peripheral in AES CBC mode */ + __HAL_CRYP_SET_MODE(CRYP_CR_ALGOMODE_AES_CBC_ENCRYPT); + + /* Set the Initialization Vector */ + CRYP_SetInitVector(hcryp, hcryp->Init.pInitVect); + + /* Set the phase */ + hcryp->Phase = HAL_CRYP_PHASE_PROCESS; + } + + /* Enable Interrupts */ + __HAL_CRYP_ENABLE_IT(AES_IT_CC); + + /* Enable CRYP */ + __HAL_CRYP_ENABLE(); + + /* Get the last input data adress */ + inputaddr = (uint32_t)hcryp->pCrypInBuffPtr; + + /* Write the Input block in the Data Input register */ + AES->DINR = *(uint32_t*)(inputaddr); + inputaddr+=4; + AES->DINR = *(uint32_t*)(inputaddr); + inputaddr+=4; + AES->DINR = *(uint32_t*)(inputaddr); + inputaddr+=4; + AES->DINR = *(uint32_t*)(inputaddr); + hcryp->pCrypInBuffPtr += 16; + hcryp->CrypInCount -= 16; + + /* Return function status */ + return HAL_OK; + } + + else if(__HAL_CRYP_GET_FLAG(AES_FLAG_CCF)) + { + /* Clear CCF Flag */ + AES->CR |= AES_CR_CCFC; + + /* Get the last Output data adress */ + outputaddr = (uint32_t)hcryp->pCrypOutBuffPtr; + + /* Read the Output block from the Data Output Register */ + *(uint32_t*)(outputaddr) = AES->DOUTR; + outputaddr+=4; + *(uint32_t*)(outputaddr) = AES->DOUTR; + outputaddr+=4; + *(uint32_t*)(outputaddr) = AES->DOUTR; + outputaddr+=4; + *(uint32_t*)(outputaddr) = AES->DOUTR; + hcryp->pCrypOutBuffPtr += 16; + hcryp->CrypOutCount -= 16; + + /* Check if all input text is encrypted */ + if(hcryp->CrypOutCount == 0) + { + /* Disable Computation Complete Interrupt */ + __HAL_CRYP_DISABLE_IT(AES_IT_CC); + + /* Process Unlocked */ + __HAL_UNLOCK(hcryp); + + /* Change the CRYP state */ + hcryp->State = HAL_CRYP_STATE_READY; + + /* Call computation complete callback */ + HAL_CRYP_ComputationCpltCallback(hcryp); + } + else /* Process the rest of input text */ + { + /* Get the last Intput data adress */ + inputaddr = (uint32_t)hcryp->pCrypInBuffPtr; + + /* Write the Input block in the Data Input register */ + AES->DINR = *(uint32_t*)(inputaddr); + inputaddr+=4; + AES->DINR = *(uint32_t*)(inputaddr); + inputaddr+=4; + AES->DINR = *(uint32_t*)(inputaddr); + inputaddr+=4; + AES->DINR = *(uint32_t*)(inputaddr); + hcryp->pCrypInBuffPtr += 16; + hcryp->CrypInCount -= 16; + } + } + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Initializes the CRYP peripheral in AES CTR encryption mode using Interrupt. + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module + * @param pPlainData: Pointer to the plaintext buffer + * @param Size: Length of the plaintext buffer, must be a multiple of 16 bytes + * @param pCypherData: Pointer to the cyphertext buffer + * @retval HAL status + */ +HAL_StatusTypeDef HAL_CRYP_AESCTR_Encrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData) +{ + uint32_t inputaddr; + uint32_t outputaddr; + + if(hcryp->State == HAL_CRYP_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hcryp); + + /* Get the buffer addresses and sizes */ + hcryp->CrypInCount = Size; + hcryp->pCrypInBuffPtr = pPlainData; + hcryp->pCrypOutBuffPtr = pCypherData; + hcryp->CrypOutCount = Size; + + /* Change the CRYP state */ + hcryp->State = HAL_CRYP_STATE_BUSY; + + /* Check if initialization phase has already been performed */ + if(hcryp->Phase == HAL_CRYP_PHASE_READY) + { + /* Set the key */ + CRYP_SetKey(hcryp, hcryp->Init.pKey); + + /* Reset the CHMOD & MODE bits & */ + AES->CR &= (uint32_t)(~CRYP_ALGO_CHAIN_MASK); + + /* Set the CRYP peripheral in AES CTR mode */ + __HAL_CRYP_SET_MODE(CRYP_CR_ALGOMODE_AES_CTR_ENCRYPT); + + /* Set the Initialization Vector */ + CRYP_SetInitVector(hcryp, hcryp->Init.pInitVect); + + /* Set the phase */ + hcryp->Phase = HAL_CRYP_PHASE_PROCESS; + } + + /* Enable Interrupts */ + __HAL_CRYP_ENABLE_IT(AES_IT_CC); + + /* Enable CRYP */ + __HAL_CRYP_ENABLE(); + + /* Get the last input data adress */ + inputaddr = (uint32_t)hcryp->pCrypInBuffPtr; + + /* Write the Input block in the Data Input register */ + AES->DINR = *(uint32_t*)(inputaddr); + inputaddr+=4; + AES->DINR = *(uint32_t*)(inputaddr); + inputaddr+=4; + AES->DINR = *(uint32_t*)(inputaddr); + inputaddr+=4; + AES->DINR = *(uint32_t*)(inputaddr); + hcryp->pCrypInBuffPtr += 16; + hcryp->CrypInCount -= 16; + + /* Return function status */ + return HAL_OK; + } + + else if(__HAL_CRYP_GET_FLAG(AES_FLAG_CCF)) + { + /* Clear CCF Flag */ + AES->CR |= AES_CR_CCFC; + + /* Get the last Output data adress */ + outputaddr = (uint32_t)hcryp->pCrypOutBuffPtr; + + /* Read the Output block from the Data Output Register */ + *(uint32_t*)(outputaddr) = AES->DOUTR; + outputaddr+=4; + *(uint32_t*)(outputaddr) = AES->DOUTR; + outputaddr+=4; + *(uint32_t*)(outputaddr) = AES->DOUTR; + outputaddr+=4; + *(uint32_t*)(outputaddr) = AES->DOUTR; + hcryp->pCrypOutBuffPtr += 16; + hcryp->CrypOutCount -= 16; + + /* Check if all input text is encrypted */ + if(hcryp->CrypOutCount == 0) + { + /* Disable Computation Complete Interrupt */ + __HAL_CRYP_DISABLE_IT(AES_IT_CC); + + /* Process Unlocked */ + __HAL_UNLOCK(hcryp); + + /* Change the CRYP state */ + hcryp->State = HAL_CRYP_STATE_READY; + + /* Call computation complete callback */ + HAL_CRYP_ComputationCpltCallback(hcryp); + } + else /* Process the rest of input text */ + { + /* Get the last Intput data adress */ + inputaddr = (uint32_t)hcryp->pCrypInBuffPtr; + + /* Write the Input block in the Data Input register */ + AES->DINR = *(uint32_t*)(inputaddr); + inputaddr+=4; + AES->DINR = *(uint32_t*)(inputaddr); + inputaddr+=4; + AES->DINR = *(uint32_t*)(inputaddr); + inputaddr+=4; + AES->DINR = *(uint32_t*)(inputaddr); + hcryp->pCrypInBuffPtr += 16; + hcryp->CrypInCount -= 16; + } + } + + /* Return function status */ + return HAL_OK; +} + + +/** + * @brief Initializes the CRYP peripheral in AES ECB decryption mode using Interrupt. + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module + * @param pCypherData: Pointer to the cyphertext buffer + * @param Size: Length of the plaintext buffer, must be a multiple of 16. + * @param pPlainData: Pointer to the plaintext buffer + * @retval HAL status + */ +HAL_StatusTypeDef HAL_CRYP_AESECB_Decrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData) +{ + uint32_t inputaddr; + uint32_t outputaddr; + + if(hcryp->State == HAL_CRYP_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hcryp); + + /* Get the buffer addresses and sizes */ + hcryp->CrypInCount = Size; + hcryp->pCrypInBuffPtr = pCypherData; + hcryp->pCrypOutBuffPtr = pPlainData; + hcryp->CrypOutCount = Size; + + /* Change the CRYP state */ + hcryp->State = HAL_CRYP_STATE_BUSY; + + /* Check if initialization phase has already been performed */ + if(hcryp->Phase == HAL_CRYP_PHASE_READY) + { + /* Set the key */ + CRYP_SetKey(hcryp, hcryp->Init.pKey); + + /* Reset the CHMOD & MODE bits & */ + AES->CR &= (uint32_t)(~CRYP_ALGO_CHAIN_MASK); + + /* Set the CRYP peripheral in AES ECB decryption mode (with key derivation) */ + __HAL_CRYP_SET_MODE(CRYP_CR_ALGOMODE_AES_ECB_KEYDERDECRYPT); + + /* Set the phase */ + hcryp->Phase = HAL_CRYP_PHASE_PROCESS; + } + + /* Enable Interrupts */ + __HAL_CRYP_ENABLE_IT(AES_IT_CC); + + /* Enable CRYP */ + __HAL_CRYP_ENABLE(); + + /* Get the last input data adress */ + inputaddr = (uint32_t)hcryp->pCrypInBuffPtr; + + /* Write the Input block in the Data Input register */ + AES->DINR = *(uint32_t*)(inputaddr); + inputaddr+=4; + AES->DINR = *(uint32_t*)(inputaddr); + inputaddr+=4; + AES->DINR = *(uint32_t*)(inputaddr); + inputaddr+=4; + AES->DINR = *(uint32_t*)(inputaddr); + hcryp->pCrypInBuffPtr += 16; + hcryp->CrypInCount -= 16; + + /* Return function status */ + return HAL_OK; + } + + else if(__HAL_CRYP_GET_FLAG(AES_FLAG_CCF)) + { + /* Clear CCF Flag */ + AES->CR |= AES_CR_CCFC; + + /* Get the last Output data adress */ + outputaddr = (uint32_t)hcryp->pCrypOutBuffPtr; + + /* Read the Output block from the Output register */ + *(uint32_t*)(outputaddr) = AES->DOUTR; + outputaddr+=4; + *(uint32_t*)(outputaddr) = AES->DOUTR; + outputaddr+=4; + *(uint32_t*)(outputaddr) = AES->DOUTR; + outputaddr+=4; + *(uint32_t*)(outputaddr) = AES->DOUTR; + + hcryp->pCrypOutBuffPtr += 16; + hcryp->CrypOutCount -= 16; + + /* Check if all input text is decrypted */ + if(hcryp->CrypOutCount == 0) + { + /* Disable Computation Complete Interrupt */ + __HAL_CRYP_DISABLE_IT(AES_IT_CC); + + /* Process Unlocked */ + __HAL_UNLOCK(hcryp); + + /* Change the CRYP state */ + hcryp->State = HAL_CRYP_STATE_READY; + + /* Call computation complete callback */ + HAL_CRYP_ComputationCpltCallback(hcryp); + } + else /* Process the rest of input text */ + { + /* Get the last Intput data adress */ + inputaddr = (uint32_t)hcryp->pCrypInBuffPtr; + + /* Write the Input block in the Data Input register */ + AES->DINR = *(uint32_t*)(inputaddr); + inputaddr+=4; + AES->DINR = *(uint32_t*)(inputaddr); + inputaddr+=4; + AES->DINR = *(uint32_t*)(inputaddr); + inputaddr+=4; + AES->DINR = *(uint32_t*)(inputaddr); + hcryp->pCrypInBuffPtr += 16; + hcryp->CrypInCount -= 16; + } + } + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Initializes the CRYP peripheral in AES CBC decryption mode using IT. + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module + * @param pCypherData: Pointer to the cyphertext buffer + * @param Size: Length of the plaintext buffer, must be a multiple of 16 + * @param pPlainData: Pointer to the plaintext buffer + * @retval HAL status + */ +HAL_StatusTypeDef HAL_CRYP_AESCBC_Decrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData) +{ + uint32_t inputaddr; + uint32_t outputaddr; + + if(hcryp->State == HAL_CRYP_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hcryp); + + /* Get the buffer addresses and sizes */ + hcryp->CrypInCount = Size; + hcryp->pCrypInBuffPtr = pCypherData; + hcryp->pCrypOutBuffPtr = pPlainData; + hcryp->CrypOutCount = Size; + + /* Change the CRYP state */ + hcryp->State = HAL_CRYP_STATE_BUSY; + + /* Check if initialization phase has already been performed */ + if(hcryp->Phase == HAL_CRYP_PHASE_READY) + { + /* Set the key */ + CRYP_SetKey(hcryp, hcryp->Init.pKey); + + /* Reset the CHMOD & MODE bits & */ + AES->CR &= (uint32_t)(~CRYP_ALGO_CHAIN_MASK); + + /* Set the CRYP peripheral in AES CBC decryption mode (with key derivation) */ + __HAL_CRYP_SET_MODE(CRYP_CR_ALGOMODE_AES_CBC_KEYDERDECRYPT); + + /* Set the Initialization Vector */ + CRYP_SetInitVector(hcryp, hcryp->Init.pInitVect); + + /* Set the phase */ + hcryp->Phase = HAL_CRYP_PHASE_PROCESS; + } + + /* Enable Interrupts */ + __HAL_CRYP_ENABLE_IT(AES_IT_CC); + + /* Enable CRYP */ + __HAL_CRYP_ENABLE(); + + /* Get the last input data adress */ + inputaddr = (uint32_t)hcryp->pCrypInBuffPtr; + + /* Write the Input block in the Data Input register */ + AES->DINR = *(uint32_t*)(inputaddr); + inputaddr+=4; + AES->DINR = *(uint32_t*)(inputaddr); + inputaddr+=4; + AES->DINR = *(uint32_t*)(inputaddr); + inputaddr+=4; + AES->DINR = *(uint32_t*)(inputaddr); + hcryp->pCrypInBuffPtr += 16; + hcryp->CrypInCount -= 16; + + /* Return function status */ + return HAL_OK; + } + + else if(__HAL_CRYP_GET_FLAG(AES_FLAG_CCF)) + { + /* Clear CCF Flag */ + AES->CR |= AES_CR_CCFC; + + /* Get the last Output data adress */ + outputaddr = (uint32_t)hcryp->pCrypOutBuffPtr; + + /* Read the Output block from the Output Register */ + *(uint32_t*)(outputaddr) = AES->DOUTR; + outputaddr+=4; + *(uint32_t*)(outputaddr) = AES->DOUTR; + outputaddr+=4; + *(uint32_t*)(outputaddr) = AES->DOUTR; + outputaddr+=4; + *(uint32_t*)(outputaddr) = AES->DOUTR; + + hcryp->pCrypOutBuffPtr += 16; + hcryp->CrypOutCount -= 16; + + /* Check if all input text is decrypted */ + if(hcryp->CrypOutCount == 0) + { + /* Disable Computation Complete Interrupt */ + __HAL_CRYP_DISABLE_IT(AES_IT_CC); + + /* Process Unlocked */ + __HAL_UNLOCK(hcryp); + + /* Change the CRYP state */ + hcryp->State = HAL_CRYP_STATE_READY; + + /* Call computation complete callback */ + HAL_CRYP_ComputationCpltCallback(hcryp); + } + else /* Process the rest of input text */ + { + /* Get the last Intput data adress */ + inputaddr = (uint32_t)hcryp->pCrypInBuffPtr; + + /* Write the Input block in the Data Input register */ + AES->DINR = *(uint32_t*)(inputaddr); + inputaddr+=4; + AES->DINR = *(uint32_t*)(inputaddr); + inputaddr+=4; + AES->DINR = *(uint32_t*)(inputaddr); + inputaddr+=4; + AES->DINR = *(uint32_t*)(inputaddr); + hcryp->pCrypInBuffPtr += 16; + hcryp->CrypInCount -= 16; + } + } + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Initializes the CRYP peripheral in AES CTR decryption mode using Interrupt. + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module + * @param pCypherData: Pointer to the cyphertext buffer + * @param Size: Length of the plaintext buffer, must be a multiple of 16 + * @param pPlainData: Pointer to the plaintext buffer + * @retval HAL status + */ +HAL_StatusTypeDef HAL_CRYP_AESCTR_Decrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData) +{ + uint32_t inputaddr; + uint32_t outputaddr; + + if(hcryp->State == HAL_CRYP_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hcryp); + + /* Get the buffer addresses and sizes */ + hcryp->CrypInCount = Size; + hcryp->pCrypInBuffPtr = pCypherData; + hcryp->pCrypOutBuffPtr = pPlainData; + hcryp->CrypOutCount = Size; + + /* Change the CRYP state */ + hcryp->State = HAL_CRYP_STATE_BUSY; + + /* Check if initialization phase has already been performed */ + if(hcryp->Phase == HAL_CRYP_PHASE_READY) + { + /* Set the key */ + CRYP_SetKey(hcryp, hcryp->Init.pKey); + + /* Reset the CHMOD & MODE bits & */ + AES->CR &= (uint32_t)(~CRYP_ALGO_CHAIN_MASK); + + /* Set the CRYP peripheral in AES CTR decryption mode */ + __HAL_CRYP_SET_MODE(CRYP_CR_ALGOMODE_AES_CTR_DECRYPT); + + /* Set the Initialization Vector */ + CRYP_SetInitVector(hcryp, hcryp->Init.pInitVect); + + /* Set the phase */ + hcryp->Phase = HAL_CRYP_PHASE_PROCESS; + } + + /* Enable Interrupts */ + __HAL_CRYP_ENABLE_IT(AES_IT_CC); + + /* Enable CRYP */ + __HAL_CRYP_ENABLE(); + + /* Get the last input data adress */ + inputaddr = (uint32_t)hcryp->pCrypInBuffPtr; + + /* Write the Input block in the Data Input register */ + AES->DINR = *(uint32_t*)(inputaddr); + inputaddr+=4; + AES->DINR = *(uint32_t*)(inputaddr); + inputaddr+=4; + AES->DINR = *(uint32_t*)(inputaddr); + inputaddr+=4; + AES->DINR = *(uint32_t*)(inputaddr); + hcryp->pCrypInBuffPtr += 16; + hcryp->CrypInCount -= 16; + + /* Return function status */ + return HAL_OK; + } + + else if(__HAL_CRYP_GET_FLAG(AES_FLAG_CCF)) + { + /* Clear CCF Flag */ + AES->CR |= AES_CR_CCFC; + + /* Get the last Output data adress */ + outputaddr = (uint32_t)hcryp->pCrypOutBuffPtr; + + /* Read the Output block from the Output Register */ + *(uint32_t*)(outputaddr) = AES->DOUTR; + outputaddr+=4; + *(uint32_t*)(outputaddr) = AES->DOUTR; + outputaddr+=4; + *(uint32_t*)(outputaddr) = AES->DOUTR; + outputaddr+=4; + *(uint32_t*)(outputaddr) = AES->DOUTR; + + hcryp->pCrypOutBuffPtr += 16; + hcryp->CrypOutCount -= 16; + + /* Check if all input text is decrypted */ + if(hcryp->CrypOutCount == 0) + { + /* Disable Computation Complete Interrupt */ + __HAL_CRYP_DISABLE_IT(AES_IT_CC); + + /* Process Unlocked */ + __HAL_UNLOCK(hcryp); + + /* Change the CRYP state */ + hcryp->State = HAL_CRYP_STATE_READY; + + /* Call computation complete callback */ + HAL_CRYP_ComputationCpltCallback(hcryp); + } + else /* Process the rest of input text */ + { + /* Get the last Intput data adress */ + inputaddr = (uint32_t)hcryp->pCrypInBuffPtr; + + /* Write the Input block in the Data Input register */ + AES->DINR = *(uint32_t*)(inputaddr); + inputaddr+=4; + AES->DINR = *(uint32_t*)(inputaddr); + inputaddr+=4; + AES->DINR = *(uint32_t*)(inputaddr); + inputaddr+=4; + AES->DINR = *(uint32_t*)(inputaddr); + hcryp->pCrypInBuffPtr += 16; + hcryp->CrypInCount -= 16; + } + } + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Initializes the CRYP peripheral in AES ECB encryption mode using DMA. + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module + * @param pPlainData: Pointer to the plaintext buffer + * @param Size: Length of the plaintext buffer, must be a multiple of 16 bytes + * @param pCypherData: Pointer to the cyphertext buffer + * @retval HAL status + */ +HAL_StatusTypeDef HAL_CRYP_AESECB_Encrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData) +{ + uint32_t inputaddr; + uint32_t outputaddr; + + if((hcryp->State == HAL_CRYP_STATE_READY) || (hcryp->Phase == HAL_CRYP_PHASE_PROCESS)) + { + /* Process Locked */ + __HAL_LOCK(hcryp); + + inputaddr = (uint32_t)pPlainData; + outputaddr = (uint32_t)pCypherData; + + /* Change the CRYP state */ + hcryp->State = HAL_CRYP_STATE_BUSY; + + /* Check if initialization phase has already been performed */ + if(hcryp->Phase == HAL_CRYP_PHASE_READY) + { + /* Set the key */ + CRYP_SetKey(hcryp, hcryp->Init.pKey); + + /* Set the CRYP peripheral in AES ECB mode */ + __HAL_CRYP_SET_MODE(CRYP_CR_ALGOMODE_AES_ECB_ENCRYPT); + + /* Set the phase */ + hcryp->Phase = HAL_CRYP_PHASE_PROCESS; + } + /* Set the input and output addresses and start DMA transfer */ + CRYP_SetDMAConfig(hcryp, inputaddr, Size, outputaddr); + + /* Process Unlocked */ + __HAL_UNLOCK(hcryp); + + /* Return function status */ + return HAL_OK; + } + else + { + return HAL_ERROR; + } +} + +/** + * @brief Initializes the CRYP peripheral in AES CBC encryption mode using DMA. + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module + * @param pPlainData: Pointer to the plaintext buffer + * @param Size: Length of the plaintext buffer, must be a multiple of 16. + * @param pCypherData: Pointer to the cyphertext buffer + * @retval HAL status + */ +HAL_StatusTypeDef HAL_CRYP_AESCBC_Encrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData) +{ + uint32_t inputaddr; + uint32_t outputaddr; + + if((hcryp->State == HAL_CRYP_STATE_READY) || (hcryp->Phase == HAL_CRYP_PHASE_PROCESS)) + { + /* Process Locked */ + __HAL_LOCK(hcryp); + + inputaddr = (uint32_t)pPlainData; + outputaddr = (uint32_t)pCypherData; + + /* Change the CRYP state */ + hcryp->State = HAL_CRYP_STATE_BUSY; + + /* Check if initialization phase has already been performed */ + if(hcryp->Phase == HAL_CRYP_PHASE_READY) + { + /* Set the key */ + CRYP_SetKey(hcryp, hcryp->Init.pKey); + + /* Set the CRYP peripheral in AES ECB mode */ + __HAL_CRYP_SET_MODE(CRYP_CR_ALGOMODE_AES_CBC_ENCRYPT); + + /* Set the Initialization Vector */ + CRYP_SetInitVector(hcryp, hcryp->Init.pInitVect); + + /* Set the phase */ + hcryp->Phase = HAL_CRYP_PHASE_PROCESS; + } + /* Set the input and output addresses and start DMA transfer */ + CRYP_SetDMAConfig(hcryp, inputaddr, Size, outputaddr); + + /* Process Unlocked */ + __HAL_UNLOCK(hcryp); + + /* Return function status */ + return HAL_OK; + } + else + { + return HAL_ERROR; + } +} + +/** + * @brief Initializes the CRYP peripheral in AES CTR encryption mode using DMA. + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module + * @param pPlainData: Pointer to the plaintext buffer + * @param Size: Length of the plaintext buffer, must be a multiple of 16. + * @param pCypherData: Pointer to the cyphertext buffer + * @retval HAL status + */ +HAL_StatusTypeDef HAL_CRYP_AESCTR_Encrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData) +{ + uint32_t inputaddr; + uint32_t outputaddr; + + if((hcryp->State == HAL_CRYP_STATE_READY) || (hcryp->Phase == HAL_CRYP_PHASE_PROCESS)) + { + /* Process Locked */ + __HAL_LOCK(hcryp); + + inputaddr = (uint32_t)pPlainData; + outputaddr = (uint32_t)pCypherData; + + /* Change the CRYP state */ + hcryp->State = HAL_CRYP_STATE_BUSY; + + /* Check if initialization phase has already been performed */ + if(hcryp->Phase == HAL_CRYP_PHASE_READY) + { + /* Set the key */ + CRYP_SetKey(hcryp, hcryp->Init.pKey); + + /* Set the CRYP peripheral in AES ECB mode */ + __HAL_CRYP_SET_MODE(CRYP_CR_ALGOMODE_AES_CTR_ENCRYPT); + + /* Set the Initialization Vector */ + CRYP_SetInitVector(hcryp, hcryp->Init.pInitVect); + + /* Set the phase */ + hcryp->Phase = HAL_CRYP_PHASE_PROCESS; + } + + /* Set the input and output addresses and start DMA transfer */ + CRYP_SetDMAConfig(hcryp, inputaddr, Size, outputaddr); + + /* Process Unlocked */ + __HAL_UNLOCK(hcryp); + + /* Return function status */ + return HAL_OK; + } + else + { + return HAL_ERROR; + } +} + +/** + * @brief Initializes the CRYP peripheral in AES ECB decryption mode using DMA. + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module + * @param pCypherData: Pointer to the cyphertext buffer + * @param Size: Length of the plaintext buffer, must be a multiple of 16 bytes + * @param pPlainData: Pointer to the plaintext buffer + * @retval HAL status + */ +HAL_StatusTypeDef HAL_CRYP_AESECB_Decrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData) +{ + uint32_t inputaddr; + uint32_t outputaddr; + + if((hcryp->State == HAL_CRYP_STATE_READY) || (hcryp->Phase == HAL_CRYP_PHASE_PROCESS)) + { + /* Process Locked */ + __HAL_LOCK(hcryp); + + inputaddr = (uint32_t)pCypherData; + outputaddr = (uint32_t)pPlainData; + + /* Change the CRYP state */ + hcryp->State = HAL_CRYP_STATE_BUSY; + + /* Check if initialization phase has already been performed */ + if(hcryp->Phase == HAL_CRYP_PHASE_READY) + { + /* Set the key */ + CRYP_SetKey(hcryp, hcryp->Init.pKey); + + /* Reset the CHMOD & MODE bits & */ + AES->CR &= (uint32_t)(~CRYP_ALGO_CHAIN_MASK); + + /* Set the CRYP peripheral in AES ECB decryption mode (with key derivation) */ + __HAL_CRYP_SET_MODE(CRYP_CR_ALGOMODE_AES_ECB_KEYDERDECRYPT); + + /* Set the phase */ + hcryp->Phase = HAL_CRYP_PHASE_PROCESS; + } + + /* Set the input and output addresses and start DMA transfer */ + CRYP_SetDMAConfig(hcryp, inputaddr, Size, outputaddr); + + /* Process Unlocked */ + __HAL_UNLOCK(hcryp); + + /* Return function status */ + return HAL_OK; + } + else + { + return HAL_ERROR; + } +} + +/** + * @brief Initializes the CRYP peripheral in AES CBC encryption mode using DMA. + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module + * @param pCypherData: Pointer to the cyphertext buffer + * @param Size: Length of the plaintext buffer, must be a multiple of 16 bytes + * @param pPlainData: Pointer to the plaintext buffer + * @retval HAL status + */ +HAL_StatusTypeDef HAL_CRYP_AESCBC_Decrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData) +{ + uint32_t inputaddr; + uint32_t outputaddr; + + if((hcryp->State == HAL_CRYP_STATE_READY) || (hcryp->Phase == HAL_CRYP_PHASE_PROCESS)) + { + /* Process Locked */ + __HAL_LOCK(hcryp); + + inputaddr = (uint32_t)pCypherData; + outputaddr = (uint32_t)pPlainData; + + /* Change the CRYP state */ + hcryp->State = HAL_CRYP_STATE_BUSY; + + /* Check if initialization phase has already been performed */ + if(hcryp->Phase == HAL_CRYP_PHASE_READY) + { + /* Set the key */ + CRYP_SetKey(hcryp, hcryp->Init.pKey); + + /* Reset the CHMOD & MODE bits & */ + AES->CR &= (uint32_t)(~CRYP_ALGO_CHAIN_MASK); + + /* Set the CRYP peripheral in AES CBC decryption mode (with key derivation) */ + __HAL_CRYP_SET_MODE(CRYP_CR_ALGOMODE_AES_CBC_KEYDERDECRYPT); + + /* Set the Initialization Vector */ + CRYP_SetInitVector(hcryp, hcryp->Init.pInitVect); + + /* Set the phase */ + hcryp->Phase = HAL_CRYP_PHASE_PROCESS; + } + + /* Set the input and output addresses and start DMA transfer */ + CRYP_SetDMAConfig(hcryp, inputaddr, Size, outputaddr); + + /* Process Unlocked */ + __HAL_UNLOCK(hcryp); + + /* Return function status */ + return HAL_OK; + } + else + { + return HAL_ERROR; + } +} + +/** + * @brief Initializes the CRYP peripheral in AES CTR decryption mode using DMA. + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module + * @param pCypherData: Pointer to the cyphertext buffer + * @param Size: Length of the plaintext buffer, must be a multiple of 16 + * @param pPlainData: Pointer to the plaintext buffer + * @retval HAL status + */ +HAL_StatusTypeDef HAL_CRYP_AESCTR_Decrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData) +{ + uint32_t inputaddr; + uint32_t outputaddr; + + if((hcryp->State == HAL_CRYP_STATE_READY) || (hcryp->Phase == HAL_CRYP_PHASE_PROCESS)) + { + /* Process Locked */ + __HAL_LOCK(hcryp); + + inputaddr = (uint32_t)pCypherData; + outputaddr = (uint32_t)pPlainData; + + /* Change the CRYP state */ + hcryp->State = HAL_CRYP_STATE_BUSY; + + /* Check if initialization phase has already been performed */ + if(hcryp->Phase == HAL_CRYP_PHASE_READY) + { + /* Set the key */ + CRYP_SetKey(hcryp, hcryp->Init.pKey); + + /* Set the CRYP peripheral in AES CTR mode */ + __HAL_CRYP_SET_MODE(CRYP_CR_ALGOMODE_AES_CTR_DECRYPT); + + /* Set the Initialization Vector */ + CRYP_SetInitVector(hcryp, hcryp->Init.pInitVect); + + /* Set the phase */ + hcryp->Phase = HAL_CRYP_PHASE_PROCESS; + } + + /* Set the input and output addresses and start DMA transfer */ + CRYP_SetDMAConfig(hcryp, inputaddr, Size, outputaddr); + + /* Process Unlocked */ + __HAL_UNLOCK(hcryp); + + /* Return function status */ + return HAL_OK; + } + else + { + return HAL_ERROR; + } +} + +/** + * @} + */ + + +/** @defgroup CRYP_Group3 DMA callback functions + * @brief DMA callback functions. + * +@verbatim + ============================================================================== + ##### DMA callback functions ##### + ============================================================================== + [..] This section provides DMA callback functions: + (+) DMA Input data transfer complete + (+) DMA Output data transfer complete + (+) DMA error + +@endverbatim + * @{ + */ + +/** + * @brief Input Computation completed callbacks. + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module + * @retval None + */ +__weak void HAL_CRYP_ComputationCpltCallback(CRYP_HandleTypeDef *hcryp) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_CRYP_ComputationCpltCallback could be implemented in the user file + */ +} + +/** + * @brief CRYP error callbacks. + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module + * @retval None + */ + __weak void HAL_CRYP_ErrorCallback(CRYP_HandleTypeDef *hcryp) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_CRYP_ErrorCallback could be implemented in the user file + */ +} + +/** + * @brief Input transfer completed callbacks. + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module + * @retval None + */ +__weak void HAL_CRYP_InCpltCallback(CRYP_HandleTypeDef *hcryp) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_CRYP_InCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Output transfer completed callbacks. + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module + * @retval None + */ +__weak void HAL_CRYP_OutCpltCallback(CRYP_HandleTypeDef *hcryp) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_CRYP_OutCpltCallback could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup CRYP_Group4 CRYP IRQ handler + * @brief CRYP IRQ handler. + * +@verbatim + ============================================================================== + ##### CRYP IRQ handler management ##### + ============================================================================== +[..] This section provides CRYP IRQ handler function. + +@endverbatim + * @{ + */ + +/** + * @brief This function handles CRYP interrupt request. + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module + * @retval None + */ +void HAL_CRYP_IRQHandler(CRYP_HandleTypeDef *hcryp) +{ + switch(AES->CR & CRYP_CR_ALGOMODE_DIRECTION) + { + case CRYP_CR_ALGOMODE_AES_ECB_ENCRYPT: + HAL_CRYP_AESECB_Encrypt_IT(hcryp, NULL, 0, NULL); + break; + + case CRYP_CR_ALGOMODE_AES_ECB_KEYDERDECRYPT: + HAL_CRYP_AESECB_Decrypt_IT(hcryp, NULL, 0, NULL); + break; + + case CRYP_CR_ALGOMODE_AES_CBC_ENCRYPT: + HAL_CRYP_AESCBC_Encrypt_IT(hcryp, NULL, 0, NULL); + break; + + case CRYP_CR_ALGOMODE_AES_CBC_KEYDERDECRYPT: + HAL_CRYP_AESCBC_Decrypt_IT(hcryp, NULL, 0, NULL); + break; + + case CRYP_CR_ALGOMODE_AES_CTR_ENCRYPT: + HAL_CRYP_AESCTR_Encrypt_IT(hcryp, NULL, 0, NULL); + break; + + case CRYP_CR_ALGOMODE_AES_CTR_DECRYPT: + HAL_CRYP_AESCTR_Decrypt_IT(hcryp, NULL, 0, NULL); + break; + + default: + break; + } +} + +/** + * @} + */ + +/** @defgroup CRYP_Group5 Peripheral State functions + * @brief Peripheral State functions. + * +@verbatim + ============================================================================== + ##### Peripheral State functions ##### + ============================================================================== + [..] + This subsection permits to get in run-time the status of the peripheral. + +@endverbatim + * @{ + */ + +/** + * @brief Returns the CRYP state. + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module + * @retval HAL state + */ +HAL_CRYP_STATETypeDef HAL_CRYP_GetState(CRYP_HandleTypeDef *hcryp) +{ + return hcryp->State; +} + +/** + * @} + */ + +/** + * @brief DMA CRYP Input Data process complete callback. + * @param hdma: DMA handle + * @retval None + */ +static void CRYP_DMAInCplt(DMA_HandleTypeDef *hdma) +{ + CRYP_HandleTypeDef* hcryp = (CRYP_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent; + + /* Disable the DMA transfer for input request */ + AES->CR &= (uint32_t)(~AES_CR_DMAINEN); + + /* Call input data transfer complete callback */ + HAL_CRYP_InCpltCallback(hcryp); +} + +/** + * @brief DMA CRYP Output Data process complete callback. + * @param hdma: DMA handle + * @retval None + */ +static void CRYP_DMAOutCplt(DMA_HandleTypeDef *hdma) +{ + CRYP_HandleTypeDef* hcryp = (CRYP_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent; + + /* Disable the DMA transfer for output request by resetting the DOEN bit + in the DMACR register */ + AES->CR &= (uint32_t)(~AES_CR_DMAOUTEN); + + /* Disable CRYP */ + __HAL_CRYP_DISABLE(); + + /* Change the CRYP state to ready */ + hcryp->State = HAL_CRYP_STATE_READY; + + /* Call output data transfer complete callback */ + HAL_CRYP_OutCpltCallback(hcryp); +} + +/** + * @brief DMA CRYP communication error callback. + * @param hdma: DMA handle + * @retval None + */ +static void CRYP_DMAError(DMA_HandleTypeDef *hdma) +{ + CRYP_HandleTypeDef* hcryp = (CRYP_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent; + hcryp->State= HAL_CRYP_STATE_READY; + HAL_CRYP_ErrorCallback(hcryp); +} + +/** + * @brief Writes the Key in Key registers. + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module + * @param Key: Pointer to Key buffer + * @param KeySize: Size of Key + * @retval None + */ +static void CRYP_SetKey(CRYP_HandleTypeDef *hcryp, uint8_t *Key) +{ + uint32_t keyaddr = (uint32_t)Key; + + AES->KEYR3 = __REV(*(uint32_t*)(keyaddr)); + keyaddr+=4; + AES->KEYR2 = __REV(*(uint32_t*)(keyaddr)); + keyaddr+=4; + AES->KEYR1 = __REV(*(uint32_t*)(keyaddr)); + keyaddr+=4; + AES->KEYR0 = __REV(*(uint32_t*)(keyaddr)); +} + +/** + * @brief Writes the InitVector/InitCounter in IV registers. + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module + * @param InitVector: Pointer to InitVector/InitCounter buffer + * @param IVSize: Size of the InitVector/InitCounter + * @retval None + */ +static void CRYP_SetInitVector(CRYP_HandleTypeDef *hcryp, uint8_t *InitVector) +{ + uint32_t ivaddr = (uint32_t)InitVector; + + AES->IVR3 = __REV(*(uint32_t*)(ivaddr)); + ivaddr+=4; + AES->IVR2 = __REV(*(uint32_t*)(ivaddr)); + ivaddr+=4; + AES->IVR1 = __REV(*(uint32_t*)(ivaddr)); + ivaddr+=4; + AES->IVR0 = __REV(*(uint32_t*)(ivaddr)); +} + +/** + * @brief Process Data: Writes Input data in polling mode and read the output data + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module + * @param Input: Pointer to the Input buffer + * @param Ilength: Length of the Input buffer, must be a multiple of 16. + * @param Output: Pointer to the returned buffer + * @retval None + */ +static HAL_StatusTypeDef CRYP_ProcessData(CRYP_HandleTypeDef *hcryp, uint8_t* Input, uint16_t Ilength, uint8_t* Output, uint32_t Timeout) +{ + uint32_t tickstart = 0; + + uint32_t i = 0; + uint32_t inputaddr = (uint32_t)Input; + uint32_t outputaddr = (uint32_t)Output; + + for(i=0; (i < Ilength); i+=16) + { + /* Write the Input block in the Data Input register */ + AES->DINR = *(uint32_t*)(inputaddr); + inputaddr+=4; + AES->DINR = *(uint32_t*)(inputaddr); + inputaddr+=4; + AES->DINR = *(uint32_t*)(inputaddr); + inputaddr+=4; + AES->DINR = *(uint32_t*)(inputaddr); + inputaddr+=4; + + /* Get timeout */ + tickstart = HAL_GetTick(); + + while(HAL_IS_BIT_CLR(AES->SR, AES_SR_CCF)) + { + /* Check for the Timeout */ + if(Timeout != HAL_MAX_DELAY) + { + if((HAL_GetTick() - tickstart ) > Timeout) + { + /* Change state */ + hcryp->State = HAL_CRYP_STATE_TIMEOUT; + + /* Process Unlocked */ + __HAL_UNLOCK(hcryp); + + return HAL_TIMEOUT; + } + } + } + /* Clear CCF Flag */ + AES->CR |= AES_CR_CCFC; + + /* Read the Output block from the Data Output Register */ + *(uint32_t*)(outputaddr) = AES->DOUTR; + outputaddr+=4; + *(uint32_t*)(outputaddr) = AES->DOUTR; + outputaddr+=4; + *(uint32_t*)(outputaddr) = AES->DOUTR; + outputaddr+=4; + *(uint32_t*)(outputaddr) = AES->DOUTR; + outputaddr+=4; + } + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Set the DMA configuration and start the DMA transfer + * @param hcryp: pointer to a CRYP_HandleTypeDef structure that contains + * the configuration information for CRYP module + * @param inputaddr: address of the Input buffer + * @param Size: Size of the Input buffer, must be a multiple of 16. + * @param outputaddr: address of the Output buffer + * @retval None + */ +static void CRYP_SetDMAConfig(CRYP_HandleTypeDef *hcryp, uint32_t inputaddr, uint16_t Size, uint32_t outputaddr) +{ + /* Set the CRYP DMA transfer complete callback */ + hcryp->hdmain->XferCpltCallback = CRYP_DMAInCplt; + /* Set the DMA error callback */ + hcryp->hdmain->XferErrorCallback = CRYP_DMAError; + + /* Set the CRYP DMA transfer complete callback */ + hcryp->hdmaout->XferCpltCallback = CRYP_DMAOutCplt; + /* Set the DMA error callback */ + hcryp->hdmaout->XferErrorCallback = CRYP_DMAError; + + /* Enable the DMA In DMA Stream */ + HAL_DMA_Start_IT(hcryp->hdmain, inputaddr, (uint32_t)&AES->DINR, Size/4); + + /* Enable the DMA Out DMA Stream */ + HAL_DMA_Start_IT(hcryp->hdmaout, (uint32_t)&AES->DOUTR, outputaddr, Size/4); + + /* Enable In and Out DMA requests */ + AES->CR |= (AES_CR_DMAINEN | AES_CR_DMAOUTEN); + + /* Enable CRYP */ + __HAL_CRYP_ENABLE(); +} + + + + + + +/** + * @} + */ +#endif /* STM32L051xx && STM32L052xx && STM32L053xx*/ +#endif /* HAL_CRYP_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_cryp.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_cryp.h new file mode 100644 index 0000000000..c6819dd612 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_cryp.h @@ -0,0 +1,306 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_cryp.h + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief Header file of CRYP HAL module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32L0xx_HAL_CRYP_H +#define __STM32L0xx_HAL_CRYP_H + +#ifdef __cplusplus + extern "C" { +#endif + +#if !defined (STM32L051xx) && !defined (STM32L052xx) && !defined (STM32L053xx) + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal_def.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @addtogroup CRYP + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ + +/** + * @brief CRYP Configuration Structure definition + */ +typedef struct +{ + uint32_t DataType; /*!< 32-bit data, 16-bit data, 8-bit data or 1-bit string. + This parameter can be a value of @ref CRYP_Data_Type */ + + uint8_t* pKey; /*!< The key used for encryption/decryption */ + + uint8_t* pInitVect; /*!< The initialization vector used also as initialization + counter in CTR mode */ + +}CRYP_InitTypeDef; + +/** + * @brief HAL CRYP State structures definition + */ +typedef enum +{ + HAL_CRYP_STATE_RESET = 0x00, /*!< CRYP not yet initialized or disabled */ + HAL_CRYP_STATE_READY = 0x01, /*!< CRYP initialized and ready for use */ + HAL_CRYP_STATE_BUSY = 0x02, /*!< CRYP internal processing is ongoing */ + HAL_CRYP_STATE_TIMEOUT = 0x03, /*!< CRYP timeout state */ + HAL_CRYP_STATE_ERROR = 0x04 /*!< CRYP error state */ + +}HAL_CRYP_STATETypeDef; + +/** + * @brief HAL CRYP phase structures definition + */ +typedef enum +{ + HAL_CRYP_PHASE_READY = 0x01, /*!< CRYP peripheral is ready for initialization. */ + HAL_CRYP_PHASE_PROCESS = 0x02, /*!< CRYP peripheral is in processing phase */ +}HAL_PhaseTypeDef; + +/** + * @brief CRYP handle Structure definition + */ +typedef struct +{ + CRYP_InitTypeDef Init; /*!< CRYP required parameters */ + + uint8_t *pCrypInBuffPtr; /*!< Pointer to CRYP processing (encryption, decryption,...) buffer */ + + uint8_t *pCrypOutBuffPtr; /*!< Pointer to CRYP processing (encryption, decryption,...) buffer */ + + __IO uint16_t CrypInCount; /*!< Counter of inputed data */ + + __IO uint16_t CrypOutCount; /*!< Counter of outputed data */ + + HAL_StatusTypeDef Status; /*!< CRYP peripheral status */ + + HAL_PhaseTypeDef Phase; /*!< CRYP peripheral phase */ + + DMA_HandleTypeDef *hdmain; /*!< CRYP In DMA handle parameters */ + + DMA_HandleTypeDef *hdmaout; /*!< CRYP Out DMA handle parameters */ + + HAL_LockTypeDef Lock; /*!< CRYP locking object */ + + __IO HAL_CRYP_STATETypeDef State; /*!< CRYP peripheral state */ + +}CRYP_HandleTypeDef; + +/* Exported constants --------------------------------------------------------*/ + +/** @defgroup CRYP_Exported_Constants + * @{ + */ + +/** @defgroup CRYP_Data_Type + * @{ + */ +#define CRYP_DATATYPE_32B ((uint32_t)0x00000000) +#define CRYP_DATATYPE_16B AES_CR_DATATYPE_0 +#define CRYP_DATATYPE_8B AES_CR_DATATYPE_1 +#define CRYP_DATATYPE_1B AES_CR_DATATYPE + +#define IS_CRYP_DATATYPE(DATATYPE) (((DATATYPE) == CRYP_DATATYPE_32B) || \ + ((DATATYPE) == CRYP_DATATYPE_16B) || \ + ((DATATYPE) == CRYP_DATATYPE_8B) || \ + ((DATATYPE) == CRYP_DATATYPE_1B)) +/** + * @} + */ + +/** @defgroup CRYP_AlgoModeDirection + * @{ + */ +#define CRYP_CR_ALGOMODE_DIRECTION (uint32_t)(AES_CR_MODE|AES_CR_CHMOD) + +#define CRYP_CR_ALGOMODE_AES_ECB_ENCRYPT ((uint32_t)0x00000000) +#define CRYP_CR_ALGOMODE_AES_ECB_KEYDERDECRYPT (AES_CR_MODE) +#define CRYP_CR_ALGOMODE_AES_CBC_ENCRYPT (AES_CR_CHMOD_0) +#define CRYP_CR_ALGOMODE_AES_CBC_KEYDERDECRYPT ((uint32_t)(AES_CR_CHMOD_0|AES_CR_MODE)) +#define CRYP_CR_ALGOMODE_AES_CTR_ENCRYPT (AES_CR_CHMOD_1) +#define CRYP_CR_ALGOMODE_AES_CTR_DECRYPT ((uint32_t)(AES_CR_CHMOD_1 | AES_CR_MODE_1)) +/** + * @} + */ + +/** @defgroup AES_Interrupts + * @{ + */ +#define AES_IT_CC AES_CR_CCIE /*!< Computation Complete interrupt */ +#define AES_IT_ERR AES_CR_ERRIE /*!< Error interrupt */ + +#define IS_AES_IT(IT) ((((IT) & (uint32_t)0xFFFFF9FF) == 0x00000000) && ((IT) != 0x00000000)) +#define IS_AES_GET_IT(IT) (((IT) == AES_IT_CC) || ((IT) == AES_IT_ERR)) + +/** + * @} + */ + + +/** @defgroup AES_Flags + * @{ + */ +#define AES_FLAG_CCF AES_SR_CCF /*!< Computation Complete Flag */ +#define AES_FLAG_RDERR AES_SR_RDERR /*!< Read Error Flag */ +#define AES_FLAG_WRERR AES_SR_WRERR /*!< Write Error Flag */ + +#define IS_AES_FLAG(FLAG) (((FLAG) == AES_FLAG_CCF) || \ + ((FLAG) == AES_FLAG_RDERR) || \ + ((FLAG) == AES_FLAG_WRERR)) +/** + * @} + */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ + +/** @brief Reset CRYP handle state + * @param __HANDLE__: specifies the CRYP Handle. + * @retval None + */ +#define __HAL_CRYP_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_CRYP_STATE_RESET) + +/** + * @brief Enable/Disable the CRYP peripheral. + * @param None + * @retval None + */ +#define __HAL_CRYP_ENABLE() (AES->CR |= AES_CR_EN) +#define __HAL_CRYP_DISABLE() (AES->CR &= ~AES_CR_EN) + +/** + * @brief Set the algorithm mode: AES-ECB, AES-CBC, AES-CTR, DES-ECB, DES-CBC,... + * @param MODE: The algorithm mode. + * @retval None + */ +#define __HAL_CRYP_SET_MODE(MODE) (AES->CR |= (uint32_t)(MODE)) + + +/** @brief Check whether the specified CRYP flag is set or not. + * @param __FLAG__: specifies the flag to check. + * This parameter can be one of the following values: + * @arg AES_FLAG_CCF : Computation Complete Flag + * @arg AES_FLAG_RDERR : Read Error Flag + * @arg AES_FLAG_WRERR : Write Error Flag + * @retval The new state of __FLAG__ (TRUE or FALSE). + */ +#define __HAL_CRYP_GET_FLAG(__FLAG__) ((AES->SR & (__FLAG__)) == (__FLAG__)) + +/** + * @brief Enable the CRYP interrupt. + * @param __INTERRUPT__: CRYP Interrupt. + * @retval None + */ +#define __HAL_CRYP_ENABLE_IT(__INTERRUPT__) ((AES->CR) |= (__INTERRUPT__)) + +/** + * @brief Disable the CRYP interrupt. + * @param __INTERRUPT__: CRYP interrupt. + * @retval None + */ +#define __HAL_CRYP_DISABLE_IT(__INTERRUPT__) ((AES->CR) &= ~(__INTERRUPT__)) + +/* Exported functions --------------------------------------------------------*/ + +/* Initialization/de-initialization functions *********************************/ +HAL_StatusTypeDef HAL_CRYP_Init(CRYP_HandleTypeDef *hcryp); +HAL_StatusTypeDef HAL_CRYP_DeInit(CRYP_HandleTypeDef *hcryp); + +/* AES encryption/decryption using polling ***********************************/ +HAL_StatusTypeDef HAL_CRYP_AESECB_Encrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData, uint32_t Timeout); +HAL_StatusTypeDef HAL_CRYP_AESECB_Decrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData, uint32_t Timeout); +HAL_StatusTypeDef HAL_CRYP_AESCBC_Encrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData, uint32_t Timeout); +HAL_StatusTypeDef HAL_CRYP_AESCBC_Decrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData, uint32_t Timeout); +HAL_StatusTypeDef HAL_CRYP_AESCTR_Encrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData, uint32_t Timeout); +HAL_StatusTypeDef HAL_CRYP_AESCTR_Decrypt(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData, uint32_t Timeout); + +/* AES encryption/decryption using interrupt *********************************/ +HAL_StatusTypeDef HAL_CRYP_AESECB_Encrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData); +HAL_StatusTypeDef HAL_CRYP_AESCBC_Encrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData); +HAL_StatusTypeDef HAL_CRYP_AESCTR_Encrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData); +HAL_StatusTypeDef HAL_CRYP_AESECB_Decrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData); +HAL_StatusTypeDef HAL_CRYP_AESCTR_Decrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData); +HAL_StatusTypeDef HAL_CRYP_AESCBC_Decrypt_IT(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData); + +/* AES encryption/decryption using DMA ***************************************/ +HAL_StatusTypeDef HAL_CRYP_AESECB_Encrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData); +HAL_StatusTypeDef HAL_CRYP_AESECB_Decrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData); +HAL_StatusTypeDef HAL_CRYP_AESCBC_Encrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData); +HAL_StatusTypeDef HAL_CRYP_AESCBC_Decrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData); +HAL_StatusTypeDef HAL_CRYP_AESCTR_Encrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pPlainData, uint16_t Size, uint8_t *pCypherData); +HAL_StatusTypeDef HAL_CRYP_AESCTR_Decrypt_DMA(CRYP_HandleTypeDef *hcryp, uint8_t *pCypherData, uint16_t Size, uint8_t *pPlainData); + +/* Processing functions ********************************************************/ +void HAL_CRYP_IRQHandler(CRYP_HandleTypeDef *hcryp); + +/* Peripheral State functions **************************************************/ +HAL_CRYP_STATETypeDef HAL_CRYP_GetState(CRYP_HandleTypeDef *hcryp); + +/* MSP functions *************************************************************/ +void HAL_CRYP_MspInit(CRYP_HandleTypeDef *hcryp); +void HAL_CRYP_MspDeInit(CRYP_HandleTypeDef *hcryp); + +/* CallBack functions ********************************************************/ +void HAL_CRYP_ComputationCpltCallback(CRYP_HandleTypeDef *hcryp); +void HAL_CRYP_InCpltCallback(CRYP_HandleTypeDef *hcryp); +void HAL_CRYP_OutCpltCallback(CRYP_HandleTypeDef *hcryp); +void HAL_CRYP_ErrorCallback(CRYP_HandleTypeDef *hcryp); + +#endif /* STM32L051xx && STM32L052xx && STM32L053xx*/ + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __STM32L0xx_HAL_CRYP_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_dac.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_dac.c new file mode 100644 index 0000000000..fa8164a428 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_dac.c @@ -0,0 +1,770 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_dac.c + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief DAC HAL module driver. + * + * This file provides firmware functions to manage the following + * functionalities of the Digital to Analog Converter (DAC) peripheral: + * + DAC channels configuration: trigger, output buffer, data format + * + DMA management + * + * + @verbatim + ============================================================================== + ##### DAC Peripheral features ##### + ============================================================================== + [..] + *** DAC Channels *** + ==================== + [..] + The device integrates 1 12-bit Digital Analog Converters: + (#) DAC channel1 with DAC_OUT1 (PA4) as output + + *** DAC Triggers *** + ==================== + [..] + Digital to Analog conversion can be non-triggered using DAC_Trigger_None + and DAC_OUT1/DAC_OUT2 is available once writing to DHRx register. + [..] + Digital to Analog conversion can be triggered by: + (#) External event: EXTI Line 9 (any GPIOx_Pin9) using DAC_Trigger_Ext_IT9. + The used pin (GPIOx_Pin9) must be configured in input mode. + + (#) Timers TRGO: TIM2, TIM6 and TIM21 + (DAC_Trigger_T2_TRGO, DAC_Trigger_T6_TRGO...) + + (#) Software using DAC_Trigger_Software + + *** DAC Buffer mode feature *** + =============================== + [..] + Each DAC channel integrates an output buffer that can be used to + reduce the output impedance, and to drive external loads directly + without having to add an external operational amplifier. + To enable, the output buffer use + sConfig.DAC_OutputBuffer = DAC_OutputBuffer_Enable; + [..] + (@) Refer to the device datasheet for more details about output + impedance value with and without output buffer. + + *** DAC wave generation feature *** + =================================== + [..] + Both DAC channels can be used to generate + (#) Noise wave using HAL_DAC_NoiseWaveGenerate() + (#) Triangle wave using HAL_DAC_TriangleWaveGenerate() + + *** DAC data format *** + ======================= + [..] + The DAC data format can be: + (#) 8-bit right alignment using DAC_ALIGN_8B_R + (#) 12-bit left alignment using DAC_ALIGN_12B_L + (#) 12-bit right alignment using DAC_ALIGN_12B_R + + *** DAC data value to voltage correspondence *** + ================================================ + [..] + The analog output voltage on each DAC channel pin is determined + by the following equation: + DAC_OUTx = VREF+ * DOR / 4095 + with DOR is the Data Output Register + VEF+ is the input voltage reference (refer to the device datasheet) + e.g. To set DAC_OUT1 to 0.7V, use + Assuming that VREF+ = 3.3V, DAC_OUT1 = (3.3 * 868) / 4095 = 0.7V + + *** DMA requests *** + ===================== + [..] + A DMA1 request can be generated when an external trigger (but not + a software trigger) occurs if DMA1 requests are enabled using + HAL_DAC_Start_DMA() + [..] + DMA1 requests are mapped as following: + (#) DAC channel1 : mapped on DMA1 Request9 channel2 which must be + already configured + + + ##### How to use this driver ##### + ============================================================================== + [..] + (+) DAC APB clock must be enabled to get write access to DAC + registers using HAL_DAC_Init() + (+) Configure DAC_OUTx (DAC_OUT1: PA4) in analog mode. + (+) Configure the DAC channel using HAL_DAC_ConfigChannel() function. + (+) Enable the DAC channel using HAL_DAC_Start() or HAL_DAC_Start_DMA functions + + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @defgroup DAC + * @brief DAC driver modules + * @{ + */ + +#ifdef HAL_DAC_MODULE_ENABLED +#if !defined (STM32L051xx) && !defined (STM32L061xx) + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +static void DAC_DMAConvCpltCh1(DMA_HandleTypeDef *hdma); +static void DAC_DMAErrorCh1(DMA_HandleTypeDef *hdma); +static void DAC_DMAHalfConvCpltCh1(DMA_HandleTypeDef *hdma); + +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup DAC_Private_Functions + * @{ + */ + +/** @defgroup DAC_Group1 Initialization and de-initialization functions + * @brief Initialization and Configuration functions + * +@verbatim + ============================================================================== + ##### Initialization and de-initialization functions ##### + ============================================================================== + [..] This section provides functions allowing to: + (+) Initialize and configure the DAC. + (+) De-initialize the DAC. + +@endverbatim + * @{ + */ + +/** + * @brief Initializes the DAC peripheral according to the specified parameters + * in the DAC_InitStruct. + * @param hdac: pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_DAC_Init(DAC_HandleTypeDef* hdac) +{ + /* Check DAC handle */ + if(hdac == NULL) + { + return HAL_ERROR; + } + /* Check the parameters */ + assert_param(IS_DAC_ALL_INSTANCE(hdac->Instance)); + + if(hdac->State == HAL_DAC_STATE_RESET) + { + /* Init the low level hardware */ + HAL_DAC_MspInit(hdac); + } + + /* Initialize the DAC state*/ + hdac->State = HAL_DAC_STATE_BUSY; + + /* Set DAC error code to none */ + hdac->ErrorCode = HAL_DAC_ERROR_NONE; + + /* Initialize the DAC state*/ + hdac->State = HAL_DAC_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Deinitializes the DAC peripheral registers to their default reset values. + * @param hdac: pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_DAC_DeInit(DAC_HandleTypeDef* hdac) +{ + /* Check DAC handle */ + if(hdac == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_DAC_ALL_INSTANCE(hdac->Instance)); + + /* Change DAC state */ + hdac->State = HAL_DAC_STATE_BUSY; + + /* DeInit the low level hardware */ + HAL_DAC_MspDeInit(hdac); + + /* Set DAC error code to none */ + hdac->ErrorCode = HAL_DAC_ERROR_NONE; + + /* Change DAC state */ + hdac->State = HAL_DAC_STATE_RESET; + + /* Release Lock */ + __HAL_UNLOCK(hdac); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Initializes the DAC MSP. + * @param hdac: pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @retval None + */ +__weak void HAL_DAC_MspInit(DAC_HandleTypeDef* hdac) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_DAC_MspInit could be implemented in the user file + */ +} + +/** + * @brief DeInitializes the DAC MSP. + * @param hdac: pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @retval None + */ +__weak void HAL_DAC_MspDeInit(DAC_HandleTypeDef* hdac) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_DAC_MspDeInit could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup DAC_Group2 I/O operation functions + * @brief I/O operation functions + * +@verbatim + ============================================================================== + ##### IO operation functions ##### + ============================================================================== + [..] This section provides functions allowing to: + (+) Start conversion. + (+) Stop conversion. + (+) Start conversion and enable DMA transfer. + (+) Stop conversion and disable DMA transfer. + (+) Get result of conversion. + +@endverbatim + * @{ + */ + +/** + * @brief Enables DAC and starts conversion of channel. + * @param hdac: pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @param channel: The selected DAC channel. + * This parameter can be one of the following values: + * @arg DAC_CHANNEL_1: DAC Channel1 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_DAC_Start(DAC_HandleTypeDef* hdac, uint32_t channel) +{ + /* Check the parameters */ + assert_param(IS_DAC_CHANNEL(channel)); + + /* Process locked */ + __HAL_LOCK(hdac); + + /* Change DAC state */ + hdac->State = HAL_DAC_STATE_BUSY; + + /* Enable the Peripharal */ + __HAL_DAC_ENABLE(hdac, channel); + + /* Check if software trigger enabled */ + if(((hdac->Instance->CR & DAC_CR_TEN1) == DAC_CR_TEN1) && ((hdac->Instance->CR & DAC_CR_TSEL1) == DAC_CR_TSEL1)) + { + /* Enable the selected DAC software conversion */ + hdac->Instance->SWTRIGR |= (uint32_t)DAC_SWTRIGR_SWTRIG1; + } + + /* Change DAC state */ + hdac->State = HAL_DAC_STATE_READY; + + /* Process unlocked */ + __HAL_UNLOCK(hdac); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Disables DAC and stop conversion of channel. + * @param hdac: pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @param channel: The selected DAC channel. + * This parameter can be one of the following values: + * @arg DAC_CHANNEL_1: DAC Channel1 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_DAC_Stop(DAC_HandleTypeDef* hdac, uint32_t channel) +{ + /* Check the parameters */ + assert_param(IS_DAC_CHANNEL(channel)); + + /* Disable the Peripheral */ + __HAL_DAC_DISABLE(hdac, channel); + + /* Change DAC state */ + hdac->State = HAL_DAC_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Enables DAC and starts conversion of channel using DMA. + * @param hdac: pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @param channel: The selected DAC channel. + * This parameter can be one of the following values: + * @arg DAC_CHANNEL_1: DAC Channel1 selected + * @param pData: The destination peripheral Buffer address. + * @param Length: The length of data to be transferred from memory to DAC peripheral + * @param alignment: Specifies the data alignment for DAC channel. + * This parameter can be one of the following values: + * @arg DAC_Align_8b_R: 8bit right data alignment selected + * @arg DAC_Align_12b_L: 12bit left data alignment selected + * @arg DAC_Align_12b_R: 12bit right data alignment selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_DAC_Start_DMA(DAC_HandleTypeDef* hdac, uint32_t channel, uint32_t* pData, uint32_t Length, uint32_t alignment) +{ + uint32_t tmpreg = 0; + + /* Check the parameters */ + assert_param(IS_DAC_CHANNEL(channel)); + assert_param(IS_DAC_ALIGN(alignment)); + + /* Process locked */ + __HAL_LOCK(hdac); + + /* Change DAC state */ + hdac->State = HAL_DAC_STATE_BUSY; + + /* Set the DMA transfer complete callback for channel1 */ + hdac->DMA_Handle1->XferCpltCallback = DAC_DMAConvCpltCh1; + + /* Set the DMA half transfer complete callback for channel1 */ + hdac->DMA_Handle1->XferHalfCpltCallback = DAC_DMAHalfConvCpltCh1; + + /* Set the DMA error callback for channel1 */ + hdac->DMA_Handle1->XferErrorCallback = DAC_DMAErrorCh1; + + /* Enable the selected DAC channel1 DMA request */ + hdac->Instance->CR |= DAC_CR_DMAEN1; + + /* Case of use of channel 1 */ + switch(alignment) + { + case DAC_ALIGN_12B_R: + /* Get DHR12R1 address */ + tmpreg = (uint32_t)&hdac->Instance->DHR12R1; + break; + case DAC_ALIGN_12B_L: + /* Get DHR12L1 address */ + tmpreg = (uint32_t)&hdac->Instance->DHR12L1; + break; + case DAC_ALIGN_8B_R: + /* Get DHR8R1 address */ + tmpreg = (uint32_t)&hdac->Instance->DHR8R1; + break; + default: + break; + } + + /* Enable the DMA Channel */ + /* Enable the DAC DMA underrun interrupt */ + __HAL_DAC_ENABLE_IT(hdac, DAC_IT_DMAUDR1); + + HAL_DMA_Start_IT(hdac->DMA_Handle1, (uint32_t)pData, tmpreg, Length); + + /* Enable the Peripharal */ + __HAL_DAC_ENABLE(hdac, channel); + + /* Process Unlocked */ + __HAL_UNLOCK(hdac); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Disables DAC and stop conversion of channel using DMA. + * @param hdac: pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @param channel: The selected DAC channel. + * This parameter can be one of the following values: + * @arg DAC_CHANNEL_1: DAC Channel1 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_DAC_Stop_DMA(DAC_HandleTypeDef* hdac, uint32_t channel) +{ + /* Check the parameters */ + assert_param(IS_DAC_CHANNEL(channel)); + + /* Disable the selected DAC channel DMA request */ + hdac->Instance->CR &= ~(DAC_CR_DMAEN1 << channel); + + /* Disable the Peripharal */ + __HAL_DAC_DISABLE(hdac, channel); + + /* Change DAC state */ + hdac->State = HAL_DAC_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Returns the last data output value of the selected DAC channel. + * @param hdac: pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @param channel: The selected DAC channel. + * This parameter can be one of the following values: + * @arg DAC_CHANNEL_1: DAC Channel1 selected + * @retval The selected DAC channel data output value. + */ +uint32_t HAL_DAC_GetValue(DAC_HandleTypeDef* hdac, uint32_t channel) +{ + /* Check the parameters */ + assert_param(IS_DAC_CHANNEL(channel)); + + /* Returns the DAC channel data output register value */ + return hdac->Instance->DOR1; +} + +/** + * @} + */ + +/** @defgroup DAC_Group3 Peripheral Control functions + * @brief Peripheral Control functions + * +@verbatim + ============================================================================== + ##### Peripheral Control functions ##### + ============================================================================== + [..] This section provides functions allowing to: + (+) Configure channels. + (+) Set the specified data holding register value for DAC channel. + (+) Set the specified data holding register value for Dual DAC channels. + +@endverbatim + * @{ + */ + +/** + * @brief Configures the selected DAC channel. + * @param hdac: pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @param sConfig: DAC configuration structure. + * @param channel: The selected DAC channel. + * This parameter can be one of the following values: + * @arg DAC_CHANNEL_1: DAC Channel1 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_DAC_ConfigChannel(DAC_HandleTypeDef* hdac, DAC_ChannelConfTypeDef* sConfig, uint32_t channel) +{ + uint32_t tmpreg1 = 0, tmpreg2 = 0; + + /* Check the DAC parameters */ + assert_param(IS_DAC_TRIGGER(sConfig->DAC_Trigger)); + assert_param(IS_DAC_OUTPUT_BUFFER_STATE(sConfig->DAC_OutputBuffer)); + assert_param(IS_DAC_TRIGGER(sConfig->DAC_Trigger)); + + /* Process locked */ + __HAL_LOCK(hdac); + + /* Change DAC state */ + hdac->State = HAL_DAC_STATE_BUSY; + + /* Get the DAC CR value */ + tmpreg1 = DAC->CR; + /* Clear BOFFx, TENx, TSELx, WAVEx and MAMPx bits */ + tmpreg1 &= ~(((uint32_t)(DAC_CR_MAMP1 | DAC_CR_WAVE1 | DAC_CR_TSEL1 | DAC_CR_TEN1 | DAC_CR_BOFF1)) << channel); + /* Configure for the selected DAC channel: buffer output, trigger */ + /* Set TSELx and TENx bits according to DAC_Trigger value */ + /* Set BOFFx bit according to DAC_OutputBuffer value */ + tmpreg2 = (sConfig->DAC_Trigger | sConfig->DAC_OutputBuffer); + /* Calculate CR register value depending on DAC_Channel */ + tmpreg1 |= tmpreg2 << channel; + /* Write to DAC CR */ + DAC->CR = tmpreg1; + /* Disable wave generation */ + DAC->CR &= ~(DAC_CR_WAVE1 << channel); + + /* Change DAC state */ + hdac->State = HAL_DAC_STATE_READY; + + /* Process unlocked */ + __HAL_UNLOCK(hdac); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Set the specified data holding register value for DAC channel. + * @param hdac: pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @param alignment: Specifies the data alignment for DAC channel1. + * This parameter can be one of the following values: + * @arg DAC_Align_8b_R: 8bit right data alignment selected + * @arg DAC_Align_12b_L: 12bit left data alignment selected + * @arg DAC_Align_12b_R: 12bit right data alignment selected + * @param data: Data to be loaded in the selected data holding register. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_DAC_SetValue(DAC_HandleTypeDef* hdac, uint32_t channel, uint32_t alignment, uint32_t data) +{ + __IO uint32_t tmp = 0; + + /* Check the parameters */ + assert_param(IS_DAC_CHANNEL(channel)); + assert_param(IS_DAC_ALIGN(alignment)); + assert_param(IS_DAC_DATA(data)); + + tmp = (uint32_t)DAC_BASE; + + tmp += __HAL_DHR12R1_ALIGNEMENT(alignment); + + /* Set the DAC channel1 selected data holding register */ + *(__IO uint32_t *) tmp = data; + + /* Return function status */ + return HAL_OK; +} + +/** + * @} + */ + +/** @defgroup DAC_Group4 DAC Peripheral State functions + * @brief DAC Peripheral State functions + * +@verbatim + ============================================================================== + ##### DAC Peripheral State functions ##### + ============================================================================== + [..] + This subsection provides functions allowing to + (+) Check the DAC state. + +@endverbatim + * @{ + */ + +/** + * @brief return the DAC state + * @param hdac: pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @retval HAL state + */ +HAL_DAC_StateTypeDef HAL_DAC_GetState(DAC_HandleTypeDef* hdac) +{ + /* Return DAC state */ + return hdac->State; +} + +/** + * @brief Handles DAC interrupt request + * @param hdac: pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @retval None + */ +void HAL_DAC_IRQHandler(DAC_HandleTypeDef* hdac) +{ + /* Check Overrun flag */ + if(__HAL_DAC_GET_FLAG(hdac, DAC_FLAG_DMAUDR1)) + { + /* Change DAC state to error state */ + hdac->State = HAL_DAC_STATE_ERROR; + + /* Set DAC error code to chanel1 DMA underrun error */ + hdac->ErrorCode |= HAL_DAC_ERROR_DMAUNDERRUNCH1; + + /* Clear the underrun flag */ + __HAL_DAC_CLEAR_FLAG(hdac,DAC_FLAG_DMAUDR1); + + /* Disable the selected DAC channel1 DMA request */ + hdac->Instance->CR &= ~DAC_CR_DMAEN1; + + /* Error callback */ + HAL_DAC_DMAUnderrunCallbackCh1(hdac); + } +} + +/** + * @brief Return the DAC error code + * @param hdac: pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @retval DAC Error Code + */ +uint32_t HAL_DAC_GetError(DAC_HandleTypeDef *hdac) +{ + return hdac->ErrorCode; +} + +/** + * @} + */ + +/** + * @brief Conversion complete callback in non blocking mode for Channel1 + * @param hdac: pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @retval None + */ +__weak void HAL_DAC_ConvCpltCallbackCh1(DAC_HandleTypeDef* hdac) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_DAC_ConvCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Conversion half DMA transfer callback in non blocking mode for Channel1 + * @param hdac: pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @retval None + */ +__weak void HAL_DAC_ConvHalfCpltCallbackCh1(DAC_HandleTypeDef* hdac) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_DAC_ConvHalfCpltCallbackCh1 could be implemented in the user file + */ +} + +/** + * @brief Error DAC callback for Channel1. + * @param hdac: pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @retval None + */ +__weak void HAL_DAC_ErrorCallbackCh1(DAC_HandleTypeDef *hdac) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_DAC_ErrorCallback could be implemented in the user file + */ +} + + +/** + * @brief DMA underrun DAC callback for channel1. + * @param hdac: pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @retval None + */ +__weak void HAL_DAC_DMAUnderrunCallbackCh1(DAC_HandleTypeDef *hdac) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_DAC_DMAUnderrunCallbackCh1 could be implemented in the user file + */ +} + +/** + * @brief DMA conversion complete callback. + * @param hdma: pointer to DMA handle. + * @retval None + */ +static void DAC_DMAConvCpltCh1(DMA_HandleTypeDef *hdma) +{ + DAC_HandleTypeDef* hdac = ( DAC_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + + HAL_DAC_ConvCpltCallbackCh1(hdac); + + hdac->State= HAL_DAC_STATE_READY; +} + +/** + * @brief DMA half transfer complete callback. + * @param hdma: pointer to DMA handle. + * @retval None + */ +static void DAC_DMAHalfConvCpltCh1(DMA_HandleTypeDef *hdma) +{ + DAC_HandleTypeDef* hdac = ( DAC_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + + /* Conversion complete callback */ + HAL_DAC_ConvHalfCpltCallbackCh1(hdac); +} + +/** + * @brief DMA error callback + * @param hdma: pointer to DMA handle. + * @retval None + */ +static void DAC_DMAErrorCh1(DMA_HandleTypeDef *hdma) +{ + DAC_HandleTypeDef* hdac = ( DAC_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + + /* Set DAC error code to DMA error */ + hdac->ErrorCode |= HAL_DAC_ERROR_DMA; + + HAL_DAC_ErrorCallbackCh1(hdac); + + hdac->State= HAL_DAC_STATE_READY; +} + +/** + * @} + */ +#endif /* STM32L051xx && STM32L061xx*/ +#endif /* HAL_DAC_MODULE_ENABLED */ + +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_dac.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_dac.h new file mode 100644 index 0000000000..98e160146d --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_dac.h @@ -0,0 +1,283 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_dac.h + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief Header file of DAC HAL module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32L0xx_HAL_DAC_H +#define __STM32L0xx_HAL_DAC_H + +#ifdef __cplusplus + extern "C" { +#endif + +#if !defined (STM32L051xx) && !defined (STM32L061xx) + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal_def.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @addtogroup DAC + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ + +/** + * @brief HAL State structures definition + */ +typedef enum +{ + HAL_DAC_STATE_RESET = 0x00, /*!< DAC not yet initialized or disabled */ + HAL_DAC_STATE_READY = 0x01, /*!< DAC initialized and ready for use */ + HAL_DAC_STATE_BUSY = 0x02, /*!< DAC internal processing is ongoing */ + HAL_DAC_STATE_TIMEOUT = 0x03, /*!< DAC timeout state */ + HAL_DAC_STATE_ERROR = 0x04 /*!< DAC error state */ + +}HAL_DAC_StateTypeDef; + +/** + * @brief DAC handle Structure definition + */ +typedef struct +{ + DAC_TypeDef *Instance; /*!< Register base address */ + + __IO HAL_DAC_StateTypeDef State; /*!< DAC communication state */ + + HAL_LockTypeDef Lock; /*!< DAC locking object */ + + DMA_HandleTypeDef *DMA_Handle1; /*!< Pointer DMA handler for channel 1 */ + + __IO uint32_t ErrorCode; /*!< DAC Error code */ + +}DAC_HandleTypeDef; + +/** + * @brief DAC Configuration regular Channel structure definition + */ +typedef struct +{ + uint32_t DAC_Trigger; /*!< Specifies the external trigger for the selected DAC channel. + This parameter can be a value of @ref DAC_trigger_selection */ + + uint32_t DAC_OutputBuffer; /*!< Specifies whether the DAC channel output buffer is enabled or disabled. + This parameter can be a value of @ref DAC_output_buffer */ + +}DAC_ChannelConfTypeDef; + +/* Exported constants --------------------------------------------------------*/ + +/** @defgroup HAL DAC Error Code + * @{ + */ +#define HAL_DAC_ERROR_NONE 0x00 /*!< No error */ +#define HAL_DAC_ERROR_DMAUNDERRUNCH1 0x01 /*!< DAC channel1 DMA underrun error */ +#define HAL_DAC_ERROR_DMA 0x04 /*!< DMA error */ +/** + * @} + */ + +/** @defgroup DAC_trigger_selection + * @{ + */ +#define DAC_TRIGGER_NONE ((uint32_t)0x00000000) /*!< Conversion is automatic once the DAC1_DHRxxxx register + has been loaded, and not by external trigger */ +#define DAC_TRIGGER_T6_TRGO ((uint32_t)DAC_CR_TEN1) /*!< TIM6 TRGO selected as external conversion trigger for DAC channel */ +#define DAC_TRIGGER_T21_TRGO ((uint32_t)(DAC_CR_TSEL1_1 | DAC_CR_TSEL1_0 | DAC_CR_TEN1)) /*!< TIM21 TRGO selected as external conversion trigger for DAC channel */ +#define DAC_TRIGGER_T2_TRGO ((uint32_t)(DAC_CR_TSEL1_2 | DAC_CR_TEN1)) /*!< TIM2 TRGO selected as external conversion trigger for DAC channel */ +#define DAC_TRIGGER_EXT_IT9 ((uint32_t)(DAC_CR_TSEL1_2 | DAC_CR_TSEL1_1 | DAC_CR_TEN1)) /*!< EXTI Line9 event selected as external conversion trigger for DAC channel */ +#define DAC_TRIGGER_SOFTWARE ((uint32_t)(DAC_CR_TSEL1 | DAC_CR_TEN1)) /*!< Conversion started by software trigger for DAC channel */ + +#define IS_DAC_TRIGGER(TRIGGER) (((TRIGGER) == DAC_TRIGGER_NONE) || \ + ((TRIGGER) == DAC_TRIGGER_T6_TRGO) || \ + ((TRIGGER) == DAC_TRIGGER_T21_TRGO) || \ + ((TRIGGER) == DAC_TRIGGER_T2_TRGO) || \ + ((TRIGGER) == DAC_TRIGGER_EXT_IT9) || \ + ((TRIGGER) == DAC_TRIGGER_SOFTWARE)) +/** + * @} + */ + +/** @defgroup DAC_output_buffer + * @{ + */ +#define DAC_OUTPUTBUFFER_ENABLE ((uint32_t)0x00000000) +#define DAC_OUTPUTBUFFER_DISABLE ((uint32_t)DAC_CR_BOFF1) + +#define IS_DAC_OUTPUT_BUFFER_STATE(STATE) (((STATE) == DAC_OUTPUTBUFFER_ENABLE) || \ + ((STATE) == DAC_OUTPUTBUFFER_DISABLE)) +/** + * @} + */ + +/** @defgroup DAC_Channel_selection + * @{ + */ +#define DAC_CHANNEL_1 ((uint32_t)0x00000000) + +#define IS_DAC_CHANNEL(CHANNEL) ((CHANNEL) == DAC_CHANNEL_1) +/** + * @} + */ + +/** @defgroup DAC_data_alignement + * @{ + */ +#define DAC_ALIGN_12B_R ((uint32_t)0x00000000) +#define DAC_ALIGN_12B_L ((uint32_t)0x00000004) +#define DAC_ALIGN_8B_R ((uint32_t)0x00000008) + +#define IS_DAC_ALIGN(ALIGN) (((ALIGN) == DAC_ALIGN_12B_R) || \ + ((ALIGN) == DAC_ALIGN_12B_L) || \ + ((ALIGN) == DAC_ALIGN_8B_R)) +/** + * @} + */ + + +/** @defgroup DAC_data + * @{ + */ +#define IS_DAC_DATA(DATA) ((DATA) <= 0xFFF0) +/** + * @} + */ + +/** @defgroup DAC_flags_definition + * @{ + */ +#define DAC_FLAG_DMAUDR1 ((uint32_t)DAC_SR_DMAUDR1) + +#define IS_DAC_FLAG(FLAG) ((FLAG) == DAC_FLAG_DMAUDR1) +/** + * @} + */ + +/** @defgroup DAC_flags_definition + * @{ + */ +#define DAC_IT_DMAUDR1 ((uint32_t)DAC_CR_DMAUDRIE1) + +#define IS_DAC_IT(IT) ((IT) == DAC_IT_DMAUDR1) + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ + +/** @brief Reset DAC handle state + * @param __HANDLE__: specifies the DAC Handle. + * @retval None + */ +#define __HAL_DAC_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_DAC_STATE_RESET) + +/* Enable the DAC peripheral */ +#define __HAL_DAC_ENABLE(__HANDLE__, __DAC_Channel__) \ +((__HANDLE__)->Instance->CR |= (DAC_CR_EN1 << (__DAC_Channel__))) + +/* Disable the DAC peripheral */ +#define __HAL_DAC_DISABLE(__HANDLE__, __DAC_Channel__) \ +((__HANDLE__)->Instance->CR &= ~(DAC_CR_EN1 << (__DAC_Channel__))) + + +/* Set DHR12R1 alignment */ +#define __HAL_DHR12R1_ALIGNEMENT(__ALIGNEMENT__) (((uint32_t)0x00000008) + (__ALIGNEMENT__)) + +/* Enable the DAC interrupt */ +#define __HAL_DAC_ENABLE_IT(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->CR) |= (__INTERRUPT__)) + +/* Disable the DAC interrupt */ +#define __HAL_DAC_DISABLE_IT(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->CR) &= ~(__INTERRUPT__)) + +/* Get the selected DAC's flag status */ +#define __HAL_DAC_GET_FLAG(__HANDLE__, __FLAG__) ((((__HANDLE__)->Instance->SR) & (__FLAG__)) == (__FLAG__)) + +/* Clear the DAC's flag */ +#define __HAL_DAC_CLEAR_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->SR) |= (__FLAG__)) + +/* Include DAC HAL Extension module */ +#include "stm32l0xx_hal_dac_ex.h" + +/* Exported functions --------------------------------------------------------*/ +/* Initialization and de-initialization functions *****************************/ +HAL_StatusTypeDef HAL_DAC_Init(DAC_HandleTypeDef* hdac); +HAL_StatusTypeDef HAL_DAC_DeInit(DAC_HandleTypeDef* hdac); +void HAL_DAC_MspInit(DAC_HandleTypeDef* hdac); +void HAL_DAC_MspDeInit(DAC_HandleTypeDef* hdac); + +/* I/O operation functions ******************************************************/ +HAL_StatusTypeDef HAL_DAC_Start(DAC_HandleTypeDef* hdac, uint32_t channel); +HAL_StatusTypeDef HAL_DAC_Stop(DAC_HandleTypeDef* hdac, uint32_t channel); +HAL_StatusTypeDef HAL_DAC_Start_DMA(DAC_HandleTypeDef* hdac, uint32_t channel, uint32_t* pData, uint32_t Length, uint32_t alignment); +HAL_StatusTypeDef HAL_DAC_Stop_DMA(DAC_HandleTypeDef* hdac, uint32_t channel); +uint32_t HAL_DAC_GetValue(DAC_HandleTypeDef* hdac, uint32_t channel); + +/* Peripheral Control functions ***********************************************/ +HAL_StatusTypeDef HAL_DAC_ConfigChannel(DAC_HandleTypeDef* hdac, DAC_ChannelConfTypeDef* sConfig, uint32_t channel); +HAL_StatusTypeDef HAL_DAC_SetValue(DAC_HandleTypeDef* hdac, uint32_t channel, uint32_t alignment, uint32_t data); + +/* Peripheral State and Error functions ***************************************/ +HAL_DAC_StateTypeDef HAL_DAC_GetState(DAC_HandleTypeDef* hdac); +void HAL_DAC_IRQHandler(DAC_HandleTypeDef* hdac); +uint32_t HAL_DAC_GetError(DAC_HandleTypeDef *hdac); + +void HAL_DAC_ConvCpltCallbackCh1(DAC_HandleTypeDef* hdac); +void HAL_DAC_ConvHalfCpltCallbackCh1(DAC_HandleTypeDef* hdac); +void HAL_DAC_ErrorCallbackCh1(DAC_HandleTypeDef *hdac); +void HAL_DAC_DMAUnderrunCallbackCh1(DAC_HandleTypeDef *hdac); + +#endif /* STM32L051xx && STM32L061xx*/ + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + + +#endif /*__STM32L0xx_HAL_DAC_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_dac_ex.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_dac_ex.c new file mode 100644 index 0000000000..8e1efdbaf5 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_dac_ex.c @@ -0,0 +1,202 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_dac_ex.c + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief DAC HAL module driver. + * + * This file provides firmware functions to manage the following + * functionalities of the Digital to Analog Converter (DAC) peripheral: + * + DAC wave generation + * + @verbatim + + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @defgroup DACEx + * @brief DAC driver modules + * @{ + */ + +#ifdef HAL_DAC_MODULE_ENABLED +#if !defined (STM32L051xx) && !defined (STM32L061xx) + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup DACEx_Private_Functions + * @{ + */ + + +/** @defgroup DACEx_Group Peripheral Control functions + * @brief Peripheral Control functions + * +@verbatim + ============================================================================== + ##### Peripheral Control functions ##### + ============================================================================== + [..] This section provides functions allowing to: + (+) Configure Triangle wave generation. + (+) Configure Noise wave generation. + +@endverbatim + * @{ + */ + +/** + * @brief Enables or disables the selected DAC channel wave triangle generation. + * @param hdac: pointer to a DAC_HandleTypeDef structure that contains + * the configuration information for the specified DAC. + * @param channel: The selected DAC channel. + * This parameter can be one of the following values: + * @arg DAC_CHANNEL_1: DAC Channel1 selected + * @param Amplitude: Select max triangle amplitude. + * This parameter can be one of the following values: + * @arg DAC_TRIANGLEAMPLITUDE_1: Select max triangle amplitude of 1 + * @arg DAC_TRIANGLEAMPLITUDE_3: Select max triangle amplitude of 3 + * @arg DAC_TRIANGLEAMPLITUDE_7: Select max triangle amplitude of 7 + * @arg DAC_TRIANGLEAMPLITUDE_15: Select max triangle amplitude of 15 + * @arg DAC_TRIANGLEAMPLITUDE_31: Select max triangle amplitude of 31 + * @arg DAC_TRIANGLEAMPLITUDE_63: Select max triangle amplitude of 63 + * @arg DAC_TRIANGLEAMPLITUDE_127: Select max triangle amplitude of 127 + * @arg DAC_TRIANGLEAMPLITUDE_255: Select max triangle amplitude of 255 + * @arg DAC_TRIANGLEAMPLITUDE_511: Select max triangle amplitude of 511 + * @arg DAC_TRIANGLEAMPLITUDE_1023: Select max triangle amplitude of 1023 + * @arg DAC_TRIANGLEAMPLITUDE_2047: Select max triangle amplitude of 2047 + * @arg DAC_TRIANGLEAMPLITUDE_4095: Select max triangle amplitude of 4095 + * @retval HAL status + */ +HAL_StatusTypeDef HAL_DACEx_TriangleWaveGenerate(DAC_HandleTypeDef* hdac, uint32_t channel, uint32_t Amplitude) +{ + /* Check the parameters */ + assert_param(IS_DAC_CHANNEL(channel)); + assert_param(IS_DAC_LFSR_UNMASK_TRIANGLE_AMPLITUDE(Amplitude)); + + /* Process locked */ + __HAL_LOCK(hdac); + + /* Change DAC state */ + hdac->State = HAL_DAC_STATE_BUSY; + + /* Enable the selected wave generation for the selected DAC channel */ + hdac->Instance->CR |= (DAC_WAVEGENERATION_TRIANGLE | Amplitude) << channel; + + /* Change DAC state */ + hdac->State = HAL_DAC_STATE_READY; + + /* Process unlocked */ + __HAL_UNLOCK(hdac); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Enables or disables the selected DAC channel wave noise generation. + * @param channel: The selected DAC channel. + * This parameter can be one of the following values: + * @arg DAC_CHANNEL_1: DAC Channel1 selected + * @param Amplitude: Unmask DAC channel LFSR for noise wave generation. + * This parameter can be one of the following values: + * @arg DAC_LFSRUNMASK_BIT0: Unmask DAC channel LFSR bit0 for noise wave generation + * @arg DAC_LFSRUNMASK_BITS1_0: Unmask DAC channel LFSR bit[1:0] for noise wave generation + * @arg DAC_LFSRUNMASK_BITS2_0: Unmask DAC channel LFSR bit[2:0] for noise wave generation + * @arg DAC_LFSRUNMASK_BITS3_0: Unmask DAC channel LFSR bit[3:0] for noise wave generation + * @arg DAC_LFSRUNMASK_BITS4_0: Unmask DAC channel LFSR bit[4:0] for noise wave generation + * @arg DAC_LFSRUNMASK_BITS5_0: Unmask DAC channel LFSR bit[5:0] for noise wave generation + * @arg DAC_LFSRUNMASK_BITS6_0: Unmask DAC channel LFSR bit[6:0] for noise wave generation + * @arg DAC_LFSRUNMASK_BITS7_0: Unmask DAC channel LFSR bit[7:0] for noise wave generation + * @arg DAC_LFSRUNMASK_BITS8_0: Unmask DAC channel LFSR bit[8:0] for noise wave generation + * @arg DAC_LFSRUNMASK_BITS9_0: Unmask DAC channel LFSR bit[9:0] for noise wave generation + * @arg DAC_LFSRUNMASK_BITS10_0: Unmask DAC channel LFSR bit[10:0] for noise wave generation + * @arg DAC_LFSRUNMASK_BITS11_0: Unmask DAC channel LFSR bit[11:0] for noise wave generation + * @retval HAL status + */ +HAL_StatusTypeDef HAL_DACEx_NoiseWaveGenerate(DAC_HandleTypeDef* hdac, uint32_t channel, uint32_t Amplitude) +{ + /* Check the parameters */ + assert_param(IS_DAC_CHANNEL(channel)); + assert_param(IS_DAC_LFSR_UNMASK_TRIANGLE_AMPLITUDE(Amplitude)); + + /* Process locked */ + __HAL_LOCK(hdac); + + /* Change DAC state */ + hdac->State = HAL_DAC_STATE_BUSY; + + /* Enable the selected wave generation for the selected DAC channel */ + hdac->Instance->CR |= (DAC_WAVEGENERATION_NOISE | Amplitude) << channel; + + /* Change DAC state */ + hdac->State = HAL_DAC_STATE_READY; + + /* Process unlocked */ + __HAL_UNLOCK(hdac); + + /* Return function status */ + return HAL_OK; +} + + +/** + * @} + */ + +/** + * @} + */ + +#endif /* STM32L051xx && STM32L061xx*/ +#endif /* HAL_DAC_MODULE_ENABLED */ + +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_dac_ex.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_dac_ex.h new file mode 100644 index 0000000000..b32b6b30b7 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_dac_ex.h @@ -0,0 +1,160 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_dac_ex.h + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief Header file of DAC HAL module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32L0xx_HAL_DAC_EX_H +#define __STM32L0xx_HAL_DAC_EX_H + +#ifdef __cplusplus + extern "C" { +#endif + +#if !defined (STM32L051xx) && !defined (STM32L061xx) + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal_def.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @addtogroup DACEx + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ + +/** + * @brief HAL State structures definition + */ + +/* Exported constants --------------------------------------------------------*/ + +/** @defgroup DACEx_wave_generation + * @{ + */ +#define DAC_WAVEGENERATION_NONE ((uint32_t)0x00000000) +#define DAC_WAVEGENERATION_NOISE ((uint32_t)DAC_CR_WAVE1_0) +#define DAC_WAVEGENERATION_TRIANGLE ((uint32_t)DAC_CR_WAVE1_1) + +#define IS_DAC_GENERATE_WAVE(WAVE) (((WAVE) == DAC_WAVEGENERATION_NONE) || \ + ((WAVE) == DAC_WAVEGENERATION_NOISE) || \ + ((WAVE) == DAC_WAVEGENERATION_TRIANGLE)) +/** + * @} + */ + +/** @defgroup DACEx_lfsrunmask_triangleamplitude + * @{ + */ +#define DAC_LFSRUNMASK_BIT0 ((uint32_t)0x00000000) /*!< Unmask DAC channel LFSR bit0 for noise wave generation */ +#define DAC_LFSRUNMASK_BITS1_0 ((uint32_t)DAC_CR_MAMP1_0) /*!< Unmask DAC channel LFSR bit[1:0] for noise wave generation */ +#define DAC_LFSRUNMASK_BITS2_0 ((uint32_t)DAC_CR_MAMP1_1) /*!< Unmask DAC channel LFSR bit[2:0] for noise wave generation */ +#define DAC_LFSRUNMASK_BITS3_0 ((uint32_t)DAC_CR_MAMP1_1 | DAC_CR_MAMP1_0)/*!< Unmask DAC channel LFSR bit[3:0] for noise wave generation */ +#define DAC_LFSRUNMASK_BITS4_0 ((uint32_t)DAC_CR_MAMP1_2) /*!< Unmask DAC channel LFSR bit[4:0] for noise wave generation */ +#define DAC_LFSRUNMASK_BITS5_0 ((uint32_t)DAC_CR_MAMP1_2 | DAC_CR_MAMP1_0) /*!< Unmask DAC channel LFSR bit[5:0] for noise wave generation */ +#define DAC_LFSRUNMASK_BITS6_0 ((uint32_t)DAC_CR_MAMP1_2 | DAC_CR_MAMP1_1) /*!< Unmask DAC channel LFSR bit[6:0] for noise wave generation */ +#define DAC_LFSRUNMASK_BITS7_0 ((uint32_t)DAC_CR_MAMP1_2 | DAC_CR_MAMP1_1 | DAC_CR_MAMP1_0) /*!< Unmask DAC channel LFSR bit[7:0] for noise wave generation */ +#define DAC_LFSRUNMASK_BITS8_0 ((uint32_t)DAC_CR_MAMP1_3) /*!< Unmask DAC channel LFSR bit[8:0] for noise wave generation */ +#define DAC_LFSRUNMASK_BITS9_0 ((uint32_t)DAC_CR_MAMP1_3 | DAC_CR_MAMP1_0) /*!< Unmask DAC channel LFSR bit[9:0] for noise wave generation */ +#define DAC_LFSRUNMASK_BITS10_0 ((uint32_t)DAC_CR_MAMP1_3 | DAC_CR_MAMP1_1) /*!< Unmask DAC channel LFSR bit[10:0] for noise wave generation */ +#define DAC_LFSRUNMASK_BITS11_0 ((uint32_t)DAC_CR_MAMP1_3 | DAC_CR_MAMP1_1 | DAC_CR_MAMP1_0) /*!< Unmask DAC channel LFSR bit[11:0] for noise wave generation */ +#define DAC_TRIANGLEAMPLITUDE_1 ((uint32_t)0x00000000) /*!< Select max triangle amplitude of 1 */ +#define DAC_TRIANGLEAMPLITUDE_3 ((uint32_t)DAC_CR_MAMP1_0) /*!< Select max triangle amplitude of 3 */ +#define DAC_TRIANGLEAMPLITUDE_7 ((uint32_t)DAC_CR_MAMP1_1) /*!< Select max triangle amplitude of 7 */ +#define DAC_TRIANGLEAMPLITUDE_15 ((uint32_t)DAC_CR_MAMP1_1 | DAC_CR_MAMP1_0) /*!< Select max triangle amplitude of 15 */ +#define DAC_TRIANGLEAMPLITUDE_31 ((uint32_t)DAC_CR_MAMP1_2) /*!< Select max triangle amplitude of 31 */ +#define DAC_TRIANGLEAMPLITUDE_63 ((uint32_t)DAC_CR_MAMP1_2 | DAC_CR_MAMP1_0) /*!< Select max triangle amplitude of 63 */ +#define DAC_TRIANGLEAMPLITUDE_127 ((uint32_t)DAC_CR_MAMP1_2 | DAC_CR_MAMP1_1) /*!< Select max triangle amplitude of 127 */ +#define DAC_TRIANGLEAMPLITUDE_255 ((uint32_t)DAC_CR_MAMP1_2 | DAC_CR_MAMP1_1 | DAC_CR_MAMP1_0) /*!< Select max triangle amplitude of 255 */ +#define DAC_TRIANGLEAMPLITUDE_511 ((uint32_t)DAC_CR_MAMP1_3) /*!< Select max triangle amplitude of 511 */ +#define DAC_TRIANGLEAMPLITUDE_1023 ((uint32_t)DAC_CR_MAMP1_3 | DAC_CR_MAMP1_0) /*!< Select max triangle amplitude of 1023 */ +#define DAC_TRIANGLEAMPLITUDE_2047 ((uint32_t)DAC_CR_MAMP1_3 | DAC_CR_MAMP1_1) /*!< Select max triangle amplitude of 2047 */ +#define DAC_TRIANGLEAMPLITUDE_4095 ((uint32_t)DAC_CR_MAMP1_3 | DAC_CR_MAMP1_1 | DAC_CR_MAMP1_0) /*!< Select max triangle amplitude of 4095 */ + +#define IS_DAC_LFSR_UNMASK_TRIANGLE_AMPLITUDE(VALUE) (((VALUE) == DAC_LFSRUNMASK_BIT0) || \ + ((VALUE) == DAC_LFSRUNMASK_BITS1_0) || \ + ((VALUE) == DAC_LFSRUNMASK_BITS2_0) || \ + ((VALUE) == DAC_LFSRUNMASK_BITS3_0) || \ + ((VALUE) == DAC_LFSRUNMASK_BITS4_0) || \ + ((VALUE) == DAC_LFSRUNMASK_BITS5_0) || \ + ((VALUE) == DAC_LFSRUNMASK_BITS6_0) || \ + ((VALUE) == DAC_LFSRUNMASK_BITS7_0) || \ + ((VALUE) == DAC_LFSRUNMASK_BITS8_0) || \ + ((VALUE) == DAC_LFSRUNMASK_BITS9_0) || \ + ((VALUE) == DAC_LFSRUNMASK_BITS10_0) || \ + ((VALUE) == DAC_LFSRUNMASK_BITS11_0) || \ + ((VALUE) == DAC_TRIANGLEAMPLITUDE_1) || \ + ((VALUE) == DAC_TRIANGLEAMPLITUDE_3) || \ + ((VALUE) == DAC_TRIANGLEAMPLITUDE_7) || \ + ((VALUE) == DAC_TRIANGLEAMPLITUDE_15) || \ + ((VALUE) == DAC_TRIANGLEAMPLITUDE_31) || \ + ((VALUE) == DAC_TRIANGLEAMPLITUDE_63) || \ + ((VALUE) == DAC_TRIANGLEAMPLITUDE_127) || \ + ((VALUE) == DAC_TRIANGLEAMPLITUDE_255) || \ + ((VALUE) == DAC_TRIANGLEAMPLITUDE_511) || \ + ((VALUE) == DAC_TRIANGLEAMPLITUDE_1023) || \ + ((VALUE) == DAC_TRIANGLEAMPLITUDE_2047) || \ + ((VALUE) == DAC_TRIANGLEAMPLITUDE_4095)) +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ +/* Exported functions --------------------------------------------------------*/ + +/* Peripheral Control methods *************************************************/ +HAL_StatusTypeDef HAL_DACEx_TriangleWaveGenerate(DAC_HandleTypeDef* hdac, uint32_t channel, uint32_t Amplitude); +HAL_StatusTypeDef HAL_DACEx_NoiseWaveGenerate(DAC_HandleTypeDef* hdac, uint32_t channel, uint32_t Amplitude); + +#endif /* STM32L051xx && STM32L061xx*/ +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + + +#endif /*__STM32L0xx_HAL_DAC_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_def.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_def.h new file mode 100644 index 0000000000..cd797a0767 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_def.h @@ -0,0 +1,180 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_def.h + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief This file contains HAL common defines, enumeration, macros and + * structures definitions. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32L0xx_HAL_DEF +#define __STM32L0xx_HAL_DEF + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx.h" + +/* Exported types ------------------------------------------------------------*/ + +/** + * @brief HAL Status structures definition + */ +typedef enum +{ + HAL_OK = 0x00, + HAL_ERROR = 0x01, + HAL_BUSY = 0x02, + HAL_TIMEOUT = 0x03 +} HAL_StatusTypeDef; + +/** + * @brief HAL Lock structures definition + */ +typedef enum +{ + HAL_UNLOCKED = 0x00, + HAL_LOCKED = 0x01 +} HAL_LockTypeDef; + +/* Exported macro ------------------------------------------------------------*/ +#ifndef NULL + #define NULL (void *) 0 +#endif + +#define HAL_MAX_DELAY 0xFFFFFFFF + +#define HAL_IS_BIT_SET(REG, BIT) (((REG) & (BIT)) != RESET) +#define HAL_IS_BIT_CLR(REG, BIT) (((REG) & (BIT)) == RESET) + +#define __HAL_LINKDMA(__HANDLE__, __PPP_DMA_FIELD__, __DMA_HANDLE__) \ + do{ \ + (__HANDLE__)->__PPP_DMA_FIELD__ = &(__DMA_HANDLE__); \ + (__DMA_HANDLE__).Parent = (__HANDLE__); \ + } while(0) + +#if (USE_RTOS == 1) + +#else + #define __HAL_LOCK(__HANDLE__) \ + do{ \ + if((__HANDLE__)->Lock == HAL_LOCKED) \ + { \ + return HAL_BUSY; \ + } \ + else \ + { \ + (__HANDLE__)->Lock = HAL_LOCKED; \ + } \ + }while (0) + + #define __HAL_UNLOCK(__HANDLE__) \ + do{ \ + (__HANDLE__)->Lock = HAL_UNLOCKED; \ + }while (0) +#endif /* USE_RTOS */ + +#if defined ( __GNUC__ ) + #ifndef __weak + #define __weak __attribute__((weak)) + #endif /* __weak */ + #ifndef __packed + #define __packed __attribute__((__packed__)) + #endif /* __packed */ +#endif /* __GNUC__ */ + + +/* Macro to get variable aligned on 4-bytes, for __ICCARM__ the directive "#pragma data_alignment=4" must be used instead */ +#if defined (__GNUC__) /* GNU Compiler */ + #ifndef __ALIGN_END + #define __ALIGN_END __attribute__ ((aligned (4))) + #endif /* __ALIGN_END */ + #ifndef __ALIGN_BEGIN + #define __ALIGN_BEGIN + #endif /* __ALIGN_BEGIN */ +#else + #ifndef __ALIGN_END + #define __ALIGN_END + #endif /* __ALIGN_END */ + #ifndef __ALIGN_BEGIN + #if defined (__CC_ARM) /* ARM Compiler */ + #define __ALIGN_BEGIN __align(4) + #elif defined (__ICCARM__) /* IAR Compiler */ + #define __ALIGN_BEGIN + #elif defined (__TASKING__) /* TASKING Compiler */ + #define __ALIGN_BEGIN __align(4) + #endif /* __CC_ARM */ + #endif /* __ALIGN_BEGIN */ +#endif /* __GNUC__ */ + +/** + * @brief __RAM_FUNC definition + */ +#if defined ( __CC_ARM ) +/* ARM Compiler + ------------ + RAM functions are defined using the toolchain options. + Functions that are executed in RAM should reside in a separate source module. + Using the 'Options for File' dialog you can simply change the 'Code / Const' + area of a module to a memory space in physical RAM. + Available memory areas are declared in the 'Target' tab of the 'Options for Target' + dialog. +*/ +#define __RAM_FUNC HAL_StatusTypeDef + +#elif defined ( __ICCARM__ ) +/* ICCARM Compiler + --------------- + RAM functions are defined using a specific toolchain keyword "__ramfunc". +*/ +#define __RAM_FUNC __ramfunc HAL_StatusTypeDef + +#elif defined ( __GNUC__ ) +/* GNU Compiler + ------------ + RAM functions are defined using a specific toolchain attribute + "__attribute__((section(".RamFunc")))". +*/ +#define __RAM_FUNC HAL_StatusTypeDef __attribute__((section(".RamFunc"))) + +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* ___STM32L0xx_HAL_DEF */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_dma.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_dma.c new file mode 100644 index 0000000000..960f4f4a84 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_dma.c @@ -0,0 +1,762 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_dma.c + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief DMA HAL module driver. + * + * This file provides firmware functions to manage the following + * functionalities of the Direct Memory Access (DMA) peripheral: + * + Initialization/de-initialization functions + * + I/O operation functions + * + Peripheral State functions + * + * + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + (#) Enable and configure the peripheral to be connected to the DMA Channel + (except for internal SRAM / FLASH memories: no initialization is + necessary). + + (#) For a given Channel, program the required configuration through the following parameters: + Channel request, Transfer Direction, Source and Destination data formats, + Circular, Normal or peripheral flow control mode, Channel Priority level, + Source and Destination Increment mode using HAL_DMA_Init() function. + + *** Polling mode IO operation *** + ================================= + [..] + (+) Use HAL_DMA_Start() to start DMA transfer after the configuration of Source + address and destination address and the Length of data to be transferred + (+) Use HAL_DMA_PollForTransfer() to poll for the end of current transfer, in this + case a fixed Timeout can be configured by User depending from his application. + + *** Interrupt mode IO operation *** + =================================== + [..] + (+) Configure the DMA interrupt priority using HAL_NVIC_SetPriority() + (+) Enable the DMA IRQ handler using HAL_NVIC_EnableIRQ() + (+) Use HAL_DMA_Start_IT() to start DMA transfer after the configuration of + Source address and destination address and the Length of data to be transferred. In this + case the DMA interrupt is configured + (+) Use HAL_DMA_IRQHandler() called under DMA_IRQHandler() Interrupt subroutine + (+) At the end of data transfer HAL_DMA_IRQHandler() function is executed and user can + add his own function by customization of function pointer XferCpltCallback and + XferErrorCallback (i.e a member of DMA handle structure). + + (#) Use HAL_DMA_GetState() function to return the DMA state and HAL_DMA_GetError() in case of error + detection. + + (#) Use HAL_DMA_Abort() function to abort the current transfer + + -@- In Memory-to-Memory transfer mode, Circular mode is not allowed. + + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @defgroup DMA + * @brief DMA HAL module driver + * @{ + */ + +#ifdef HAL_DMA_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +#define HAL_TIMEOUT_DMA_ABORT ((uint32_t)1000) /* 1s */ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +static void DMA_SetConfig(DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t DstAddress, uint32_t DataLength); + +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup DMA_Private_Functions + * @{ + */ + +/** @defgroup DMA_Group1 Initialization/de-initialization functions + * @brief Initialization/de-initialization functions + * +@verbatim + =============================================================================== + ##### Initialization and de-initialization functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Initialize and configure the DMA + (+) De-Initialize the DMA + +@endverbatim + * @{ + */ + +/** + * @brief Initializes the DMA according to the specified + * parameters in the DMA_InitTypeDef and create the associated handle. + * @param hdma: Pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA Channel. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_DMA_Init(DMA_HandleTypeDef *hdma) +{ + uint32_t tmp = 0; + + /* Check the DMA peripheral state */ + if(hdma == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_DMA_ALL_PERIPH(hdma->Instance)); + assert_param(IS_DMA_ALL_REQUEST(hdma->Init.Request)); + assert_param(IS_DMA_DIRECTION(hdma->Init.Direction)); + assert_param(IS_DMA_PERIPHERAL_INC_STATE(hdma->Init.PeriphInc)); + assert_param(IS_DMA_MEMORY_INC_STATE(hdma->Init.MemInc)); + assert_param(IS_DMA_PERIPHERAL_DATA_SIZE(hdma->Init.PeriphDataAlignment)); + assert_param(IS_DMA_MEMORY_DATA_SIZE(hdma->Init.MemDataAlignment)); + assert_param(IS_DMA_MODE(hdma->Init.Mode)); + assert_param(IS_DMA_PRIORITY(hdma->Init.Priority)); + + /* Change DMA peripheral state */ + hdma->State = HAL_DMA_STATE_BUSY; + + /* Get the CR register value */ + tmp = hdma->Instance->CCR; + + /* Clear PL, MSIZE, PSIZE, MINC, PINC, CIRC, DIR bits */ + tmp &= ((uint32_t)~(DMA_CCR_PL | DMA_CCR_MSIZE | DMA_CCR_PSIZE | \ + DMA_CCR_MINC | DMA_CCR_PINC | DMA_CCR_CIRC | \ + DMA_CCR_DIR)); + + /* Prepare the DMA Channel configuration */ + tmp |= hdma->Init.Direction | + hdma->Init.PeriphInc | hdma->Init.MemInc | + hdma->Init.PeriphDataAlignment | hdma->Init.MemDataAlignment | + hdma->Init.Mode | hdma->Init.Priority; + + /* Write to DMA Channel CR register */ + hdma->Instance->CCR = tmp; + + /* Write to DMA channel selection register */ + if (hdma->Instance == DMA1_Channel1) + { + /*Reset request selection for DMA1 Channel1*/ + DMA1_CSELR->CSELR &= ~DMA_CSELR_C1S; + + /* Configure request selection for DMA1 Channel1 */ + DMA1_CSELR->CSELR |= hdma->Init.Request; + } + else if (hdma->Instance == DMA1_Channel2) + { + /*Reset request selection for DMA1 Channel2*/ + DMA1_CSELR->CSELR &= ~DMA_CSELR_C2S; + + /* Configure request selection for DMA1 Channel2 */ + DMA1_CSELR->CSELR |= (uint32_t)(hdma->Init.Request << 4); + } + else if (hdma->Instance == DMA1_Channel3) + { + /*Reset request selection for DMA1 Channel3*/ + DMA1_CSELR->CSELR &= ~DMA_CSELR_C3S; + + /* Configure request selection for DMA1 Channel3 */ + DMA1_CSELR->CSELR |= (uint32_t) (hdma->Init.Request << 8); + } + else if (hdma->Instance == DMA1_Channel4) + { + /*Reset request selection for DMA1 Channel4*/ + DMA1_CSELR->CSELR &= ~DMA_CSELR_C4S; + + /* Configure request selection for DMA1 Channel4 */ + DMA1_CSELR->CSELR |= (uint32_t) (hdma->Init.Request << 12); + } + else if (hdma->Instance == DMA1_Channel5) + { + /*Reset request selection for DMA1 Channel5*/ + DMA1_CSELR->CSELR &= ~DMA_CSELR_C5S; + + /* Configure request selection for DMA1 Channel5 */ + DMA1_CSELR->CSELR |= (uint32_t) (hdma->Init.Request << 16); + } + else if (hdma->Instance == DMA1_Channel6) + { + /*Reset request selection for DMA1 Channel6*/ + DMA1_CSELR->CSELR &= ~DMA_CSELR_C6S; + + /* Configure request selection for DMA1 Channel6 */ + DMA1_CSELR->CSELR |= (uint32_t) (hdma->Init.Request << 20); + } + else if (hdma->Instance == DMA1_Channel7) + { + /*Reset request selection for DMA1 Channel7*/ + DMA1_CSELR->CSELR &= ~DMA_CSELR_C7S; + + /* Configure request selection for DMA1 Channel7 */ + DMA1_CSELR->CSELR |= (uint32_t) (hdma->Init.Request << 24); + } + + /* Initialize the DMA state*/ + hdma->State = HAL_DMA_STATE_READY; + + return HAL_OK; +} + +/** + * @brief DeInitializes the DMA peripheral + * @param hdma: pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA Channel. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_DMA_DeInit(DMA_HandleTypeDef *hdma) +{ + /* Check the DMA peripheral state */ + if(hdma->State == HAL_DMA_STATE_BUSY) + { + return HAL_ERROR; + } + + /* Disable the selected DMA Channelx */ + __HAL_DMA_DISABLE(hdma); + + /* Reset DMA Channel control register */ + hdma->Instance->CCR = 0; + + /* Reset DMA Channel Number of Data to Transfer register */ + hdma->Instance->CNDTR = 0; + + /* Reset DMA Channel peripheral address register */ + hdma->Instance->CPAR = 0; + + /* Reset DMA Channel memory address register */ + hdma->Instance->CMAR = 0; + + /* Clear all flags */ + __HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_GI_FLAG_INDEX(hdma)); + __HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_TC_FLAG_INDEX(hdma)); + __HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_TE_FLAG_INDEX(hdma)); + __HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_HT_FLAG_INDEX(hdma)); + + /* Reset DMA channel selection register */ + if (hdma->Instance == DMA1_Channel1) + { + /*Reset DMA request*/ + DMA1_CSELR->CSELR &= ~DMA_CSELR_C1S; + } + else if (hdma->Instance == DMA1_Channel2) + { + /*Reset DMA request*/ + DMA1_CSELR->CSELR &= ~DMA_CSELR_C2S; + } + else if (hdma->Instance == DMA1_Channel3) + { + /*Reset DMA request*/ + DMA1_CSELR->CSELR &= ~DMA_CSELR_C3S; + } + else if (hdma->Instance == DMA1_Channel4) + { + /*Reset DMA request*/ + DMA1_CSELR->CSELR &= ~DMA_CSELR_C4S; + } + else if (hdma->Instance == DMA1_Channel5) + { + /*Reset DMA request*/ + DMA1_CSELR->CSELR &= ~DMA_CSELR_C5S; + } + else if (hdma->Instance == DMA1_Channel6) + { + /*Reset DMA request*/ + DMA1_CSELR->CSELR &= ~DMA_CSELR_C6S; + } + else if (hdma->Instance == DMA1_Channel7) + { + /*Reset DMA request*/ + DMA1_CSELR->CSELR &= ~DMA_CSELR_C7S; + } + + /* Initialise the error code */ + hdma->ErrorCode = HAL_DMA_ERROR_NONE; + + /* Initialize the DMA state */ + hdma->State = HAL_DMA_STATE_RESET; + + /* Release Lock */ + __HAL_UNLOCK(hdma); + + return HAL_OK; +} + +/** + * @} + */ + +/** @defgroup DMA_Group2 I/O operation functions + * @brief I/O operation functions + * +@verbatim + =============================================================================== + ##### IO operation functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Configure the source, destination address and data length and Start DMA transfer + (+) Configure the source, destination address and data length and + Start DMA transfer with interrupt + (+) Abort DMA transfer + (+) Poll for transfer complete + (+) Handle DMA interrupt request + +@endverbatim + * @{ + */ + +/** + * @brief Starts the DMA Transfer. + * @param hdma : pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA Channel. + * @param SrcAddress: The source memory Buffer address + * @param DstAddress: The destination memory Buffer address + * @param DataLength: The length of data to be transferred from source to destination + * @retval HAL status + */ +HAL_StatusTypeDef HAL_DMA_Start(DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t DstAddress, uint32_t DataLength) +{ + /* Process locked */ + __HAL_LOCK(hdma); + + /* Change DMA peripheral state */ + hdma->State = HAL_DMA_STATE_BUSY; + + /* Check the parameters */ + assert_param(IS_DMA_BUFFER_SIZE(DataLength)); + + /* Disable the peripheral */ + __HAL_DMA_DISABLE(hdma); + + /* Configure the source, destination address and the data length */ + DMA_SetConfig(hdma, SrcAddress, DstAddress, DataLength); + + /* Enable the Peripheral */ + __HAL_DMA_ENABLE(hdma); + + return HAL_OK; +} + +/** + * @brief Start the DMA Transfer with interrupt enabled. + * @param hdma: pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA Channel. + * @param SrcAddress: The source memory Buffer address + * @param DstAddress: The destination memory Buffer address + * @param DataLength: The length of data to be transferred from source to destination + * @retval HAL status + */ +HAL_StatusTypeDef HAL_DMA_Start_IT(DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t DstAddress, uint32_t DataLength) +{ + /* Process locked */ + __HAL_LOCK(hdma); + + /* Change DMA peripheral state */ + hdma->State = HAL_DMA_STATE_BUSY; + + /* Check the parameters */ + assert_param(IS_DMA_BUFFER_SIZE(DataLength)); + + /* Disable the peripheral */ + __HAL_DMA_DISABLE(hdma); + + /* Configure the source, destination address and the data length */ + DMA_SetConfig(hdma, SrcAddress, DstAddress, DataLength); + + /* Enable the transfer complete interrupt */ + __HAL_DMA_ENABLE_IT(hdma, DMA_IT_TC); + + /* Enable the Half transfer complete interrupt */ + __HAL_DMA_ENABLE_IT(hdma, DMA_IT_HT); + + /* Enable the transfer Error interrupt */ + __HAL_DMA_ENABLE_IT(hdma, DMA_IT_TE); + + /* Enable the Peripheral */ + __HAL_DMA_ENABLE(hdma); + + return HAL_OK; +} + +/** + * @brief Aborts the DMA Transfer. + * @param hdma : pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA Channel. + * @param Timeout: Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_DMA_Abort(DMA_HandleTypeDef *hdma) +{ + uint32_t tickstart = 0; + + /* Disable the channel */ + __HAL_DMA_DISABLE(hdma); + + /* Get timeout */ + tickstart = HAL_GetTick(); + + /* Check if the DMA Channel is effectively disabled */ + while((hdma->Instance->CCR & DMA_CCR_EN) != 0) + { + /* Check for the Timeout */ + if((int32_t) (HAL_GetTick() - tickstart ) > HAL_TIMEOUT_DMA_ABORT) + { + /* Update error code */ + hdma->ErrorCode |= HAL_DMA_ERROR_TIMEOUT; + + /* Process Unlocked */ + __HAL_UNLOCK(hdma); + + /* Change the DMA state */ + hdma->State = HAL_DMA_STATE_TIMEOUT; + + return HAL_TIMEOUT; + } + } + /* Process Unlocked */ + __HAL_UNLOCK(hdma); + + /* Change the DMA state*/ + hdma->State = HAL_DMA_STATE_READY; + + return HAL_OK; +} + +/** + * @brief Polling for transfer complete. + * @param hdma: pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA Channel. + * @param CompleteLevel: Specifies the DMA level complete. + * @param Timeout: Timeout duration. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_DMA_PollForTransfer(DMA_HandleTypeDef *hdma, uint32_t CompleteLevel, uint32_t Timeout) +{ + uint32_t temp; + uint32_t tickstart = 0; + + /* Get the level transfer complete flag */ + if(CompleteLevel == HAL_DMA_FULL_TRANSFER) + { + /* Transfer Complete flag */ + temp = __HAL_DMA_GET_TC_FLAG_INDEX(hdma); + } + else + { + /* Half Transfer Complete flag */ + temp = __HAL_DMA_GET_HT_FLAG_INDEX(hdma); + } + + /* Get timeout */ + tickstart = HAL_GetTick(); + + while(__HAL_DMA_GET_FLAG(hdma, temp) == RESET) + { + if((__HAL_DMA_GET_FLAG(hdma, __HAL_DMA_GET_TE_FLAG_INDEX(hdma)) != RESET)) + { + /* Clear the transfer error flags */ + __HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_TE_FLAG_INDEX(hdma)); + + /* Change the DMA state */ + hdma->State= HAL_DMA_STATE_ERROR; + + /* Process Unlocked */ + __HAL_UNLOCK(hdma); + + return HAL_ERROR; + } + /* Check for the Timeout */ + if(Timeout != HAL_MAX_DELAY) + { + if((int32_t) (HAL_GetTick() - tickstart ) > Timeout) + { + /* Update error code */ + hdma->ErrorCode |= HAL_DMA_ERROR_TIMEOUT; + + /* Process Unlocked */ + __HAL_UNLOCK(hdma); + + /* Change the DMA state */ + hdma->State = HAL_DMA_STATE_TIMEOUT; + + return HAL_TIMEOUT; + } + } + } + /* Clear the half transfer complete flag */ + __HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_HT_FLAG_INDEX(hdma)); + + /* Change DMA peripheral state */ + hdma->State = HAL_DMA_STATE_READY_HALF; + + if(CompleteLevel == HAL_DMA_FULL_TRANSFER) + { + /* Clear the transfer complete flag */ + __HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_TC_FLAG_INDEX(hdma)); + + /* The selected Channelx EN bit is cleared (DMA is disabled and + all transfers are complete) */ + hdma->State = HAL_DMA_STATE_READY; + + /* Process unlocked */ + __HAL_UNLOCK(hdma); + } + else + { + /* Clear the half transfer complete flag */ + __HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_HT_FLAG_INDEX(hdma)); + + /* The selected Channelx EN bit is cleared (DMA is disabled and + all transfers are complete) */ + hdma->State = HAL_DMA_STATE_READY_HALF; + } + + return HAL_OK; +} +/** + * @brief Handles DMA interrupt request. + * @param hdma: pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA Channel. + * @retval None + */ +void HAL_DMA_IRQHandler(DMA_HandleTypeDef *hdma) +{ + /* Transfer Error Interrupt management ***************************************/ + if(__HAL_DMA_GET_FLAG(hdma, __HAL_DMA_GET_TE_FLAG_INDEX(hdma)) != RESET) + { + if(__HAL_DMA_GET_IT_SOURCE(hdma, DMA_IT_TE) != RESET) + { + /* Disable the transfer error interrupt */ + __HAL_DMA_DISABLE_IT(hdma, DMA_IT_TE); + + /* Clear the transfer error flag */ + __HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_TE_FLAG_INDEX(hdma)); + + /* Update error code */ + hdma->ErrorCode |= HAL_DMA_ERROR_TE; + + /* Change the DMA state */ + hdma->State = HAL_DMA_STATE_ERROR; + + /* Process Unlocked */ + __HAL_UNLOCK(hdma); + + if (hdma->XferErrorCallback != NULL) + { + /* Transfer error callback */ + hdma->XferErrorCallback(hdma); + } + } + } + + /* Half Transfer Complete Interrupt management ******************************/ + if(__HAL_DMA_GET_FLAG(hdma, __HAL_DMA_GET_HT_FLAG_INDEX(hdma)) != RESET) + { + if(__HAL_DMA_GET_IT_SOURCE(hdma, DMA_IT_HT) != RESET) + { + /* Disable the half transfer interrupt if the DMA mode is not CIRCULAR */ + if((hdma->Instance->CCR & DMA_CCR_CIRC) == 0) + { + /* Disable the half transfer interrupt */ + __HAL_DMA_DISABLE_IT(hdma, DMA_IT_HT); + } + /* Clear the half transfer complete flag */ + __HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_HT_FLAG_INDEX(hdma)); + + /* Change DMA peripheral state */ + hdma->State = HAL_DMA_STATE_READY_HALF; + + if(hdma->XferHalfCpltCallback != NULL) + { + /* Half transfer callback */ + hdma->XferHalfCpltCallback(hdma); + } + } + } + + /* Transfer Complete Interrupt management ***********************************/ + if(__HAL_DMA_GET_FLAG(hdma, __HAL_DMA_GET_TC_FLAG_INDEX(hdma)) != RESET) + { + if(__HAL_DMA_GET_IT_SOURCE(hdma, DMA_IT_TC) != RESET) + { + if((hdma->Instance->CCR & DMA_CCR_CIRC) == 0) + { + /* Disable the transfer complete interrupt */ + __HAL_DMA_DISABLE_IT(hdma, DMA_IT_TC); + } + /* Clear the transfer complete flag */ + __HAL_DMA_CLEAR_FLAG(hdma, __HAL_DMA_GET_TC_FLAG_INDEX(hdma)); + + /* Update error code */ + hdma->ErrorCode |= HAL_DMA_ERROR_NONE; + + /* Change the DMA state */ + hdma->State = HAL_DMA_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hdma); + + if(hdma->XferCpltCallback != NULL) + { + /* Transfer complete callback */ + hdma->XferCpltCallback(hdma); + } + } + } +} + +/** + * @} + */ + +/** @defgroup DMA_Group3 Peripheral State functions + * @brief Peripheral State functions + * +@verbatim + =============================================================================== + ##### Peripheral State functions ##### + =============================================================================== + [..] + This subsection provides functions allowing to + (+) Check the DMA state + (+) Get error code + +@endverbatim + * @{ + */ + +/** + * @brief Returns the DMA state. + * @param hdma: pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA Channel. + * @retval HAL state + */ +HAL_DMA_StateTypeDef HAL_DMA_GetState(DMA_HandleTypeDef *hdma) +{ + return hdma->State; +} + +/** + * @brief Return the DMA error code + * @param hdma : pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA Channel. + * @retval DMA Error Code + */ +uint32_t HAL_DMA_GetError(DMA_HandleTypeDef *hdma) +{ + return hdma->ErrorCode; +} + +/** + * @} + */ + +/** @defgroup DMA_Group4 Extanded feature functions + * @brief Extanded feature functions + * +@verbatim + =============================================================================== + ##### Extanded feature functions ##### + =============================================================================== + [..] + This subsection provides functions allowing to + (+) Configure the source, destination address and data length + +@endverbatim + * @{ + */ +/** + * @brief Sets the DMA Transfer parameter. + * @param hdma: pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA Channel. + * @param SrcAddress: The source memory Buffer address + * @param DstAddress: The destination memory Buffer address + * @param DataLength: The length of data to be transferred from source to destination + * @retval HAL status + */ +static void DMA_SetConfig(DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t DstAddress, uint32_t DataLength) +{ + /* Configure DMA Channel data length */ + hdma->Instance->CNDTR = DataLength; + + /* Peripheral to Memory */ + if((hdma->Init.Direction) == DMA_MEMORY_TO_PERIPH) + { + /* Configure DMA Channel destination address */ + hdma->Instance->CPAR = DstAddress; + + /* Configure DMA Channel source address */ + hdma->Instance->CMAR = SrcAddress; + } + /* Memory to Peripheral */ + else + { + /* Configure DMA Channel source address */ + hdma->Instance->CPAR = SrcAddress; + + /* Configure DMA Channel destination address */ + hdma->Instance->CMAR = DstAddress; + } +} + +/** + * @} + */ + +/** + * @} + */ + +#endif /* HAL_DMA_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_dma.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_dma.h new file mode 100644 index 0000000000..0549a8ae9a --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_dma.h @@ -0,0 +1,542 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_dma.h + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief Header file of DMA HAL module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32L0xx_HAL_DMA_H +#define __STM32L0xx_HAL_DMA_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal_def.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @addtogroup DMA + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ + +/** + * @brief DMA Configuration Structure definition + */ +typedef struct +{ + uint32_t Request; /*!< Specifies the request selected for the specified channel. + This parameter can be a value of @ref DMA_request */ + + uint32_t Direction; /*!< Specifies if the data will be transferred from memory to peripheral, + from memory to memory or from peripheral to memory. + This parameter can be a value of @ref Data_transfer_direction */ + + uint32_t PeriphInc; /*!< Specifies whether the Peripheral address register should be incremented or not. + This parameter can be a value of @ref Peripheral_incremented_mode */ + + uint32_t MemInc; /*!< Specifies whether the memory address register should be incremented or not. + This parameter can be a value of @ref Memory_incremented_mode */ + + uint32_t PeriphDataAlignment; /*!< Specifies the Peripheral data width. + This parameter can be a value of @ref Peripheral_data_size */ + + uint32_t MemDataAlignment; /*!< Specifies the Memory data width. + This parameter can be a value of @ref Memory_data_size */ + + uint32_t Mode; /*!< Specifies the operation mode of the DMAy Channelx. + This parameter can be a value of @ref DMA_mode + @note The circular buffer mode cannot be used if the memory-to-memory + data transfer is configured on the selected Channel */ + + uint32_t Priority; /*!< Specifies the software priority for the DMAy Channelx. + This parameter can be a value of @ref Priority_level */ +} DMA_InitTypeDef; + +/** + * @brief DMA Configuration enumeration values definition + */ +typedef enum +{ + DMA_MODE = 0, /*!< Control related DMA mode Parameter in DMA_InitTypeDef */ + DMA_PRIORITY = 1, /*!< Control related priority level Parameter in DMA_InitTypeDef */ + +} DMA_ControlTypeDef; + +/** + * @brief HAL DMA State structures definition + */ +typedef enum +{ + HAL_DMA_STATE_RESET = 0x00, /*!< DMA not yet initialized or disabled */ + HAL_DMA_STATE_READY = 0x01, /*!< DMA process success and ready for use */ + HAL_DMA_STATE_BUSY = 0x02, /*!< DMA process is ongoing */ + HAL_DMA_STATE_TIMEOUT = 0x03, /*!< DMA timeout state */ + HAL_DMA_STATE_ERROR = 0x04, /*!< DMA error state */ + HAL_DMA_STATE_READY_HALF = 0x05, /*!< DMA Half process success */ +}HAL_DMA_StateTypeDef; + +/** + * @brief HAL DMA Error Code structure definition + */ +typedef enum +{ + HAL_DMA_FULL_TRANSFER = 0x00, /*!< Full transfer */ + HAL_DMA_HALF_TRANSFER = 0x01, /*!< Half Transfer */ + +}HAL_DMA_LevelCompleteTypeDef; + + +/** + * @brief DMA handle Structure definition + */ +typedef struct __DMA_HandleTypeDef +{ + DMA_Channel_TypeDef *Instance; /*!< Register base address */ + + DMA_InitTypeDef Init; /*!< DMA communication parameters */ + + HAL_LockTypeDef Lock; /*!< DMA locking object */ + + __IO HAL_DMA_StateTypeDef State; /*!< DMA transfer state */ + + void *Parent; /*!< Parent object state */ + + void (* XferCpltCallback)( struct __DMA_HandleTypeDef * hdma); /*!< DMA transfer complete callback */ + + void (* XferHalfCpltCallback)( struct __DMA_HandleTypeDef * hdma); /*!< DMA Half transfer complete callback */ + + void (* XferErrorCallback)( struct __DMA_HandleTypeDef * hdma); /*!< DMA transfer error callback */ + + __IO uint32_t ErrorCode; /*!< DMA Error code */ + +} DMA_HandleTypeDef; + +/* Exported constants --------------------------------------------------------*/ + +/** @defgroup DMA_Exported_Constants + * @{ + */ + +/** @defgroup DMA_Error_Code + * @{ + */ +#define HAL_DMA_ERROR_NONE ((uint32_t)0x00000000) /*!< No error */ +#define HAL_DMA_ERROR_TE ((uint32_t)0x00000001) /*!< Transfer error */ +#define HAL_DMA_ERROR_TIMEOUT ((uint32_t)0x00000020) /*!< Timeout error */ +/** + * @} + */ + +#define IS_DMA_ALL_PERIPH(PERIPH) (((PERIPH) == DMA1_Channel1) || \ + ((PERIPH) == DMA1_Channel2) || \ + ((PERIPH) == DMA1_Channel3) || \ + ((PERIPH) == DMA1_Channel4) || \ + ((PERIPH) == DMA1_Channel5) || \ + ((PERIPH) == DMA1_Channel6) || \ + ((PERIPH) == DMA1_Channel7)) + +#define IS_DMA_ALL_CONTROLLER(CONTROLLER) (((CONTROLLER) == DMA1)) + +/** + * @} + */ + +/** @defgroup DMA_request + * @{ + */ +#define DMA_REQUEST_0 ((uint32_t)0x00000000) +#define DMA_REQUEST_1 ((uint32_t)0x00000001) +#define DMA_REQUEST_2 ((uint32_t)0x00000002) +#define DMA_REQUEST_3 ((uint32_t)0x00000003) +#define DMA_REQUEST_4 ((uint32_t)0x00000004) +#define DMA_REQUEST_5 ((uint32_t)0x00000005) +#define DMA_REQUEST_6 ((uint32_t)0x00000006) +#define DMA_REQUEST_7 ((uint32_t)0x00000007) +#define DMA_REQUEST_8 ((uint32_t)0x00000008) +#define DMA_REQUEST_9 ((uint32_t)0x00000009) +#define DMA_REQUEST_11 ((uint32_t)0x0000000B) + +#define IS_DMA_ALL_REQUEST(REQUEST) (((REQUEST) == DMA_REQUEST_0) || \ + ((REQUEST) == DMA_REQUEST_1) || \ + ((REQUEST) == DMA_REQUEST_2) || \ + ((REQUEST) == DMA_REQUEST_3) || \ + ((REQUEST) == DMA_REQUEST_4) || \ + ((REQUEST) == DMA_REQUEST_5) || \ + ((REQUEST) == DMA_REQUEST_6) || \ + ((REQUEST) == DMA_REQUEST_7) || \ + ((REQUEST) == DMA_REQUEST_8) || \ + ((REQUEST) == DMA_REQUEST_9) || \ + ((REQUEST) == DMA_REQUEST_11)) +/** + * @} + */ + +/** @defgroup DMA_Data_transfer_direction + * @{ + */ +#define DMA_PERIPH_TO_MEMORY ((uint32_t)0x00000000) /*!< Peripheral to memory direction */ +#define DMA_MEMORY_TO_PERIPH ((uint32_t)DMA_CCR_DIR) /*!< Memory to peripheral direction */ +#define DMA_MEMORY_TO_MEMORY ((uint32_t)(DMA_CCR_MEM2MEM)) /*!< Memory to memory direction */ + +#define IS_DMA_DIRECTION(DIRECTION) (((DIRECTION) == DMA_PERIPH_TO_MEMORY ) || \ + ((DIRECTION) == DMA_MEMORY_TO_PERIPH) || \ + ((DIRECTION) == DMA_MEMORY_TO_MEMORY)) +/** + * @} + */ + +/** @defgroup DMA_Data_buffer_size + * @{ + */ +#define IS_DMA_BUFFER_SIZE(SIZE) (((SIZE) >= 0x1) && ((SIZE) < 0x10000)) +/** + * @} + */ + +/** @defgroup DMA_Peripheral_incremented_mode + * @{ + */ +#define DMA_PINC_ENABLE ((uint32_t)DMA_CCR_PINC) /*!< Peripheral increment mode Enable */ +#define DMA_PINC_DISABLE ((uint32_t)0x00000000) /*!< Peripheral increment mode Disable */ + +#define IS_DMA_PERIPHERAL_INC_STATE(STATE) (((STATE) == DMA_PINC_ENABLE) || \ + ((STATE) == DMA_PINC_DISABLE)) +/** + * @} + */ + +/** @defgroup DMA_Memory_incremented_mode + * @{ + */ +#define DMA_MINC_ENABLE ((uint32_t)DMA_CCR_MINC) /*!< Memory increment mode Enable */ +#define DMA_MINC_DISABLE ((uint32_t)0x00000000) /*!< Memory increment mode Disable */ + +#define IS_DMA_MEMORY_INC_STATE(STATE) (((STATE) == DMA_MINC_ENABLE) || \ + ((STATE) == DMA_MINC_DISABLE)) +/** + * @} + */ + +/** @defgroup DMA_Peripheral_data_size + * @{ + */ +#define DMA_PDATAALIGN_BYTE ((uint32_t)0x00000000) /*!< Peripheral data alignment : Byte */ +#define DMA_PDATAALIGN_HALFWORD ((uint32_t)DMA_CCR_PSIZE_0) /*!< Peripheral data alignment : HalfWord */ +#define DMA_PDATAALIGN_WORD ((uint32_t)DMA_CCR_PSIZE_1) /*!< Peripheral data alignment : Word */ + +#define IS_DMA_PERIPHERAL_DATA_SIZE(SIZE) (((SIZE) == DMA_PDATAALIGN_BYTE) || \ + ((SIZE) == DMA_PDATAALIGN_HALFWORD) || \ + ((SIZE) == DMA_PDATAALIGN_WORD)) +/** + * @} + */ + + +/** @defgroup DMA_Memory_data_size + * @{ + */ +#define DMA_MDATAALIGN_BYTE ((uint32_t)0x00000000) /*!< Memory data alignment : Byte */ +#define DMA_MDATAALIGN_HALFWORD ((uint32_t)DMA_CCR_MSIZE_0) /*!< Memory data alignment : HalfWord */ +#define DMA_MDATAALIGN_WORD ((uint32_t)DMA_CCR_MSIZE_1) /*!< Memory data alignment : Word */ + +#define IS_DMA_MEMORY_DATA_SIZE(SIZE) (((SIZE) == DMA_MDATAALIGN_BYTE) || \ + ((SIZE) == DMA_MDATAALIGN_HALFWORD) || \ + ((SIZE) == DMA_MDATAALIGN_WORD )) +/** + * @} + */ + +/** @defgroup DMA_mode + * @{ + */ +#define DMA_NORMAL ((uint32_t)0x00000000) /*!< Normal Mode */ +#define DMA_CIRCULAR ((uint32_t)DMA_CCR_CIRC) /*!< Circular Mode */ + +#define IS_DMA_MODE(MODE) (((MODE) == DMA_NORMAL ) || \ + ((MODE) == DMA_CIRCULAR)) +/** + * @} + */ + +/** @defgroup DMA_Priority_level + * @{ + */ +#define DMA_PRIORITY_LOW ((uint32_t)0x00000000) /*!< Priority level : Low */ +#define DMA_PRIORITY_MEDIUM ((uint32_t)DMA_CCR_PL_0) /*!< Priority level : Medium */ +#define DMA_PRIORITY_HIGH ((uint32_t)DMA_CCR_PL_1) /*!< Priority level : High */ +#define DMA_PRIORITY_VERY_HIGH ((uint32_t)DMA_CCR_PL) /*!< Priority level : Very_High */ + +#define IS_DMA_PRIORITY(PRIORITY) (((PRIORITY) == DMA_PRIORITY_LOW ) || \ + ((PRIORITY) == DMA_PRIORITY_MEDIUM) || \ + ((PRIORITY) == DMA_PRIORITY_HIGH) || \ + ((PRIORITY) == DMA_PRIORITY_VERY_HIGH)) +/** + * @} + */ + + +/** @defgroup DMA_interrupt_enable_definitions + * @{ + */ + +#define DMA_IT_TC ((uint32_t)DMA_CCR_TCIE) +#define DMA_IT_HT ((uint32_t)DMA_CCR_HTIE) +#define DMA_IT_TE ((uint32_t)DMA_CCR_TEIE) + +/** + * @} + */ + +/** @defgroup DMA_flag_definitions + * @{ + */ + +#define DMA_FLAG_GL1 ((uint32_t)0x00000001) +#define DMA_FLAG_TC1 ((uint32_t)0x00000002) +#define DMA_FLAG_HT1 ((uint32_t)0x00000004) +#define DMA_FLAG_TE1 ((uint32_t)0x00000008) +#define DMA_FLAG_GL2 ((uint32_t)0x00000010) +#define DMA_FLAG_TC2 ((uint32_t)0x00000020) +#define DMA_FLAG_HT2 ((uint32_t)0x00000040) +#define DMA_FLAG_TE2 ((uint32_t)0x00000080) +#define DMA_FLAG_GL3 ((uint32_t)0x00000100) +#define DMA_FLAG_TC3 ((uint32_t)0x00000200) +#define DMA_FLAG_HT3 ((uint32_t)0x00000400) +#define DMA_FLAG_TE3 ((uint32_t)0x00000800) +#define DMA_FLAG_GL4 ((uint32_t)0x00001000) +#define DMA_FLAG_TC4 ((uint32_t)0x00002000) +#define DMA_FLAG_HT4 ((uint32_t)0x00004000) +#define DMA_FLAG_TE4 ((uint32_t)0x00008000) +#define DMA_FLAG_GL5 ((uint32_t)0x00010000) +#define DMA_FLAG_TC5 ((uint32_t)0x00020000) +#define DMA_FLAG_HT5 ((uint32_t)0x00040000) +#define DMA_FLAG_TE5 ((uint32_t)0x00080000) +#define DMA_FLAG_GL6 ((uint32_t)0x00100000) +#define DMA_FLAG_TC6 ((uint32_t)0x00200000) +#define DMA_FLAG_HT6 ((uint32_t)0x00400000) +#define DMA_FLAG_TE6 ((uint32_t)0x00800000) +#define DMA_FLAG_GL7 ((uint32_t)0x01000000) +#define DMA_FLAG_TC7 ((uint32_t)0x02000000) +#define DMA_FLAG_HT7 ((uint32_t)0x04000000) +#define DMA_FLAG_TE7 ((uint32_t)0x08000000) + + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ + +/** @brief Reset DMA handle state + * @param __HANDLE__: DMA handle + * @retval None + */ +#define __HAL_DMA_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_DMA_STATE_RESET) + +/** + * @brief Enable the specified DMA Channel. + * @param __HANDLE__: DMA handle + * @retval None. + */ +#define __HAL_DMA_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CCR |= DMA_CCR_EN) + +/** + * @brief Disable the specified DMA Channel. + * @param __HANDLE__: DMA handle + * @retval None. + */ +#define __HAL_DMA_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CCR &= ~DMA_CCR_EN) + + +/* Interrupt & Flag management */ + +/** + * @brief Returns the current DMA Channel transfer complete flag. + * @param __HANDLE__: DMA handle + * @retval The specified transfer complete flag index. + */ + +#define __HAL_DMA_GET_TC_FLAG_INDEX(__HANDLE__) \ +(((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel1))? DMA_FLAG_TC1 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel2))? DMA_FLAG_TC2 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel3))? DMA_FLAG_TC3 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel4))? DMA_FLAG_TC4 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel5))? DMA_FLAG_TC5 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel6))? DMA_FLAG_TC6 :\ + DMA_FLAG_TC7) + +/** + * @brief Returns the current DMA Channel half transfer complete flag. + * @param __HANDLE__: DMA handle + * @retval The specified half transfer complete flag index. + */ +#define __HAL_DMA_GET_HT_FLAG_INDEX(__HANDLE__)\ +(((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel1))? DMA_FLAG_HT1 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel2))? DMA_FLAG_HT2 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel3))? DMA_FLAG_HT3 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel4))? DMA_FLAG_HT4 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel5))? DMA_FLAG_HT5 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel6))? DMA_FLAG_HT6 :\ + DMA_FLAG_HT7) + +/** + * @brief Returns the current DMA Channel transfer error flag. + * @param __HANDLE__: DMA handle + * @retval The specified transfer error flag index. + */ +#define __HAL_DMA_GET_TE_FLAG_INDEX(__HANDLE__)\ +(((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel1))? DMA_FLAG_TE1 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel2))? DMA_FLAG_TE2 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel3))? DMA_FLAG_TE3 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel4))? DMA_FLAG_TE4 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel5))? DMA_FLAG_TE5 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel6))? DMA_FLAG_TE6 :\ + DMA_FLAG_TE7) + +/** + * @brief Returns the current DMA Channel Global interrupt flag. + * @param __HANDLE__: DMA handle + * @retval The specified transfer error flag index. + */ +#define __HAL_DMA_GET_GI_FLAG_INDEX(__HANDLE__)\ +(((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel1))? DMA_ISR_GIF1 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel2))? DMA_ISR_GIF2 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel3))? DMA_ISR_GIF3 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel4))? DMA_ISR_GIF4 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel5))? DMA_ISR_GIF5 :\ + ((uint32_t)((__HANDLE__)->Instance) == ((uint32_t)DMA1_Channel6))? DMA_ISR_GIF6 :\ + DMA_ISR_GIF7) +/** + * @brief Get the DMA Channel pending flags. + * @param __HANDLE__: DMA handle + * @param __FLAG__: Get the specified flag. + * This parameter can be any combination of the following values: + * @arg DMA_FLAG_TCIFx: Transfer complete flag + * @arg DMA_FLAG_HTIFx: Half transfer complete flag + * @arg DMA_FLAG_TEIFx: Transfer error flag + * @arg DMA_ISR_GIFx: Global interrupt flag + * Where x can be 0_4, 1_5, 2_6 or 3_7 to select the DMA Channel flag. + * @retval The state of FLAG (SET or RESET). + */ +#define __HAL_DMA_GET_FLAG(__HANDLE__, __FLAG__) (DMA1->ISR & (__FLAG__)) + +/** + * @brief Clears the DMA Channel pending flags. + * @param __HANDLE__: DMA handle + * @param __FLAG__: specifies the flag to clear. + * This parameter can be any combination of the following values: + * @arg DMA_FLAG_TCIFx: Transfer complete flag + * @arg DMA_FLAG_HTIFx: Half transfer complete flag + * @arg DMA_FLAG_TEIFx: Transfer error flag + * @arg DMA_ISR_GIFx: Global interrupt flag + * Where x can be 0_4, 1_5, 2_6 or 3_7 to select the DMA Channel flag. + * @retval None + */ +#define __HAL_DMA_CLEAR_FLAG(__HANDLE__, __FLAG__) (DMA1->IFCR |= (__FLAG__)) + +/** + * @brief Enables the specified DMA Channel interrupts. + * @param __HANDLE__: DMA handle + * @param __INTERRUPT__: specifies the DMA interrupt sources to be enabled or disabled. + * This parameter can be any combination of the following values: + * @arg DMA_IT_TC: Transfer complete interrupt mask + * @arg DMA_IT_HT: Half transfer complete interrupt mask + * @arg DMA_IT_TE: Transfer error interrupt mask + * @retval None + */ +#define __HAL_DMA_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CCR |= (__INTERRUPT__)) + +/** + * @brief Disables the specified DMA Channel interrupts. + * @param __HANDLE__: DMA handle + * @param __INTERRUPT__: specifies the DMA interrupt sources to be enabled or disabled. + * This parameter can be any combination of the following values: + * @arg DMA_IT_TC: Transfer complete interrupt mask + * @arg DMA_IT_HT: Half transfer complete interrupt mask + * @arg DMA_IT_TE: Transfer error interrupt mask + * @retval None + */ +#define __HAL_DMA_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CCR &= ~(__INTERRUPT__)) + +/** + * @brief Checks whether the specified DMA Channel interrupt has occurred or not. + * @param __HANDLE__: DMA handle + * @param __INTERRUPT__: specifies the DMA interrupt source to check. + * This parameter can be one of the following values: + * @arg DMA_IT_TC: Transfer complete interrupt mask + * @arg DMA_IT_HT: Half transfer complete interrupt mask + * @arg DMA_IT_TE: Transfer error interrupt mask + * @retval The state of DMA_IT (SET or RESET). + */ +#define __HAL_DMA_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->CCR & (__INTERRUPT__))) + + +/* Exported functions --------------------------------------------------------*/ + +/* Initialization and de-initialization functions *****************************/ +HAL_StatusTypeDef HAL_DMA_Init(DMA_HandleTypeDef *hdma); +HAL_StatusTypeDef HAL_DMA_DeInit (DMA_HandleTypeDef *hdma); + +/* IO operation functions *****************************************************/ +HAL_StatusTypeDef HAL_DMA_Start (DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t DstAddress, uint32_t DataLength); +HAL_StatusTypeDef HAL_DMA_Start_IT(DMA_HandleTypeDef *hdma, uint32_t SrcAddress, uint32_t DstAddress, uint32_t DataLength); +HAL_StatusTypeDef HAL_DMA_Abort(DMA_HandleTypeDef *hdma); +HAL_StatusTypeDef HAL_DMA_PollForTransfer(DMA_HandleTypeDef *hdma, uint32_t CompleteLevel, uint32_t Timeout); +void HAL_DMA_IRQHandler(DMA_HandleTypeDef *hdma); + +/* Peripheral State and Error functions ***************************************/ +HAL_DMA_StateTypeDef HAL_DMA_GetState(DMA_HandleTypeDef *hdma); +uint32_t HAL_DMA_GetError(DMA_HandleTypeDef *hdma); + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __STM32L0xx_HAL_DMA_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_flash.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_flash.c new file mode 100644 index 0000000000..aa587d1093 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_flash.c @@ -0,0 +1,710 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_flash.c + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief FLASH HAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the internal FLASH memory: + * + FLASH Interface configuration + * + FLASH Memory Programming + * + DATA EEPROM Programming + * + Option Bytes Programming + * + Interrupts and flags management + * + * @verbatim + + ============================================================================== + ##### FLASH peripheral features ##### + ============================================================================== + + [..] The Flash memory interface manages CPU accesses to the Flash memory. + It implements the erase and program Flash memory operations + and the read and write protection mechanisms. + + [..] The FLASH main features are: + (+) Flash memory read operations + (+) Flash memory program/erase operations + (+) Read / write protections + (+) Option Bytes programming + + ##### How to use this driver ##### + ============================================================================== + [..] + This driver provides functions and macros to configure and program the FLASH + memory of all STM32L0xx devices. + + (#) FLASH Memory IO Programming functions: + (++) Lock and Unlock the FLASH interface using HAL_FLASH_Unlock() and + HAL_FLASH_Lock() functions + (++) Program functions: byte, half word and word + (++) There Two modes of programming : + (+++) Polling mode using HAL_FLASH_Program() function + (+++) Interrupt mode using HAL_FLASH_Program_IT() function + + (#) Interrupts and flags management functions : + (++) Handle FLASH interrupts by calling HAL_FLASH_IRQHandler() + (++) Wait for last FLASH operation according to its status + (++) Get error flag status by calling HAL_GetErrorCode() + + [..] + In addition to these functions, this driver includes a set of macros allowing + to handle the following operations: + (+) Set the latency + (+) Enable/Disable the prefetch buffer + (+) Enable/Disable the preread buffer + (+) Enable/Disable the Flash power-down + (+) Enable/Disable the FLASH interrupts + (+) Monitor the FLASH flags status + + =============================================================================== + ##### Programming operation functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to manage the FLASH + program operations. + + [..] The FLASH Memory Programming functions, includes the following functions: + (+) HAL_FLASH_Unlock(void); + (+) HAL_FLASH_Lock(void); + (+) HAL_FLASH_Program(uint32_t TypeProgram, uint32_t Address, uint32_t Data) + (+) HAL_FLASH_Program_IT(uint32_t TypeProgram, uint32_t Address, uint32_t Data) + + [..] Any operation of erase or program should follow these steps: + (#) Call the HAL_FLASH_Unlock() function to enable the flash control register and + program memory access. + (#) Call the desired function to erase page or program data. + (#) Call the HAL_FLASH_Lock() to disable the flash program memory access + (recommended to protect the FLASH memory against possible unwanted operation). + + ============================================================================== + ##### Option Bytes Programming functions ##### + ============================================================================== + + [..] The FLASH_Option Bytes Programming_functions, includes the following functions: + (+) HAL_FLASH_OB_Unlock(void); + (+) HAL_FLASH_OB_Lock(void); + (+) HAL_FLASH_OB_Launch(void); + (+) HAL_FLASHEx_OBProgram(FLASH_OBProgramInitTypeDef *pOBInit); + (+) HAL_FLASHEx_OBGetConfig(FLASH_OBProgramInitTypeDef *pOBInit); + + [..] Any operation of erase or program should follow these steps: + (#) Call the HAL_FLASH_OB_Unlock() function to enable the Flash option control + register access. + (#) Call the following functions to program the desired option bytes. + (++) HAL_FLASHEx_OBProgram(FLASH_OBProgramInitTypeDef *pOBInit); + (#) Once all needed option bytes to be programmed are correctly written, call the + HAL_FLASH_OB_Launch(void) function to launch the Option Bytes programming process. + (#) Call the HAL_FLASH_OB_Lock() to disable the Flash option control register access (recommended + to protect the option Bytes against possible unwanted operations). + + [..] Proprietary code Read Out Protection (PcROP): + (#) The PcROP sector is selected by using the same option bytes as the Write + protection (nWRPi bits). As a result, these 2 options are exclusive each other. + (#) In order to activate the PcROP (change the function of the nWRPi option bits), + the SPRMOD option bit must be activated. + (#) The active value of nWRPi bits is inverted when PCROP mode is active, this + means: if SPRMOD = 1 and nWRPi = 1 (default value), then the user page "i" + is read/write protected. + (#) To activate PCROP mode for Flash page(s), you need to follow the sequence below: + (++) For page(s) within the first 64KB of the Flash, use this function + HAL_FLASHEx_AdvOBProgram with PCROPState = PCROPSTATE_ENABLE. + + + * @endverbatim + * + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @defgroup FLASH + * @brief FLASH driver modules + * @{ + */ + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +#define HAL_FLASH_TIMEOUT_VALUE ((uint32_t)0xFFFF0) + +/* FLASH Mask */ +#define WRP01_MASK ((uint32_t)0x0000FFFF) +#define PAGESIZE ((uint32_t)0x00000080) + +/* Private macro -------------------------------------------------------------*/ +/*Variables used for Erase sectors under interruption*/ +FLASH_ProcessTypeDef pFlash; + +/* Private function prototypes -----------------------------------------------*/ +static void FLASH_Program_Word(uint32_t Address, uint32_t Data); +HAL_StatusTypeDef FLASH_WaitForLastOperation(uint32_t Timeout); +static void FLASH_SetErrorCode(void); +static HAL_StatusTypeDef DATA_EEPROM_Unlock(void); + +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup FLASH_Private_Functions + * @{ + */ + +/** @defgroup FLASH_Group1 Programming operation functions + * @brief Programming operation functions + * +@verbatim +@endverbatim + * @{ + */ +/** + * @brief Program word at a specified address + * @param TypeProgram: Indicate the way to program at a specified address. + * This parameter can be a value of @ref FLASH_Type_Program + * @param Address: specifies the address to be programmed. + * @param Data: specifies the data to be programmed + * + * @retval HAL_StatusTypeDef HAL Status + */ +HAL_StatusTypeDef HAL_FLASH_Program(uint32_t TypeProgram, uint32_t Address, uint32_t Data) +{ + HAL_StatusTypeDef status = HAL_ERROR; + + /* Process Locked */ + __HAL_LOCK(&pFlash); + + /* Check the parameters */ + assert_param(IS_TYPEPROGRAM(TypeProgram)); + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE); + + if(status == HAL_OK) + { + if(TypeProgram == TYPEPROGRAM_WORD) + { + /*Program word (32-bit) at a specified address.*/ + FLASH_Program_Word(Address, (uint32_t) Data); + } + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE); + + /* Reset PROG bit */ + FLASH->PECR &= ~FLASH_PECR_PROG; + } + + /* Process Unlocked */ + __HAL_UNLOCK(&pFlash); + + return status; +} + +/** + * @brief Program word at a specified address with interrupt enabled. + * @param TypeProgram: Indicate the way to program at a specified address. + * This parameter can be a value of @ref FLASH_Type_Program + * @param Address: specifies the address to be programmed. + * @param Data: specifies the data to be programmed + * + * @retval HAL_StatusTypeDef HAL Status + */ +HAL_StatusTypeDef HAL_FLASH_Program_IT(uint32_t TypeProgram, uint32_t Address, uint32_t Data) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Process Locked */ + __HAL_LOCK(&pFlash); + + /* Check the parameters */ + assert_param(IS_TYPEPROGRAM(TypeProgram)); + + /* Enable End of FLASH Operation interrupt */ + __HAL_FLASH_ENABLE_IT(FLASH_IT_EOP); + + /* Enable Error source interrupt */ + __HAL_FLASH_ENABLE_IT(FLASH_IT_ERR); + + /* Clear pending flags (if any) */ + __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP | FLASH_FLAG_ENDHV | FLASH_FLAG_WRPERR |\ + FLASH_FLAG_PGAERR | FLASH_FLAG_SIZERR| FLASH_FLAG_OPTVERR |\ + FLASH_FLAG_RDERR | FLASH_FLAG_NOTZEROERR); + + pFlash.ProcedureOnGoing = FLASH_PROC_PROGRAM; + pFlash.Address = Address; + + if(TypeProgram == TYPEPROGRAM_WORD) + { + /*Program word (32-bit) at a specified address.*/ + FLASH_Program_Word(Address, (uint32_t) Data); + } + + /* Process Unlocked */ + __HAL_UNLOCK(&pFlash); + + return status; +} + +/** + * @brief This function handles FLASH interrupt request. + * @param None + * @retval None + */ +void HAL_FLASH_IRQHandler(void) +{ + uint32_t temp; + + /* If the program operation is completed, disable the PROG Bit */ + FLASH->PECR &= (~FLASH_PECR_PROG); + + /* If the erase operation is completed, disable the ERASE Bit */ + FLASH->PECR &= (~FLASH_PECR_ERASE); + + /* Check FLASH End of Operation flag */ + if(__HAL_FLASH_GET_FLAG(FLASH_FLAG_EOP)) + { + if(pFlash.ProcedureOnGoing == FLASH_PROC_PAGEERASE) + { + /*Nb of sector to erased can be decreased*/ + pFlash.NbPagesToErase--; + + /* Check if there are still sectors to erase*/ + if(pFlash.NbPagesToErase != 0) + { + temp = pFlash.Page; + /*Indicate user which sector has been erased*/ + HAL_FLASH_EndOfOperationCallback(temp); + + /* Clear pending flags (if any) */ + __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP | FLASH_FLAG_ENDHV | FLASH_FLAG_WRPERR |\ + FLASH_FLAG_PGAERR | FLASH_FLAG_SIZERR| FLASH_FLAG_OPTVERR |\ + FLASH_FLAG_RDERR | FLASH_FLAG_NOTZEROERR); + + /*Increment sector number*/ + temp = pFlash.Page + PAGESIZE; + pFlash.Page = pFlash.Page + PAGESIZE; + FLASH_Erase_Page(temp); + } + else + { + /*No more sectors to Erase, user callback can be called.*/ + /*Reset Sector and stop Erase sectors procedure*/ + pFlash.Page = temp = 0xFFFFFFFF; + pFlash.ProcedureOnGoing = FLASH_PROC_NONE; + /* FLASH EOP interrupt user callback */ + HAL_FLASH_EndOfOperationCallback(temp); + /* Clear FLASH End of Operation pending bit */ + __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP); + } + } + else + { + if(pFlash.ProcedureOnGoing == FLASH_PROC_PROGRAM) + { + /*Program ended. Return the selected address*/ + /* FLASH EOP interrupt user callback */ + HAL_FLASH_EndOfOperationCallback(pFlash.Address); + } + pFlash.ProcedureOnGoing = FLASH_PROC_NONE; + /* Clear FLASH End of Operation pending bit */ + __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP); + } + + } + /* Check FLASH operation error flags */ + if(__HAL_FLASH_GET_FLAG((FLASH_FLAG_EOP | FLASH_FLAG_ENDHV | FLASH_FLAG_WRPERR |\ + FLASH_FLAG_PGAERR | FLASH_FLAG_SIZERR| FLASH_FLAG_OPTVERR |\ + FLASH_FLAG_RDERR | FLASH_FLAG_NOTZEROERR))) + { + if(pFlash.ProcedureOnGoing == FLASH_PROC_PAGEERASE) + { + /*return the faulty sector*/ + temp = pFlash.Page; + pFlash.Page = 0xFFFFFFFF; + } + else + { + /*retrun the faulty address*/ + temp = pFlash.Address; + } + + /*Save the Error code*/ + FLASH_SetErrorCode(); + + /* FLASH error interrupt user callback */ + HAL_FLASH_OperationErrorCallback(temp); + /* Clear FLASH error pending bits */ + __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP | FLASH_FLAG_ENDHV | FLASH_FLAG_WRPERR |\ + FLASH_FLAG_PGAERR | FLASH_FLAG_SIZERR| FLASH_FLAG_OPTVERR |\ + FLASH_FLAG_RDERR | FLASH_FLAG_NOTZEROERR); + + /*Stop the procedure ongoing*/ + pFlash.ProcedureOnGoing = FLASH_PROC_NONE; + } + + if(pFlash.ProcedureOnGoing == FLASH_PROC_NONE) + { + /* Disable End of FLASH Operation interrupt */ + __HAL_FLASH_DISABLE_IT(FLASH_IT_EOP); + + /* Disable Error source interrupt */ + __HAL_FLASH_DISABLE_IT(FLASH_IT_ERR); + + /* Process Unlocked */ + __HAL_UNLOCK(&pFlash); + } + +} + +/** + * @brief FLASH end of operation interrupt callback + * @param ReturnValue: The value saved in this parameter depends on the ongoing procedure + * - Pages Erase: Sector which has been erased + * (if 0xFFFFFFFF, it means that all the selected sectors have been erased) + * - Program: Address which was selected for data program + * @retval none + */ +__weak void HAL_FLASH_EndOfOperationCallback(uint32_t ReturnValue) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_FLASH_EndOfOperationCallback could be implemented in the user file + */ +} + +/** + * @brief FLASH operation error interrupt callback + * @param ReturnValue: The value saved in this parameter depends on the ongoing procedure + * - Pagess Erase: Sector number which returned an error + * - Program: Address which was selected for data program + * @retval none + */ +__weak void HAL_FLASH_OperationErrorCallback(uint32_t ReturnValue) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_FLASH_OperationErrorCallback could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup FLASH_Group2 Peripheral Control functions + * @brief management functions + * +@verbatim + =============================================================================== + ##### Peripheral Control functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to control the FLASH + memory operations. + +@endverbatim + * @{ + */ +/** + * @brief Unlock the FLASH control register access + * @param None + * @retval HAL_StatusTypeDef HAL Status + */ +HAL_StatusTypeDef HAL_FLASH_Unlock(void) +{ + if((FLASH->PECR & FLASH_PECR_PRGLOCK) != RESET) + { + /* Unlocking the data memory and FLASH_PECR register access */ + DATA_EEPROM_Unlock(); + + /* Unlocking the program memory access */ + FLASH->PRGKEYR = FLASH_PRGKEY1; + FLASH->PRGKEYR = FLASH_PRGKEY2; + } + else + { + return HAL_ERROR; + } + + return HAL_OK; +} + +/** + * @brief Locks the FLASH control register access + * @param None + * @retval HAL_StatusTypeDef HAL Status + */ +HAL_StatusTypeDef HAL_FLASH_Lock(void) +{ + /* Set the PRGLOCK Bit to lock the program memory access */ + FLASH->PECR |= FLASH_PECR_PRGLOCK; + + return HAL_OK; +} + +/** + * @brief Unlock the FLASH Option Control Registers access. + * @param None + * @retval HAL_StatusTypeDef HAL Status + */ +HAL_StatusTypeDef HAL_FLASH_OB_Unlock(void) +{ + if((FLASH->PECR & FLASH_PECR_OPTLOCK) != RESET) + { + /* Unlocking the data memory and FLASH_PECR register access */ + DATA_EEPROM_Unlock(); + + /* Unlocking the option bytes block access */ + FLASH->OPTKEYR = FLASH_OPTKEY1; + FLASH->OPTKEYR = FLASH_OPTKEY2; + } + else + { + return HAL_ERROR; + } + + return HAL_OK; +} + +/** + * @brief Lock the FLASH Option Control Registers access. + * @param None + * @retval HAL_StatusTypeDef HAL Status + */ +HAL_StatusTypeDef HAL_FLASH_OB_Lock(void) +{ + /* Set the OPTLOCK Bit to lock the option bytes block access */ + FLASH->PECR |= FLASH_PECR_OPTLOCK; + + return HAL_OK; +} + +/** + * @brief Launch the option byte loading. + * @param None + * @retval HAL_StatusTypeDef HAL Status + */ +HAL_StatusTypeDef HAL_FLASH_OB_Launch(void) +{ + /* Set the OBL_Launch bit to lauch the option byte loading */ + FLASH->PECR |= FLASH_PECR_OBL_LAUNCH; + + /* Wait for last operation to be completed */ + return(FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE)); +} + +/** + * @brief Unlocks the data memory and FLASH_PECR register access. + * @param None + * @retval HAL_StatusTypeDef HAL Status + */ +static HAL_StatusTypeDef DATA_EEPROM_Unlock(void) +{ + if((FLASH->PECR & FLASH_PECR_PELOCK) != RESET) + { + /* Unlocking the Data memory and FLASH_PECR register access*/ + FLASH->PEKEYR = FLASH_PEKEY1; + FLASH->PEKEYR = FLASH_PEKEY2; + } + else + { + return HAL_ERROR; + } + return HAL_OK; +} + +/** + * @} + */ + +/** @defgroup FLASH_Group3 Peripheral State and Errors functions + * @brief Peripheral Errors functions + * +@verbatim + =============================================================================== + ##### Peripheral Errors functions ##### + =============================================================================== + [..] + This subsection permit to get in run-time Errors of the FLASH peripheral. + +@endverbatim + * @{ + */ + +/** + * @brief Get the specific FLASH error flag. + * @param None + * @retval FLASH_ErrorCode: The returned value can be: + * @arg FLASH_ERROR_RD: FLASH Read Protection error flag (PCROP) + * @arg FLASH_ERROR_ENDHV: FLASH Programming Sequence error flag + * @arg FLASH_ERROR_SIZE: FLASH Programming Parallelism error flag + * @arg FLASH_ERROR_PGA: FLASH Programming Alignment error flag + * @arg FLASH_ERROR_WRP: FLASH Write protected error flag + * @arg FLASH_ERROR_OPTV: FLASH Option valid error flag + * @arg FLASH_ERROR_NOTZERO: FLASH write operation is done in a not-erased region + */ +FLASH_ErrorTypeDef HAL_FLASH_GetError(void) +{ + return pFlash.ErrorCode; +} + +/** + * @brief Wait for a FLASH operation to complete. + * @param Timeout: maximum flash operationtimeout + * @retval HAL_StatusTypeDef HAL Status + */ +HAL_StatusTypeDef FLASH_WaitForLastOperation(uint32_t Timeout) +{ + uint32_t tickstart = 0; + + /* Wait for the FLASH operation to complete by polling on BUSY flag to be reset. + Even if the FLASH operation fails, the BUSY flag will be reset and an error + flag will be set */ + + tickstart = HAL_GetTick(); + + while(__HAL_FLASH_GET_FLAG(FLASH_FLAG_BSY)) + { + if(Timeout != HAL_MAX_DELAY) + { + if((HAL_GetTick() - tickstart ) > Timeout) + { + return HAL_TIMEOUT; + } + } + } + + if(__HAL_FLASH_GET_FLAG((FLASH_FLAG_WRPERR | FLASH_FLAG_PGAERR | FLASH_FLAG_SIZERR | FLASH_FLAG_OPTVERR |\ + FLASH_FLAG_RDERR | FLASH_FLAG_NOTZEROERR))) + { + /*Save the error code*/ + FLASH_SetErrorCode(); + return HAL_ERROR; + } + + /* If there is an error flag set */ + return HAL_OK; +} + +/** + * @brief Set the specific FLASH error flag. + * @param None + * @retval None + */ +static void FLASH_SetErrorCode(void) +{ + if(__HAL_FLASH_GET_FLAG(FLASH_FLAG_ENDHV)) + { + pFlash.ErrorCode = FLASH_ERROR_ENDHV; + } + if(__HAL_FLASH_GET_FLAG(FLASH_FLAG_WRPERR)) + { + pFlash.ErrorCode = FLASH_ERROR_WRP; + } + if(__HAL_FLASH_GET_FLAG(FLASH_FLAG_PGAERR)) + { + pFlash.ErrorCode = FLASH_ERROR_PGA; + } + if(__HAL_FLASH_GET_FLAG(FLASH_FLAG_SIZERR)) + { + pFlash.ErrorCode = FLASH_ERROR_SIZE; + } + if(__HAL_FLASH_GET_FLAG(FLASH_FLAG_OPTVERR)) + { + pFlash.ErrorCode = FLASH_ERROR_OPTV; + } + if(__HAL_FLASH_GET_FLAG(FLASH_FLAG_RDERR)) + { + pFlash.ErrorCode = FLASH_ERROR_RD; + } + if(__HAL_FLASH_GET_FLAG(FLASH_FLAG_NOTZEROERR)) + { + pFlash.ErrorCode = FLASH_ERROR_NOTZERO; + } +} + +/** + * @brief Erases a specified page in program memory. + * @note To correctly run this function, the HAL_FLASH_Unlock() function + * must be called before. + * Call the HAL_FLASH_Lock() to disable the flash memory access + * (recommended to protect the FLASH memory against possible unwanted operation) + * @param Page_Address: The page address in program memory to be erased. + * @note A Page is erased in the Program memory only if the address to load + * is the start address of a page (multiple of 256 bytes). + * @retval HAL_StatusTypeDef HAL Status + */ +void FLASH_Erase_Page(uint32_t Page_Address) +{ + /* Set the ERASE bit */ + FLASH->PECR |= FLASH_PECR_ERASE; + + /* Set PROG bit */ + FLASH->PECR |= FLASH_PECR_PROG; + + /* Write 00000000h to the first word of the program page to erase */ + *(__IO uint32_t *)Page_Address = 0x00000000; +} + +/** + * @} + */ + +/** + * @} + */ +/** + * @brief Program word (32-bit) at a specified address. + * @param Address: specifies the address to be programmed. + * @param Data: specifies the data to be programmed. + * @retval None + */ +static void FLASH_Program_Word(uint32_t Address, uint32_t Data) +{ + /* Check the parameters */ + assert_param(IS_FLASH_PROGRAM_ADDRESS(Address)); + + /* Set PROG bit */ + FLASH->PECR |= FLASH_PECR_PROG; + + *(__IO uint32_t*)Address = Data; +} + +/** + * @} + */ + +/** + * @} +*/ + + + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_flash.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_flash.h new file mode 100644 index 0000000000..fecec662fb --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_flash.h @@ -0,0 +1,503 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_flash.h + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief This file contains all the functions prototypes for the FLASH + * firmware library. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32L0XX_HAL_FLASH_H +#define __STM32L0XX_HAL_FLASH_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal_def.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @addtogroup FLASH + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/** + * @brief FLASH Error structure definition + */ +typedef enum +{ + FLASH_ERROR_RD = 0x01, + FLASH_ERROR_ENDHV = 0x02, + FLASH_ERROR_SIZE = 0x04, + FLASH_ERROR_PGA = 0x08, + FLASH_ERROR_WRP = 0x10, + FLASH_ERROR_OPTV = 0x20, + FLASH_ERROR_NOTZERO = 0x40 +}FLASH_ErrorTypeDef; + +/** + * @brief FLASH Procedure structure definition + */ +typedef enum +{ + FLASH_PROC_NONE = 0, + FLASH_PROC_PAGEERASE, + FLASH_PROC_PROGRAM +} FLASH_ProcedureTypeDef; + +/** + * @brief FLASH Erase structure definition + */ +typedef struct +{ + uint32_t TypeErase; /*!< TypeErase: Mass erase or sector Erase. + This parameter can be a value of @ref FLASH_Type_Erase */ + + uint32_t Page; /*!< Sector: Initial FLASH sector to erase when Mass erase is disabled + This parameter must be a value of @ref FLASH_Sectors */ + + uint32_t NbPages; /*!< NbSectors: Number of sectors to be erased. + This parameter must be a value between 1 and (max number of sectors - value of Initial sector)*/ + +} FLASH_EraseInitTypeDef; + +/** + * @brief FLASH Option Bytes PROGRAM structure definition + */ +typedef struct +{ + uint32_t OptionType; /*!< OptionType: Option byte to be configured. + This parameter can be a value of @ref FLASH_Option_Type */ + + uint32_t WRPState; /*!< WRPState: Write protection activation or deactivation. + This parameter can be a value of @ref FLASH_WRP_State */ + + uint32_t WRPSector; /*!< WRPSector: specifies the sector(s) to be write protected + The value of this parameter depend on device used within the same series */ + + uint32_t RDPLevel; /*!< RDPLevel: Set the read protection level.. + This parameter can be a value of @ref FLASH_Option_Bytes_Read_Protection */ + + uint32_t BORLevel; /*!< BORLevel: Set the BOR Level. + This parameter can be a value of @ref Option_Bytes_BOR_Level */ + uint8_t USERConfig; /*!< USERConfig: Program the FLASH User Option Byte: IWDG_SW / RST_STOP / RST_STDBY. + This parameter can be a combination of @ref FLASH_Option_Bytes_IWatchdog, @ref FLASH_Option_Bytes_nRST_STOP and @ref FLASH_Option_Bytes_nRST_STDBY*/ +} FLASH_OBProgramInitTypeDef; + +/** + * @brief FLASH handle Structure definition + */ +typedef struct +{ + __IO FLASH_ProcedureTypeDef ProcedureOnGoing; /*Internal variable to indicate which procedure is ongoing or not in IT context*/ + + __IO uint32_t NbPagesToErase; /*Internal variable to save the remaining sectors to erase in IT context*/ + + __IO uint32_t Page; /*Internal variable to define the current sector which is erasing*/ + + __IO uint32_t Address; /*Internal variable to save address selected for program*/ + + HAL_LockTypeDef Lock; /* FLASH locking object */ + + __IO FLASH_ErrorTypeDef ErrorCode; /* FLASH error code */ + +}FLASH_ProcessTypeDef; + +/* Exported constants --------------------------------------------------------*/ + +/** @defgroup FLASH_Exported_Constants FLASH Exported Constants + * @{ + */ + +/** @defgroup FLASH_Type_Erase FLASH Type Erase + * @{ + */ +#define TYPEERASE_PAGEERASE ((uint32_t)0x00) /*!= 0x08080000) && ((ADDRESS) <= 0x080807FF)) /* 2K */ +#define IS_FLASH_PROGRAM_ADDRESS(ADDRESS) (((ADDRESS) >= 0x08000000) && ((ADDRESS) <= 0x0800FFFF)) /* 64K */ +#define IS_NBPAGES(PAGES) (((PAGES) >= 1) && ((PAGES) <= 512)) /* 512 pages from page0 to page 511 */ +/** + * @} + */ + +/** @defgroup Option_Bytes_Write_Protection + * @{ + */ +#define OB_WRP_Pages0to31 ((uint32_t)0x00000001) /* Write protection of Sector0 */ +#define OB_WRP_Pages32to63 ((uint32_t)0x00000002) /* Write protection of Sector1 */ +#define OB_WRP_Pages64to95 ((uint32_t)0x00000004) /* Write protection of Sector2 */ +#define OB_WRP_Pages96to127 ((uint32_t)0x00000008) /* Write protection of Sector3 */ +#define OB_WRP_Pages128to159 ((uint32_t)0x00000010) /* Write protection of Sector4 */ +#define OB_WRP_Pages160to191 ((uint32_t)0x00000020) /* Write protection of Sector5 */ +#define OB_WRP_Pages192to223 ((uint32_t)0x00000040) /* Write protection of Sector6 */ +#define OB_WRP_Pages224to255 ((uint32_t)0x00000080) /* Write protection of Sector7 */ +#define OB_WRP_Pages256to287 ((uint32_t)0x00000100) /* Write protection of Sector8 */ +#define OB_WRP_Pages288to319 ((uint32_t)0x00000200) /* Write protection of Sector9 */ +#define OB_WRP_Pages320to351 ((uint32_t)0x00000400) /* Write protection of Sector10 */ +#define OB_WRP_Pages352to383 ((uint32_t)0x00000800) /* Write protection of Sector11 */ +#define OB_WRP_Pages384to415 ((uint32_t)0x00001000) /* Write protection of Sector12 */ +#define OB_WRP_Pages416to447 ((uint32_t)0x00002000) /* Write protection of Sector13 */ +#define OB_WRP_Pages448to479 ((uint32_t)0x00004000) /* Write protection of Sector14 */ +#define OB_WRP_Pages480to511 ((uint32_t)0x00008000) /* Write protection of Sector15 */ + +#define OB_WRP_AllPages ((uint32_t)0x0000FFFF) /*!< Write protection of all Sectors */ + +#define IS_OB_WRP(PAGE) (((PAGE) != 0x0000000)) +/** + * @} + */ + +/** @defgroup Option_Bytes_Read_Protection + * @{ + */ + +/** + * @brief FLASH_Option_Bytes_Read_Protection + */ +#define OB_RDP_Level_0 ((uint8_t)0xAA) +#define OB_RDP_Level_1 ((uint8_t)0xBB) +/*#define OB_RDP_Level_2 ((uint8_t)0xCC)*/ /* Warning: When enabling read protection level 2 + it's no more possible to go back to level 1 or 0 */ + +#define IS_OB_RDP(LEVEL) (((LEVEL) == OB_RDP_Level_0)||\ + ((LEVEL) == OB_RDP_Level_1))/*||\ + ((LEVEL) == OB_RDP_Level_2))*/ +/** + * @} + */ + +/** @defgroup Option_Bytes_IWatchdog + * @{ + */ +#define OB_IWDG_SW ((uint8_t)0x10) /*!< Software WDG selected */ +#define OB_IWDG_HW ((uint8_t)0x00) /*!< Hardware WDG selected */ +#define IS_OB_IWDG_SOURCE(SOURCE) (((SOURCE) == OB_IWDG_SW) || ((SOURCE) == OB_IWDG_HW)) +/** + * @} + */ + +/** @defgroup Option_Bytes_nRST_STOP + * @{ + */ +#define OB_STOP_NoRST ((uint8_t)0x20) /*!< No reset generated when entering in STOP */ +#define OB_STOP_RST ((uint8_t)0x00) /*!< Reset generated when entering in STOP */ +#define IS_OB_STOP_SOURCE(SOURCE) (((SOURCE) == OB_STOP_NoRST) || ((SOURCE) == OB_STOP_RST)) +/** + * @} + */ + +/** @defgroup Option_Bytes_nRST_STDBY + * @{ + */ +#define OB_STDBY_NoRST ((uint8_t)0x40) /*!< No reset generated when entering in STANDBY */ +#define OB_STDBY_RST ((uint8_t)0x00) /*!< Reset generated when entering in STANDBY */ +#define IS_OB_STDBY_SOURCE(SOURCE) (((SOURCE) == OB_STDBY_NoRST) || ((SOURCE) == OB_STDBY_RST)) +/** + * @} + */ + +/** @defgroup Option_Bytes_BOR_Level + * @{ + */ + +#define OB_BOR_OFF ((uint8_t)0x00) /*!< BOR is disabled at power down, the reset is asserted when the VDD + power supply reaches the PDR(Power Down Reset) threshold (1.5V) */ +#define OB_BOR_LEVEL1 ((uint8_t)0x08) /*!< BOR Reset threshold levels for 1.7V - 1.8V VDD power supply */ +#define OB_BOR_LEVEL2 ((uint8_t)0x09) /*!< BOR Reset threshold levels for 1.9V - 2.0V VDD power supply */ +#define OB_BOR_LEVEL3 ((uint8_t)0x0A) /*!< BOR Reset threshold levels for 2.3V - 2.4V VDD power supply */ +#define OB_BOR_LEVEL4 ((uint8_t)0x0B) /*!< BOR Reset threshold levels for 2.55V - 2.65V VDD power supply */ +#define OB_BOR_LEVEL5 ((uint8_t)0x0C) /*!< BOR Reset threshold levels for 2.8V - 2.9V VDD power supply */ + +#define IS_OB_BOR_LEVEL(LEVEL) (((LEVEL) == OB_BOR_OFF) || \ + ((LEVEL) == OB_BOR_LEVEL1) || \ + ((LEVEL) == OB_BOR_LEVEL2) || \ + ((LEVEL) == OB_BOR_LEVEL3) || \ + ((LEVEL) == OB_BOR_LEVEL4) || \ + ((LEVEL) == OB_BOR_LEVEL5)) + +/** + * @} + */ + +/** @defgroup FLASH_Flags + * @{ + */ + +#define FLASH_FLAG_BSY FLASH_SR_BSY /*!< FLASH Busy flag */ +#define FLASH_FLAG_EOP FLASH_SR_EOP /*!< FLASH End of Programming flag */ +#define FLASH_FLAG_ENDHV FLASH_SR_ENHV /*!< FLASH End of High Voltage flag */ +#define FLASH_FLAG_READY FLASH_SR_READY /*!< FLASH Ready flag after low power mode */ +#define FLASH_FLAG_WRPERR FLASH_SR_WRPERR /*!< FLASH Write protected error flag */ +#define FLASH_FLAG_PGAERR FLASH_SR_PGAERR /*!< FLASH Programming Alignment error flag */ +#define FLASH_FLAG_SIZERR FLASH_SR_SIZERR /*!< FLASH Size error flag */ +#define FLASH_FLAG_OPTVERR FLASH_SR_OPTVERR /*!< FLASH Option Validity error flag */ +#define FLASH_FLAG_RDERR FLASH_SR_RDERR /*!< FLASH Read protected error flag */ +#define FLASH_FLAG_NOTZEROERR FLASH_SR_NOTZEROERR /*!< FLASH Read protected error flag */ + +#define IS_FLASH_CLEAR_FLAG(FLAG) ((((FLAG) & (uint32_t)0xFFFED0FF) == 0x00000000) && ((FLAG) != 0x00000000)) + +#define IS_FLASH_GET_FLAG(FLAG) (((FLAG) == FLASH_FLAG_BSY) || ((FLAG) == FLASH_FLAG_EOP) || \ + ((FLAG) == FLASH_FLAG_ENDHV) || ((FLAG) == FLASH_FLAG_READY ) || \ + ((FLAG) == FLASH_FLAG_WRPERR) || ((FLAG) == FLASH_FLAG_PGAERR ) || \ + ((FLAG) == FLASH_FLAG_SIZERR) || ((FLAG) == FLASH_FLAG_OPTVERR) || \ + ((FLAG) == FLASH_FLAG_RDERR) || ((FLAG) == FLASH_FLAG_NOTZEROERR)) +/** + * @} + */ + +/** @defgroup FLASH_Keys + * @{ + */ + +#define FLASH_PDKEY1 ((uint32_t)0x04152637) /*!< Flash power down key1 */ +#define FLASH_PDKEY2 ((uint32_t)0xFAFBFCFD) /*!< Flash power down key2: used with FLASH_PDKEY1 + to unlock the RUN_PD bit in FLASH_ACR */ + +#define FLASH_PEKEY1 ((uint32_t)0x89ABCDEF) /*!< Flash program erase key1 */ +#define FLASH_PEKEY2 ((uint32_t)0x02030405) /*!< Flash program erase key: used with FLASH_PEKEY2 + to unlock the write access to the FLASH_PECR register and + data EEPROM */ + +#define FLASH_PRGKEY1 ((uint32_t)0x8C9DAEBF) /*!< Flash program memory key1 */ +#define FLASH_PRGKEY2 ((uint32_t)0x13141516) /*!< Flash program memory key2: used with FLASH_PRGKEY2 + to unlock the program memory */ + +#define FLASH_OPTKEY1 ((uint32_t)0xFBEAD9C8) /*!< Flash option key1 */ +#define FLASH_OPTKEY2 ((uint32_t)0x24252627) /*!< Flash option key2: used with FLASH_OPTKEY1 to + unlock the write access to the option byte block */ +/** + * @} + */ + +/** @defgroup CMSIS_Legacy + * @{ + */ +#if defined ( __ICCARM__ ) +#define InterruptType_ACTLR_DISMCYCINT_Msk IntType_ACTLR_DISMCYCINT_Msk +#endif +/** + * @} + */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ +/** @defgroup FLASH_Interrupt FLASH Interrupt + * @brief macros to handle FLASH interrupts + * @{ + */ + +/** + * @brief Enables or disables the specified FLASH interrupts. + * @param __INTERRUPT__: specifies the FLASH interrupt sources to be enabled or + * disabled. + * This parameter can be any combination of the following values: + * @arg FLASH_IT_EOP: FLASH end of programming Interrupt + * @arg FLASH_IT_ERR: FLASH Error Interrupt + * @retval None + */ +#define __HAL_FLASH_ENABLE_IT(__INTERRUPT__) (FLASH->PECR |= (__INTERRUPT__)) + +/** + * @brief Disable the specified FLASH interrupt. + * @param __INTERRUPT__ : FLASH interrupt + * This parameter can be any combination of the following values: + * @arg FLASH_IT_EOP: End of FLASH Operation Interrupt + * @arg FLASH_IT_ERR: Error Interrupt + * @retval none + */ +#define __HAL_FLASH_DISABLE_IT(__INTERRUPT__) (FLASH->PECR &= ~(uint32_t)(__INTERRUPT__)) + +/** + * @brief Checks whether the specified FLASH flag is set or not. + * @param __FLAG__: specifies the FLASH flag to check. + * This parameter can be one of the following values: + * @arg FLASH_FLAG_BSY: FLASH write/erase operations in progress flag + * @arg FLASH_FLAG_EOP: FLASH End of Operation flag + * @arg FLASH_FLAG_READY: FLASH Ready flag after low power mode + * @arg FLASH_FLAG_ENDHV: FLASH End of high voltage flag + * @arg FLASH_FLAG_WRPERR: FLASH Write protected error flag + * @arg FLASH_FLAG_PGAERR: FLASH Programming Alignment error flag + * @arg FLASH_FLAG_SIZERR: FLASH size error flag + * @arg FLASH_FLAG_OPTVERR: FLASH Option validity error flag + * @arg FLASH_FLAG_OPTVERRUSR: FLASH Option User validity error flag + * @arg FLASH_FLAG_RDERR: FLASH Read protected error flag + * @arg FLASH_FLAG_NOTZEROERR: Not Zero area error flag + * @retval The new state of FLASH_FLAG (SET or RESET). + */ +#define __HAL_FLASH_GET_FLAG(__FLAG__) ((FLASH->SR & (__FLAG__)) == (__FLAG__)) + +/** + * @brief Clears the FLASH's pending flags. + * @param __FLAG__: specifies the FLASH flags to clear. + * This parameter can be any combination of the following values: + * @arg FLASH_FLAG_EOP: FLASH End of Operation flag + * @arg FLASH_FLAG_WRPERR: FLASH Write protected error flag + * @arg FLASH_FLAG_PGAERR: FLASH Programming Alignment error flag + * @arg FLASH_FLAG_SIZERR: FLASH size error flag + * @arg FLASH_FLAG_OPTVERR: FLASH Option validity error flag + * @arg FLASH_FLAG_OPTVERRUSR: FLASH Option User validity error flag + * @arg FLASH_FLAG_RDERR: FLASH Read protected error flag + * @arg FLASH_FLAG_NOTZEROERR: Not Zero area error flag + * @retval None + */ +#define __HAL_FLASH_CLEAR_FLAG(__FLAG__) (FLASH->SR = (__FLAG__)) + +/** + * @} + */ + +/* Include FLASH HAL Extension module */ +#include "stm32l0xx_hal_flash_ex.h" +#include "stm32l0xx_hal_flash_ramfunc.h" + +/* Exported functions ------------------------------------------------------- */ + +/** + * @brief FLASH memory functions that can be executed from FLASH. + */ +/* Program operation functions ***********************************************/ +HAL_StatusTypeDef HAL_FLASH_Program(uint32_t TypeProgram, uint32_t Address, uint32_t Data); +HAL_StatusTypeDef HAL_FLASH_Program_IT(uint32_t TypeProgram, uint32_t Address, uint32_t Data); + +/* FLASH IRQ handler function */ +void HAL_FLASH_IRQHandler(void); + +/* Callbacks in non blocking modes */ +void HAL_FLASH_EndOfOperationCallback(uint32_t ReturnValue); +void HAL_FLASH_OperationErrorCallback(uint32_t ReturnValue); + +/* Peripheral Control functions **********************************************/ +HAL_StatusTypeDef HAL_FLASH_Unlock(void); +HAL_StatusTypeDef HAL_FLASH_Lock(void); +HAL_StatusTypeDef HAL_FLASH_OB_Unlock(void); +HAL_StatusTypeDef HAL_FLASH_OB_Lock(void); + +/* Option bytes control */ +HAL_StatusTypeDef HAL_FLASH_OB_Launch(void); + +/* Peripheral State functions ************************************************/ +FLASH_ErrorTypeDef HAL_FLASH_GetError(void); + +/* Non-User functions ********************************************************/ +HAL_StatusTypeDef FLASH_WaitForLastOperation(uint32_t Timeout); +void FLASH_Erase_Page(uint32_t Page_Address); + +#ifdef __cplusplus +} +#endif + +#endif /* __STM32L0XX_HAL_FLASH_H */ + +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_flash_ex.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_flash_ex.c new file mode 100644 index 0000000000..fe1aa4e764 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_flash_ex.c @@ -0,0 +1,1177 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_flash_ex.c + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief FLASH HAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the internal FLASH memory: + * + FLASH Interface configuration + * + FLASH Memory Programming + * + DATA EEPROM Programming + * + Option Bytes Programming + * + Interrupts and flags management + * + * @verbatim + ============================================================================== + ##### Flash peripheral Extended features ##### + ============================================================================== + + [..] Comparing to other products, the FLASH interface for STM32L0xx + devices contains the following additional features + (+) DATA_EEPROM memory management + (+) BOOT option bit configuration + (+) PCROP protection for all sectors + + ##### How to use this driver ##### + ============================================================================== + [..] This driver provides functions to configure and program the FLASH memory + of all STM32L0xx. It includes: + (+) Full DATA_EEPROM erase and program management + (+) Boot activation + (+) PCROP protection configuration and control for all pages + + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal.h" +/** @addtogroup STM32L0XX_HAL_Driver + * @{ + */ + +/** @defgroup FLASHEx HAL FLASH Driver + * @brief FLASH HAL Extension module driver + * @{ + */ + +#ifdef HAL_FLASH_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +#define HAL_FLASH_TIMEOUT_VALUE ((uint32_t)0x50000 +#define WRP01_MASK ((uint32_t)0x0000FFFF) +#define PAGESIZE ((uint32_t)0x00000080) + +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/*Variables used for Erase sectors under interruption*/ +extern FLASH_ProcessTypeDef pFlash; + +/* Private function prototypes -----------------------------------------------*/ +static HAL_StatusTypeDef FLASH_OB_PCROPConfig(uint32_t OB_WRP, FunctionalState NewState); +static HAL_StatusTypeDef FLASH_OB_PCROPSelectionConfig(uint16_t OB_PcROP); +static HAL_StatusTypeDef FLASH_OB_BootConfig(uint16_t OB_BOOT); +static HAL_StatusTypeDef DATA_EEPROM_FastProgramByte(uint32_t Address, uint8_t Data); +static HAL_StatusTypeDef DATA_EEPROM_FastProgramHalfWord(uint32_t Address, uint16_t Data); +static HAL_StatusTypeDef DATA_EEPROM_FastProgramWord(uint32_t Address, uint32_t Data); +static HAL_StatusTypeDef DATA_EEPROM_ProgramByte(uint32_t Address, uint8_t Data); +static HAL_StatusTypeDef DATA_EEPROM_ProgramHalfWord(uint32_t Address, uint16_t Data); +static HAL_StatusTypeDef DATA_EEPROM_ProgramWord(uint32_t Address, uint32_t Data); +static uint8_t FLASH_OB_GetUser(void); +static uint32_t FLASH_OB_GetWRP(void); +static FlagStatus FLASH_OB_GetRDP(void); +static uint8_t FLASH_OB_GetBOR(void); +static HAL_StatusTypeDef FLASH_OB_WRPConfig(uint32_t OB_WRP, FunctionalState NewState); +static HAL_StatusTypeDef FLASH_OB_RDPConfig(uint8_t OB_RDP); +static HAL_StatusTypeDef FLASH_OB_UserConfig(uint8_t OB_IWDG, uint8_t OB_STOP, uint8_t OB_STDBY); +static HAL_StatusTypeDef FLASH_OB_BORConfig(uint8_t OB_BOR); + +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup Extended_FLASHEx_Private_Functions Extended FLASH Private functions + * @{ + */ + +/** @defgroup HAL_FLASHEx_Group1 Peripheral extended features functions + * @brief Data transfers functions + * +@verbatim + =============================================================================== + ##### Extended Features functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to manage the FLASH data + transfers. + +@endverbatim + * @{ + */ + +/** + * @brief Program option bytes + * @param pAdvOBInit: pointer to an FLASH_AdvOBProgramInitTypeDef structure that + * contains the configuration information for the programming. + * + * @retval HAL_StatusTypeDef HAL Status + */ +HAL_StatusTypeDef HAL_FLASHEx_AdvOBProgram (FLASH_AdvOBProgramInitTypeDef *pAdvOBInit) +{ + HAL_StatusTypeDef status = HAL_ERROR; + + /* Check the parameters */ + assert_param(IS_OBEX(pAdvOBInit->OptionType)); + + /*Program PCROP option byte*/ + if ((pAdvOBInit->OptionType&OBEX_PCROP) == OBEX_PCROP) + { + /* Check the parameters */ + assert_param(IS_PCROPSTATE(pAdvOBInit->PCROPState)); + if (pAdvOBInit->PCROPState == PCROPSTATE_ENABLE) + { + /*Enable of Write protection on the selected Sector*/ + status = FLASH_OB_PCROPConfig(pAdvOBInit->Pages, ENABLE); + status = FLASH_OB_PCROPSelectionConfig(OB_PCROP_SELECTED); + } + else + { + /*Disable of Write protection on the selected Sector*/ + status = FLASH_OB_PCROPConfig(pAdvOBInit->Pages, DISABLE); + status = FLASH_OB_PCROPSelectionConfig(OB_PCROP_DESELECTED); + } + } + /*Program BOOT config option byte*/ + if ((pAdvOBInit->OptionType&OBEX_BOOTCONFIG) == OBEX_BOOTCONFIG) + { + status = FLASH_OB_BootConfig(pAdvOBInit->BootConfig); + } + + return status; +} + +/** + * @brief Get the OBEX byte configuration + * @param pAdvOBInit: pointer to an FLASH_AdvOBProgramInitTypeDef structure that + * contains the configuration information for the programming. + * + * @retval None + */ +void HAL_FLASHEx_AdvOBGetConfig(FLASH_AdvOBProgramInitTypeDef *pAdvOBInit) +{ + pAdvOBInit->OptionType = OBEX_PCROP| OBEX_BOOTCONFIG; + /*Get PCROP state */ + pAdvOBInit->PCROPState = (FLASH->OBR & 0x00000100) >> 8; + /*Get PCROP protected Pages */ + pAdvOBInit->Pages = FLASH->WRPR; + /*Get Boot config OB*/ + pAdvOBInit->BootConfig = (FLASH->OBR & 0x80000000) >> 24; +} + +/** @defgroup HAL_FLASHEx_Group2 DATA EEPROM Programming functions + * @brief DATA EEPROM Programming functions + * +@verbatim + =============================================================================== + ##### DATA EEPROM Programming functions ##### + =============================================================================== + + [..] The DATA_EEPROM Programming_Functions, includes the following functions: + (+) HAL_DATA_EEPROMEx_Unlock(void); + (+) HAL_DATA_EEPROMEx_Lock(void); + (+) HAL_DATA_EEPROMEx_Erase(uint32_t Address) + (+) HAL_DATA_EEPROMEx_Program(uint32_t TypeProgram, uint32_t Address, uint32_t Data) + + [..] Any operation of erase or program should follow these steps: + (#) Call the HAL_DATA_EEPROMEx_Unlock() function to enable the data EEPROM access + and Flash program erase control register access. + (#) Call the desired function to erase or program data. + (#) Call the HAL_DATA_EEPROMEx_Lock() to disable the data EEPROM access + and Flash program erase control register access(recommended + to protect the DATA_EEPROM against possible unwanted operation). + +@endverbatim + * @{ + */ +/** + * @brief Unlocks the data memory and FLASH_PECR register access. + * @param None + * @retval HAL_StatusTypeDef HAL Status + */ +HAL_StatusTypeDef HAL_DATA_EEPROMEx_Unlock(void) +{ + if((FLASH->PECR & FLASH_PECR_PELOCK) != RESET) + { + /* Unlocking the Data memory and FLASH_PECR register access*/ + FLASH->PEKEYR = FLASH_PEKEY1; + FLASH->PEKEYR = FLASH_PEKEY2; + } + else + { + return HAL_ERROR; + } + return HAL_OK; +} + +/** + * @brief Locks the Data memory and FLASH_PECR register access. + * @param None + * @retval HAL_StatusTypeDef HAL Status + */ +HAL_StatusTypeDef HAL_DATA_EEPROMEx_Lock(void) +{ + /* Set the PELOCK Bit to lock the data memory and FLASH_PECR register access */ + FLASH->PECR |= FLASH_PECR_PELOCK; + + return HAL_OK; +} + +/** + * @brief Erase a word in data memory. + * @param Address: specifies the address to be erased. + * @note To correctly run this function, the DATA_EEPROM_Unlock() function + * must be called before. + * Call the DATA_EEPROM_Lock() to the data EEPROM access + * and Flash program erase control register access(recommended to protect + * the DATA_EEPROM against possible unwanted operation). + * @retval FLASH Status: The returned value can be: + * FLASH_ERROR_PROGRAM, FLASH_ERROR_WRP, FLASH_COMPLETE or FLASH_TIMEOUT. + */ +HAL_StatusTypeDef HAL_DATA_EEPROMEx_Erase(uint32_t Address) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Check the parameters */ + assert_param(IS_FLASH_DATA_ADDRESS(Address)); + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE)); + + if(status == HAL_OK) + { + /* Write "00000000h" to valid address in the data memory" */ + *(__IO uint32_t *) Address = 0x00000000; + } + + /* Return the erase status */ + return status; +} + +/** + * @brief Program word at a specified address + * @param TypeProgram: Indicate the way to program at a specified address. + * This parameter can be a value of @ref FLASH_Type_Program + * @param Address: specifies the address to be programmed. + * @param Data: specifies the data to be programmed + * + * @retval HAL_StatusTypeDef HAL Status + */ + +HAL_StatusTypeDef HAL_DATA_EEPROMEx_Program(uint32_t TypeProgram, uint32_t Address, uint32_t Data) +{ + HAL_StatusTypeDef status = HAL_ERROR; + + /* Process Locked */ + __HAL_LOCK(&pFlash); + + /* Check the parameters */ + assert_param(IS_TYPEPROGRAM(TypeProgram)); + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE)); + + if(status == HAL_OK) + { + if(TypeProgram == TYPEPROGRAM_FASTBYTE) + { + /*Program word (8-bit) at a specified address.*/ + DATA_EEPROM_FastProgramByte(Address, (uint8_t) Data); + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE)); + } + + if(TypeProgram == TYPEPROGRAM_FASTHALFWORD) + { + /*Program word (16-bit) at a specified address.*/ + DATA_EEPROM_FastProgramHalfWord(Address, (uint16_t) Data); + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE)); + } + if(TypeProgram == TYPEPROGRAM_FASTWORD) + { + /*Program word (32-bit) at a specified address.*/ + DATA_EEPROM_FastProgramWord(Address, (uint32_t) Data); + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE)); + } + if(TypeProgram == TYPEPROGRAM_WORD) + { + /*Program word (32-bit) at a specified address.*/ + DATA_EEPROM_ProgramWord(Address, (uint32_t) Data); + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE)); + } + + if(TypeProgram == TYPEPROGRAM_HALFWORD) + { + /*Program word (16-bit) at a specified address.*/ + DATA_EEPROM_ProgramHalfWord(Address, (uint16_t) Data); + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE)); + } + + if(TypeProgram == TYPEPROGRAM_BYTE) + { + /*Program word (8-bit) at a specified address.*/ + DATA_EEPROM_ProgramByte(Address, (uint8_t) Data); + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE)); + } + } + /* Process Unlocked */ + __HAL_UNLOCK(&pFlash); + + return status; +} + +/** + * @brief Erase the specified FLASH memory Pages + * @param[in] pEraseInit: pointer to an FLASH_EraseInitTypeDef structure that + * contains the configuration information for the erasing. + * + * @param[out] PageError: pointer to variable that + * contains the configuration information on faulty sector in case of error + * (0xFFFFFFFF means that all the sectors have been correctly erased) + * + * @retval HAL_StatusTypeDef HAL Status + */ +HAL_StatusTypeDef HAL_FLASHEx_Erase(FLASH_EraseInitTypeDef *pEraseInit, uint32_t *PageError) +{ + HAL_StatusTypeDef status = HAL_ERROR; + uint32_t index = 0; + + /* Process Locked */ + __HAL_LOCK(&pFlash); + + /* Check the parameters */ + assert_param(IS_TYPEERASE(pEraseInit->TypeErase)); + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE)); + + if (status == HAL_OK) + { + /*Initialization of PageError variable*/ + *PageError = 0xFFFFFFFF; + + /* Check the parameters */ + assert_param(IS_NBPAGES(pEraseInit->NbPages + pEraseInit->Page)); + + /* Erase by sector by sector to be done*/ + for(index = pEraseInit->Page; index < ((pEraseInit->NbPages*PAGESIZE)+ pEraseInit->Page); index+=PAGESIZE) + { + FLASH_Erase_Page(index); + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE)); + + /* If the erase operation is completed, disable the ERASE Bit */ + FLASH->PECR &= (~FLASH_PECR_PROG); + FLASH->PECR &= (~FLASH_PECR_ERASE); + + if (status != HAL_OK) + { + /* In case of error, stop erase procedure and return the faulty sector*/ + *PageError = index; + break; + } + } + } + + /* Process Unlocked */ + __HAL_UNLOCK(&pFlash); + + return status; +} + +/** + * @brief Perform a page erase of the specified FLASH memory pages with interrupt enabled + * @param pEraseInit: pointer to an FLASH_EraseInitTypeDef structure that + * contains the configuration information for the erasing. + * + * @retval HAL_StatusTypeDef HAL Status + */ +HAL_StatusTypeDef HAL_FLASHEx_Erase_IT(FLASH_EraseInitTypeDef *pEraseInit) +{ + HAL_StatusTypeDef status = HAL_OK; + + /* Process Locked */ + __HAL_LOCK(&pFlash); + + /* Check the parameters */ + assert_param(IS_TYPEERASE(pEraseInit->TypeErase)); + + /* Enable End of FLASH Operation interrupt */ + __HAL_FLASH_ENABLE_IT(FLASH_IT_EOP); + + /* Enable Error source interrupt */ + __HAL_FLASH_ENABLE_IT(FLASH_IT_ERR); + + /* Clear pending flags (if any) */ + __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP | FLASH_FLAG_ENDHV | FLASH_FLAG_WRPERR |\ + FLASH_FLAG_PGAERR | FLASH_FLAG_SIZERR| FLASH_FLAG_OPTVERR |\ + FLASH_FLAG_RDERR | FLASH_FLAG_NOTZEROERR); + + if (pEraseInit->TypeErase == TYPEERASE_PAGEERASE) + { + /* Erase by sector to be done*/ + + /* Check the parameters */ + assert_param(IS_NBPAGES(pEraseInit->NbPages + pEraseInit->Page)); + + pFlash.ProcedureOnGoing = FLASH_PROC_PAGEERASE; + pFlash.NbPagesToErase = pEraseInit->NbPages; + pFlash.Page = pEraseInit->Page; + + /*Erase 1st page and wait for IT*/ + FLASH_Erase_Page(pEraseInit->Page); + } + + return status; +} + + +/** + * @brief Program option bytes + * @param pOBInit: pointer to an FLASH_OBInitStruct structure that + * contains the configuration information for the programming. + * + * @retval HAL_StatusTypeDef HAL Status + */ +HAL_StatusTypeDef HAL_FLASHEx_OBProgram(FLASH_OBProgramInitTypeDef *pOBInit) +{ + HAL_StatusTypeDef status = HAL_ERROR; + + /* Process Locked */ + __HAL_LOCK(&pFlash); + + /* Check the parameters */ + assert_param(IS_OPTIONBYTE(pOBInit->OptionType)); + + /*Write protection configuration*/ + if((pOBInit->OptionType & OPTIONBYTE_WRP) == OPTIONBYTE_WRP) + { + assert_param(IS_WRPSTATE(pOBInit->WRPState)); + if (pOBInit->WRPState == WRPSTATE_ENABLE) + { + /*Enable of Write protection on the selected Sector*/ + status = FLASH_OB_WRPConfig(pOBInit->WRPSector, ENABLE); + } + else + { + /*Disable of Write protection on the selected Sector*/ + status = FLASH_OB_WRPConfig(pOBInit->WRPSector, DISABLE); + } + } + + /* Read protection configuration*/ + if((pOBInit->OptionType & OPTIONBYTE_RDP) == OPTIONBYTE_RDP) + { + status = FLASH_OB_RDPConfig(pOBInit->RDPLevel); + } + + /* USER configuration*/ + if((pOBInit->OptionType & OPTIONBYTE_USER) == OPTIONBYTE_USER) + { + status = FLASH_OB_UserConfig(pOBInit->USERConfig&OB_IWDG_SW, + pOBInit->USERConfig&OB_STOP_NoRST, + pOBInit->USERConfig&OB_STDBY_NoRST); + } + + /* BOR Level configuration*/ + if((pOBInit->OptionType & OPTIONBYTE_BOR) == OPTIONBYTE_BOR) + { + status = FLASH_OB_BORConfig(pOBInit->BORLevel); + } + /* Process Unlocked */ + __HAL_UNLOCK(&pFlash); + + return status; +} + +/** + * @brief Get the Option byte configuration + * @param pOBInit: pointer to an FLASH_OBInitStruct structure that + * contains the configuration information for the programming. + * + * @retval None + */ +void HAL_FLASHEx_OBGetConfig(FLASH_OBProgramInitTypeDef *pOBInit) +{ + pOBInit->OptionType = OPTIONBYTE_WRP | OPTIONBYTE_RDP | OPTIONBYTE_USER | OPTIONBYTE_BOR; + + /*Get WRP*/ + pOBInit->WRPSector = FLASH_OB_GetWRP(); + + /*Get RDP Level*/ + pOBInit->RDPLevel = FLASH_OB_GetRDP(); + + /*Get USER*/ + pOBInit->USERConfig = FLASH_OB_GetUser(); + + /*Get BOR Level*/ + pOBInit->BORLevel = FLASH_OB_GetBOR(); +} + + +/** + * @brief Returns the FLASH User Option Bytes values. + * @param None + * @retval The FLASH User Option Bytes. + */ +static uint8_t FLASH_OB_GetUser(void) +{ + /* Return the User Option Byte */ + return (uint8_t)(FLASH->OBR >> 20); +} + +/** + * @brief Returns the FLASH Write Protection Option Bytes value. + * @param None + * @retval The FLASH Write Protection Option Bytes value. + */ +static uint32_t FLASH_OB_GetWRP(void) +{ + /* Return the FLASH write protection Register value */ + return (uint32_t)(FLASH->WRPR); +} + +/** + * @brief Checks whether the FLASH Read out Protection Status is set or not. + * @param None + * @retval FLASH ReadOut Protection Status(SET or RESET). + */ +static FlagStatus FLASH_OB_GetRDP(void) +{ + FlagStatus readstatus = RESET; + + if ((uint8_t)(FLASH->OBR) != (uint8_t)OB_RDP_Level_0) + { + readstatus = SET; + } + else + { + readstatus = RESET; + } + return readstatus; +} + +/** + * @brief Returns the FLASH BOR level. + * @param None + * @retval The FLASH User Option Bytes. + */ +static uint8_t FLASH_OB_GetBOR(void) +{ + /* Return the BOR level */ + return (uint8_t)((FLASH->OBR & (uint32_t)0x000F0000) >> 16); +} + +/** + * @brief Write protects the desired pages of the first 64KB of the Flash. + * @param OB_WRP: specifies the address of the pages to be write protected. + * This parameter can be: + * @arg value between OB_WRP_Pages0to31 and OB_WRP_Pages480to511 + * @arg OB_WRP_AllPages + * @param NewState: new state of the specified FLASH Pages Wtite protection. + * This parameter can be: ENABLE or DISABLE. + * @retval HAL_StatusTypeDef + */ +static HAL_StatusTypeDef FLASH_OB_WRPConfig(uint32_t OB_WRP, FunctionalState NewState) +{ + HAL_StatusTypeDef status = HAL_OK; + uint32_t WRP01_Data = 0; + uint32_t tmp1 = 0; + + /* Check the parameters */ + assert_param(IS_OB_WRP(OB_WRP)); + assert_param(IS_FUNCTIONAL_STATE(NewState)); + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE)); + + if(status == HAL_OK) + { + if (NewState != DISABLE) + { + WRP01_Data = (uint16_t)(((OB_WRP & WRP01_MASK) | OB->WRP01)); + tmp1 = (uint32_t)(~(WRP01_Data) << 16)|(WRP01_Data); + OB->WRP01 = tmp1; + } + else + { + WRP01_Data = (uint16_t)(~OB_WRP & (WRP01_MASK & OB->WRP01)); + tmp1 = (uint32_t)((~WRP01_Data) << 16)|(WRP01_Data); + OB->WRP01 = tmp1; + } + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation(HAL_FLASH_TIMEOUT_VALUE)); + } + + /* Return the write protection operation Status */ + return status; +} +/** + * @brief Enables or disables the read out protection. + * @note To correctly run this function, the FLASH_OB_Unlock() function + * must be called before. + * @param FLASH_ReadProtection_Level: specifies the read protection level. + * This parameter can be: + * @arg OB_RDP_Level_0: No protection + * @arg OB_RDP_Level_1: Read protection of the memory + * @arg OB_RDP_Level_2: Chip protection + * + * !!!Warning!!! When enabling OB_RDP_Level_2 it's no more possible to go back to level 1 or 0 + * + * @retval FLASH Status: The returned value can be: + * FLASH_ERROR_PROGRAM, FLASH_ERROR_WRP, FLASH_COMPLETE or FLASH_TIMEOUT. + */ +static HAL_StatusTypeDef FLASH_OB_RDPConfig(uint8_t OB_RDP) +{ + HAL_StatusTypeDef status = HAL_OK; + uint8_t tmp1 = 0; + uint32_t tmp2 = 0; + + /* Check the parameters */ + assert_param(IS_OB_RDP(OB_RDP)); + status = FLASH_WaitForLastOperation(HAL_FLASH_TIMEOUT_VALUE)); + + /* calculate the option byte to write */ + tmp1 = (uint8_t)(~(OB_RDP )); + tmp2 = (uint32_t)(((uint32_t)((uint32_t)(tmp1) << 16)) | ((uint32_t)OB_RDP)); + + if(status == HAL_OK) + { + /* program read protection level */ + OB->RDP = tmp2; + } + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE)); + + /* Return the Read protection operation Status */ + return status; +} + +/** + * @brief Programs the FLASH User Option Byte: IWDG_SW / RST_STOP / RST_STDBY. + * @param OB_IWDG: Selects the WDG mode. + * This parameter can be one of the following values: + * @arg OB_IWDG_SW: Software WDG selected + * @arg OB_IWDG_HW: Hardware WDG selected + * @param OB_STOP: Reset event when entering STOP mode. + * This parameter can be one of the following values: + * @arg OB_STOP_NoRST: No reset generated when entering in STOP + * @arg OB_STOP_RST: Reset generated when entering in STOP + * @param OB_STDBY: Reset event when entering Standby mode. + * This parameter can be one of the following values: + * @arg OB_STDBY_NoRST: No reset generated when entering in STANDBY + * @arg OB_STDBY_RST: Reset generated when entering in STANDBY + * @retval FLASH Status: The returned value can be: + * FLASH_ERROR_PROGRAM, FLASH_ERROR_WRP, FLASH_COMPLETE or FLASH_TIMEOUT. + */ +static HAL_StatusTypeDef FLASH_OB_UserConfig(uint8_t OB_IWDG, uint8_t OB_STOP, uint8_t OB_STDBY) +{ + HAL_StatusTypeDef status = HAL_OK; + uint32_t tmp = 0, tmp1 = 0; + + /* Check the parameters */ + assert_param(IS_OB_IWDG_SOURCE(OB_IWDG)); + assert_param(IS_OB_STOP_SOURCE(OB_STOP)); + assert_param(IS_OB_STDBY_SOURCE(OB_STDBY)); + + /* Get the User Option byte register */ + tmp1 = (FLASH->OBR & 0x800F0000) >> 16; + + /* Calculate the user option byte to write */ + tmp = (uint32_t)(((uint32_t)~((uint32_t)((uint32_t)(OB_IWDG) | (uint32_t)(OB_STOP) | (uint32_t)(OB_STDBY) | tmp1))) << 16); + tmp |= ((uint32_t)(OB_IWDG) | ((uint32_t)OB_STOP) | (uint32_t)(OB_STDBY) | tmp1); + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE)); + + if(status == HAL_OK) + { + /* Write the User Option Byte */ + OB->USER = tmp; + } + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE)); + + /* Return the Option Byte program Status */ + return status; +} + +/** + * @brief Programs the FLASH brownout reset threshold level Option Byte. + * @param OB_BOR: Selects the brownout reset threshold level. + * This parameter can be one of the following values: + * @arg OB_BOR_OFF: BOR is disabled at power down, the reset is asserted when the VDD + * power supply reaches the PDR(Power Down Reset) threshold (1.5V) + * @arg OB_BOR_LEVEL1: BOR Reset threshold levels for 1.7V - 1.8V VDD power supply + * @arg OB_BOR_LEVEL2: BOR Reset threshold levels for 1.9V - 2.0V VDD power supply + * @arg OB_BOR_LEVEL3: BOR Reset threshold levels for 2.3V - 2.4V VDD power supply + * @arg OB_BOR_LEVEL4: BOR Reset threshold levels for 2.55V - 2.65V VDD power supply + * @arg OB_BOR_LEVEL5: BOR Reset threshold levels for 2.8V - 2.9V VDD power supply + * @retval FLASH Status: The returned value can be: + * FLASH_ERROR_PROGRAM, FLASH_ERROR_WRP, FLASH_COMPLETE or FLASH_TIMEOUT. + */ +static HAL_StatusTypeDef FLASH_OB_BORConfig(uint8_t OB_BOR) +{ + HAL_StatusTypeDef status = HAL_OK; + uint32_t tmp = 0, tmp1 = 0; + + /* Check the parameters */ + assert_param(IS_OB_BOR_LEVEL(OB_BOR)); + + /* Get the User Option byte register */ + tmp1 = (FLASH->OBR & 0x000F0000) >> 16; + + /* Calculate the option byte to write */ + tmp = (uint32_t)~(OB_BOR | tmp1)<<16; + tmp |= (OB_BOR | tmp1); + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE)); + + if(status == HAL_OK) + { + /* Write the BOR Option Byte */ + OB->USER = tmp; + } + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE)); + + /* Return the Option Byte program Status */ + return status; +} + +/** + * @} + */ +/** + * @brief Enables or disables the read/write protection (PCROP) of the desired + * sectors, for the first 64KB of the Flash. + * @param OB_WRP: specifies the address of the pages to be write protected. + * This parameter can be: + * @arg value between OB_WRP_Pages0to31 and OB_WRP_Pages480to511 + * @arg OB_WRP_AllPages + * @param NewState: new state of the specified FLASH Pages Write protection. + * This parameter can be: ENABLE or DISABLE. + * @retval FLASH Status: The returned value can be: + * FLASH_ERROR_PROGRAM, FLASH_ERROR_WRP, FLASH_COMPLETE or FLASH_TIMEOUT. + */ +static HAL_StatusTypeDef FLASH_OB_PCROPConfig(uint32_t OB_WRP, FunctionalState NewState) +{ + HAL_StatusTypeDef status = HAL_OK; + uint32_t WRP01_Data = 0; + uint32_t tmp1 = 0; + + /* Check the parameters */ + assert_param(IS_OB_WRP(OB_WRP)); + assert_param(IS_FUNCTIONAL_STATE(NewState)); + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE)); + + if(status == HAL_OK) + { + if (NewState != DISABLE) + { + WRP01_Data = (uint16_t)(~OB_WRP & (WRP01_MASK & OB->WRP01)); + + tmp1 = (uint32_t)((~WRP01_Data) << 16)|(WRP01_Data); + OB->WRP01 = tmp1; + } + + else + { + WRP01_Data = (uint16_t)((OB_WRP & WRP01_MASK) | OB->WRP01); + + tmp1 = (uint32_t)(~(WRP01_Data) << 16)|(WRP01_Data); + OB->WRP01 = tmp1; + } + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE)); + } + + /* Return the write protection operation Status */ + return status; +} + +/** + * @brief Select the Protection Mode (SPRMOD). + * @note Once SPRMOD bit is active, unprotection of a protected sector is not possible + * @note Read a protected sector will set RDERR Flag and write a protected sector will set WRPERR Flag + * @param OB_PcROP: Select the Protection Mode of WPR bits. + * This parameter can be: + * @arg OB_PCROP_SELECTED: nWRP control the read&write protection (PcROP) of respective user sectors. + * @arg OB_PCROP_DESELECTED: nWRP control the write protection of respective user sectors. + * @retval FLASH Status: The returned value can be: + * FLASH_ERROR_PROGRAM, FLASH_ERROR_WRP, FLASH_COMPLETE or FLASH_TIMEOUT. + */ +static HAL_StatusTypeDef FLASH_OB_PCROPSelectionConfig(uint16_t OB_PcROP) +{ + HAL_StatusTypeDef status = HAL_OK; + uint16_t tmp1 = 0; + uint32_t tmp2 = 0; + uint8_t optiontmp = 0; + uint16_t optiontmp2 = 0; + + /* Check the parameters */ + assert_param(IS_OB_PCROP_SELECT(OB_PcROP)); + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE)); + + /* Mask RDP Byte */ + optiontmp = (uint8_t)(*(__IO uint8_t *)(OB_BASE)); + + /* Update Option Byte */ + optiontmp2 = (uint16_t)(OB_PcROP | optiontmp); + + + /* calculate the option byte to write */ + tmp1 = (uint16_t)(~(optiontmp2 )); + tmp2 = (uint32_t)(((uint32_t)((uint32_t)(tmp1) << 16)) | ((uint32_t)optiontmp2)); + + if(status == HAL_OK) + { + /* program PCRop */ + OB->RDP = tmp2; + } + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation(HAL_FLASH_TIMEOUT_VALUE)); + + /* Return the Read protection operation Status */ + return status; +} + +/** + * @brief Sets or resets the BOOT1 option bit. + * @param OB_BOOT1: Set or Reset the BOOT1 option bit. + * This parameter can be one of the following values: + * @arg OB_BOOT1_RESET: BOOT1 option bit reset + * @arg OB_BOOT1_SET: BOOT1 option bit set + * @retval None + */ +static HAL_StatusTypeDef FLASH_OB_BootConfig(uint16_t OB_BOOT) +{ + HAL_StatusTypeDef status = HAL_OK; + uint32_t tmp = 0, tmp1 = 0; + + /* Check the parameters */ + assert_param(IS_OB_BOOT1(OB_BOOT)); + + /* Get the User Option byte register */ + tmp1 = (FLASH->OBR & 0x007F0000) >> 16; + + /* Calculate the option byte to write */ + tmp = (uint32_t)~(OB_BOOT | tmp1)<<16; + tmp |= (OB_BOOT | tmp1); + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE)); + + if(status == HAL_OK) + { + /* Write the BOOT Option Byte */ + OB->USER = tmp; + } + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE)); + + /* Return the Option Byte program Status */ + return status; +} + +/** + * @brief Write a Byte at a specified address in data memory. + * @note To correctly run this function, the DATA_EEPROM_Unlock() function + * must be called before. + * Call the DATA_EEPROM_Lock() to the data EEPROM access + * and Flash program erase control register access(recommended to protect + * the DATA_EEPROM against possible unwanted operation). + * @param Address: specifies the address to be written. + * @param Data: specifies the data to be written. + * @note This function assumes that data word is already erased. + * @retval FLASH Status: The returned value can be: + * FLASH_ERROR_PROGRAM, FLASH_ERROR_WRP, FLASH_COMPLETE or FLASH_TIMEOUT. + */ +static HAL_StatusTypeDef DATA_EEPROM_FastProgramByte(uint32_t Address, uint8_t Data) +{ + HAL_StatusTypeDef status = HAL_ERROR; + + /* Check the parameters */ + assert_param(IS_FLASH_DATA_ADDRESS(Address)); + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE)); + + if(status == HAL_OK) + { + /* Clear the FTDW bit */ + FLASH->PECR &= (uint32_t)(~((uint32_t)FLASH_PECR_FTDW)); + + /* If the previous operation is completed, proceed to write the new Data */ + *(__IO uint8_t *)Address = Data; + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE)); + } + /* Return the Write Status */ + return status; +} + +/** + * @brief Writes a half word at a specified address in data memory. + * @note To correctly run this function, the DATA_EEPROM_Unlock() function + * must be called before. + * Call the DATA_EEPROM_Lock() to he data EEPROM access + * and Flash program erase control register access(recommended to protect + * the DATA_EEPROM against possible unwanted operation). + * @param Address: specifies the address to be written. + * @param Data: specifies the data to be written. + * @note This function assumes that the is data word is already erased. + * @retval FLASH Status: The returned value can be: + * FLASH_ERROR_PROGRAM, FLASH_ERROR_WRP, FLASH_COMPLETE or FLASH_TIMEOUT. + */ +static HAL_StatusTypeDef DATA_EEPROM_FastProgramHalfWord(uint32_t Address, uint16_t Data) +{ + HAL_StatusTypeDef status = HAL_ERROR; + + /* Check the parameters */ + assert_param(IS_FLASH_DATA_ADDRESS(Address)); + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE)); + + if(status == HAL_OK) + { + /* Clear the FTDW bit */ + FLASH->PECR &= (uint32_t)(~((uint32_t)FLASH_PECR_FTDW)); + + /* If the previous operation is completed, proceed to write the new data */ + *(__IO uint16_t *)Address = Data; + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE)); + } + /* Return the Write Status */ + return status; +} + +/** + * @brief Programs a word at a specified address in data memory. + * @note To correctly run this function, the DATA_EEPROM_Unlock() function + * must be called before. + * Call the DATA_EEPROM_Lock() to the data EEPROM access + * and Flash program erase control register access(recommended to protect + * the DATA_EEPROM against possible unwanted operation). + * @param Address: specifies the address to be written. + * @param Data: specifies the data to be written. + * @note This function assumes that the is data word is already erased. + * @retval FLASH Status: The returned value can be: + * FLASH_ERROR_PROGRAM, FLASH_ERROR_WRP, FLASH_COMPLETE or FLASH_TIMEOUT. + */ +static HAL_StatusTypeDef DATA_EEPROM_FastProgramWord(uint32_t Address, uint32_t Data) +{ + HAL_StatusTypeDef status = HAL_ERROR; + + /* Check the parameters */ + assert_param(IS_FLASH_DATA_ADDRESS(Address)); + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE)); + + if(status == HAL_OK) + { + /* Clear the FTDW bit */ + FLASH->PECR &= (uint32_t)(~((uint32_t)FLASH_PECR_FTDW)); + + /* If the previous operation is completed, proceed to program the new data */ + *(__IO uint32_t *)Address = Data; + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE)); + } + /* Return the Write Status */ + return status; +} + +/** + * @brief Write a Byte at a specified address in data memory without erase. + * @note To correctly run this function, the DATA_EEPROM_Unlock() function + * must be called before. + * Call the DATA_EEPROM_Lock() to he data EEPROM access + * and Flash program erase control register access(recommended to protect + * the DATA_EEPROM against possible unwanted operation). + * @note The function DATA_EEPROM_FixedTimeProgramCmd() can be called before + * this function to configure the Fixed Time Programming. + * @param Address: specifies the address to be written. + * @param Data: specifies the data to be written. + * @retval FLASH Status: The returned value can be: + * FLASH_ERROR_PROGRAM, FLASH_ERROR_WRP, FLASH_COMPLETE or FLASH_TIMEOUT. + */ +static HAL_StatusTypeDef DATA_EEPROM_ProgramByte(uint32_t Address, uint8_t Data) +{ + HAL_StatusTypeDef status = HAL_ERROR; + + /* Check the parameters */ + assert_param(IS_FLASH_DATA_ADDRESS(Address)); + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE)); + + if(status == HAL_OK) + { + /* Set the FTDW bit */ + FLASH->PECR |= (uint32_t)FLASH_PECR_FTDW; + + *(__IO uint8_t *)Address = Data; + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE)); + } + /* Return the Write Status */ + return status; +} + +/** + * @brief Writes a half word at a specified address in data memory without erase. + * @note To correctly run this function, the DATA_EEPROM_Unlock() function + * must be called before. + * Call the DATA_EEPROM_Lock() to he data EEPROM access + * and Flash program erase control register access(recommended to protect + * the DATA_EEPROM against possible unwanted operation). + * @note The function DATA_EEPROM_FixedTimeProgramCmd() can be called before + * this function to configure the Fixed Time Programming + * @param Address: specifies the address to be written. + * @param Data: specifies the data to be written. + * @retval FLASH Status: The returned value can be: + * FLASH_ERROR_PROGRAM, FLASH_ERROR_WRP, FLASH_COMPLETE or FLASH_TIMEOUT. + */ +static HAL_StatusTypeDef DATA_EEPROM_ProgramHalfWord(uint32_t Address, uint16_t Data) +{ + HAL_StatusTypeDef status = HAL_ERROR; + + /* Check the parameters */ + assert_param(IS_FLASH_DATA_ADDRESS(Address)); + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE)); + + if(status == HAL_OK) + { + /* Set the FTDW bit */ + FLASH->PECR |= (uint32_t)FLASH_PECR_FTDW; + + *(__IO uint16_t *)Address = Data; + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE)); + } + /* Return the Write Status */ + return status; +} + +/** + * @brief Programs a word at a specified address in data memory without erase. + * @note To correctly run this function, the DATA_EEPROM_Unlock() function + * must be called before. + * Call the DATA_EEPROM_Lock() to he data EEPROM access + * and Flash program erase control register access(recommended to protect + * the DATA_EEPROM against possible unwanted operation). + * @note The function DATA_EEPROM_FixedTimeProgramCmd() can be called before + * this function to configure the Fixed Time Programming. + * @param Address: specifies the address to be written. + * @param Data: specifies the data to be written. + * @retval FLASH Status: The returned value can be: + * FLASH_ERROR_PROGRAM, FLASH_ERROR_WRP, FLASH_COMPLETE or FLASH_TIMEOUT. + */ +static HAL_StatusTypeDef DATA_EEPROM_ProgramWord(uint32_t Address, uint32_t Data) +{ + HAL_StatusTypeDef status = HAL_ERROR; + + /* Check the parameters */ + assert_param(IS_FLASH_DATA_ADDRESS(Address)); + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE)); + + if(status == HAL_OK) + { + /* Set the FTDW bit */ + FLASH->PECR |= (uint32_t)FLASH_PECR_FTDW; + + *(__IO uint32_t *)Address = Data; + + /* Wait for last operation to be completed */ + status = FLASH_WaitForLastOperation((uint32_t)HAL_FLASH_TIMEOUT_VALUE)); + } + /* Return the Write Status */ + return status; +} + + +/** + * @} + */ + +/** + * @} + */ +#endif /* HAL_FLASH_MODULE_ENABLED */ + + + +/** + * @} + */ + +/** + * @} + */ + + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ + + diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_flash_ex.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_flash_ex.h new file mode 100644 index 0000000000..072c385a92 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_flash_ex.h @@ -0,0 +1,289 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_flash_ex.h + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief Header file of FLASH HAL Extension module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32L0xx_HAL_FLASH_EX_H +#define __STM32L0xx_HAL_FLASH_EX_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal_def.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @addtogroup FLASHEx + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/** + * @brief FLASH Advanced Option Bytes Program structure definition + */ +typedef struct +{ + uint32_t OptionType; /*!< OptionType: Option byte to be configured for extension . + This parameter can be a value of @ref FLASHEx_OptionEx_Type */ + + uint32_t PCROPState; /*!< PCROPState: PCROP activation or deactivation. + This parameter can be a value of @ref FLASHEx_PCROP_State */ + + uint16_t Pages; /*!< Sectors: specifies the sector(s) set for PCROP + This parameter can be a value of @ref FLASHEx_Option_Bytes_PC_ReadWrite_Protection */ + + uint16_t BootConfig; /*!< BootConfig: specifies Option bytes for boot config + This parameter can be a value of @ref FLASHEx_Dual_Boot */ +} FLASH_AdvOBProgramInitTypeDef; + +/* Exported constants --------------------------------------------------------*/ + +/** @defgroup FLASHEx_Exported_Constants FLASH Exported Constants + * @{ + */ +/** @defgroup FLASHEx_PCROP_State FLASH PCROP State + * @{ + */ +#define PCROPSTATE_DISABLE ((uint32_t)0x00) /*!ACR, FLASH_ACR_LATENCY, (uint32_t)(__LATENCY__)) + +/** + * @brief Enable the FLASH prefetch buffer. + * @retval none + */ +#define __HAL_FLASH_PREFETCH_BUFFER_ENABLE() (FLASH->ACR |= FLASH_ACR_PRFTEN) + +/** + * @brief Disable the FLASH prefetch buffer. + * @retval none + */ +#define __HAL_FLASH_PREFETCH_BUFFER_DISABLE() (FLASH->ACR &= (~FLASH_ACR_PRFTEN)) + +/** + * @brief Enable the FLASH Buffer cache. + * @retval none + */ +#define __HAL_FLASH_BUFFER_CACHE_ENABLE() (FLASH->ACR &= (~FLASH_ACR_DISAB_BUF)) + +/** + * @brief Disable the FLASH Buffer cache. + * @retval none + */ +#define __HAL_FLASH_BUFFER_CACHE_DISABLE() (FLASH->ACR |= FLASH_ACR_DISAB_BUF) + +/** + * @brief Enable the FLASH preread buffer + * @retval none + */ +#define __HAL_FLASH_PREREAD_BUFFER_ENABLE() (FLASH->ACR |= FLASH_ACR_PRE_READ) + +/** + * @brief Disable the FLASH preread buffer + * @retval none + */ +#define __HAL_FLASH_PREREAD_BUFFER_DISABLE() (FLASH->ACR &= (~FLASH_ACR_PRE_READ)) + +/** + * @brief Enable the FLASH power down during Sleep mode + * @retval none + */ +#define __HAL_FLASH_SLEEP_POWERDOWN_ENABLE() SET_BIT(FLASH->ACR, FLASH_ACR_SLEEP_PD) + +/** + * @brief Disable the FLASH power down during Sleep mode + * @retval none + */ +#define __HAL_FLASH_SLEEP_POWERDOWN_DISABLE() CLEAR_BIT(FLASH->ACR, FLASH_ACR_SLEEP_PD) + +/** + * @brief Macro to enable or disable the Flash Run power down mode. + * @note Writing this bit to 0 this bit, automatically the keys are + * loss and a new unlock sequence is necessary to re-write it to 1. + */ + +#define __HAL_FLASH_POWER_DOWN_ENABLE() do { FLASH->PDKEYR = FLASH_PDKEY1; \ + FLASH->PDKEYR = FLASH_PDKEY2; \ + SET_BIT(FLASH->ACR, FLASH_ACR_RUN_PD); \ + } while (0) + +#define __HAL_FLASH_POWER_DOWN_DISABLE() do { FLASH->PDKEYR = FLASH_PDKEY1; \ + FLASH->PDKEYR = FLASH_PDKEY2; \ + CLEAR_BIT(FLASH->ACR, FLASH_ACR_RUN_PD); \ + } while (0) +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ + +/* I/O operation functions *****************************************************/ +/* Peripheral Control functions ************************************************/ +HAL_StatusTypeDef HAL_DATA_EEPROMEx_Unlock(void); +HAL_StatusTypeDef HAL_DATA_EEPROMEx_Lock(void); + +HAL_StatusTypeDef HAL_DATA_EEPROMEx_Erase(uint32_t Address); +HAL_StatusTypeDef HAL_DATA_EEPROMEx_Program(uint32_t TypeProgram, uint32_t Address, uint32_t Data); + +HAL_StatusTypeDef HAL_FLASHEx_Erase(FLASH_EraseInitTypeDef *pEraseInit, uint32_t *PageError); +HAL_StatusTypeDef HAL_FLASHEx_Erase_IT(FLASH_EraseInitTypeDef *pEraseInit); + +HAL_StatusTypeDef HAL_FLASHEx_OBProgram(FLASH_OBProgramInitTypeDef *pOBInit); +void HAL_FLASHEx_OBGetConfig(FLASH_OBProgramInitTypeDef *pOBInit); + +HAL_StatusTypeDef HAL_FLASHEx_AdvOBProgram (FLASH_AdvOBProgramInitTypeDef *pAdvOBInit); +void HAL_FLASHEx_AdvOBGetConfig(FLASH_AdvOBProgramInitTypeDef *pAdvOBInit); + + + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __STM32L0xx_HAL_FLASH_EX_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_flash_ramfunc.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_flash_ramfunc.c new file mode 100644 index 0000000000..c58bfcc6d6 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_flash_ramfunc.c @@ -0,0 +1,212 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_flash_ramfunc.c + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief FLASH RAMFUNC driver. + * This file provides a Flash firmware functions which should be + * executed from internal SRAM + * + FLASH HalfPage Programming + * + FLASH Power Down in Run mode + * + * @verbatim + + *** ARM Compiler *** + -------------------- + [..] RAM functions are defined using the toolchain options. + Functions that are be executed in RAM should reside in a separate + source module. Using the 'Options for File' dialog you can simply change + the 'Code / Const' area of a module to a memory space in physical RAM. + Available memory areas are declared in the 'Target' tab of the + Options for Target' dialog. + + *** ICCARM Compiler *** + ----------------------- + [..] RAM functions are defined using a specific toolchain keyword "__ramfunc". + + *** GNU Compiler *** + -------------------- + [..] RAM functions are defined using a specific toolchain attribute + "__attribute__((section(".RamFunc")))". + + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal.h" +/** @addtogroup STM32L0XX_HAL_Driver + * @{ + */ + +/** @defgroup FLASH_RAMFUNC Driver + * @brief FLASH functions executed from RAM + * @{ + */ + +#ifdef HAL_FLASH_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +static __RAM_FUNC FLASH_Program_HalfPage(uint32_t Address, uint32_t *Data); + +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup FLASH_RAMFUNC_Private_Functions + * @{ + */ + +/** @defgroup FLASH_RAMFUNC_Group1 Peripheral features functions + * @brief Data transfers functions + * +@verbatim + =============================================================================== + ##### ramfunc functions ##### + =============================================================================== + [..] + This subsection provides a set of functions that should be executed from RAM + transfers. + +@endverbatim + * @{ + */ + +/** + * @brief Program a half page word at a specified address, + * @note This function should be executed from RAM + * @param Address: specifies the address to be programmed, + * the address should be half page aligned. + * @param *Data: specifies the buffer of data to be programmed, + * the size of the buffer is 16 words. + * + * @retval HAL_StatusTypeDef HAL Status + */ +__RAM_FUNC FLASH_HalfPageProgram(uint32_t Address, uint32_t *Data) +{ + HAL_StatusTypeDef status = HAL_OK; + uint32_t timeout = 0xFFFFFFFF; + /*Program word (32-bit) at a specified address.*/ + FLASH_Program_HalfPage(Address, Data); + + /* Wait for a FLASH operation to complete or a TIMEOUT to occur */ + while(((FLASH->SR & FLASH_FLAG_BSY) != 0x00) && (timeout != 0x00)) + { + timeout--; + } + + /* Reset PROG bit */ + FLASH->PECR &= ~FLASH_PECR_PROG; + FLASH->PECR &= ~FLASH_PECR_FPRG; + return status; +} + +/** + * @brief Program a half page in program memory. + * @param Address: The Half page address in program memory to be written. + * @param Data: + * @retval None + */ +static __RAM_FUNC FLASH_Program_HalfPage(uint32_t Address, uint32_t *Data) +{ + HAL_StatusTypeDef status = HAL_OK; + uint32_t i =0; + + /* Set PROG bit */ + FLASH->PECR |= FLASH_PECR_PROG; + + /* Set FPRG bit */ + FLASH->PECR |= FLASH_PECR_FPRG; + + *(__IO uint32_t*)Address = Data[0]; + + for(i = 1; i <= 15; i++) + { + *(__IO uint32_t*)(Address + 4) = Data[i]; + } + return status; +} + +/** + * @brief Enable the Power down in Run Mode + * @note This fuction should be called and executed from SRAM memory + * @param None + * @retval None + */ +__RAM_FUNC FLASH_EnableRunPowerDown(void) +{ + /* Enable the Power Down in Run mode*/ + __HAL_FLASH_POWER_DOWN_ENABLE(); + + return HAL_OK; + +} + +/** + * @brief Disable the Power down in Run Mode + * @note This fuction should be called and executed from SRAM memory + * @param None + * @retval None + */ +__RAM_FUNC FLASH_DisableRunPowerDown(void) +{ + /* Disable the Power Down in Run mode*/ + __HAL_FLASH_POWER_DOWN_DISABLE(); + + return HAL_OK; +} + + +/** + * @} + */ + +/** + * @} + */ +#endif /* HAL_FLASH_MODULE_ENABLED */ + + + +/** + * @} + */ + +/** + * @} + */ + + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ + + diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_flash_ramfunc.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_flash_ramfunc.h new file mode 100644 index 0000000000..723df6037e --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_flash_ramfunc.h @@ -0,0 +1,85 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_flash_ramfunc.h + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief Header file of FLASH RAMFUNC driver. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32L0xx_FLASH_RAMFUNC_H +#define __STM32L0xx_FLASH_RAMFUNC_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal_def.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @addtogroup FLASH_RAMFUNC + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ + + +/* Exported functions --------------------------------------------------------*/ + +/* I/O operation functions *****************************************************/ +/* Peripheral Control functions ************************************************/ + + +__RAM_FUNC FLASH_HalfPageProgram(uint32_t Address, uint32_t *Data); +__RAM_FUNC FLASH_EnableRunPowerDown(void); +__RAM_FUNC FLASH_DisableRunPowerDown(void); + + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __STM32L0xx_FLASH_RAMFUNC_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_gpio.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_gpio.c new file mode 100644 index 0000000000..cafdee42ab --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_gpio.c @@ -0,0 +1,490 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_gpio.c + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief GPIO HAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the General Purpose Input/Output (GPIO) peripheral: + * + Initialization and de-initialization functions + * + IO operation functions + * + @verbatim + ============================================================================== + ##### GPIO Peripheral features ##### + ============================================================================== + [..] + (+) Each port bit of the general-purpose I/O (GPIO) ports can be individually + configured by software in several modes: + (++) Input mode + (++) Analog mode + (++) Output mode + (++) Alternate function mode + (++) External interrupt/event lines + + (+) During and just after reset, the alternate functions and external interrupt + lines are not active and the I/O ports are configured in input floating mode. + + (+) All GPIO pins have weak internal pull-up and pull-down resistors, which can be + activated or not. + + (+) In Output or Alternate mode, each IO can be configured on open-drain or push-pull + type and the IO speed can be selected depending on the VDD value. + + (+) The microcontroller IO pins are connected to onboard peripherals/modules through a + multiplexer that allows only one peripheral alternate function (AF) connected + to an IO pin at a time. In this way, there can be no conflict between peripherals + sharing the same IO pin. + + (+) All ports have external interrupt/event capability. To use external interrupt + lines, the port must be configured in input mode. All available GPIO pins are + connected to the 16 external interrupt/event lines from EXTI0 to EXTI15. + + (+) The external interrupt/event controller consists of up to 23 edge detectors + (16 lines are connected to GPIO) for generating event/interrupt requests (each + input line can be independently configured to select the type (interrupt or event) + and the corresponding trigger event (rising or falling or both). Each line can + also be masked independently. + + ##### How to use this driver ##### + ============================================================================== + [..] + (#) Enable the GPIO IOPORT clock using the following function: __GPIOx_CLK_ENABLE(). + + (#) In case of external interrupt/event mode selection, enable the SYSCFG clock + using the following function __SYSCFG_CLK_ENABLE(). + + (#) Configure the GPIO pin(s) using HAL_GPIO_Init(). + (++) Configure the IO mode using "Mode" member from GPIO_InitTypeDef structure + (++) Activate Pull-up, Pull-down resistor using "Pull" member from GPIO_InitTypeDef + structure. + (++) In case of Output or alternate function mode selection: the speed is + configured through "Speed" member from GPIO_InitTypeDef structure. + (++) In alternate mode is selection, the alternate function connected to the IO + is configured through "Alternate" member from GPIO_InitTypeDef structure. + (++) Analog mode is required when a pin is to be used as ADC channel + or DAC output. + (++) In case of external interrupt/event selection the "Mode" member from + GPIO_InitTypeDef structure select the type (interrupt or event) and + the corresponding trigger event (rising or falling or both). + + (#) In case of external interrupt/event mode selection, configure NVIC IRQ priority + mapped to the EXTI line using HAL_NVIC_SetPriority() and enable it using + HAL_NVIC_EnableIRQ(). + + (#) To get the level of a pin configured in input mode use HAL_GPIO_ReadPin(). + + (#) To set/reset the level of a pin configured in output mode use + HAL_GPIO_WritePin()/HAL_GPIO_TogglePin(). + + (#) During and just after reset, the alternate functions are not + active and the GPIO pins are configured in input floating mode (except JTAG + pins). + + (#) The LSE oscillator pins OSC32_IN and OSC32_OUT can be used as general purpose + (PC14 and PC15, respectively) when the LSE oscillator is off. The LSE has + priority over the GPIO function. + + (#) The HSE oscillator pins OSC_IN/OSC_OUT can be used as + general purpose PH0 and PH1, respectively, when the HSE oscillator is off. + The HSE has priority over the GPIO function. + + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @defgroup GPIO + * @brief GPIO HAL module driver + * @{ + */ + +#ifdef HAL_GPIO_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +#define __HAL_GET_GPIO_SOURCE(__GPIOx__) \ +(((uint32_t)(__GPIOx__) == ((uint32_t)GPIOA_BASE))? 0 :\ + ((uint32_t)(__GPIOx__) == ((uint32_t)(GPIOA_BASE + 0x0400)))? 1 :\ + ((uint32_t)(__GPIOx__) == ((uint32_t)(GPIOA_BASE + 0x0800)))? 2 :\ + ((uint32_t)(__GPIOx__) == ((uint32_t)(GPIOA_BASE + 0x0C00)))? 3 :\ + ((uint32_t)(__GPIOx__) == ((uint32_t)(GPIOA_BASE + 0x1C00)))? 4 : 5) + + +#define GPIO_MODE ((uint32_t)0x00000003) +#define EXTI_MODE ((uint32_t)0x10000000) +#define GPIO_MODE_IT ((uint32_t)0x00010000) +#define GPIO_MODE_EVT ((uint32_t)0x00020000) +#define RISING_EDGE ((uint32_t)0x00100000) +#define FALLING_EDGE ((uint32_t)0x00200000) +#define GPIO_OUTPUT_TYPE ((uint32_t)0x00000010) + +#define GPIO_NUMBER ((uint32_t)16) +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup GPIO_Private_Functions + * @{ + */ + +/** @defgroup GPIO_Group1 Initialization and de-initialization functions + * @brief Initialization and Configuration functions + * +@verbatim + =============================================================================== + ##### Initialization and de-initialization functions ##### + =============================================================================== + +@endverbatim + * @{ + */ + +/** + * @brief Initializes the GPIOx peripheral according to the specified parameters in the GPIO_Init. + * @param GPIOx: where x can be (A..D and H) to select the GPIO peripheral for STM32L0XX family devices. + * @param GPIO_Init: pointer to a GPIO_InitTypeDef structure that contains + * the configuration information for the specified GPIO peripheral. + * @retval None + */ +void HAL_GPIO_Init(GPIO_TypeDef *GPIOx, GPIO_InitTypeDef *GPIO_Init) +{ + uint32_t position; + uint32_t ioposition = 0x00; + uint32_t iocurrent = 0x00; + uint32_t temp = 0x00; + + /* Check the parameters */ + assert_param(IS_GPIO_PIN(GPIO_Init->Pin)); + assert_param(IS_GPIO_MODE(GPIO_Init->Mode)); + assert_param(IS_GPIO_PULL(GPIO_Init->Pull)); + + /* Configure the port pins */ + for(position = 0; position < GPIO_NUMBER; position++) + { + /* Get the IO position */ + ioposition = ((uint32_t)0x01) << position; + /* Get the current IO position */ + iocurrent = (uint32_t)(GPIO_Init->Pin) & ioposition; + + if(iocurrent == ioposition) + { + /*--------------------- GPIO Mode Configuration ------------------------*/ + /* In case of Alternate function mode selection */ + if((GPIO_Init->Mode == GPIO_MODE_AF_PP) || (GPIO_Init->Mode == GPIO_MODE_AF_OD)) + { + /* Check the Alternate function parameter */ + assert_param(IS_GPIO_AF(GPIO_Init->Alternate)); + /* Configure Alternate function mapped with the current IO */ + temp = GPIOx->AFR[position >> 3]; + temp &= ~((uint32_t)0xF << ((uint32_t)(position & (uint32_t)0x07) * 4)) ; + temp |= ((uint32_t)(GPIO_Init->Alternate) << (((uint32_t)position & (uint32_t)0x07) * 4)) ; + GPIOx->AFR[position >> 3] = temp; + } + + /* In case of Output or Alternate function mode selection */ + if((GPIO_Init->Mode == GPIO_MODE_OUTPUT_PP) || (GPIO_Init->Mode == GPIO_MODE_AF_PP) || + (GPIO_Init->Mode == GPIO_MODE_OUTPUT_OD) || (GPIO_Init->Mode == GPIO_MODE_AF_OD)) + { + /* Check the Speed parameter */ + assert_param(IS_GPIO_SPEED(GPIO_Init->Speed)); + /* Configure the IO Speed */ + temp = GPIOx->OSPEEDR; + temp &= ~(GPIO_OSPEEDER_OSPEED0 << (position * 2)); + temp |= (GPIO_Init->Speed << (position * 2)); + GPIOx->OSPEEDR = temp; + + /* Configure the IO Output Type */ + temp= GPIOx->OTYPER; + temp &= ~(GPIO_OTYPER_OT_0 << position) ; + temp |= (((GPIO_Init->Mode & GPIO_OUTPUT_TYPE) >> 4) << position); + GPIOx->OTYPER = temp; + } + + /* Configure IO Direction mode (Input, Output, Alternate or Analog) */ + temp = GPIOx->MODER; + temp &= ~(GPIO_MODER_MODE0 << (position * 2)); + temp |= ((GPIO_Init->Mode & GPIO_MODE) << (position * 2)); + GPIOx->MODER = temp; + + /* Activate the Pull-up or Pull down resistor for the current IO */ + temp = GPIOx->PUPDR; + temp &= ~(GPIO_PUPDR_PUPD0 << (position * 2)); + temp |= ((GPIO_Init->Pull) << (position * 2)); + GPIOx->PUPDR = temp; + + /*--------------------- EXTI Mode Configuration ------------------------*/ + /* Configure the External Interrupt or event for the current IO */ + if((GPIO_Init->Mode & EXTI_MODE) == EXTI_MODE) + { + /* Enable SYSCFG Clock */ + __SYSCFG_CLK_ENABLE(); + + temp = SYSCFG->EXTICR[position >> 2]; + temp &= ~((uint32_t)0x0F) << (4 * (position & 0x03)); + temp |= ((uint32_t)(__HAL_GET_GPIO_SOURCE(GPIOx)) << (4 * (position & 0x03))); + SYSCFG->EXTICR[position >> 2] = temp; + + /* Clear EXTI line configuration */ + temp = EXTI->IMR; + temp &= ~((uint32_t)iocurrent); + if((GPIO_Init->Mode & GPIO_MODE_IT) == GPIO_MODE_IT) + { + temp |= iocurrent; + } + EXTI->IMR = temp; + + temp = EXTI->EMR; + temp &= ~((uint32_t)iocurrent); + if((GPIO_Init->Mode & GPIO_MODE_EVT) == GPIO_MODE_EVT) + { + temp |= iocurrent; + } + EXTI->EMR = temp; + + /* Clear Rising Falling edge configuration */ + temp = EXTI->RTSR; + temp &= ~((uint32_t)iocurrent); + if((GPIO_Init->Mode & RISING_EDGE) == RISING_EDGE) + { + temp |= iocurrent; + } + EXTI->RTSR = temp; + + temp = EXTI->FTSR; + temp &= ~((uint32_t)iocurrent); + if((GPIO_Init->Mode & FALLING_EDGE) == FALLING_EDGE) + { + temp |= iocurrent; + } + EXTI->FTSR = temp; + } + } + } +} + +/** + * @brief De-initializes the GPIOx peripheral registers to their default reset values. + * @param GPIOx: where x can be (A..D and H) to select the GPIO peripheral for STM32L0XX family devices. + * @param GPIO_Pin: specifies the port bit to be written. + * This parameter can be one of GPIO_PIN_x where x can be (0..15) except for GPIOD(2) and GPIOH(1:0). + * @retval None + */ +void HAL_GPIO_DeInit(GPIO_TypeDef *GPIOx, uint32_t GPIO_Pin) +{ + uint32_t position; + uint32_t ioposition = 0x00; + uint32_t iocurrent = 0x00; + uint32_t tmp = 0x00; + + /* Configure the port pins */ + for(position = 0; position < GPIO_NUMBER; position++) + { + /* Get the IO position */ + ioposition = ((uint32_t)0x01) << position; + /* Get the current IO position */ + iocurrent = (GPIO_Pin) & ioposition; + + if(iocurrent == ioposition) + { + /*------------------------- GPIO Mode Configuration --------------------*/ + /* Configure IO Direction in Input Floting Mode */ + GPIOx->MODER &= ~(GPIO_MODER_MODE0 << (position * 2)); + + /* Configure the default Alternate Function in current IO */ + GPIOx->AFR[position >> 3] &= ~((uint32_t)0xF << ((uint32_t)(position & (uint32_t)0x07) * 4)) ; + + /* Configure the default value for IO Speed */ + GPIOx->OSPEEDR &= ~(GPIO_OSPEEDER_OSPEED0 << (position * 2)); + + /* Configure the default value IO Output Type */ + GPIOx->OTYPER &= ~(GPIO_OTYPER_OT_0 << position) ; + + /* Deactivate the Pull-up oand Pull-down resistor for the current IO */ + GPIOx->PUPDR &= ~(GPIO_PUPDR_PUPD0 << (position * 2)); + + + /*------------------------- EXTI Mode Configuration --------------------*/ + /* Configure the External Interrupt or event for the current IO */ + tmp = ((uint32_t)0x0F) << (4 * (position & 0x03)); + SYSCFG->EXTICR[position >> 2] &= ~tmp; + + /* Clear EXTI line configuration */ + EXTI->IMR &= ~((uint32_t)iocurrent); + EXTI->EMR &= ~((uint32_t)iocurrent); + + /* Clear Rising Falling edge configuration */ + EXTI->RTSR &= ~((uint32_t)iocurrent); + EXTI->FTSR &= ~((uint32_t)iocurrent); + } + } +} + +/** + * @} + */ + +/** @defgroup GPIO_Group2 IO operation functions + * @brief GPIO Read and Write + * +@verbatim + =============================================================================== + ##### IO operation functions ##### + =============================================================================== + +@endverbatim + * @{ + */ + +/** + * @brief Reads the specified input port pin. + * @param GPIOx: where x can be (A..D and H) to select the GPIO peripheral for STM32L0xx family devices. + * @param GPIO_Pin: specifies the port bit to read. + * This parameter can be GPIO_PIN_x where x can be (0..15) except for GPIOD(2) and GPIOH(1:0). + * @retval The input port pin value. + */ +GPIO_PinState HAL_GPIO_ReadPin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin) +{ + GPIO_PinState bitstatus; + + /* Check the parameters */ + assert_param(IS_GET_GPIO_PIN(GPIO_Pin)); + + if((GPIOx->IDR & GPIO_Pin) != (uint32_t)GPIO_PIN_RESET) + { + bitstatus = GPIO_PIN_SET; + } + else + { + bitstatus = GPIO_PIN_RESET; + } + return bitstatus; +} + +/** + * @brief Sets or clears the selected data port bit. + * + * @note This function uses GPIOx_BSRR register to allow atomic read/modify + * accesses. In this way, there is no risk of an IRQ occurring between + * the read and the modify access. + * + * @param GPIOx: where x can be (A..D and H) to select the GPIO peripheral for STM32L0xx family devices. + * @param GPIO_Pin: specifies the port bit to be written. + * This parameter can be one of GPIO_PIN_x where x can be (0..15) except for GPIOD(2) and GPIOH(1:0). + * @param PinState: specifies the value to be written to the selected bit. + * This parameter can be one of the GPIO_PinState enum values: + * @arg GPIO_PIN_RESET: to clear the port pin + * @arg GPIO_PIN_SET: to set the port pin + * @retval None + */ +void HAL_GPIO_WritePin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin, GPIO_PinState PinState) +{ + /* Check the parameters */ + assert_param(IS_GET_GPIO_PIN(GPIO_Pin)); + assert_param(IS_GPIO_PIN_ACTION(PinState)); + + if(PinState != GPIO_PIN_RESET) + { + GPIOx->BSRR = GPIO_Pin; + } + else + { + GPIOx->BRR = GPIO_Pin ; + } +} + +/** + * @brief Toggles the specified GPIO pins. + * @param GPIOx: Where x can be (A..D and H) to select the GPIO peripheral for STM32L0xx family devices. + * @param GPIO_Pin: Specifies the pins to be toggled. + * @retval None + */ +void HAL_GPIO_TogglePin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin) +{ + /* Check the parameters */ + assert_param(IS_GET_GPIO_PIN(GPIO_Pin)); + + GPIOx->ODR ^= GPIO_Pin; +} + +/** + * @brief This function handles EXTI interrupt request. + * @param GPIO_Pin: Specifies the pins connected EXTI line + * @retval None + */ +void HAL_GPIO_EXTI_IRQHandler(uint16_t GPIO_Pin) +{ + /* EXTI line interrupt detected */ + if(__HAL_GPIO_EXTI_GET_IT(GPIO_Pin) != RESET) + { + __HAL_GPIO_EXTI_CLEAR_IT(GPIO_Pin); + HAL_GPIO_EXTI_Callback(GPIO_Pin); + } +} + +/** + * @brief EXTI line detection callbacks. + * @param GPIO_Pin: Specifies the pins connected EXTI line + * @retval None + */ +__weak void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin) +{ + /* NOTE: This function Should not be modified, when the callback is needed, + the HAL_GPIO_EXTI_Callback could be implemented in the user file + */ +} + +/** + * @} + */ + + +/** + * @} + */ + +#endif /* HAL_GPIO_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_gpio.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_gpio.h new file mode 100644 index 0000000000..03af6eb5da --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_gpio.h @@ -0,0 +1,284 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_gpio.h + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief Header file of GPIO HAL module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32L0xx_HAL_GPIO_H +#define __STM32L0xx_HAL_GPIO_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal_def.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @addtogroup GPIO + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ + +/** + * @brief GPIO Init structure definition + */ +typedef struct +{ + uint32_t Pin; /*!< Specifies the GPIO pins to be configured. + This parameter can be any value of @ref GPIO_pins_define */ + + uint32_t Mode; /*!< Specifies the operating mode for the selected pins. + This parameter can be a value of @ref GPIO_mode_define */ + + uint32_t Pull; /*!< Specifies the Pull-up or Pull-Down activation for the selected pins. + This parameter can be a value of @ref GPIO_pull_define */ + + uint32_t Speed; /*!< Specifies the speed for the selected pins. + This parameter can be a value of @ref GPIO_speed_define */ + + uint32_t Alternate; /*!< Peripheral to be connected to the selected pins + This parameter can be a value of @ref GPIOEx_Alternate_function_selection */ +}GPIO_InitTypeDef; + +/** + * @brief GPIO Bit SET and Bit RESET enumeration + */ +typedef enum +{ + GPIO_PIN_RESET = 0, + GPIO_PIN_SET +}GPIO_PinState; +#define IS_GPIO_PIN_ACTION(ACTION) (((ACTION) == GPIO_PIN_RESET) || ((ACTION) == GPIO_PIN_SET)) + +/* Exported constants --------------------------------------------------------*/ + +/** @defgroup GPIO_Exported_Constants + * @{ + */ + +/** @defgroup GPIO_pins_define + * @{ + */ +#define GPIO_PIN_0 ((uint16_t)0x0001) /* Pin 0 selected */ +#define GPIO_PIN_1 ((uint16_t)0x0002) /* Pin 1 selected */ +#define GPIO_PIN_2 ((uint16_t)0x0004) /* Pin 2 selected */ +#define GPIO_PIN_3 ((uint16_t)0x0008) /* Pin 3 selected */ +#define GPIO_PIN_4 ((uint16_t)0x0010) /* Pin 4 selected */ +#define GPIO_PIN_5 ((uint16_t)0x0020) /* Pin 5 selected */ +#define GPIO_PIN_6 ((uint16_t)0x0040) /* Pin 6 selected */ +#define GPIO_PIN_7 ((uint16_t)0x0080) /* Pin 7 selected */ +#define GPIO_PIN_8 ((uint16_t)0x0100) /* Pin 8 selected */ +#define GPIO_PIN_9 ((uint16_t)0x0200) /* Pin 9 selected */ +#define GPIO_PIN_10 ((uint16_t)0x0400) /* Pin 10 selected */ +#define GPIO_PIN_11 ((uint16_t)0x0800) /* Pin 11 selected */ +#define GPIO_PIN_12 ((uint16_t)0x1000) /* Pin 12 selected */ +#define GPIO_PIN_13 ((uint16_t)0x2000) /* Pin 13 selected */ +#define GPIO_PIN_14 ((uint16_t)0x4000) /* Pin 14 selected */ +#define GPIO_PIN_15 ((uint16_t)0x8000) /* Pin 15 selected */ +#define GPIO_PIN_All ((uint16_t)0xFFFF) /* All pins selected */ + +#define IS_GPIO_PIN(PIN) ((((PIN) & (uint32_t)0x00) == 0x00) && ((PIN) != (uint32_t)0x00)) +#define IS_GET_GPIO_PIN(PIN) (((PIN) == GPIO_PIN_0) || \ + ((PIN) == GPIO_PIN_1) || \ + ((PIN) == GPIO_PIN_2) || \ + ((PIN) == GPIO_PIN_3) || \ + ((PIN) == GPIO_PIN_4) || \ + ((PIN) == GPIO_PIN_5) || \ + ((PIN) == GPIO_PIN_6) || \ + ((PIN) == GPIO_PIN_7) || \ + ((PIN) == GPIO_PIN_8) || \ + ((PIN) == GPIO_PIN_9) || \ + ((PIN) == GPIO_PIN_10) || \ + ((PIN) == GPIO_PIN_11) || \ + ((PIN) == GPIO_PIN_12) || \ + ((PIN) == GPIO_PIN_13) || \ + ((PIN) == GPIO_PIN_14) || \ + ((PIN) == GPIO_PIN_15)) +/** + * @} + */ + +/** @defgroup GPIO_mode_define + * @brief GPIO Configuration Mode + * Elements values convention: 0xX0yz00YZ + * - X : GPIO mode or EXTI Mode + * - y : External IT or Event trigger detection + * - z : IO configuration on External IT or Event + * - Y : Output type (Push Pull or Open Drain) + * - Z : IO Direction mode (Input, Output, Alternate or Analog) + * @{ + */ +#define GPIO_MODE_INPUT ((uint32_t)0x00000000) /*!< Input Floating Mode */ +#define GPIO_MODE_OUTPUT_PP ((uint32_t)0x00000001) /*!< Output Push Pull Mode */ +#define GPIO_MODE_OUTPUT_OD ((uint32_t)0x00000011) /*!< Output Open Drain Mode */ +#define GPIO_MODE_AF_PP ((uint32_t)0x00000002) /*!< Alternate Function Push Pull Mode */ +#define GPIO_MODE_AF_OD ((uint32_t)0x00000012) /*!< Alternate Function Open Drain Mode */ + +#define GPIO_MODE_ANALOG ((uint32_t)0x00000003) /*!< Analog Mode */ + +#define GPIO_MODE_IT_RISING ((uint32_t)0x10110000) /*!< External Interrupt Mode with Rising edge trigger detection */ +#define GPIO_MODE_IT_FALLING ((uint32_t)0x10210000) /*!< External Interrupt Mode with Falling edge trigger detection */ +#define GPIO_MODE_IT_RISING_FALLING ((uint32_t)0x10310000) /*!< External Interrupt Mode with Rising/Falling edge trigger detection */ + +#define GPIO_MODE_EVT_RISING ((uint32_t)0x10120000) /*!< External Event Mode with Rising edge trigger detection */ +#define GPIO_MODE_EVT_FALLING ((uint32_t)0x10220000) /*!< External Event Mode with Falling edge trigger detection */ +#define GPIO_MODE_EVT_RISING_FALLING ((uint32_t)0x10320000) /*!< External Event Mode with Rising/Falling edge trigger detection */ + +#define IS_GPIO_MODE(MODE) (((MODE) == GPIO_MODE_INPUT) ||\ + ((MODE) == GPIO_MODE_OUTPUT_PP) ||\ + ((MODE) == GPIO_MODE_OUTPUT_OD) ||\ + ((MODE) == GPIO_MODE_AF_PP) ||\ + ((MODE) == GPIO_MODE_AF_OD) ||\ + ((MODE) == GPIO_MODE_IT_RISING) ||\ + ((MODE) == GPIO_MODE_IT_FALLING) ||\ + ((MODE) == GPIO_MODE_IT_RISING_FALLING) ||\ + ((MODE) == GPIO_MODE_EVT_RISING) ||\ + ((MODE) == GPIO_MODE_EVT_FALLING) ||\ + ((MODE) == GPIO_MODE_EVT_RISING_FALLING) ||\ + ((MODE) == GPIO_MODE_ANALOG)) + +/** + * @} + */ +/** @defgroup GPIO_speed_define + * @brief GPIO Output Maximum frequency + * @{ + */ +#define GPIO_SPEED_LOW ((uint32_t)0x00000000) /*!< Low speed */ +#define GPIO_SPEED_MEDIUM ((uint32_t)0x00000001) /*!< Medium speed */ +#define GPIO_SPEED_FAST ((uint32_t)0x00000002) /*!< Fast speed */ +#define GPIO_SPEED_HIGH ((uint32_t)0x00000003) /*!< High speed */ + +#define IS_GPIO_SPEED(SPEED) (((SPEED) == GPIO_SPEED_LOW) || ((SPEED) == GPIO_SPEED_MEDIUM) || \ + ((SPEED) == GPIO_SPEED_FAST) || ((SPEED) == GPIO_SPEED_HIGH)) +/** + * @} + */ + + /** @defgroup GPIO_pull_define + * @brief GPIO Pull-Up or Pull-Down Activation + * @{ + */ +#define GPIO_NOPULL ((uint32_t)0x00000000) /*!< No Pull-up or Pull-down activation */ +#define GPIO_PULLUP ((uint32_t)0x00000001) /*!< Pull-up activation */ +#define GPIO_PULLDOWN ((uint32_t)0x00000002) /*!< Pull-down activation */ + +#define IS_GPIO_PULL(PULL) (((PULL) == GPIO_NOPULL) || ((PULL) == GPIO_PULLUP) || \ + ((PULL) == GPIO_PULLDOWN)) +/** + * @} + */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ + +/** + * @brief Checks whether the specified EXTI line flag is set or not. + * @param __EXTI_LINE__: specifies the EXTI line flag to check. + * This parameter can be GPIO_PIN_x where x can be(0..15) + * @retval The new state of __EXTI_LINE__ (SET or RESET). + */ +#define __HAL_GPIO_EXTI_GET_FLAG(__EXTI_LINE__) (EXTI->PR & (__EXTI_LINE__)) + +/** + * @brief Clears the EXTI's line pending flags. + * @param __EXTI_LINE__: specifies the EXTI lines flags to clear. + * This parameter can be any combination of GPIO_PIN_x where x can be (0..15) + * @retval None + */ +#define __HAL_GPIO_EXTI_CLEAR_FLAG(__EXTI_LINE__) (EXTI->PR = (__EXTI_LINE__)) + +/** + * @brief Checks whether the specified EXTI line is asserted or not. + * @param __EXTI_LINE__: specifies the EXTI line to check. + * This parameter can be GPIO_PIN_x where x can be(0..15) + * @retval The new state of __EXTI_LINE__ (SET or RESET). + */ +#define __HAL_GPIO_EXTI_GET_IT(__EXTI_LINE__) (EXTI->PR & (__EXTI_LINE__)) + +/** + * @brief Clears the EXTI's line pending bits. + * @param __EXTI_LINE__: specifies the EXTI lines to clear. + * This parameter can be any combination of GPIO_PIN_x where x can be (0..15) + * @retval None + */ +#define __HAL_GPIO_EXTI_CLEAR_IT(__EXTI_LINE__) (EXTI->PR = (__EXTI_LINE__)) + +/** + * @brief Generates a Software interrupt on selected EXTI line. + * @param __EXTI_LINE__: specifies the EXTI line to check. + * This parameter can be GPIO_PIN_x where x can be(0..15) + * @retval None + */ +#define __HAL_GPIO_EXTI_GENERATE_SWIT(__EXTI_LINE__) (EXTI->SWIER |= (__EXTI_LINE__)) + +/* Include GPIO HAL Extension module */ +#include "stm32l0xx_hal_gpio_ex.h" + +/* Exported functions --------------------------------------------------------*/ +/* Initialization and de-initialization functions *******************************/ +void HAL_GPIO_Init(GPIO_TypeDef *GPIOx, GPIO_InitTypeDef *GPIO_Init); +void HAL_GPIO_DeInit(GPIO_TypeDef *GPIOx, uint32_t GPIO_Pin); + +/* IO operation functions *******************************************************/ +GPIO_PinState HAL_GPIO_ReadPin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin); +void HAL_GPIO_WritePin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin, GPIO_PinState PinState); +void HAL_GPIO_TogglePin(GPIO_TypeDef* GPIOx, uint16_t GPIO_Pin); +void HAL_GPIO_EXTI_IRQHandler(uint16_t GPIO_Pin); +void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin); + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __STM32L0xx_HAL_GPIO_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_gpio_ex.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_gpio_ex.h new file mode 100644 index 0000000000..c55b0acae3 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_gpio_ex.h @@ -0,0 +1,428 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_gpio_ex.h + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief Header file of GPIO HAL Extension module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32L0xx_HAL_GPIO_EX_H +#define __STM32L0xx_HAL_GPIO_EX_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal_def.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @addtogroup GPIOEx + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ + +/* Exported constants --------------------------------------------------------*/ + +/** @defgroup GPIOEx_Exported_Constants + * @{ + */ + +/** @defgroup GPIOEx_Alternate_function_selection + * @{ + */ + +/*------------------------- STM32L053xx/STM32L063xx---------------------------*/ +#if defined (STM32L053xx) || defined (STM32L063xx) +/** + * @brief AF 0 selection + */ +#define GPIO_AF0_SPI1 ((uint8_t)0x00) /* SPI1 Alternate Function mapping */ +#define GPIO_AF0_SPI2 ((uint8_t)0x00) /* SPI2 Alternate Function mapping */ +#define GPIO_AF0_USART1 ((uint8_t)0x00) /* USART1 Alternate Function mapping */ +#define GPIO_AF0_USART2 ((uint8_t)0x00) /* USART2 Alternate Function mapping */ +#define GPIO_AF0_LPUART1 ((uint8_t)0x00) /* LPUART1 Alternate Function mapping */ +#define GPIO_AF0_USB ((uint8_t)0x00) /* USB Alternate Function mapping */ +#define GPIO_AF0_LPTIM ((uint8_t)0x00) /* LPTIM Alternate Function mapping */ +#define GPIO_AF0_TSC ((uint8_t)0x00) /* TSC Alternate Function mapping */ +#define GPIO_AF0_TIM2 ((uint8_t)0x00) /* TIM2 Alternate Function mapping */ +#define GPIO_AF0_TIM21 ((uint8_t)0x00) /* TIM21 Alternate Function mapping */ +#define GPIO_AF0_TIM22 ((uint8_t)0x00) /* TIM22 Alternate Function mapping */ +#define GPIO_AF0_EVENTOUT ((uint8_t)0x00) /* EVENTOUT Alternate Function mapping */ +#define GPIO_AF0_MCO ((uint8_t)0x00) /* MCO Alternate Function mapping */ +#define GPIO_AF0_SWDIO ((uint8_t)0x00) /* SWDIO Alternate Function mapping */ +#define GPIO_AF0_SWCLK ((uint8_t)0x00) /* SWCLK Alternate Function mapping */ + +/** + * @brief AF 1 selection + */ +#define GPIO_AF1_SPI1 ((uint8_t)0x01) /* SPI1 Alternate Function mapping */ +#define GPIO_AF1_SPI2 ((uint8_t)0x01) /* SPI2 Alternate Function mapping */ +#define GPIO_AF1_I2C1 ((uint8_t)0x01) /* I2C1 Alternate Function mapping */ +#define GPIO_AF1_LCD ((uint8_t)0x01) /* LCD Alternate Function mapping */ +#define GPIO_AF1_TIM2 ((uint8_t)0x01) /* TIM2 Alternate Function mapping */ +#define GPIO_AF1_TIM21 ((uint8_t)0x01) /* TIM21 Alternate Function mapping */ +/** + * @brief AF 2 selection + */ +#define GPIO_AF2_SPI2 ((uint8_t)0x02) /* SPI2 Alternate Function mapping */ +#define GPIO_AF2_LPUART1 ((uint8_t)0x02) /* LPUART1 Alternate Function mapping */ +#define GPIO_AF2_USB ((uint8_t)0x02) /* USB Alternate Function mapping */ +#define GPIO_AF2_LPTIM ((uint8_t)0x02) /* LPTIM Alternate Function mapping */ +#define GPIO_AF2_TIM2 ((uint8_t)0x02) /* TIM2 Alternate Function mapping */ +#define GPIO_AF2_TIM22 ((uint8_t)0x02) /* TIM22 Alternate Function mapping */ +#define GPIO_AF2_EVENTOUT ((uint8_t)0x02) /* EVENTOUT Alternate Function mapping */ +#define GPIO_AF2_RTC_50Hz ((uint8_t)0x02) /* RTC_OUT Alternate Function mapping */ + +/** + * @brief AF 3 selection + */ +#define GPIO_AF3_I2C1 ((uint8_t)0x03) /* I2C1 Alternate Function mapping */ +#define GPIO_AF3_TSC ((uint8_t)0x03) /* TSC Alternate Function mapping */ +#define GPIO_AF3_EVENTOUT ((uint8_t)0x03) /* EVENTOUT Alternate Function mapping */ + +/** + * @brief AF 4 selection + */ +#define GPIO_AF4_I2C1 ((uint8_t)0x04) /* I2C1 Alternate Function mapping */ +#define GPIO_AF4_USART1 ((uint8_t)0x04) /* USART1 Alternate Function mapping */ +#define GPIO_AF4_USART2 ((uint8_t)0x04) /* USART2 Alternate Function mapping */ +#define GPIO_AF4_LPUART1 ((uint8_t)0x04) /* LPUART1 Alternate Function mapping */ +#define GPIO_AF4_TIM22 ((uint8_t)0x04) /* TIM22 Alternate Function mapping */ +#define GPIO_AF4_EVENTOUT ((uint8_t)0x04) /* EVENTOUT Alternate Function mapping */ + +/** + * @brief AF 5 selection + */ +#define GPIO_AF5_SPI2 ((uint8_t)0x05) /* SPI2 Alternate Function mapping */ +#define GPIO_AF5_I2C2 ((uint8_t)0x05) /* I2C2 Alternate Function mapping */ +#define GPIO_AF5_TIM2 ((uint8_t)0x05) /* TIM2 Alternate Function mapping */ +#define GPIO_AF5_TIM21 ((uint8_t)0x05) /* TIM21 Alternate Function mapping */ +#define GPIO_AF5_TIM22 ((uint8_t)0x05) /* TIM22 Alternate Function mapping */ + +/** + * @brief AF 6 selection + */ +#define GPIO_AF6_I2C2 ((uint8_t)0x06) /* I2C2 Alternate Function mapping */ +#define GPIO_AF6_TIM21 ((uint8_t)0x06) /* TIM21 Alternate Function mapping */ +#define GPIO_AF6_EVENTOUT ((uint8_t)0x06) /* EVENTOUT Alternate Function mapping */ + +/** + * @brief AF 7 selection + */ +#define GPIO_AF7_COMP1 ((uint8_t)0x07) /* COMP1 Alternate Function mapping */ +#define GPIO_AF7_COMP2 ((uint8_t)0x07) /* COMP2 Alternate Function mapping */ + + +#define IS_GPIO_AF(AF) (((AF) == GPIO_AF0_SPI1) || ((AF) == GPIO_AF2_SPI2) || \ + ((AF) == GPIO_AF0_SPI2) || ((AF) == GPIO_AF2_LPUART1) || \ + ((AF) == GPIO_AF0_USART1) || ((AF) == GPIO_AF2_USB) || \ + ((AF) == GPIO_AF0_USART2) || ((AF) == GPIO_AF2_LPTIM) || \ + ((AF) == GPIO_AF0_LPUART1) || ((AF) == GPIO_AF2_TIM2) || \ + ((AF) == GPIO_AF0_USB) || ((AF) == GPIO_AF2_TIM22) || \ + ((AF) == GPIO_AF0_LPTIM) || ((AF) == GPIO_AF2_EVENTOUT) || \ + ((AF) == GPIO_AF0_TSC) || ((AF) == GPIO_AF2_RTC_50Hz) || \ + ((AF) == GPIO_AF0_TIM2) || ((AF) == GPIO_AF3_I2C1) || \ + ((AF) == GPIO_AF0_TIM21) || ((AF) == GPIO_AF3_TSC) || \ + ((AF) == GPIO_AF0_TIM22) || ((AF) == GPIO_AF3_EVENTOUT) || \ + ((AF) == GPIO_AF0_EVENTOUT) || ((AF) == GPIO_AF4_I2C1) || \ + ((AF) == GPIO_AF0_MCO) || ((AF) == GPIO_AF4_USART1) || \ + ((AF) == GPIO_AF0_SWDIO) || ((AF) == GPIO_AF0_SWCLK) || \ + ((AF) == GPIO_AF1_SPI1) || ((AF) == GPIO_AF4_USART2) || \ + ((AF) == GPIO_AF1_SPI2) || ((AF) == GPIO_AF4_LPUART1) || \ + ((AF) == GPIO_AF1_TIM2) || ((AF) == GPIO_AF4_TIM22) || \ + ((AF) == GPIO_AF1_I2C1) || ((AF) == GPIO_AF4_EVENTOUT) || \ + ((AF) == GPIO_AF1_LCD) || ((AF) == GPIO_AF5_SPI2) || \ + ((AF) == GPIO_AF5_I2C2) || ((AF) == GPIO_AF5_TIM2) || \ + ((AF) == GPIO_AF5_TIM21) || ((AF) == GPIO_AF5_TIM22) || \ + ((AF) == GPIO_AF6_I2C2) || ((AF) == GPIO_AF6_TIM21) || \ + ((AF) == GPIO_AF6_EVENTOUT) || ((AF) == GPIO_AF7_COMP1) || \ + ((AF) == GPIO_AF7_COMP2) || ((AF) == GPIO_AF1_TIM21)) + +#endif /* STM32L053xx || STM32L063xx */ +/*------------------------------------------------------------------------------------------*/ + +/*------------------------- STM32L052xx/STM32L062xx---------------------------*/ +#if defined (STM32L052xx) || defined (STM32L062xx) +/** + * @brief AF 0 selection + */ +#define GPIO_AF0_SPI1 ((uint8_t)0x00) /* SPI1 Alternate Function mapping */ +#define GPIO_AF0_SPI2 ((uint8_t)0x00) /* SPI2 Alternate Function mapping */ +#define GPIO_AF0_USART1 ((uint8_t)0x00) /* USART1 Alternate Function mapping */ +#define GPIO_AF0_USART2 ((uint8_t)0x00) /* USART2 Alternate Function mapping */ +#define GPIO_AF0_LPUART1 ((uint8_t)0x00) /* LPUART1 Alternate Function mapping */ +#define GPIO_AF0_USB ((uint8_t)0x00) /* USB Alternate Function mapping */ +#define GPIO_AF0_LPTIM ((uint8_t)0x00) /* LPTIM Alternate Function mapping */ +#define GPIO_AF0_TSC ((uint8_t)0x00) /* TSC Alternate Function mapping */ +#define GPIO_AF0_TIM2 ((uint8_t)0x00) /* TIM2 Alternate Function mapping */ +#define GPIO_AF0_TIM21 ((uint8_t)0x00) /* TIM21 Alternate Function mapping */ +#define GPIO_AF0_TIM22 ((uint8_t)0x00) /* TIM22 Alternate Function mapping */ +#define GPIO_AF0_EVENTOUT ((uint8_t)0x00) /* EVENTOUT Alternate Function mapping */ +#define GPIO_AF0_MCO ((uint8_t)0x00) /* MCO Alternate Function mapping */ +#define GPIO_AF0_SWDIO ((uint8_t)0x00) /* SWDIO Alternate Function mapping */ +#define GPIO_AF0_SWCLK ((uint8_t)0x00) /* SWCLK Alternate Function mapping */ + + +/** + * @brief AF 1 selection + */ +#define GPIO_AF1_SPI1 ((uint8_t)0x01) /* SPI1 Alternate Function mapping */ +#define GPIO_AF1_SPI2 ((uint8_t)0x01) /* SPI2 Alternate Function mapping */ +#define GPIO_AF1_I2C1 ((uint8_t)0x01) /* I2C1 Alternate Function mapping */ +#define GPIO_AF1_TIM2 ((uint8_t)0x01) /* TIM2 Alternate Function mapping */ +#define GPIO_AF1_TIM21 ((uint8_t)0x01) /* TIM21 Alternate Function mapping */ +/** + * @brief AF 2 selection + */ +#define GPIO_AF2_SPI2 ((uint8_t)0x02) /* SPI2 Alternate Function mapping */ +#define GPIO_AF2_LPUART1 ((uint8_t)0x02) /* LPUART1 Alternate Function mapping */ +#define GPIO_AF2_USB ((uint8_t)0x02) /* USB Alternate Function mapping */ +#define GPIO_AF2_LPTIM ((uint8_t)0x02) /* LPTIM Alternate Function mapping */ +#define GPIO_AF2_TIM2 ((uint8_t)0x02) /* TIM2 Alternate Function mapping */ +#define GPIO_AF2_TIM22 ((uint8_t)0x02) /* TIM22 Alternate Function mapping */ +#define GPIO_AF2_EVENTOUT ((uint8_t)0x02) /* EVENTOUT Alternate Function mapping */ +#define GPIO_AF2_RTC_50Hz ((uint8_t)0x02) /* RTC_OUT Alternate Function mapping */ + +/** + * @brief AF 3 selection + */ +#define GPIO_AF3_I2C1 ((uint8_t)0x03) /* I2C1 Alternate Function mapping */ +#define GPIO_AF3_TSC ((uint8_t)0x03) /* TSC Alternate Function mapping */ +#define GPIO_AF3_EVENTOUT ((uint8_t)0x03) /* EVENTOUT Alternate Function mapping */ + +/** + * @brief AF 4 selection + */ +#define GPIO_AF4_I2C1 ((uint8_t)0x04) /* I2C1 Alternate Function mapping */ +#define GPIO_AF4_USART1 ((uint8_t)0x04) /* USART1 Alternate Function mapping */ +#define GPIO_AF4_USART2 ((uint8_t)0x04) /* USART2 Alternate Function mapping */ +#define GPIO_AF4_LPUART1 ((uint8_t)0x04) /* LPUART1 Alternate Function mapping */ +#define GPIO_AF4_TIM22 ((uint8_t)0x04) /* TIM22 Alternate Function mapping */ +#define GPIO_AF4_EVENTOUT ((uint8_t)0x04) /* EVENTOUT Alternate Function mapping */ + +/** + * @brief AF 5 selection + */ +#define GPIO_AF5_SPI2 ((uint8_t)0x05) /* SPI2 Alternate Function mapping */ +#define GPIO_AF5_I2C2 ((uint8_t)0x05) /* I2C2 Alternate Function mapping */ +#define GPIO_AF5_TIM2 ((uint8_t)0x05) /* TIM2 Alternate Function mapping */ +#define GPIO_AF5_TIM21 ((uint8_t)0x05) /* TIM21 Alternate Function mapping */ +#define GPIO_AF5_TIM22 ((uint8_t)0x05) /* TIM22 Alternate Function mapping */ + +/** + * @brief AF 6 selection + */ +#define GPIO_AF6_I2C2 ((uint8_t)0x06) /* I2C2 Alternate Function mapping */ +#define GPIO_AF6_TIM21 ((uint8_t)0x06) /* TIM21 Alternate Function mapping */ +#define GPIO_AF6_EVENTOUT ((uint8_t)0x06) /* EVENTOUT Alternate Function mapping */ + +/** + * @brief AF 7 selection + */ +#define GPIO_AF7_COMP1 ((uint8_t)0x07) /* COMP1 Alternate Function mapping */ +#define GPIO_AF7_COMP2 ((uint8_t)0x07) /* COMP2 Alternate Function mapping */ + + +#define IS_GPIO_AF(AF) (((AF) == GPIO_AF0_SPI1) || ((AF) == GPIO_AF2_SPI2) || \ + ((AF) == GPIO_AF0_SPI2) || ((AF) == GPIO_AF2_LPUART1) || \ + ((AF) == GPIO_AF0_USART1) || ((AF) == GPIO_AF2_USB) || \ + ((AF) == GPIO_AF0_USART2) || ((AF) == GPIO_AF2_LPTIM) || \ + ((AF) == GPIO_AF0_LPUART1) || ((AF) == GPIO_AF2_TIM2) || \ + ((AF) == GPIO_AF0_USB) || ((AF) == GPIO_AF2_TIM22) || \ + ((AF) == GPIO_AF0_LPTIM) || ((AF) == GPIO_AF2_EVENTOUT) || \ + ((AF) == GPIO_AF0_TSC) || ((AF) == GPIO_AF2_RTC_50Hz) || \ + ((AF) == GPIO_AF0_TIM2) || ((AF) == GPIO_AF3_I2C1) || \ + ((AF) == GPIO_AF0_TIM21) || ((AF) == GPIO_AF3_TSC) || \ + ((AF) == GPIO_AF0_TIM22) || ((AF) == GPIO_AF3_EVENTOUT) || \ + ((AF) == GPIO_AF0_EVENTOUT) || ((AF) == GPIO_AF4_I2C1) || \ + ((AF) == GPIO_AF0_MCO) || ((AF) == GPIO_AF4_USART1) || \ + ((AF) == GPIO_AF0_SWDIO) || ((AF) == GPIO_AF0_SWCLK) || \ + ((AF) == GPIO_AF1_SPI1) || ((AF) == GPIO_AF4_USART2) || \ + ((AF) == GPIO_AF1_SPI2) || ((AF) == GPIO_AF4_LPUART1) || \ + ((AF) == GPIO_AF1_TIM2) || ((AF) == GPIO_AF4_TIM22) || \ + ((AF) == GPIO_AF1_I2C1) || ((AF) == GPIO_AF4_EVENTOUT) || \ + ((AF) == GPIO_AF6_EVENTOUT) || ((AF) == GPIO_AF5_SPI2) || \ + ((AF) == GPIO_AF5_I2C2) || ((AF) == GPIO_AF5_TIM2) || \ + ((AF) == GPIO_AF5_TIM21) || ((AF) == GPIO_AF5_TIM22) || \ + ((AF) == GPIO_AF6_I2C2) || ((AF) == GPIO_AF6_TIM21) || \ + ((AF) == GPIO_AF7_COMP2) || ((AF) == GPIO_AF7_COMP1) || \ + ((AF) == GPIO_AF1_TIM21)) + +#endif /* STM32L052xx || STM32L062xx */ +/*------------------------------------------------------------------------------------------*/ + +/*------------------------- STM32L051xx/STM32L061xx---------------------------*/ +#if defined (STM32L051xx)|| defined (STM32L061xx) +/** + * @brief AF 0 selection + */ +#define GPIO_AF0_SPI1 ((uint8_t)0x00) /* SPI1 Alternate Function mapping */ +#define GPIO_AF0_SPI2 ((uint8_t)0x00) /* SPI2 Alternate Function mapping */ +#define GPIO_AF0_USART1 ((uint8_t)0x00) /* USART1 Alternate Function mapping */ +#define GPIO_AF0_USART2 ((uint8_t)0x00) /* USART2 Alternate Function mapping */ +#define GPIO_AF0_LPUART1 ((uint8_t)0x00) /* LPUART1 Alternate Function mapping */ +#define GPIO_AF0_LPTIM ((uint8_t)0x00) /* LPTIM Alternate Function mapping */ +#define GPIO_AF0_TSC ((uint8_t)0x00) /* TSC Alternate Function mapping */ +#define GPIO_AF0_TIM2 ((uint8_t)0x00) /* TIM2 Alternate Function mapping */ +#define GPIO_AF0_TIM21 ((uint8_t)0x00) /* TIM21 Alternate Function mapping */ +#define GPIO_AF0_TIM22 ((uint8_t)0x00) /* TIM22 Alternate Function mapping */ +#define GPIO_AF0_EVENTOUT ((uint8_t)0x00) /* EVENTOUT Alternate Function mapping */ +#define GPIO_AF0_MCO ((uint8_t)0x00) /* MCO Alternate Function mapping */ +#define GPIO_AF0_SWDIO ((uint8_t)0x00) /* SWDIO Alternate Function mapping */ +#define GPIO_AF0_SWCLK ((uint8_t)0x00) /* SWCLK Alternate Function mapping */ + + +/** + * @brief AF 1 selection + */ +#define GPIO_AF1_SPI1 ((uint8_t)0x01) /* SPI1 Alternate Function mapping */ +#define GPIO_AF1_SPI2 ((uint8_t)0x01) /* SPI2 Alternate Function mapping */ +#define GPIO_AF1_I2C1 ((uint8_t)0x01) /* I2C1 Alternate Function mapping */ +#define GPIO_AF1_TIM2 ((uint8_t)0x01) /* TIM2 Alternate Function mapping */ +#define GPIO_AF1_TIM21 ((uint8_t)0x01) /* TIM21 Alternate Function mapping */ +/** + * @brief AF 2 selection + */ +#define GPIO_AF2_SPI2 ((uint8_t)0x02) /* SPI2 Alternate Function mapping */ +#define GPIO_AF2_LPUART1 ((uint8_t)0x02) /* LPUART1 Alternate Function mapping */ +#define GPIO_AF2_LPTIM ((uint8_t)0x02) /* LPTIM Alternate Function mapping */ +#define GPIO_AF2_TIM2 ((uint8_t)0x02) /* TIM2 Alternate Function mapping */ +#define GPIO_AF2_TIM22 ((uint8_t)0x02) /* TIM22 Alternate Function mapping */ +#define GPIO_AF2_EVENTOUT ((uint8_t)0x02) /* EVENTOUT Alternate Function mapping */ +#define GPIO_AF2_RTC_50Hz ((uint8_t)0x02) /* RTC_OUT Alternate Function mapping */ + +/** + * @brief AF 3 selection + */ +#define GPIO_AF3_I2C1 ((uint8_t)0x03) /* I2C1 Alternate Function mapping */ +#define GPIO_AF3_TSC ((uint8_t)0x03) /* TSC Alternate Function mapping */ +#define GPIO_AF3_EVENTOUT ((uint8_t)0x03) /* EVENTOUT Alternate Function mapping */ + + +/** + * @brief AF 4 selection + */ +#define GPIO_AF4_I2C1 ((uint8_t)0x04) /* I2C1 Alternate Function mapping */ +#define GPIO_AF4_USART1 ((uint8_t)0x04) /* USART1 Alternate Function mapping */ +#define GPIO_AF4_USART2 ((uint8_t)0x04) /* USART2 Alternate Function mapping */ +#define GPIO_AF4_LPUART1 ((uint8_t)0x04) /* LPUART1 Alternate Function mapping */ +#define GPIO_AF4_TIM22 ((uint8_t)0x04) /* TIM22 Alternate Function mapping */ +#define GPIO_AF4_EVENTOUT ((uint8_t)0x04) /* EVENTOUT Alternate Function mapping */ + +/** + * @brief AF 5 selection + */ +#define GPIO_AF5_SPI2 ((uint8_t)0x05) /* SPI2 Alternate Function mapping */ +#define GPIO_AF5_I2C2 ((uint8_t)0x05) /* I2C2 Alternate Function mapping */ +#define GPIO_AF5_TIM2 ((uint8_t)0x05) /* TIM2 Alternate Function mapping */ +#define GPIO_AF5_TIM21 ((uint8_t)0x05) /* TIM21 Alternate Function mapping */ +#define GPIO_AF5_TIM22 ((uint8_t)0x05) /* TIM22 Alternate Function mapping */ + +/** + * @brief AF 6 selection + */ +#define GPIO_AF6_I2C2 ((uint8_t)0x06) /* I2C2 Alternate Function mapping */ +#define GPIO_AF6_TIM21 ((uint8_t)0x06) /* TIM21 Alternate Function mapping */ +#define GPIO_AF6_EVENTOUT ((uint8_t)0x06) /* EVENTOUT Alternate Function mapping */ + +/** + * @brief AF 7 selection + */ +#define GPIO_AF7_COMP1 ((uint8_t)0x07) /* COMP1 Alternate Function mapping */ +#define GPIO_AF7_COMP2 ((uint8_t)0x07) /* COMP2 Alternate Function mapping */ + + +#define IS_GPIO_AF(AF) (((AF) == GPIO_AF0_SPI1) || ((AF) == GPIO_AF2_SPI2) || \ + ((AF) == GPIO_AF0_SPI2) || ((AF) == GPIO_AF2_LPUART1) || \ + ((AF) == GPIO_AF0_USART1) || ((AF) == GPIO_AF2_TIM22) || \ + ((AF) == GPIO_AF0_USART2) || ((AF) == GPIO_AF2_LPTIM) || \ + ((AF) == GPIO_AF0_LPUART1) || ((AF) == GPIO_AF2_TIM2) || \ + ((AF) == GPIO_AF0_LPTIM) || ((AF) == GPIO_AF2_EVENTOUT) || \ + ((AF) == GPIO_AF1_TIM21) || ((AF) == GPIO_AF2_RTC_50Hz) || \ + ((AF) == GPIO_AF0_TIM2) || ((AF) == GPIO_AF3_I2C1) || \ + ((AF) == GPIO_AF0_TIM21) || ((AF) == GPIO_AF3_TSC) || \ + ((AF) == GPIO_AF0_TIM22) || ((AF) == GPIO_AF3_EVENTOUT) || \ + ((AF) == GPIO_AF0_EVENTOUT) || ((AF) == GPIO_AF4_I2C1) || \ + ((AF) == GPIO_AF0_MCO) || ((AF) == GPIO_AF4_USART1) || \ + ((AF) == GPIO_AF0_SWDIO) || ((AF) == GPIO_AF0_SWCLK) || \ + ((AF) == GPIO_AF1_SPI1) || ((AF) == GPIO_AF4_USART2) || \ + ((AF) == GPIO_AF1_SPI2) || ((AF) == GPIO_AF4_LPUART1) || \ + ((AF) == GPIO_AF1_TIM2) || ((AF) == GPIO_AF4_TIM22) || \ + ((AF) == GPIO_AF1_I2C1) || ((AF) == GPIO_AF4_EVENTOUT) || \ + ((AF) == GPIO_AF6_EVENTOUT) || ((AF) == GPIO_AF5_SPI2) || \ + ((AF) == GPIO_AF5_I2C2) || ((AF) == GPIO_AF5_TIM2) || \ + ((AF) == GPIO_AF5_TIM21) || ((AF) == GPIO_AF5_TIM22) || \ + ((AF) == GPIO_AF6_I2C2) || ((AF) == GPIO_AF6_TIM21) || \ + ((AF) == GPIO_AF7_COMP2) || ((AF) == GPIO_AF7_COMP1)) + + +#endif /* STM32L051xx/STM32L061xx*/ + +/* Aliases define maintained for legacy */ +#define GPIO_AF0_EVENOUT GPIO_AF0_EVENTOUT +#define GPIO_AF2_EVENOUT GPIO_AF2_EVENTOUT +#define GPIO_AF3_EVENOUT GPIO_AF3_EVENTOUT +#define GPIO_AF6_EVENOUT GPIO_AF6_EVENTOUT +/*------------------------------------------------------------------------------------------*/ +/** + * @} + */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ +/* Exported functions --------------------------------------------------------*/ + + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __STM32L0xx_HAL_GPIO_EX_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_i2c.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_i2c.c new file mode 100644 index 0000000000..39a787d34a --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_i2c.c @@ -0,0 +1,3797 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_i2c.c + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief I2C HAL module driver. + * + * This file provides firmware functions to manage the following + * functionalities of the Inter Integrated Circuit (I2C) peripheral: + * + Initialization and de-initialization functions + * + IO operation functions + * + Peripheral State functions + * + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + The I2C HAL driver can be used as follows: + + (#) Declare a I2C_HandleTypeDef handle structure, for example: + I2C_HandleTypeDef hi2c; + + (#)Initialize the I2C low level resources by implement the HAL_I2C_MspInit ()API: + (##) Enable the I2Cx interface clock + (##) I2C pins configuration + (+++) Enable the clock for the I2C GPIOs + (+++) Configure I2C pins as alternate function open-drain + (##) NVIC configuration if you need to use interrupt process + (+++) Configure the I2Cx interrupt priority + (+++) Enable the NVIC I2C IRQ Channel + (##) DMA Configuration if you need to use DMA process + (+++) Declare a DMA_HandleTypeDef handle structure for the transmit or receive stream + (+++) Enable the DMAx interface clock using + (+++) Configure the DMA handle parameters + (+++) Configure the DMA Tx or Rx Stream + (+++) Associate the initilalized DMA handle to the hi2c DMA Tx or Rx handle + (+++) Configure the priority and enable the NVIC for the transfer complete interrupt on the DMA Tx or Rx Stream + + (#) Configure the Communication Clock Timing, Own Address1, Master Adressing Mode, Dual Addressing mode, + Own Address2, Own Address2 Mask, General call and Nostretch mode in the hi2c Init structure. + + (#) Initialize the I2C registers by calling the HAL_I2C_Init() API: + (+++) These API's configures also the low level Hardware GPIO, CLOCK, CORTEX...etc) + by calling the customed HAL_I2C_MspInit(&hi2c) API. + + (#) To check if target device is ready for communication, use the function HAL_I2C_IsDeviceReady() + + (#) For I2C IO and IO MEM operations, three mode of operations are available within this driver : + + *** Polling mode IO operation *** + ================================= + [..] + (+) Transmit in master mode an amount of data in blocking mode using HAL_I2C_Master_Transmit() + (+) Receive in master mode an amount of data in blocking mode using HAL_I2C_Master_Receive() + (+) Transmit in slave mode an amount of data in blocking mode using HAL_I2C_Slave_Transmit() + (+) Receive in slave mode an amount of data in blocking mode using HAL_I2C_Slave_Receive() + + *** Polling mode IO MEM operation *** + ===================================== + [..] + (+) Write an amount of data in blocking mode to a specific memory address using HAL_I2C_Mem_Write() + (+) Read an amount of data in blocking mode from a specific memory address using HAL_I2C_Mem_Read() + + + *** Interrupt mode IO operation *** + =================================== + [..] + (+) Transmit in master mode an amount of data in non blocking mode using HAL_I2C_Master_Transmit_IT() + (+) At transmission end of transfer HAL_I2C_MasterTxCpltCallback is executed and user can + add his own code by customization of function pointer HAL_I2C_MasterTxCpltCallback + (+) Receive in master mode an amount of data in non blocking mode using HAL_I2C_Master_Receive_IT() + (+) At reception end of transfer HAL_I2C_MasterRxCpltCallback is executed and user can + add his own code by customization of function pointer HAL_I2C_MasterRxCpltCallback + (+) Transmit in slave mode an amount of data in non blocking mode using HAL_I2C_Slave_Transmit_IT() + (+) At transmission end of transfer HAL_I2C_SlaveTxCpltCallback is executed and user can + add his own code by customization of function pointer HAL_I2C_SlaveTxCpltCallback + (+) Receive in slave mode an amount of data in non blocking mode using HAL_I2C_Slave_Receive_IT() + (+) At reception end of transfer HAL_I2C_SlaveRxCpltCallback is executed and user can + add his own code by customization of function pointer HAL_I2C_SlaveRxCpltCallback + (+) In case of transfer Error, HAL_I2C_ErrorCallback() function is executed and user can + add his own code by customization of function pointer HAL_I2C_ErrorCallback + + *** Interrupt mode IO MEM operation *** + ======================================= + [..] + (+) Write an amount of data in no-blocking mode with Interrupt to a specific memory address using + HAL_I2C_Mem_Write_IT() + (+) At MEM end of write transfer HAL_I2C_MemTxCpltCallback is executed and user can + add his own code by customization of function pointer HAL_I2C_MemTxCpltCallback + (+) Read an amount of data in no-blocking mode with Interrupt from a specific memory address using + HAL_I2C_Mem_Read_IT() + (+) At MEM end of read transfer HAL_I2C_MemRxCpltCallback is executed and user can + add his own code by customization of function pointer HAL_I2C_MemRxCpltCallback + (+) In case of transfer Error, HAL_I2C_ErrorCallback() function is executed and user can + add his own code by customization of function pointer HAL_I2C_ErrorCallback + + *** DMA mode IO operation *** + ============================== + [..] + (+) Transmit in master mode an amount of data in non blocking mode (DMA) using + HAL_I2C_Master_Transmit_DMA() + (+) At transmission end of transfer HAL_I2C_MasterTxCpltCallback is executed and user can + add his own code by customization of function pointer HAL_I2C_MasterTxCpltCallback + (+) Receive in master mode an amount of data in non blocking mode (DMA) using + HAL_I2C_Master_Receive_DMA() + (+) At reception end of transfer HAL_I2C_MasterRxCpltCallback is executed and user can + add his own code by customization of function pointer HAL_I2C_MasterRxCpltCallback + (+) Transmit in slave mode an amount of data in non blocking mode (DMA) using + HAL_I2C_Slave_Transmit_DMA() + (+) At transmission end of transfer HAL_I2C_SlaveTxCpltCallback is executed and user can + add his own code by customization of function pointer HAL_I2C_SlaveTxCpltCallback + (+) Receive in slave mode an amount of data in non blocking mode (DMA) using + HAL_I2C_Slave_Receive_DMA() + (+) At reception end of transfer HAL_I2C_SlaveRxCpltCallback is executed and user can + add his own code by customization of function pointer HAL_I2C_SlaveRxCpltCallback + (+) In case of transfer Error, HAL_I2C_ErrorCallback() function is executed and user can + add his own code by customization of function pointer HAL_I2C_ErrorCallback + + *** DMA mode IO MEM operation *** + ================================= + [..] + (+) Write an amount of data in no-blocking mode with DMA to a specific memory address using + HAL_I2C_Mem_Write_DMA() + (+) At MEM end of write transfer HAL_I2C_MemTxCpltCallback is executed and user can + add his own code by customization of function pointer HAL_I2C_MemTxCpltCallback + (+) Read an amount of data in no-blocking mode with DMA from a specific memory address using + HAL_I2C_Mem_Read_DMA() + (+) At MEM end of read transfer HAL_I2C_MemRxCpltCallback is executed and user can + add his own code by customization of function pointer HAL_I2C_MemRxCpltCallback + (+) In case of transfer Error, HAL_I2C_ErrorCallback() function is executed and user can + add his own code by customization of function pointer HAL_I2C_ErrorCallback + + + *** I2C HAL driver macros list *** + ================================== + [..] + Below the list of most used macros in I2C HAL driver. + + (+) __HAL_I2C_ENABLE: Enable the I2C peripheral + (+) __HAL_I2C_DISABLE: Disable the I2C peripheral + (+) __HAL_I2C_GET_FLAG : Checks whether the specified I2C flag is set or not + (+) __HAL_I2C_CLEAR_FLAG : Clears the specified I2C pending flag + (+) __HAL_I2C_ENABLE_IT: Enables the specified I2C interrupt + (+) __HAL_I2C_DISABLE_IT: Disables the specified I2C interrupt + + [..] + (@) You can refer to the I2C HAL driver header file for more useful macros + + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @defgroup I2C + * @brief I2C HAL module driver + * @{ + */ + +#ifdef HAL_I2C_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +#define TIMING_CLEAR_MASK ((uint32_t)0xF0FFFFFF) /*Instance)); + assert_param(IS_I2C_OWN_ADDRESS1(hi2c->Init.OwnAddress1)); + assert_param(IS_I2C_ADDRESSING_MODE(hi2c->Init.AddressingMode)); + assert_param(IS_I2C_DUAL_ADDRESS(hi2c->Init.DualAddressMode)); + assert_param(IS_I2C_OWN_ADDRESS2(hi2c->Init.OwnAddress2)); + assert_param(IS_I2C_OWN_ADDRESS2_MASK(hi2c->Init.OwnAddress2Masks)); + assert_param(IS_I2C_GENERAL_CALL(hi2c->Init.GeneralCallMode)); + assert_param(IS_I2C_NO_STRETCH(hi2c->Init.NoStretchMode)); + + if(hi2c->State == HAL_I2C_STATE_RESET) + { + /* Init the low level hardware : GPIO, CLOCK, CORTEX...etc */ + HAL_I2C_MspInit(hi2c); + } + + hi2c->State = HAL_I2C_STATE_BUSY; + + /* Disable the selected I2C peripheral */ + __HAL_I2C_DISABLE(hi2c); + + /*---------------------------- I2Cx TIMINGR Configuration ------------------*/ + /* Configure I2Cx: Frequency range */ + hi2c->Instance->TIMINGR = hi2c->Init.Timing & TIMING_CLEAR_MASK; + + /*---------------------------- I2Cx OAR1 Configuration ---------------------*/ + /* Configure I2Cx: Own Address1 and ack own address1 mode */ + hi2c->Instance->OAR1 &= ~I2C_OAR1_OA1EN; + if(hi2c->Init.OwnAddress1 != 0) + { + if(hi2c->Init.AddressingMode == I2C_ADDRESSINGMODE_7BIT) + { + hi2c->Instance->OAR1 = (I2C_OAR1_OA1EN | hi2c->Init.OwnAddress1); + } + else /* I2C_ADDRESSINGMODE_10BIT */ + { + hi2c->Instance->OAR1 = (I2C_OAR1_OA1EN | I2C_OAR1_OA1MODE | hi2c->Init.OwnAddress1); + } + } + + /*---------------------------- I2Cx CR2 Configuration ----------------------*/ + /* Configure I2Cx: Addressing Master mode */ + if(hi2c->Init.AddressingMode == I2C_ADDRESSINGMODE_10BIT) + { + hi2c->Instance->CR2 = (I2C_CR2_ADD10); + } + /* Enable the AUTOEND by default, and enable NACK (should be disable only during Slave process */ + hi2c->Instance->CR2 |= (I2C_CR2_AUTOEND | I2C_CR2_NACK); + + /*---------------------------- I2Cx OAR2 Configuration ---------------------*/ + /* Configure I2Cx: Dual mode and Own Address2 */ + hi2c->Instance->OAR2 = (hi2c->Init.DualAddressMode | hi2c->Init.OwnAddress2 | (hi2c->Init.OwnAddress2Masks << 8)); + + /*---------------------------- I2Cx CR1 Configuration ----------------------*/ + /* Configure I2Cx: Generalcall and NoStretch mode */ + hi2c->Instance->CR1 = (hi2c->Init.GeneralCallMode | hi2c->Init.NoStretchMode); + + /* Enable the selected I2C peripheral */ + __HAL_I2C_ENABLE(hi2c); + + hi2c->ErrorCode = HAL_I2C_ERROR_NONE; + hi2c->State = HAL_I2C_STATE_READY; + + return HAL_OK; +} + +/** + * @brief DeInitializes the I2C peripheral. + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2C_DeInit(I2C_HandleTypeDef *hi2c) +{ + /* Check the I2C handle allocation */ + if(hi2c == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_I2C_ALL_INSTANCE(hi2c->Instance)); + + hi2c->State = HAL_I2C_STATE_BUSY; + + /* Disable the I2C Peripheral Clock */ + __HAL_I2C_DISABLE(hi2c); + + /* DeInit the low level hardware: GPIO, CLOCK, NVIC */ + HAL_I2C_MspDeInit(hi2c); + + hi2c->ErrorCode = HAL_I2C_ERROR_NONE; + hi2c->State = HAL_I2C_STATE_RESET; + + /* Release Lock */ + __HAL_UNLOCK(hi2c); + + return HAL_OK; +} + +/** + * @brief I2C MSP Init. + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @retval None + */ + __weak void HAL_I2C_MspInit(I2C_HandleTypeDef *hi2c) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_I2C_MspInit could be implemented in the user file + */ +} + +/** + * @brief I2C MSP DeInit + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @retval None + */ + __weak void HAL_I2C_MspDeInit(I2C_HandleTypeDef *hi2c) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_I2C_MspDeInit could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup HAL_I2C_Group2 I/O operation functions + * @brief Data transfers functions + * +@verbatim + =============================================================================== + ##### IO operation functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to manage the I2C data + transfers. + + (#) There is two mode of transfer: + (++) Blocking mode : The communication is performed in the polling mode. + The status of all data processing is returned by the same function + after finishing transfer. + (++) No-Blocking mode : The communication is performed using Interrupts + or DMA. These functions return the status of the transfer startup. + The end of the data processing will be indicated through the + dedicated I2C IRQ when using Interrupt mode or the DMA IRQ when + using DMA mode. + + (#) Blocking mode functions are : + (++) HAL_I2C_Master_Transmit() + (++) HAL_I2C_Master_Receive() + (++) HAL_I2C_Slave_Transmit() + (++) HAL_I2C_Slave_Receive() + (++) HAL_I2C_Mem_Write() + (++) HAL_I2C_Mem_Read() + (++) HAL_I2C_IsDeviceReady() + + (#) No-Blocking mode functions with Interrupt are : + (++) HAL_I2C_Master_Transmit_IT() + (++) HAL_I2C_Master_Receive_IT() + (++) HAL_I2C_Slave_Transmit_IT() + (++) HAL_I2C_Slave_Receive_IT() + (++) HAL_I2C_Mem_Write_IT() + (++) HAL_I2C_Mem_Read_IT() + + (#) No-Blocking mode functions with DMA are : + (++) HAL_I2C_Master_Transmit_DMA() + (++) HAL_I2C_Master_Receive_DMA() + (++) HAL_I2C_Slave_Transmit_DMA() + (++) HAL_I2C_Slave_Receive_DMA() + (++) HAL_I2C_Mem_Write_DMA() + (++) HAL_I2C_Mem_Read_DMA() + + (#) A set of Transfer Complete Callbacks are provided in No_Blocking mode: + (++) HAL_I2C_MemTxCpltCallback() + (++) HAL_I2C_MemRxCpltCallback() + (++) HAL_I2C_MasterTxCpltCallback() + (++) HAL_I2C_MasterRxCpltCallback() + (++) HAL_I2C_SlaveTxCpltCallback() + (++) HAL_I2C_SlaveRxCpltCallback() + (++) HAL_I2C_ErrorCallback() + +@endverbatim + * @{ + */ + +/** + * @brief Transmits in master mode an amount of data in blocking mode. + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param DevAddress: Target device address + * @param pData: Pointer to data buffer + * @param Size: Amount of data to be sent + * @param Timeout: Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2C_Master_Transmit(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t Timeout) +{ + uint32_t sizetmp = 0; + + if(hi2c->State == HAL_I2C_STATE_READY) + { + if((pData == NULL ) || (Size == 0)) + { + return HAL_ERROR; + } + + if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) == SET) + { + return HAL_BUSY; + } + + /* Process Locked */ + __HAL_LOCK(hi2c); + + hi2c->State = HAL_I2C_STATE_MASTER_BUSY_TX; + hi2c->ErrorCode = HAL_I2C_ERROR_NONE; + + /* Send Slave Address */ + /* Set NBYTES to write and reload if size > 255 and generate RESTART */ + /* Size > 255, need to set RELOAD bit */ + if(Size > 255) + { + I2C_TransferConfig(hi2c,DevAddress,255, I2C_RELOAD_MODE, I2C_GENERATE_START_WRITE); + sizetmp = 255; + } + else + { + I2C_TransferConfig(hi2c,DevAddress,Size, I2C_AUTOEND_MODE, I2C_GENERATE_START_WRITE); + sizetmp = Size; + } + + do + { + /* Wait until TXIS flag is set */ + if(I2C_WaitOnTXISFlagUntilTimeout(hi2c, Timeout) != HAL_OK) + { + if(hi2c->ErrorCode == HAL_I2C_ERROR_AF) + { + return HAL_ERROR; + } + else + { + return HAL_TIMEOUT; + } + } + /* Write data to TXDR */ + hi2c->Instance->TXDR = (*pData++); + sizetmp--; + Size--; + + if((sizetmp == 0)&&(Size!=0)) + { + /* Wait until TXE flag is set */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_TCR, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + if(Size > 255) + { + I2C_TransferConfig(hi2c,DevAddress,255, I2C_RELOAD_MODE, I2C_NO_STARTSTOP); + sizetmp = 255; + } + else + { + I2C_TransferConfig(hi2c,DevAddress,Size, I2C_AUTOEND_MODE, I2C_NO_STARTSTOP); + sizetmp = Size; + } + } + + }while(Size > 0); + + /* No need to Check TC flag, with AUTOEND mode the stop is automatically generated */ + /* Wait until STOPF flag is set */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_STOPF, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + /* Clear STOP Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); + + /* Clear Configuration Register 2 */ + __HAL_I2C_RESET_CR2(hi2c); + + hi2c->State = HAL_I2C_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receives in master mode an amount of data in blocking mode. + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param DevAddress: Target device address + * @param pData: Pointer to data buffer + * @param Size: Amount of data to be sent + * @param Timeout: Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2C_Master_Receive(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t Timeout) +{ + uint32_t sizetmp = 0; + + if(hi2c->State == HAL_I2C_STATE_READY) + { + if((pData == NULL ) || (Size == 0)) + { + return HAL_ERROR; + } + + if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) == SET) + { + return HAL_BUSY; + } + + /* Process Locked */ + __HAL_LOCK(hi2c); + + hi2c->State = HAL_I2C_STATE_MASTER_BUSY_RX; + hi2c->ErrorCode = HAL_I2C_ERROR_NONE; + + /* Send Slave Address */ + /* Set NBYTES to write and reload if size > 255 and generate RESTART */ + /* Size > 255, need to set RELOAD bit */ + if(Size > 255) + { + I2C_TransferConfig(hi2c,DevAddress,255, I2C_RELOAD_MODE, I2C_GENERATE_START_READ); + sizetmp = 255; + } + else + { + I2C_TransferConfig(hi2c,DevAddress,Size, I2C_AUTOEND_MODE, I2C_GENERATE_START_READ); + sizetmp = Size; + } + + do + { + /* Wait until RXNE flag is set */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_RXNE, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + /* Write data to RXDR */ + (*pData++) =hi2c->Instance->RXDR; + sizetmp--; + Size--; + + if((sizetmp == 0)&&(Size!=0)) + { + /* Wait until TCR flag is set */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_TCR, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + if(Size > 255) + { + I2C_TransferConfig(hi2c,DevAddress,255, I2C_RELOAD_MODE, I2C_NO_STARTSTOP); + sizetmp = 255; + } + else + { + I2C_TransferConfig(hi2c,DevAddress,Size, I2C_AUTOEND_MODE, I2C_NO_STARTSTOP); + sizetmp = Size; + } + } + + }while(Size > 0); + + /* No need to Check TC flag, with AUTOEND mode the stop is automatically generated */ + /* Wait until STOPF flag is set */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_STOPF, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + /* Clear STOP Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); + + /* Clear Configuration Register 2 */ + __HAL_I2C_RESET_CR2(hi2c); + + hi2c->State = HAL_I2C_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Transmits in slave mode an amount of data in blocking mode. + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param pData: Pointer to data buffer + * @param Size: Amount of data to be sent + * @param Timeout: Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2C_Slave_Transmit(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size, uint32_t Timeout) +{ + if(hi2c->State == HAL_I2C_STATE_READY) + { + if((pData == NULL ) || (Size == 0)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(hi2c); + + hi2c->State = HAL_I2C_STATE_SLAVE_BUSY_RX; + hi2c->ErrorCode = HAL_I2C_ERROR_NONE; + + /* Enable Address Acknowledge */ + hi2c->Instance->CR2 &= ~I2C_CR2_NACK; + + /* Wait until ADDR flag is set */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, RESET, Timeout) != HAL_OK) + { + /* Disable Address Acknowledge */ + hi2c->Instance->CR2 |= I2C_CR2_NACK; + return HAL_TIMEOUT; + } + + /* Clear ADDR flag */ + __HAL_I2C_CLEAR_FLAG(hi2c,I2C_FLAG_ADDR); + + /* If 10bit addressing mode is selected */ + if(hi2c->Init.AddressingMode == I2C_ADDRESSINGMODE_10BIT) + { + /* Wait until ADDR flag is set */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, RESET, Timeout) != HAL_OK) + { + /* Disable Address Acknowledge */ + hi2c->Instance->CR2 |= I2C_CR2_NACK; + return HAL_TIMEOUT; + } + + /* Clear ADDR flag */ + __HAL_I2C_CLEAR_FLAG(hi2c,I2C_FLAG_ADDR); + } + + /* Wait until DIR flag is set Transmitter mode */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_DIR, RESET, Timeout) != HAL_OK) + { + /* Disable Address Acknowledge */ + hi2c->Instance->CR2 |= I2C_CR2_NACK; + return HAL_TIMEOUT; + } + + do + { + /* Wait until TXIS flag is set */ + if(I2C_WaitOnTXISFlagUntilTimeout(hi2c, Timeout) != HAL_OK) + { + /* Disable Address Acknowledge */ + hi2c->Instance->CR2 |= I2C_CR2_NACK; + + if(hi2c->ErrorCode == HAL_I2C_ERROR_AF) + { + return HAL_ERROR; + } + else + { + return HAL_TIMEOUT; + } + } + + /* Read data from TXDR */ + hi2c->Instance->TXDR = (*pData++); + Size--; + }while(Size > 0); + + /* Wait until STOP flag is set */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_STOPF, RESET, Timeout) != HAL_OK) + { + /* Disable Address Acknowledge */ + hi2c->Instance->CR2 |= I2C_CR2_NACK; + return HAL_TIMEOUT; + } + + /* Clear STOP flag */ + __HAL_I2C_CLEAR_FLAG(hi2c,I2C_FLAG_STOPF); + + /* Wait until BUSY flag is reset */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, Timeout) != HAL_OK) + { + /* Disable Address Acknowledge */ + hi2c->Instance->CR2 |= I2C_CR2_NACK; + return HAL_TIMEOUT; + } + + /* Disable Address Acknowledge */ + hi2c->Instance->CR2 |= I2C_CR2_NACK; + + hi2c->State = HAL_I2C_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive in slave mode an amount of data in blocking mode + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param pData: Pointer to data buffer + * @param Size: Amount of data to be sent + * @param Timeout: Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2C_Slave_Receive(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size, uint32_t Timeout) +{ + if(hi2c->State == HAL_I2C_STATE_READY) + { + if((pData == NULL ) || (Size == 0)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(hi2c); + + hi2c->State = HAL_I2C_STATE_SLAVE_BUSY_RX; + hi2c->ErrorCode = HAL_I2C_ERROR_NONE; + + /* Enable Address Acknowledge */ + hi2c->Instance->CR2 &= ~I2C_CR2_NACK; + + /* Wait until ADDR flag is set */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, RESET, Timeout) != HAL_OK) + { + /* Disable Address Acknowledge */ + hi2c->Instance->CR2 |= I2C_CR2_NACK; + return HAL_TIMEOUT; + } + + /* Clear ADDR flag */ + __HAL_I2C_CLEAR_FLAG(hi2c,I2C_FLAG_ADDR); + + /* Wait until DIR flag is reset Receiver mode */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_DIR, SET, Timeout) != HAL_OK) + { + /* Disable Address Acknowledge */ + hi2c->Instance->CR2 |= I2C_CR2_NACK; + return HAL_TIMEOUT; + } + + while(Size > 0) + { + /* Wait until RXNE flag is set */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_RXNE, RESET, Timeout) != HAL_OK) + { + /* Disable Address Acknowledge */ + hi2c->Instance->CR2 |= I2C_CR2_NACK; + return HAL_TIMEOUT; + } + + /* Read data from RXDR */ + (*pData++) = hi2c->Instance->RXDR; + Size--; + } + + /* Wait until STOP flag is set */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_STOPF, RESET, Timeout) != HAL_OK) + { + /* Disable Address Acknowledge */ + hi2c->Instance->CR2 |= I2C_CR2_NACK; + return HAL_TIMEOUT; + } + + /* Clear STOP flag */ + __HAL_I2C_CLEAR_FLAG(hi2c,I2C_FLAG_STOPF); + + /* Wait until BUSY flag is reset */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, Timeout) != HAL_OK) + { + /* Disable Address Acknowledge */ + hi2c->Instance->CR2 |= I2C_CR2_NACK; + return HAL_TIMEOUT; + } + + + /* Disable Address Acknowledge */ + hi2c->Instance->CR2 |= I2C_CR2_NACK; + + hi2c->State = HAL_I2C_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Transmit in master mode an amount of data in no-blocking mode with Interrupt + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param DevAddress: Target device address + * @param pData: Pointer to data buffer + * @param Size: Amount of data to be sent + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2C_Master_Transmit_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size) +{ + if(hi2c->State == HAL_I2C_STATE_READY) + { + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) == SET) + { + return HAL_BUSY; + } + + /* Process Locked */ + __HAL_LOCK(hi2c); + + hi2c->State = HAL_I2C_STATE_MASTER_BUSY_TX; + hi2c->ErrorCode = HAL_I2C_ERROR_NONE; + + hi2c->pBuffPtr = pData; + hi2c->XferCount = Size; + if(Size > 255) + { + hi2c->XferSize = 255; + } + else + { + hi2c->XferSize = Size; + } + + /* Send Slave Address */ + /* Set NBYTES to write and reload if size > 255 and generate RESTART */ + if( (hi2c->XferSize == 255) && (hi2c->XferSize < hi2c->XferCount) ) + { + I2C_TransferConfig(hi2c,DevAddress,hi2c->XferSize, I2C_RELOAD_MODE, I2C_GENERATE_START_WRITE); + } + else + { + I2C_TransferConfig(hi2c,DevAddress,hi2c->XferSize, I2C_AUTOEND_MODE, I2C_GENERATE_START_WRITE); + } + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + /* Note : The I2C interrupts must be enabled after unlocking current process + to avoid the risk of I2C interrupt handle execution before current + process unlock */ + + + /* Enable ERR, TC, STOP, NACK, TXI interrupt */ + /* possible to enable all of these */ + /* I2C_IT_ERRI | I2C_IT_TCI| I2C_IT_STOPI| I2C_IT_NACKI | I2C_IT_ADDRI | I2C_IT_RXI | I2C_IT_TXI */ + __HAL_I2C_ENABLE_IT(hi2c,I2C_IT_ERRI | I2C_IT_TCI| I2C_IT_STOPI| I2C_IT_NACKI | I2C_IT_TXI ); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive in master mode an amount of data in no-blocking mode with Interrupt + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param DevAddress: Target device address + * @param pData: Pointer to data buffer + * @param Size: Amount of data to be sent + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2C_Master_Receive_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size) +{ + if(hi2c->State == HAL_I2C_STATE_READY) + { + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) == SET) + { + return HAL_BUSY; + } + + /* Process Locked */ + __HAL_LOCK(hi2c); + + hi2c->State = HAL_I2C_STATE_MASTER_BUSY_RX; + hi2c->ErrorCode = HAL_I2C_ERROR_NONE; + + hi2c->pBuffPtr = pData; + hi2c->XferCount = Size; + if(Size > 255) + { + hi2c->XferSize = 255; + } + else + { + hi2c->XferSize = Size; + } + + /* Send Slave Address */ + /* Set NBYTES to write and reload if size > 255 and generate RESTART */ + if( (hi2c->XferSize == 255) && (hi2c->XferSize < hi2c->XferCount) ) + { + I2C_TransferConfig(hi2c,DevAddress,hi2c->XferSize, I2C_RELOAD_MODE, I2C_GENERATE_START_READ); + } + else + { + I2C_TransferConfig(hi2c,DevAddress,hi2c->XferSize, I2C_AUTOEND_MODE, I2C_GENERATE_START_READ); + } + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + /* Note : The I2C interrupts must be enabled after unlocking current process + to avoid the risk of I2C interrupt handle execution before current + process unlock */ + + /* Enable ERR, TC, STOP, NACK, RXI interrupt */ + /* possible to enable all of these */ + /* I2C_IT_ERRI | I2C_IT_TCI| I2C_IT_STOPI| I2C_IT_NACKI | I2C_IT_ADDRI | I2C_IT_RXI | I2C_IT_TXI */ + __HAL_I2C_ENABLE_IT(hi2c,I2C_IT_ERRI | I2C_IT_TCI| I2C_IT_STOPI| I2C_IT_NACKI | I2C_IT_RXI ); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Transmit in slave mode an amount of data in no-blocking mode with Interrupt + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param pData: Pointer to data buffer + * @param Size: Amount of data to be sent + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2C_Slave_Transmit_IT(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size) +{ + if(hi2c->State == HAL_I2C_STATE_READY) + { + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(hi2c); + + hi2c->State = HAL_I2C_STATE_SLAVE_BUSY_TX; + hi2c->ErrorCode = HAL_I2C_ERROR_NONE; + + /* Enable Address Acknowledge */ + hi2c->Instance->CR2 &= ~I2C_CR2_NACK; + + hi2c->pBuffPtr = pData; + hi2c->XferSize = Size; + hi2c->XferCount = Size; + + /* Wait until ADDR flag is set */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, RESET, I2C_TIMEOUT_ADDR) != HAL_OK) + { + /* Disable Address Acknowledge */ + hi2c->Instance->CR2 |= I2C_CR2_NACK; + return HAL_TIMEOUT; + } + + + /* Clear ADDR flag */ + __HAL_I2C_CLEAR_FLAG(hi2c,I2C_FLAG_ADDR); + + /* In case of 10BIT addressingmode */ + /* A new ADDR flag is set */ + if(hi2c->Init.AddressingMode == I2C_ADDRESSINGMODE_10BIT) + { + /* Wait until ADDR flag is set */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, RESET, I2C_TIMEOUT_ADDR) != HAL_OK) + { + /* Disable Address Acknowledge */ + hi2c->Instance->CR2 |= I2C_CR2_NACK; + return HAL_TIMEOUT; + } + + /* Clear ADDR flag */ + __HAL_I2C_CLEAR_FLAG(hi2c,I2C_FLAG_ADDR); + } + + /* Wait until DIR flag is set Transmitter mode */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_DIR, RESET, I2C_TIMEOUT_DIR) != HAL_OK) + { + /* Disable Address Acknowledge */ + hi2c->Instance->CR2 |= I2C_CR2_NACK; + return HAL_TIMEOUT; + } + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + /* Note : The I2C interrupts must be enabled after unlocking current process + to avoid the risk of I2C interrupt handle execution before current + process unlock */ + + /* Enable ERR, TC, STOP, NACK, TXI interrupt */ + /* possible to enable all of these */ + /* I2C_IT_ERRI | I2C_IT_TCI| I2C_IT_STOPI| I2C_IT_NACKI | I2C_IT_ADDRI | I2C_IT_RXI | I2C_IT_TXI */ + __HAL_I2C_ENABLE_IT(hi2c,I2C_IT_ERRI | I2C_IT_TCI| I2C_IT_STOPI| I2C_IT_NACKI | I2C_IT_TXI ); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive in slave mode an amount of data in no-blocking mode with Interrupt + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param pData: Pointer to data buffer + * @param Size: Amount of data to be sent + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2C_Slave_Receive_IT(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size) +{ + if(hi2c->State == HAL_I2C_STATE_READY) + { + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(hi2c); + + hi2c->State = HAL_I2C_STATE_SLAVE_BUSY_RX; + hi2c->ErrorCode = HAL_I2C_ERROR_NONE; + + /* Enable Address Acknowledge */ + hi2c->Instance->CR2 &= ~I2C_CR2_NACK; + + hi2c->pBuffPtr = pData; + hi2c->XferSize = Size; + hi2c->XferCount = Size; + + /* Wait until ADDR flag is set */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, RESET, I2C_TIMEOUT_ADDR) != HAL_OK) + { + /* Disable Address Acknowledge */ + hi2c->Instance->CR2 |= I2C_CR2_NACK; + return HAL_TIMEOUT; + } + + /* Clear ADDR flag */ + __HAL_I2C_CLEAR_FLAG(hi2c,I2C_FLAG_ADDR); + + /* Wait until DIR flag is reset Receiver mode */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_DIR, SET, I2C_TIMEOUT_DIR) != HAL_OK) + { + /* Disable Address Acknowledge */ + hi2c->Instance->CR2 |= I2C_CR2_NACK; + return HAL_TIMEOUT; + } + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + /* Note : The I2C interrupts must be enabled after unlocking current process + to avoid the risk of I2C interrupt handle execution before current + process unlock */ + + /* Enable ERR, TC, STOP, NACK, RXI interrupt */ + /* possible to enable all of these */ + /* I2C_IT_ERRI | I2C_IT_TCI| I2C_IT_STOPI| I2C_IT_NACKI | I2C_IT_ADDRI | I2C_IT_RXI | I2C_IT_TXI */ + __HAL_I2C_ENABLE_IT(hi2c,I2C_IT_ERRI | I2C_IT_TCI| I2C_IT_STOPI| I2C_IT_NACKI | I2C_IT_RXI ); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Transmit in master mode an amount of data in no-blocking mode with DMA + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param DevAddress: Target device address + * @param pData: Pointer to data buffer + * @param Size: Amount of data to be sent + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2C_Master_Transmit_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size) +{ + if(hi2c->State == HAL_I2C_STATE_READY) + { + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) == SET) + { + return HAL_BUSY; + } + + /* Process Locked */ + __HAL_LOCK(hi2c); + + hi2c->State = HAL_I2C_STATE_MASTER_BUSY_TX; + hi2c->ErrorCode = HAL_I2C_ERROR_NONE; + + hi2c->pBuffPtr = pData; + hi2c->XferCount = Size; + if(Size > 255) + { + hi2c->XferSize = 255; + } + else + { + hi2c->XferSize = Size; + } + + /* Set the I2C DMA transfert complete callback */ + hi2c->hdmatx->XferCpltCallback = I2C_DMAMasterTransmitCplt; + + /* Set the DMA error callback */ + hi2c->hdmatx->XferErrorCallback = I2C_DMAError; + + /* Enable the DMA Stream */ + HAL_DMA_Start_IT(hi2c->hdmatx, (uint32_t)pData, (uint32_t)&hi2c->Instance->TXDR, hi2c->XferSize); + + /* Send Slave Address */ + /* Set NBYTES to write and reload if size > 255 and generate RESTART */ + if( (hi2c->XferSize == 255) && (hi2c->XferSize < hi2c->XferCount) ) + { + I2C_TransferConfig(hi2c,DevAddress,hi2c->XferSize, I2C_RELOAD_MODE, I2C_GENERATE_START_WRITE); + } + else + { + I2C_TransferConfig(hi2c,DevAddress,hi2c->XferSize, I2C_AUTOEND_MODE, I2C_GENERATE_START_WRITE); + } + + /* Wait until TXIS flag is set */ + if(I2C_WaitOnTXISFlagUntilTimeout(hi2c, I2C_TIMEOUT_TXIS) != HAL_OK) + { + /* Disable Address Acknowledge */ + hi2c->Instance->CR2 |= I2C_CR2_NACK; + + if(hi2c->ErrorCode == HAL_I2C_ERROR_AF) + { + return HAL_ERROR; + } + else + { + return HAL_TIMEOUT; + } + } + + + /* Enable DMA Request */ + hi2c->Instance->CR1 |= I2C_CR1_TXDMAEN; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive in master mode an amount of data in no-blocking mode with DMA + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param DevAddress: Target device address + * @param pData: Pointer to data buffer + * @param Size: Amount of data to be sent + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2C_Master_Receive_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size) +{ + if(hi2c->State == HAL_I2C_STATE_READY) + { + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) == SET) + { + return HAL_BUSY; + } + + /* Process Locked */ + __HAL_LOCK(hi2c); + + hi2c->State = HAL_I2C_STATE_MASTER_BUSY_RX; + hi2c->ErrorCode = HAL_I2C_ERROR_NONE; + + hi2c->pBuffPtr = pData; + hi2c->XferCount = Size; + if(Size > 255) + { + hi2c->XferSize = 255; + } + else + { + hi2c->XferSize = Size; + } + + /* Set the I2C DMA transfert complete callback */ + hi2c->hdmarx->XferCpltCallback = I2C_DMAMasterReceiveCplt; + + /* Set the DMA error callback */ + hi2c->hdmarx->XferErrorCallback = I2C_DMAError; + + /* Enable the DMA Stream */ + HAL_DMA_Start_IT(hi2c->hdmarx, (uint32_t)&hi2c->Instance->RXDR, (uint32_t)pData, hi2c->XferSize); + + /* Send Slave Address */ + /* Set NBYTES to write and reload if size > 255 and generate RESTART */ + if( (hi2c->XferSize == 255) && (hi2c->XferSize < hi2c->XferCount) ) + { + I2C_TransferConfig(hi2c,DevAddress,hi2c->XferSize, I2C_RELOAD_MODE, I2C_GENERATE_START_READ); + } + else + { + I2C_TransferConfig(hi2c,DevAddress,hi2c->XferSize, I2C_AUTOEND_MODE, I2C_GENERATE_START_READ); + } + + /* Wait until RXNE flag is set */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_RXNE, RESET, I2C_TIMEOUT_RXNE) != HAL_OK) + { + return HAL_TIMEOUT; + } + + + /* Enable DMA Request */ + hi2c->Instance->CR1 |= I2C_CR1_RXDMAEN; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Transmit in slave mode an amount of data in no-blocking mode with DMA + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param pData: Pointer to data buffer + * @param Size: Amount of data to be sent + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2C_Slave_Transmit_DMA(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size) +{ + if(hi2c->State == HAL_I2C_STATE_READY) + { + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + /* Process Locked */ + __HAL_LOCK(hi2c); + + hi2c->State = HAL_I2C_STATE_SLAVE_BUSY_TX; + hi2c->ErrorCode = HAL_I2C_ERROR_NONE; + + hi2c->pBuffPtr = pData; + hi2c->XferCount = Size; + hi2c->XferSize = Size; + + /* Set the I2C DMA transfert complete callback */ + hi2c->hdmatx->XferCpltCallback = I2C_DMASlaveTransmitCplt; + + /* Set the DMA error callback */ + hi2c->hdmatx->XferErrorCallback = I2C_DMAError; + + /* Enable the DMA Stream */ + HAL_DMA_Start_IT(hi2c->hdmatx, (uint32_t)pData, (uint32_t)&hi2c->Instance->TXDR, hi2c->XferSize); + + /* Enable Address Acknowledge */ + hi2c->Instance->CR2 &= ~I2C_CR2_NACK; + + /* Wait until ADDR flag is set */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, RESET, I2C_TIMEOUT_ADDR) != HAL_OK) + { + /* Disable Address Acknowledge */ + hi2c->Instance->CR2 |= I2C_CR2_NACK; + return HAL_TIMEOUT; + } + + /* Clear ADDR flag */ + __HAL_I2C_CLEAR_FLAG(hi2c,I2C_FLAG_ADDR); + + /* If 10bits addressing mode is selected */ + if(hi2c->Init.AddressingMode == I2C_ADDRESSINGMODE_10BIT) + { + /* Wait until ADDR flag is set */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, RESET, I2C_TIMEOUT_ADDR) != HAL_OK) + { + /* Disable Address Acknowledge */ + hi2c->Instance->CR2 |= I2C_CR2_NACK; + return HAL_TIMEOUT; + } + + /* Clear ADDR flag */ + __HAL_I2C_CLEAR_FLAG(hi2c,I2C_FLAG_ADDR); + } + + /* Wait until DIR flag is set Transmitter mode */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_DIR, RESET, I2C_TIMEOUT_BUSY) != HAL_OK) + { + /* Disable Address Acknowledge */ + hi2c->Instance->CR2 |= I2C_CR2_NACK; + return HAL_TIMEOUT; + } + + /* Enable DMA Request */ + hi2c->Instance->CR1 |= I2C_CR1_TXDMAEN; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive in slave mode an amount of data in no-blocking mode with DMA + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param pData: Pointer to data buffer + * @param Size: Amount of data to be sent + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2C_Slave_Receive_DMA(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size) +{ + if(hi2c->State == HAL_I2C_STATE_READY) + { + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + /* Process Locked */ + __HAL_LOCK(hi2c); + + hi2c->State = HAL_I2C_STATE_SLAVE_BUSY_RX; + hi2c->ErrorCode = HAL_I2C_ERROR_NONE; + + hi2c->pBuffPtr = pData; + hi2c->XferSize = Size; + hi2c->XferCount = Size; + + /* Set the I2C DMA transfert complete callback */ + hi2c->hdmarx->XferCpltCallback = I2C_DMASlaveReceiveCplt; + + /* Set the DMA error callback */ + hi2c->hdmarx->XferErrorCallback = I2C_DMAError; + + /* Enable the DMA Stream */ + HAL_DMA_Start_IT(hi2c->hdmarx, (uint32_t)&hi2c->Instance->RXDR, (uint32_t)pData, Size); + + /* Enable Address Acknowledge */ + hi2c->Instance->CR2 &= ~I2C_CR2_NACK; + + /* Wait until ADDR flag is set */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_ADDR, RESET, I2C_TIMEOUT_ADDR) != HAL_OK) + { + /* Disable Address Acknowledge */ + hi2c->Instance->CR2 |= I2C_CR2_NACK; + return HAL_TIMEOUT; + } + + /* Clear ADDR flag */ + __HAL_I2C_CLEAR_FLAG(hi2c,I2C_FLAG_ADDR); + + /* Wait until DIR flag is set Receiver mode */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_DIR, SET, I2C_TIMEOUT_DIR) != HAL_OK) + { + /* Disable Address Acknowledge */ + hi2c->Instance->CR2 |= I2C_CR2_NACK; + return HAL_TIMEOUT; + } + + /* Enable DMA Request */ + hi2c->Instance->CR1 |= I2C_CR1_RXDMAEN; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} +/** + * @brief Write an amount of data in blocking mode to a specific memory address + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param DevAddress: Target device address + * @param MemAddress: Internal memory address + * @param MemAddSize: Size of internal memory address + * @param pData: Pointer to data buffer + * @param Size: Amount of data to be sent + * @param Timeout: Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2C_Mem_Write(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size, uint32_t Timeout) +{ + uint32_t Sizetmp = 0; + + /* Check the parameters */ + assert_param(IS_I2C_MEMADD_SIZE(MemAddSize)); + + if(hi2c->State == HAL_I2C_STATE_READY) + { + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) == SET) + { + return HAL_BUSY; + } + + /* Process Locked */ + __HAL_LOCK(hi2c); + + hi2c->State = HAL_I2C_STATE_MEM_BUSY_TX; + hi2c->ErrorCode = HAL_I2C_ERROR_NONE; + + /* Send Slave Address and Memory Address */ + if(I2C_RequestMemoryWrite(hi2c, DevAddress, MemAddress, MemAddSize, Timeout) != HAL_OK) + { + if(hi2c->ErrorCode == HAL_I2C_ERROR_AF) + { + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + return HAL_ERROR; + } + else + { + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + return HAL_TIMEOUT; + } + } + + /* Set NBYTES to write and reload if size > 255 and generate RESTART */ + /* Size > 255, need to set RELOAD bit */ + if(Size > 255) + { + I2C_TransferConfig(hi2c,DevAddress,255, I2C_RELOAD_MODE, I2C_NO_STARTSTOP); + Sizetmp = 255; + } + else + { + I2C_TransferConfig(hi2c,DevAddress,Size, I2C_AUTOEND_MODE, I2C_NO_STARTSTOP); + Sizetmp = Size; + } + + do + { + /* Wait until TXIS flag is set */ + if(I2C_WaitOnTXISFlagUntilTimeout(hi2c, Timeout) != HAL_OK) + { + if(hi2c->ErrorCode == HAL_I2C_ERROR_AF) + { + return HAL_ERROR; + } + else + { + return HAL_TIMEOUT; + } + } + + /* Write data to DR */ + hi2c->Instance->TXDR = (*pData++); + Sizetmp--; + Size--; + + if((Sizetmp == 0)&&(Size!=0)) + { + /* Wait until TCR flag is set */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_TCR, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + + if(Size > 255) + { + I2C_TransferConfig(hi2c,DevAddress,255, I2C_RELOAD_MODE, I2C_NO_STARTSTOP); + Sizetmp = 255; + } + else + { + I2C_TransferConfig(hi2c,DevAddress,Size, I2C_AUTOEND_MODE, I2C_NO_STARTSTOP); + Sizetmp = Size; + } + } + + }while(Size > 0); + + /* No need to Check TC flag, with AUTOEND mode the stop is automatically generated */ + /* Wait until STOPF flag is reset */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_STOPF, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + /* Clear STOP Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); + + /* Clear Configuration Register 2 */ + __HAL_I2C_RESET_CR2(hi2c); + + hi2c->State = HAL_I2C_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Read an amount of data in blocking mode from a specific memory address + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param DevAddress: Target device address + * @param MemAddress: Internal memory address + * @param MemAddSize: Size of internal memory address + * @param pData: Pointer to data buffer + * @param Size: Amount of data to be sent + * @param Timeout: Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2C_Mem_Read(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size, uint32_t Timeout) +{ + uint32_t Sizetmp = 0; + + /* Check the parameters */ + assert_param(IS_I2C_MEMADD_SIZE(MemAddSize)); + + if(hi2c->State == HAL_I2C_STATE_READY) + { + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) == SET) + { + return HAL_BUSY; + } + + /* Process Locked */ + __HAL_LOCK(hi2c); + + hi2c->State = HAL_I2C_STATE_MEM_BUSY_RX; + hi2c->ErrorCode = HAL_I2C_ERROR_NONE; + + /* Send Slave Address and Memory Address */ + if(I2C_RequestMemoryRead(hi2c, DevAddress, MemAddress, MemAddSize, Timeout) != HAL_OK) + { + if(hi2c->ErrorCode == HAL_I2C_ERROR_AF) + { + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + return HAL_ERROR; + } + else + { + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + return HAL_TIMEOUT; + } + } + + /* Send Slave Address */ + /* Set NBYTES to write and reload if size > 255 and generate RESTART */ + /* Size > 255, need to set RELOAD bit */ + if(Size > 255) + { + I2C_TransferConfig(hi2c,DevAddress,255, I2C_RELOAD_MODE, I2C_GENERATE_START_READ); + Sizetmp = 255; + } + else + { + I2C_TransferConfig(hi2c,DevAddress,Size, I2C_AUTOEND_MODE, I2C_GENERATE_START_READ); + Sizetmp = Size; + } + + do + { + /* Wait until RXNE flag is set */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_RXNE, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + /* Read data from RXDR */ + (*pData++) = hi2c->Instance->RXDR; + + /* Decrement the Size counter */ + Sizetmp--; + Size--; + + if((Sizetmp == 0)&&(Size!=0)) + { + /* Wait until TCR flag is set */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_TCR, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + if(Size > 255) + { + I2C_TransferConfig(hi2c,DevAddress,255, I2C_RELOAD_MODE, I2C_NO_STARTSTOP); + Sizetmp = 255; + } + else + { + I2C_TransferConfig(hi2c,DevAddress,Size, I2C_AUTOEND_MODE, I2C_NO_STARTSTOP); + Sizetmp = Size; + } + } + + }while(Size > 0); + + /* No need to Check TC flag, with AUTOEND mode the stop is automatically generated */ + /* Wait until STOPF flag is reset */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_STOPF, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + /* Clear STOP Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); + + /* Clear Configuration Register 2 */ + __HAL_I2C_RESET_CR2(hi2c); + + hi2c->State = HAL_I2C_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} +/** + * @brief Write an amount of data in no-blocking mode with Interrupt to a specific memory address + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param DevAddress: Target device address + * @param MemAddress: Internal memory address + * @param MemAddSize: Size of internal memory address + * @param pData: Pointer to data buffer + * @param Size: Amount of data to be sent + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2C_Mem_Write_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size) +{ + /* Check the parameters */ + assert_param(IS_I2C_MEMADD_SIZE(MemAddSize)); + + if(hi2c->State == HAL_I2C_STATE_READY) + { + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) == SET) + { + return HAL_BUSY; + } + + /* Process Locked */ + __HAL_LOCK(hi2c); + + hi2c->State = HAL_I2C_STATE_MEM_BUSY_TX; + hi2c->ErrorCode = HAL_I2C_ERROR_NONE; + + hi2c->pBuffPtr = pData; + hi2c->XferCount = Size; + if(Size > 255) + { + hi2c->XferSize = 255; + } + else + { + hi2c->XferSize = Size; + } + + /* Send Slave Address and Memory Address */ + if(I2C_RequestMemoryWrite(hi2c, DevAddress, MemAddress, MemAddSize, I2C_TIMEOUT_FLAG) != HAL_OK) + { + if(hi2c->ErrorCode == HAL_I2C_ERROR_AF) + { + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + return HAL_ERROR; + } + else + { + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + return HAL_TIMEOUT; + } + } + + /* Set NBYTES to write and reload if size > 255 and generate RESTART */ + /* Size > 255, need to set RELOAD bit */ + /* Set NBYTES to write and reload if size > 255 and generate RESTART */ + if( (hi2c->XferSize == 255) && (hi2c->XferSize < hi2c->XferCount) ) + { + I2C_TransferConfig(hi2c,DevAddress,hi2c->XferSize, I2C_RELOAD_MODE, I2C_NO_STARTSTOP); + } + else + { + I2C_TransferConfig(hi2c,DevAddress,hi2c->XferSize, I2C_AUTOEND_MODE, I2C_NO_STARTSTOP); + } + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + /* Note : The I2C interrupts must be enabled after unlocking current process + to avoid the risk of I2C interrupt handle execution before current + process unlock */ + + /* Enable ERR, TC, STOP, NACK, TXI interrupt */ + /* possible to enable all of these */ + /* I2C_IT_ERRI | I2C_IT_TCI| I2C_IT_STOPI| I2C_IT_NACKI | I2C_IT_ADDRI | I2C_IT_RXI | I2C_IT_TXI */ + __HAL_I2C_ENABLE_IT(hi2c,I2C_IT_ERRI | I2C_IT_TCI| I2C_IT_STOPI| I2C_IT_NACKI | I2C_IT_TXI ); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Read an amount of data in no-blocking mode with Interrupt from a specific memory address + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param DevAddress: Target device address + * @param MemAddress: Internal memory address + * @param MemAddSize: Size of internal memory address + * @param pData: Pointer to data buffer + * @param Size: Amount of data to be sent + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2C_Mem_Read_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size) +{ + /* Check the parameters */ + assert_param(IS_I2C_MEMADD_SIZE(MemAddSize)); + + if(hi2c->State == HAL_I2C_STATE_READY) + { + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) == SET) + { + return HAL_BUSY; + } + + /* Process Locked */ + __HAL_LOCK(hi2c); + + hi2c->State = HAL_I2C_STATE_MEM_BUSY_RX; + + hi2c->pBuffPtr = pData; + hi2c->XferCount = Size; + if(Size > 255) + { + hi2c->XferSize = 255; + } + else + { + hi2c->XferSize = Size; + } + + /* Send Slave Address and Memory Address */ + if(I2C_RequestMemoryRead(hi2c, DevAddress, MemAddress, MemAddSize, I2C_TIMEOUT_FLAG) != HAL_OK) + { + if(hi2c->ErrorCode == HAL_I2C_ERROR_AF) + { + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + return HAL_ERROR; + } + else + { + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_TIMEOUT; + } + } + + /* Set NBYTES to write and reload if size > 255 and generate RESTART */ + /* Size > 255, need to set RELOAD bit */ + /* Set NBYTES to read and reload if size > 255 and generate RESTART */ + if( (hi2c->XferSize == 255) && (hi2c->XferSize < hi2c->XferCount) ) + { + I2C_TransferConfig(hi2c,DevAddress,hi2c->XferSize, I2C_RELOAD_MODE, I2C_GENERATE_START_READ); + } + else + { + I2C_TransferConfig(hi2c,DevAddress,hi2c->XferSize, I2C_AUTOEND_MODE, I2C_GENERATE_START_READ); + } + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + /* Note : The I2C interrupts must be enabled after unlocking current process + to avoid the risk of I2C interrupt handle execution before current + process unlock */ + + /* Enable ERR, TC, STOP, NACK, RXI interrupt */ + /* possible to enable all of these */ + /* I2C_IT_ERRI | I2C_IT_TCI| I2C_IT_STOPI| I2C_IT_NACKI | I2C_IT_ADDRI | I2C_IT_RXI | I2C_IT_TXI */ + __HAL_I2C_ENABLE_IT(hi2c,I2C_IT_ERRI | I2C_IT_TCI| I2C_IT_STOPI| I2C_IT_NACKI | I2C_IT_RXI ); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} +/** + * @brief Write an amount of data in no-blocking mode with DMA to a specific memory address + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param DevAddress: Target device address + * @param MemAddress: Internal memory address + * @param MemAddSize: Size of internal memory address + * @param pData: Pointer to data buffer + * @param Size: Amount of data to be sent + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2C_Mem_Write_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size) +{ + /* Check the parameters */ + assert_param(IS_I2C_MEMADD_SIZE(MemAddSize)); + + if(hi2c->State == HAL_I2C_STATE_READY) + { + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) == SET) + { + return HAL_BUSY; + } + + /* Process Locked */ + __HAL_LOCK(hi2c); + + hi2c->State = HAL_I2C_STATE_MEM_BUSY_TX; + hi2c->ErrorCode = HAL_I2C_ERROR_NONE; + + hi2c->pBuffPtr = pData; + hi2c->XferCount = Size; + if(Size > 255) + { + hi2c->XferSize = 255; + } + else + { + hi2c->XferSize = Size; + } + + /* Set the I2C DMA transfert complete callback */ + hi2c->hdmatx->XferCpltCallback = I2C_DMAMemTransmitCplt; + + /* Set the DMA error callback */ + hi2c->hdmatx->XferErrorCallback = I2C_DMAError; + + /* Enable the DMA Stream */ + HAL_DMA_Start_IT(hi2c->hdmatx, (uint32_t)pData, (uint32_t)&hi2c->Instance->TXDR, hi2c->XferSize); + + /* Send Slave Address and Memory Address */ + if(I2C_RequestMemoryWrite(hi2c, DevAddress, MemAddress, MemAddSize, I2C_TIMEOUT_FLAG) != HAL_OK) + { + if(hi2c->ErrorCode == HAL_I2C_ERROR_AF) + { + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + return HAL_ERROR; + } + else + { + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + return HAL_TIMEOUT; + } + } + + /* Send Slave Address */ + /* Set NBYTES to write and reload if size > 255 and generate RESTART */ + if( (hi2c->XferSize == 255) && (hi2c->XferSize < hi2c->XferCount) ) + { + I2C_TransferConfig(hi2c,DevAddress,hi2c->XferSize, I2C_RELOAD_MODE, I2C_NO_STARTSTOP); + } + else + { + I2C_TransferConfig(hi2c,DevAddress,hi2c->XferSize, I2C_AUTOEND_MODE, I2C_NO_STARTSTOP); + } + + /* Wait until TXIS flag is set */ + if(I2C_WaitOnTXISFlagUntilTimeout(hi2c, I2C_TIMEOUT_TXIS) != HAL_OK) + { + if(hi2c->ErrorCode == HAL_I2C_ERROR_AF) + { + return HAL_ERROR; + } + else + { + return HAL_TIMEOUT; + } + } + + /* Enable DMA Request */ + hi2c->Instance->CR1 |= I2C_CR1_TXDMAEN; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Reads an amount of data in no-blocking mode with DMA from a specific memory address. + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param DevAddress: Target device address + * @param MemAddress: Internal memory address + * @param MemAddSize: Size of internal memory address + * @param pData: Pointer to data buffer + * @param Size: Amount of data to be read + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2C_Mem_Read_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size) +{ + /* Check the parameters */ + assert_param(IS_I2C_MEMADD_SIZE(MemAddSize)); + + if(hi2c->State == HAL_I2C_STATE_READY) + { + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) == SET) + { + return HAL_BUSY; + } + + /* Process Locked */ + __HAL_LOCK(hi2c); + + hi2c->State = HAL_I2C_STATE_MEM_BUSY_RX; + + hi2c->pBuffPtr = pData; + hi2c->XferCount = Size; + if(Size > 255) + { + hi2c->XferSize = 255; + } + else + { + hi2c->XferSize = Size; + } + + /* Set the I2C DMA transfert complete callback */ + hi2c->hdmarx->XferCpltCallback = I2C_DMAMemReceiveCplt; + + /* Set the DMA error callback */ + hi2c->hdmarx->XferErrorCallback = I2C_DMAError; + + /* Enable the DMA Stream */ + HAL_DMA_Start_IT(hi2c->hdmarx, (uint32_t)&hi2c->Instance->RXDR, (uint32_t)pData, hi2c->XferSize); + + /* Send Slave Address and Memory Address */ + if(I2C_RequestMemoryRead(hi2c, DevAddress, MemAddress, MemAddSize, I2C_TIMEOUT_FLAG) != HAL_OK) + { + if(hi2c->ErrorCode == HAL_I2C_ERROR_AF) + { + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + return HAL_ERROR; + } + else + { + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + return HAL_TIMEOUT; + } + } + + /* Set NBYTES to write and reload if size > 255 and generate RESTART */ + if( (hi2c->XferSize == 255) && (hi2c->XferSize < hi2c->XferCount) ) + { + I2C_TransferConfig(hi2c,DevAddress,hi2c->XferSize, I2C_RELOAD_MODE, I2C_GENERATE_START_READ); + } + else + { + I2C_TransferConfig(hi2c,DevAddress,hi2c->XferSize, I2C_AUTOEND_MODE, I2C_GENERATE_START_READ); + } + + /* Wait until RXNE flag is set */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_RXNE, RESET, I2C_TIMEOUT_RXNE) != HAL_OK) + { + return HAL_TIMEOUT; + } + + /* Enable DMA Request */ + hi2c->Instance->CR1 |= I2C_CR1_RXDMAEN; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Checks if target device is ready for communication. + * @note This function is used with Memory devices + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param DevAddress: Target device address + * @param Trials: Number of trials + * @param Timeout: Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2C_IsDeviceReady(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint32_t Trials, uint32_t Timeout) +{ + uint32_t tickstart = 0x00; + + __IO uint32_t I2C_Trials = 0; + + if(hi2c->State == HAL_I2C_STATE_READY) + { + if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BUSY) == SET) + { + return HAL_BUSY; + } + + /* Process Locked */ + __HAL_LOCK(hi2c); + + hi2c->State = HAL_I2C_STATE_BUSY; + hi2c->ErrorCode = HAL_I2C_ERROR_NONE; + + do + { + /* Generate Start */ + hi2c->Instance->CR2 = __HAL_I2C_GENERATE_START(hi2c->Init.AddressingMode,DevAddress); + + /* No need to Check TC flag, with AUTOEND mode the stop is automatically generated */ + /* Wait until STOPF flag is set or a NACK flag is set*/ + tickstart = HAL_GetTick(); + while((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_STOPF) == RESET) && (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_AF) == RESET) && (hi2c->State != HAL_I2C_STATE_TIMEOUT)) + { + if((HAL_GetTick() - tickstart ) > Timeout) + { + hi2c->State = HAL_I2C_STATE_TIMEOUT; + } + } + + /* Check if the NACKF flag has not been set */ + if (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_AF) == RESET) + { + /* Wait until STOPF flag is reset */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_STOPF, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + /* Clear STOP Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); + + /* Device is ready */ + hi2c->State = HAL_I2C_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_OK; + } + else + { + /* Wait until STOPF flag is reset */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_STOPF, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + /* Clear NACK Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); + + /* Clear STOP Flag, auto generated with autoend*/ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); + } + + /* Check if the maximum allowed numbe of trials has bee reached */ + if (I2C_Trials++ == Trials) + { + /* Generate Stop */ + hi2c->Instance->CR2 |= I2C_CR2_STOP; + + /* Wait until STOPF flag is reset */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_STOPF, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + /* Clear STOP Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); + } + }while(I2C_Trials++ < Trials); + + hi2c->State = HAL_I2C_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_TIMEOUT; + + } + + else + { + return HAL_BUSY; + } +} + +/** + * @brief This function handles I2C event interrupt request. + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @retval None + */ +void HAL_I2C_EV_IRQHandler(I2C_HandleTypeDef *hi2c) +{ + /* I2C in mode Transmitter ---------------------------------------------------*/ + if (((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_TXIS) == SET) || (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_TCR) == SET) || (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_TC) == SET) || (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_STOPF) == SET) || (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_AF) == SET)) && (__HAL_I2C_GET_IT_SOURCE(hi2c, (I2C_IT_TCI| I2C_IT_STOPI| I2C_IT_NACKI | I2C_IT_TXI)) == SET)) + { + /* Slave mode selected */ + if (hi2c->State == HAL_I2C_STATE_SLAVE_BUSY_TX) + { + I2C_SlaveTransmit_ISR(hi2c); + } + /* Master mode selected */ + else + { + I2C_MasterTransmit_ISR(hi2c); + } + } + + /* I2C in mode Receiver ----------------------------------------------------*/ + if (((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_RXNE) == SET) || (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_TCR) == SET) || (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_TC) == SET) || (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_STOPF) == SET) || (__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_AF) == SET)) && (__HAL_I2C_GET_IT_SOURCE(hi2c, (I2C_IT_TCI| I2C_IT_STOPI| I2C_IT_NACKI | I2C_IT_RXI)) == SET)) + { + /* Slave mode selected */ + if (hi2c->State == HAL_I2C_STATE_SLAVE_BUSY_RX) + { + I2C_SlaveReceive_ISR(hi2c); + } + /* Master mode selected */ + else + { + I2C_MasterReceive_ISR(hi2c); + } + } +} + +/** + * @brief This function handles I2C error interrupt request. + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @retval None + */ +void HAL_I2C_ER_IRQHandler(I2C_HandleTypeDef *hi2c) +{ + /* I2C Bus error interrupt occurred ------------------------------------*/ + if((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_BERR) == SET) && (__HAL_I2C_GET_IT_SOURCE(hi2c, I2C_IT_ERRI) == SET)) + { + hi2c->ErrorCode |= HAL_I2C_ERROR_BERR; + + /* Clear BERR flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_BERR); + } + + /* I2C Over-Run/Under-Run interrupt occurred ----------------------------------------*/ + if((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_OVR) == SET) && (__HAL_I2C_GET_IT_SOURCE(hi2c, I2C_IT_ERRI) == SET)) + { + hi2c->ErrorCode |= HAL_I2C_ERROR_OVR; + + /* Clear OVR flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_OVR); + } + + /* I2C Arbitration Loss error interrupt occurred -------------------------------------*/ + if((__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_ARLO) == SET) && (__HAL_I2C_GET_IT_SOURCE(hi2c, I2C_IT_ERRI) == SET)) + { + hi2c->ErrorCode |= HAL_I2C_ERROR_ARLO; + + /* Clear ARLO flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_ARLO); + } + + /* Call the Error Callback in case of Error detected */ + if(hi2c->ErrorCode != HAL_I2C_ERROR_NONE) + { + hi2c->State = HAL_I2C_STATE_READY; + + HAL_I2C_ErrorCallback(hi2c); + } +} + +/** + * @brief Master Tx Transfer completed callbacks. + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @retval None + */ + __weak void HAL_I2C_MasterTxCpltCallback(I2C_HandleTypeDef *hi2c) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_I2C_TxCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Master Rx Transfer completed callbacks. + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @retval None + */ +__weak void HAL_I2C_MasterRxCpltCallback(I2C_HandleTypeDef *hi2c) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_I2C_TxCpltCallback could be implemented in the user file + */ +} + +/** @brief Slave Tx Transfer completed callbacks. + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @retval None + */ + __weak void HAL_I2C_SlaveTxCpltCallback(I2C_HandleTypeDef *hi2c) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_I2C_TxCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Slave Rx Transfer completed callbacks. + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @retval None + */ +__weak void HAL_I2C_SlaveRxCpltCallback(I2C_HandleTypeDef *hi2c) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_I2C_TxCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Memory Tx Transfer completed callbacks. + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @retval None + */ + __weak void HAL_I2C_MemTxCpltCallback(I2C_HandleTypeDef *hi2c) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_I2C_TxCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Memory Rx Transfer completed callbacks. + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @retval None + */ +__weak void HAL_I2C_MemRxCpltCallback(I2C_HandleTypeDef *hi2c) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_I2C_TxCpltCallback could be implemented in the user file + */ +} + +/** + * @brief I2C error callbacks. + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @retval None + */ + __weak void HAL_I2C_ErrorCallback(I2C_HandleTypeDef *hi2c) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_I2C_ErrorCallback could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup I2C_Group3 Peripheral State and Errors functions + * @brief Peripheral State and Errors functions + * +@verbatim + =============================================================================== + ##### Peripheral State and Errors functions ##### + =============================================================================== + [..] + This subsection permit to get in run-time the status of the peripheral + and the data flow. + +@endverbatim + * @{ + */ + +/** + * @brief Returns the I2C state. + * @param hi2c : I2C handle + * @retval HAL state + */ +HAL_I2C_StateTypeDef HAL_I2C_GetState(I2C_HandleTypeDef *hi2c) +{ + return hi2c->State; +} + +/** +* @brief Return the I2C error code +* @param hi2c : pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. +* @retval I2C Error Code +*/ +uint32_t HAL_I2C_GetError(I2C_HandleTypeDef *hi2c) +{ + return hi2c->ErrorCode; +} + + + + +/** + * @} + */ + +/** + * @brief Handle Interrupt Flags Master Transmit Mode + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @retval HAL status + */ +static HAL_StatusTypeDef I2C_MasterTransmit_ISR(I2C_HandleTypeDef *hi2c) +{ + uint16_t DevAddress; + + /* Process Locked */ + __HAL_LOCK(hi2c); + + if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_TXIS) == SET) + { + /* Write data to TXDR */ + hi2c->Instance->TXDR = (*hi2c->pBuffPtr++); + hi2c->XferSize--; + hi2c->XferCount--; + + } + else if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_TCR) == SET) + { + if((hi2c->XferSize == 0)&&(hi2c->XferCount!=0)) + { + DevAddress = (hi2c->Instance->CR2 & I2C_CR2_SADD); + + if(hi2c->XferCount > 255) + { + I2C_TransferConfig(hi2c,DevAddress,255, I2C_RELOAD_MODE, I2C_NO_STARTSTOP); + hi2c->XferSize = 255; + } + else + { + I2C_TransferConfig(hi2c,DevAddress,hi2c->XferCount, I2C_AUTOEND_MODE, I2C_NO_STARTSTOP); + hi2c->XferSize = hi2c->XferCount; + } + } + else + { + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + /* Wrong size Status regarding TCR flag event */ + hi2c->ErrorCode |= HAL_I2C_ERROR_SIZE; + HAL_I2C_ErrorCallback(hi2c); + } + } + else if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_TC) == SET) + { + if(hi2c->XferCount == 0) + { + /* Generate Stop */ + hi2c->Instance->CR2 |= I2C_CR2_STOP; + } + else + { + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + /* Wrong size Status regarding TCR flag event */ + hi2c->ErrorCode |= HAL_I2C_ERROR_SIZE; + HAL_I2C_ErrorCallback(hi2c); + } + } + else if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_STOPF) == SET) + { + /* Disable ERR, TC, STOP, NACK, TXI interrupt */ + __HAL_I2C_DISABLE_IT(hi2c,I2C_IT_ERRI | I2C_IT_TCI| I2C_IT_STOPI| I2C_IT_NACKI | I2C_IT_TXI ); + + /* Clear STOP Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); + + /* Clear Configuration Register 2 */ + __HAL_I2C_RESET_CR2(hi2c); + + hi2c->State = HAL_I2C_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + if(hi2c->State == HAL_I2C_STATE_MEM_BUSY_TX) + { + HAL_I2C_MemTxCpltCallback(hi2c); + } + else + { + HAL_I2C_MasterTxCpltCallback(hi2c); + } + } + else if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_AF) == SET) + { + /* Clear NACK Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); + + hi2c->State = HAL_I2C_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + hi2c->ErrorCode |= HAL_I2C_ERROR_AF; + HAL_I2C_ErrorCallback(hi2c); + } + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_OK; +} + +/** + * @brief Handle Interrupt Flags Master Receive Mode + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @retval HAL status + */ +static HAL_StatusTypeDef I2C_MasterReceive_ISR(I2C_HandleTypeDef *hi2c) +{ + uint16_t DevAddress; + + /* Process Locked */ + __HAL_LOCK(hi2c); + + if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_RXNE) == SET) + { + /* Read data from RXDR */ + (*hi2c->pBuffPtr++) = hi2c->Instance->RXDR; + hi2c->XferSize--; + hi2c->XferCount--; + } + else if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_TCR) == SET) + { + if((hi2c->XferSize == 0)&&(hi2c->XferCount!=0)) + { + DevAddress = (hi2c->Instance->CR2 & I2C_CR2_SADD); + + if(hi2c->XferCount > 255) + { + I2C_TransferConfig(hi2c,DevAddress,255, I2C_RELOAD_MODE, I2C_NO_STARTSTOP); + hi2c->XferSize = 255; + } + else + { + I2C_TransferConfig(hi2c,DevAddress,hi2c->XferCount, I2C_AUTOEND_MODE, I2C_NO_STARTSTOP); + hi2c->XferSize = hi2c->XferCount; + } + } + else + { + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + /* Wrong size Status regarding TCR flag event */ + hi2c->ErrorCode |= HAL_I2C_ERROR_SIZE; + HAL_I2C_ErrorCallback(hi2c); + } + } + else if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_TC) == SET) + { + if(hi2c->XferCount == 0) + { + /* Generate Stop */ + hi2c->Instance->CR2 |= I2C_CR2_STOP; + } + else + { + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + /* Wrong size Status regarding TCR flag event */ + hi2c->ErrorCode |= HAL_I2C_ERROR_SIZE; + HAL_I2C_ErrorCallback(hi2c); + } + } + else if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_STOPF) == SET) + { + /* Disable ERR, TC, STOP, NACK, TXI interrupt */ + __HAL_I2C_DISABLE_IT(hi2c,I2C_IT_ERRI | I2C_IT_TCI| I2C_IT_STOPI| I2C_IT_NACKI | I2C_IT_RXI ); + + /* Clear STOP Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); + + /* Clear Configuration Register 2 */ + __HAL_I2C_RESET_CR2(hi2c); + + hi2c->State = HAL_I2C_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + if(hi2c->State == HAL_I2C_STATE_MEM_BUSY_RX) + { + HAL_I2C_MemRxCpltCallback(hi2c); + } + else + { + HAL_I2C_MasterRxCpltCallback(hi2c); + } + } + else if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_AF) == SET) + { + /* Clear NACK Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); + + hi2c->State = HAL_I2C_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + hi2c->ErrorCode |= HAL_I2C_ERROR_AF; + HAL_I2C_ErrorCallback(hi2c); + } + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_OK; + +} + +/** + * @brief Handle Interrupt Flags Slave Transmit Mode + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @retval HAL status + */ +static HAL_StatusTypeDef I2C_SlaveTransmit_ISR(I2C_HandleTypeDef *hi2c) +{ + /* Process locked */ + __HAL_LOCK(hi2c); + + /* Check first if STOPF is set */ + /* to prevent a Write Data in TX buffer */ + /* which is stuck in TXDR until next */ + /* communication with Master */ + if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_STOPF) == SET) + + + { + /* Disable ERRI, TCI, STOPI, NACKI, ADDRI, RXI, TXI interrupt */ + __HAL_I2C_DISABLE_IT(hi2c,I2C_IT_ERRI | I2C_IT_TCI| I2C_IT_STOPI| I2C_IT_NACKI | I2C_IT_ADDRI | I2C_IT_RXI | I2C_IT_TXI ); + + /* Disable Address Acknowledge */ + hi2c->Instance->CR2 |= I2C_CR2_NACK; + + /* Clear STOP Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); + + hi2c->State = HAL_I2C_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + HAL_I2C_SlaveTxCpltCallback(hi2c); + } + else if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_TXIS) == SET) + { + /* Write data to TXDR only if XferCount not reach "0" */ + /* A TXIS flag can be set, during STOP treatment */ + if(hi2c->XferCount > 0) + { + /* Write data to TXDR */ + hi2c->Instance->TXDR = (*hi2c->pBuffPtr++); + hi2c->XferCount--; + } + } + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_OK; +} + +/** + * @brief Handle Interrupt Flags Slave Receive Mode + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @retval HAL status + */ +static HAL_StatusTypeDef I2C_SlaveReceive_ISR(I2C_HandleTypeDef *hi2c) +{ + /* Process Locked */ + __HAL_LOCK(hi2c); + + if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_RXNE) == SET) + { + /* Read data from RXDR */ + (*hi2c->pBuffPtr++) = hi2c->Instance->RXDR; + hi2c->XferSize--; + hi2c->XferCount--; + } + else if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_STOPF) == SET) + { + /* Disable ERRI, TCI, STOPI, NACKI, ADDRI, RXI, TXI interrupt */ + __HAL_I2C_DISABLE_IT(hi2c,I2C_IT_ERRI | I2C_IT_TCI| I2C_IT_STOPI| I2C_IT_NACKI | I2C_IT_ADDRI | I2C_IT_RXI | I2C_IT_RXI ); + + /* Disable Address Acknowledge */ + hi2c->Instance->CR2 |= I2C_CR2_NACK; + + /* Clear STOP Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); + + hi2c->State = HAL_I2C_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + HAL_I2C_SlaveRxCpltCallback(hi2c); + } + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_OK; +} + +/** + * @brief Master sends target device address followed by internal memory address for write request. + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param DevAddress: Target device address + * @param MemAddress: Internal memory address + * @param MemAddSize: Size of internal memory address + * @param Timeout: Timeout duration + * @retval HAL status + */ +static HAL_StatusTypeDef I2C_RequestMemoryWrite(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint32_t Timeout) +{ + + + I2C_TransferConfig(hi2c,DevAddress,MemAddSize, I2C_RELOAD_MODE, I2C_GENERATE_START_WRITE); + + /* Wait until TXIS flag is set */ + if(I2C_WaitOnTXISFlagUntilTimeout(hi2c, Timeout) != HAL_OK) + { + if(hi2c->ErrorCode == HAL_I2C_ERROR_AF) + { + return HAL_ERROR; + } + else + { + return HAL_TIMEOUT; + } + } + + /* If Memory address size is 8Bit */ + if(MemAddSize == I2C_MEMADD_SIZE_8BIT) + { + /* Send Memory Address */ + hi2c->Instance->TXDR = __HAL_I2C_MEM_ADD_LSB(MemAddress); + } + /* If Memory address size is 16Bit */ + else + { + /* Send MSB of Memory Address */ + hi2c->Instance->TXDR = __HAL_I2C_MEM_ADD_MSB(MemAddress); + + /* Wait until TXIS flag is set */ + if(I2C_WaitOnTXISFlagUntilTimeout(hi2c, Timeout) != HAL_OK) + { + if(hi2c->ErrorCode == HAL_I2C_ERROR_AF) + { + return HAL_ERROR; + } + else + { + return HAL_TIMEOUT; + } + } + + /* Send LSB of Memory Address */ + hi2c->Instance->TXDR = __HAL_I2C_MEM_ADD_LSB(MemAddress); + } + + /* Wait until TCR flag is set */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_TCR, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + +return HAL_OK; +} + +/** + * @brief Master sends target device address followed by internal memory address for read request. + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param DevAddress: Target device address + * @param MemAddress: Internal memory address + * @param MemAddSize: Size of internal memory address + * @param Timeout: Timeout duration + * @retval HAL status + */ +static HAL_StatusTypeDef I2C_RequestMemoryRead(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint32_t Timeout) +{ + I2C_TransferConfig(hi2c,DevAddress,MemAddSize, I2C_SOFTEND_MODE, I2C_GENERATE_START_WRITE); + + /* Wait until TXIS flag is set */ + if(I2C_WaitOnTXISFlagUntilTimeout(hi2c, Timeout) != HAL_OK) + { + if(hi2c->ErrorCode == HAL_I2C_ERROR_AF) + { + return HAL_ERROR; + } + else + { + return HAL_TIMEOUT; + } + } + + /* If Memory address size is 8Bit */ + if(MemAddSize == I2C_MEMADD_SIZE_8BIT) + { + /* Send Memory Address */ + hi2c->Instance->TXDR = __HAL_I2C_MEM_ADD_LSB(MemAddress); + } + /* If Mememory address size is 16Bit */ + else + { + /* Send MSB of Memory Address */ + hi2c->Instance->TXDR = __HAL_I2C_MEM_ADD_MSB(MemAddress); + + /* Wait until TXIS flag is set */ + if(I2C_WaitOnTXISFlagUntilTimeout(hi2c, Timeout) != HAL_OK) + { + if(hi2c->ErrorCode == HAL_I2C_ERROR_AF) + { + return HAL_ERROR; + } + else + { + return HAL_TIMEOUT; + } + } + + /* Send LSB of Memory Address */ + hi2c->Instance->TXDR = __HAL_I2C_MEM_ADD_LSB(MemAddress); + } + + /* Wait until TC flag is set */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_TC, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + return HAL_OK; +} + + +/** + * @brief DMA I2C master transmit process complete callback. + * @param hdma: DMA handle + * @retval None + */ +static void I2C_DMAMasterTransmitCplt(DMA_HandleTypeDef *hdma) +{ + uint16_t DevAddress; + I2C_HandleTypeDef* hi2c = (I2C_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent; + + /* Check if last DMA request was done with RELOAD */ + /* Set NBYTES to write and reload if size > 255 and generate RESTART */ + if( (hi2c->XferSize == 255) && (hi2c->XferSize < hi2c->XferCount) ) + { + /* Wait until TCR flag is set */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_TCR, RESET, I2C_TIMEOUT_TCR) != HAL_OK) + { + hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; + } + + /* Disable DMA Request */ + hi2c->Instance->CR1 &= ~I2C_CR1_TXDMAEN; + + /* Check if Errors has been detected during transfer */ + if(hi2c->ErrorCode != HAL_I2C_ERROR_NONE) + { + /* No need to Check TC flag, with AUTOEND mode the stop is automatically generated */ + /* Wait until STOPF flag is reset */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_STOPF, RESET, I2C_TIMEOUT_STOPF) != HAL_OK) + { + hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; + } + + /* Clear STOP Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); + + /* Clear Configuration Register 2 */ + __HAL_I2C_RESET_CR2(hi2c); + + hi2c->XferCount = 0; + + hi2c->State = HAL_I2C_STATE_READY; + HAL_I2C_ErrorCallback(hi2c); + } + else + { + hi2c->pBuffPtr += hi2c->XferSize; + hi2c->XferCount -= hi2c->XferSize; + if(hi2c->XferCount > 255) + { + hi2c->XferSize = 255; + } + else + { + hi2c->XferSize = hi2c->XferCount; + } + + DevAddress = (hi2c->Instance->CR2 & I2C_CR2_SADD); + + /* Enable the DMA Stream */ + HAL_DMA_Start_IT(hi2c->hdmatx, (uint32_t)hi2c->pBuffPtr, (uint32_t)&hi2c->Instance->TXDR, hi2c->XferSize); + + /* Send Slave Address */ + /* Set NBYTES to write and reload if size > 255 and generate RESTART */ + if( (hi2c->XferSize == 255) && (hi2c->XferSize < hi2c->XferCount) ) + { + I2C_TransferConfig(hi2c,DevAddress,hi2c->XferSize, I2C_RELOAD_MODE, I2C_NO_STARTSTOP); + } + else + { + I2C_TransferConfig(hi2c,DevAddress,hi2c->XferSize, I2C_AUTOEND_MODE, I2C_NO_STARTSTOP); + } + + /* Wait until TXIS flag is set */ + if(I2C_WaitOnTXISFlagUntilTimeout(hi2c, I2C_TIMEOUT_TXIS) != HAL_OK) + { + /* No need to Check TC flag, with AUTOEND mode the stop is automatically generated */ + /* Wait until STOPF flag is reset */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_STOPF, RESET, I2C_TIMEOUT_STOPF) != HAL_OK) + { + hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; + } + + /* Clear STOP Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); + + /* Clear Configuration Register 2 */ + __HAL_I2C_RESET_CR2(hi2c); + + hi2c->XferCount = 0; + + hi2c->State = HAL_I2C_STATE_READY; + HAL_I2C_ErrorCallback(hi2c); + } + else + { + /* Enable DMA Request */ + hi2c->Instance->CR1 |= I2C_CR1_TXDMAEN; + } + } + } + else + { + /* No need to Check TC flag, with AUTOEND mode the stop is automatically generated */ + /* Wait until STOPF flag is reset */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_STOPF, RESET, I2C_TIMEOUT_STOPF) != HAL_OK) + { + hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; + } + + /* Clear STOP Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); + + /* Clear Configuration Register 2 */ + __HAL_I2C_RESET_CR2(hi2c); + + /* Disable DMA Request */ + hi2c->Instance->CR1 &= ~I2C_CR1_TXDMAEN; + + hi2c->XferCount = 0; + + hi2c->State = HAL_I2C_STATE_READY; + + /* Check if Errors has been detected during transfer */ + if(hi2c->ErrorCode != HAL_I2C_ERROR_NONE) + { + HAL_I2C_ErrorCallback(hi2c); + } + else + { + HAL_I2C_MasterTxCpltCallback(hi2c); + } + } +} + +/** + * @brief DMA I2C slave transmit process complete callback. + * @param hdma: DMA handle + * @retval None + */ +static void I2C_DMASlaveTransmitCplt(DMA_HandleTypeDef *hdma) +{ + I2C_HandleTypeDef* hi2c = (I2C_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent; + + /* Wait until STOP flag is set */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_STOPF, RESET, I2C_TIMEOUT_STOPF) != HAL_OK) + { + hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; + } + + /* Clear STOP flag */ + __HAL_I2C_CLEAR_FLAG(hi2c,I2C_FLAG_STOPF); + + /* Wait until BUSY flag is reset */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, I2C_TIMEOUT_BUSY) != HAL_OK) + { + hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; + } + + /* Disable DMA Request */ + hi2c->Instance->CR1 &= ~I2C_CR1_TXDMAEN; + + hi2c->XferCount = 0; + + hi2c->State = HAL_I2C_STATE_READY; + + /* Check if Errors has been detected during transfer */ + if(hi2c->ErrorCode != HAL_I2C_ERROR_NONE) + { + HAL_I2C_ErrorCallback(hi2c); + } + else + { + HAL_I2C_SlaveTxCpltCallback(hi2c); + } +} + +/** + * @brief DMA I2C master receive process complete callback + * @param hdma: DMA handle + * @retval None + */ +static void I2C_DMAMasterReceiveCplt(DMA_HandleTypeDef *hdma) +{ + I2C_HandleTypeDef* hi2c = (I2C_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent; + uint16_t DevAddress; + + /* Check if last DMA request was done with RELOAD */ + /* Set NBYTES to write and reload if size > 255 and generate RESTART */ + if( (hi2c->XferSize == 255) && (hi2c->XferSize < hi2c->XferCount) ) + { + /* Wait until TCR flag is set */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_TCR, RESET, I2C_TIMEOUT_TCR) != HAL_OK) + { + hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; + } + + /* Disable DMA Request */ + hi2c->Instance->CR1 &= ~I2C_CR1_RXDMAEN; + + /* Check if Errors has been detected during transfer */ + if(hi2c->ErrorCode != HAL_I2C_ERROR_NONE) + { + /* No need to Check TC flag, with AUTOEND mode the stop is automatically generated */ + /* Wait until STOPF flag is reset */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_STOPF, RESET, I2C_TIMEOUT_STOPF) != HAL_OK) + { + hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; + } + + /* Clear STOP Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); + + /* Clear Configuration Register 2 */ + __HAL_I2C_RESET_CR2(hi2c); + + hi2c->XferCount = 0; + + hi2c->State = HAL_I2C_STATE_READY; + HAL_I2C_ErrorCallback(hi2c); + } + else + { + hi2c->pBuffPtr += hi2c->XferSize; + hi2c->XferCount -= hi2c->XferSize; + if(hi2c->XferCount > 255) + { + hi2c->XferSize = 255; + } + else + { + hi2c->XferSize = hi2c->XferCount; + } + + DevAddress = (hi2c->Instance->CR2 & I2C_CR2_SADD); + + /* Enable the DMA Stream */ + HAL_DMA_Start_IT(hi2c->hdmarx, (uint32_t)&hi2c->Instance->RXDR, (uint32_t)hi2c->pBuffPtr, hi2c->XferSize); + + /* Send Slave Address */ + /* Set NBYTES to write and reload if size > 255 and generate RESTART */ + if( (hi2c->XferSize == 255) && (hi2c->XferSize < hi2c->XferCount) ) + { + I2C_TransferConfig(hi2c,DevAddress,hi2c->XferSize, I2C_RELOAD_MODE, I2C_NO_STARTSTOP); + } + else + { + I2C_TransferConfig(hi2c,DevAddress,hi2c->XferSize, I2C_AUTOEND_MODE, I2C_NO_STARTSTOP); + } + + /* Wait until RXNE flag is set */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_RXNE, RESET, I2C_TIMEOUT_RXNE) != HAL_OK) + { + hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; + } + + /* Check if Errors has been detected during transfer */ + if(hi2c->ErrorCode != HAL_I2C_ERROR_NONE) + { + /* No need to Check TC flag, with AUTOEND mode the stop is automatically generated */ + /* Wait until STOPF flag is reset */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_STOPF, RESET, I2C_TIMEOUT_STOPF) != HAL_OK) + { + hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; + } + + /* Clear STOP Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); + + /* Clear Configuration Register 2 */ + __HAL_I2C_RESET_CR2(hi2c); + + hi2c->XferCount = 0; + + hi2c->State = HAL_I2C_STATE_READY; + + HAL_I2C_ErrorCallback(hi2c); + } + else + { + /* Enable DMA Request */ + hi2c->Instance->CR1 |= I2C_CR1_RXDMAEN; + } + } + } + else + { + /* No need to Check TC flag, with AUTOEND mode the stop is automatically generated */ + /* Wait until STOPF flag is reset */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_STOPF, RESET, I2C_TIMEOUT_STOPF) != HAL_OK) + { + hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; + } + + /* Clear STOP Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); + + /* Clear Configuration Register 2 */ + __HAL_I2C_RESET_CR2(hi2c); + + /* Disable DMA Request */ + hi2c->Instance->CR1 &= ~I2C_CR1_RXDMAEN; + + hi2c->XferCount = 0; + + hi2c->State = HAL_I2C_STATE_READY; + + /* Check if Errors has been detected during transfer */ + if(hi2c->ErrorCode != HAL_I2C_ERROR_NONE) + { + HAL_I2C_ErrorCallback(hi2c); + } + else + { + HAL_I2C_MasterRxCpltCallback(hi2c); + } + } +} + +/** + * @brief DMA I2C slave receive process complete callback. + * @param hdma: DMA handle + * @retval None + */ +static void I2C_DMASlaveReceiveCplt(DMA_HandleTypeDef *hdma) +{ + I2C_HandleTypeDef* hi2c = (I2C_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent; + + /* Wait until STOPF flag is reset */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_STOPF, RESET, I2C_TIMEOUT_STOPF) != HAL_OK) + { + hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; + } + + /* Clear STOPF flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); + + /* Wait until BUSY flag is reset */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_BUSY, SET, I2C_TIMEOUT_BUSY) != HAL_OK) + { + hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; + } + + /* Disable DMA Request */ + hi2c->Instance->CR1 &= ~I2C_CR1_RXDMAEN; + + /* Disable Address Acknowledge */ + hi2c->Instance->CR2 |= I2C_CR2_NACK; + + hi2c->XferCount = 0; + + hi2c->State = HAL_I2C_STATE_READY; + + /* Check if Errors has been detected during transfer */ + if(hi2c->ErrorCode != HAL_I2C_ERROR_NONE) + { + HAL_I2C_ErrorCallback(hi2c); + } + else + { + HAL_I2C_SlaveRxCpltCallback(hi2c); + } +} + +/** + * @brief DMA I2C Memory Write process complete callback + * @param hdma : DMA handle + * @retval None + */ +static void I2C_DMAMemTransmitCplt(DMA_HandleTypeDef *hdma) +{ + uint16_t DevAddress; + I2C_HandleTypeDef* hi2c = ( I2C_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + + /* Check if last DMA request was done with RELOAD */ + /* Set NBYTES to write and reload if size > 255 and generate RESTART */ + if( (hi2c->XferSize == 255) && (hi2c->XferSize < hi2c->XferCount) ) + { + /* Wait until TCR flag is set */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_TCR, RESET, I2C_TIMEOUT_TCR) != HAL_OK) + { + hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; + } + + /* Disable DMA Request */ + hi2c->Instance->CR1 &= ~I2C_CR1_TXDMAEN; + + /* Check if Errors has been detected during transfer */ + if(hi2c->ErrorCode != HAL_I2C_ERROR_NONE) + { + /* No need to Check TC flag, with AUTOEND mode the stop is automatically generated */ + /* Wait until STOPF flag is reset */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_STOPF, RESET, I2C_TIMEOUT_STOPF) != HAL_OK) + { + hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; + } + + /* Clear STOP Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); + + /* Clear Configuration Register 2 */ + __HAL_I2C_RESET_CR2(hi2c); + + hi2c->XferCount = 0; + + hi2c->State = HAL_I2C_STATE_READY; + HAL_I2C_ErrorCallback(hi2c); + } + else + { + hi2c->pBuffPtr += hi2c->XferSize; + hi2c->XferCount -= hi2c->XferSize; + if(hi2c->XferCount > 255) + { + hi2c->XferSize = 255; + } + else + { + hi2c->XferSize = hi2c->XferCount; + } + + DevAddress = (hi2c->Instance->CR2 & I2C_CR2_SADD); + + /* Enable the DMA Stream */ + HAL_DMA_Start_IT(hi2c->hdmatx, (uint32_t)hi2c->pBuffPtr, (uint32_t)&hi2c->Instance->TXDR, hi2c->XferSize); + + /* Send Slave Address */ + /* Set NBYTES to write and reload if size > 255 and generate RESTART */ + if( (hi2c->XferSize == 255) && (hi2c->XferSize < hi2c->XferCount) ) + { + I2C_TransferConfig(hi2c,DevAddress,hi2c->XferSize, I2C_RELOAD_MODE, I2C_NO_STARTSTOP); + } + else + { + I2C_TransferConfig(hi2c,DevAddress,hi2c->XferSize, I2C_AUTOEND_MODE, I2C_NO_STARTSTOP); + } + + /* Wait until TXIS flag is set */ + if(I2C_WaitOnTXISFlagUntilTimeout(hi2c, I2C_TIMEOUT_TXIS) != HAL_OK) + { + /* No need to Check TC flag, with AUTOEND mode the stop is automatically generated */ + /* Wait until STOPF flag is reset */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_STOPF, RESET, I2C_TIMEOUT_STOPF) != HAL_OK) + { + hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; + } + + /* Clear STOP Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); + + /* Clear Configuration Register 2 */ + __HAL_I2C_RESET_CR2(hi2c); + + hi2c->XferCount = 0; + + hi2c->State = HAL_I2C_STATE_READY; + + + + HAL_I2C_ErrorCallback(hi2c); + } + else + { + /* Enable DMA Request */ + hi2c->Instance->CR1 |= I2C_CR1_TXDMAEN; + } + } + } + else + { + /* No need to Check TC flag, with AUTOEND mode the stop is automatically generated */ + /* Wait until STOPF flag is reset */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_STOPF, RESET, I2C_TIMEOUT_STOPF) != HAL_OK) + { + hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; + } + + /* Clear STOP Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); + + /* Clear Configuration Register 2 */ + __HAL_I2C_RESET_CR2(hi2c); + + /* Disable DMA Request */ + hi2c->Instance->CR1 &= ~I2C_CR1_TXDMAEN; + + hi2c->XferCount = 0; + + hi2c->State = HAL_I2C_STATE_READY; + + /* Check if Errors has been detected during transfer */ + if(hi2c->ErrorCode != HAL_I2C_ERROR_NONE) + { + HAL_I2C_ErrorCallback(hi2c); + } + else + { + HAL_I2C_MemTxCpltCallback(hi2c); + } + } +} + +/** + * @brief DMA I2C Memory Read process complete callback + * @param hdma: DMA handle + * @retval None + */ +static void I2C_DMAMemReceiveCplt(DMA_HandleTypeDef *hdma) +{ + I2C_HandleTypeDef* hi2c = ( I2C_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + uint16_t DevAddress; + + /* Check if last DMA request was done with RELOAD */ + /* Set NBYTES to write and reload if size > 255 and generate RESTART */ + if( (hi2c->XferSize == 255) && (hi2c->XferSize < hi2c->XferCount) ) + { + /* Wait until TCR flag is set */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_TCR, RESET, I2C_TIMEOUT_TCR) != HAL_OK) + { + hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; + } + + /* Disable DMA Request */ + hi2c->Instance->CR1 &= ~I2C_CR1_RXDMAEN; + + /* Check if Errors has been detected during transfer */ + if(hi2c->ErrorCode != HAL_I2C_ERROR_NONE) + { + /* No need to Check TC flag, with AUTOEND mode the stop is automatically generated */ + /* Wait until STOPF flag is reset */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_STOPF, RESET, I2C_TIMEOUT_STOPF) != HAL_OK) + { + hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; + } + + /* Clear STOP Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); + + /* Clear Configuration Register 2 */ + __HAL_I2C_RESET_CR2(hi2c); + + hi2c->XferCount = 0; + + hi2c->State = HAL_I2C_STATE_READY; + HAL_I2C_ErrorCallback(hi2c); + } + else + { + hi2c->pBuffPtr += hi2c->XferSize; + hi2c->XferCount -= hi2c->XferSize; + if(hi2c->XferCount > 255) + { + hi2c->XferSize = 255; + } + else + { + hi2c->XferSize = hi2c->XferCount; + } + + DevAddress = (hi2c->Instance->CR2 & I2C_CR2_SADD); + + /* Enable the DMA Stream */ + HAL_DMA_Start_IT(hi2c->hdmarx, (uint32_t)&hi2c->Instance->RXDR, (uint32_t)hi2c->pBuffPtr, hi2c->XferSize); + + /* Send Slave Address */ + /* Set NBYTES to write and reload if size > 255 and generate RESTART */ + if( (hi2c->XferSize == 255) && (hi2c->XferSize < hi2c->XferCount) ) + { + I2C_TransferConfig(hi2c,DevAddress,hi2c->XferSize, I2C_RELOAD_MODE, I2C_NO_STARTSTOP); + } + else + { + I2C_TransferConfig(hi2c,DevAddress,hi2c->XferSize, I2C_AUTOEND_MODE, I2C_NO_STARTSTOP); + } + + /* Wait until RXNE flag is set */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_RXNE, RESET, I2C_TIMEOUT_RXNE) != HAL_OK) + { + hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; + } + + /* Check if Errors has been detected during transfer */ + if(hi2c->ErrorCode != HAL_I2C_ERROR_NONE) + { + /* No need to Check TC flag, with AUTOEND mode the stop is automatically generated */ + /* Wait until STOPF flag is reset */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_STOPF, RESET, I2C_TIMEOUT_STOPF) != HAL_OK) + { + hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; + } + + /* Clear STOP Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); + + /* Clear Configuration Register 2 */ + __HAL_I2C_RESET_CR2(hi2c); + + hi2c->XferCount = 0; + + hi2c->State = HAL_I2C_STATE_READY; + HAL_I2C_ErrorCallback(hi2c); + } + else + { + /* Enable DMA Request */ + hi2c->Instance->CR1 |= I2C_CR1_RXDMAEN; + } + } + } + else + { + /* No need to Check TC flag, with AUTOEND mode the stop is automatically generated */ + /* Wait until STOPF flag is reset */ + if(I2C_WaitOnFlagUntilTimeout(hi2c, I2C_FLAG_STOPF, RESET, I2C_TIMEOUT_STOPF) != HAL_OK) + { + hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; + } + + /* Clear STOP Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_STOPF); + + /* Clear Configuration Register 2 */ + __HAL_I2C_RESET_CR2(hi2c); + + /* Disable DMA Request */ + hi2c->Instance->CR1 &= ~I2C_CR1_RXDMAEN; + + hi2c->XferCount = 0; + + hi2c->State = HAL_I2C_STATE_READY; + + /* Check if Errors has been detected during transfer */ + if(hi2c->ErrorCode != HAL_I2C_ERROR_NONE) + { + HAL_I2C_ErrorCallback(hi2c); + } + else + { + HAL_I2C_MemRxCpltCallback(hi2c); + } + } +} + +/** + * @brief DMA I2C communication error callback. + * @param hdma : DMA handle + * @retval None + */ +static void I2C_DMAError(DMA_HandleTypeDef *hdma) +{ + I2C_HandleTypeDef* hi2c = ( I2C_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + + /* Disable Acknowledge */ + hi2c->Instance->CR2 |= I2C_CR2_NACK; + + hi2c->XferCount = 0; + + hi2c->State = HAL_I2C_STATE_READY; + + hi2c->ErrorCode |= HAL_I2C_ERROR_DMA; + + HAL_I2C_ErrorCallback(hi2c); +} + +/** + * @brief This function handles I2C Communication Timeout. + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param Flag: specifies the I2C flag to check. + * @param Status: The new Flag status (SET or RESET). + * @param Timeout: Timeout duration + * @retval HAL status + */ +static HAL_StatusTypeDef I2C_WaitOnFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Flag, FlagStatus Status, uint32_t Timeout) +{ + uint32_t tickstart = 0x00; + tickstart = HAL_GetTick(); + + /* Wait until flag is set */ + if(Status == RESET) + { + while(__HAL_I2C_GET_FLAG(hi2c, Flag) == RESET) + { + /* Check for the Timeout */ + if(Timeout != HAL_MAX_DELAY) + { + if((HAL_GetTick() - tickstart ) > Timeout) + { + hi2c->State= HAL_I2C_STATE_READY; + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + return HAL_TIMEOUT; + } + } + } + } + else + { + while(__HAL_I2C_GET_FLAG(hi2c, Flag) != RESET) + { + /* Check for the Timeout */ + if(Timeout != HAL_MAX_DELAY) + { + if((HAL_GetTick() - tickstart ) > Timeout) + { + hi2c->State= HAL_I2C_STATE_READY; + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + return HAL_TIMEOUT; + } + } + } + } + return HAL_OK; +} + +/** + * @brief This function handles I2C Communication Timeout for specific usage of TXIS flag. + * @param hi2c : Pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2C. + * @param Timeout: Timeout duration + * @retval HAL status + */ +static HAL_StatusTypeDef I2C_WaitOnTXISFlagUntilTimeout(I2C_HandleTypeDef *hi2c, uint32_t Timeout) +{ + uint32_t tickstart = 0x00; + tickstart = HAL_GetTick(); + + while(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_TXIS) == RESET) + { + if(__HAL_I2C_GET_FLAG(hi2c, I2C_FLAG_AF) == SET) + { + /* Clear NACKF Flag */ + __HAL_I2C_CLEAR_FLAG(hi2c, I2C_FLAG_AF); + + hi2c->ErrorCode |= HAL_I2C_ERROR_AF; + hi2c->State= HAL_I2C_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_ERROR; + } + + /* Check for the Timeout */ + if((HAL_GetTick() - tickstart ) > Timeout) + { + hi2c->ErrorCode |= HAL_I2C_ERROR_TIMEOUT; + hi2c->State= HAL_I2C_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_TIMEOUT; + } + } + return HAL_OK; +} + +/** + * @brief Handles I2Cx communication when starting transfer or during transfer (TC or TCR flag are set). + * @param hi2c: I2C handle. + * @param DevAddress: specifies the slave address to be programmed. + * @param Size: specifies the number of bytes to be programmed. + * This parameter must be a value between 0 and 255. + * @param Mode: new state of the I2C START condition generation. + * This parameter can be one of the following values: + * @arg I2C_RELOAD_MODE: Enable Reload mode . + * @arg I2C_AUTOEND_MODE: Enable Automatic end mode. + * @arg I2C_SOFTEND_MODE: Enable Software end mode. + * @param Request: new state of the I2C START condition generation. + * This parameter can be one of the following values: + * @arg I2C_NO_STARTSTOP: Don't Generate stop and start condition. + * @arg I2C_GENERATE_STOP: Generate stop condition (Size should be set to 0). + * @arg I2C_GENERATE_START_READ: Generate Restart for read request. + * @arg I2C_GENERATE_START_WRITE: Generate Restart for write request. + * @retval None + */ +static void I2C_TransferConfig(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t Size, uint32_t Mode, uint32_t Request) +{ + uint32_t tmpreg = 0; + + /* Check the parameters */ + assert_param(IS_I2C_ALL_INSTANCE(hi2c->Instance)); + assert_param(IS_TRANSFER_MODE(Mode)); + assert_param(IS_TRANSFER_REQUEST(Request)); + + /* Get the CR2 register value */ + tmpreg = hi2c->Instance->CR2; + + /* clear tmpreg specific bits */ + tmpreg &= (uint32_t)~((uint32_t)(I2C_CR2_SADD | I2C_CR2_NBYTES | I2C_CR2_RELOAD | I2C_CR2_AUTOEND | I2C_CR2_RD_WRN | I2C_CR2_START | I2C_CR2_STOP)); + + /* update tmpreg */ + tmpreg |= (uint32_t)(((uint32_t)DevAddress & I2C_CR2_SADD) | (((uint32_t)Size << 16 ) & I2C_CR2_NBYTES) | \ + (uint32_t)Mode | (uint32_t)Request); + + /* update CR2 register */ + hi2c->Instance->CR2 = tmpreg; +} + + +/** + * @} + */ + +/** + * @} + */ + +#endif /* HAL_I2C_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_i2c.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_i2c.h new file mode 100644 index 0000000000..a28b8d71d2 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_i2c.h @@ -0,0 +1,496 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_i2c.h + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief Header file of I2C HAL module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32L0xx_HAL_I2C_H +#define __STM32L0xx_HAL_I2C_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal_def.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @addtogroup I2C + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ + +/** + * @brief I2C Configuration Structure definition + */ +typedef struct +{ + uint32_t Timing; /*!< Specifies the I2C_TIMINGR_register value. + This parameter calculated by referring to I2C initialization + section in Reference manual */ + + uint32_t OwnAddress1; /*!< Specifies the first device own address. + This parameter can be a 7-bit or 10-bit address. */ + + uint32_t AddressingMode; /*!< Specifies if 7-bit or 10-bit addressing mode is selected. + This parameter can be a value of @ref I2C_addressing_mode */ + + uint32_t DualAddressMode; /*!< Specifies if dual addressing mode is selected. + This parameter can be a value of @ref I2C_dual_addressing_mode */ + + uint32_t OwnAddress2; /*!< Specifies the second device own address if dual addressing mode is selected + This parameter can be a 7-bit address. */ + + uint32_t OwnAddress2Masks; /*!< Specifies the acknoledge mask address second device own address if dual addressing mode is selected + This parameter can be a value of @ref I2C_own_address2_masks. */ + + uint32_t GeneralCallMode; /*!< Specifies if general call mode is selected. + This parameter can be a value of @ref I2C_general_call_addressing_mode. */ + + uint32_t NoStretchMode; /*!< Specifies if nostretch mode is selected. + This parameter can be a value of @ref I2C_nostretch_mode */ + +}I2C_InitTypeDef; + +/** + * @brief HAL State structures definition + */ +typedef enum +{ + HAL_I2C_STATE_RESET = 0x00, /*!< I2C not yet initialized or disabled */ + HAL_I2C_STATE_READY = 0x01, /*!< I2C initialized and ready for use */ + HAL_I2C_STATE_BUSY = 0x02, /*!< I2C internal process is ongoing */ + HAL_I2C_STATE_MASTER_BUSY_TX = 0x12, /*!< Master Data Transmission process is ongoing */ + HAL_I2C_STATE_MASTER_BUSY_RX = 0x22, /*!< Master Data Reception process is ongoing */ + HAL_I2C_STATE_SLAVE_BUSY_TX = 0x32, /*!< Slave Data Transmission process is ongoing */ + HAL_I2C_STATE_SLAVE_BUSY_RX = 0x42, /*!< Slave Data Reception process is ongoing */ + HAL_I2C_STATE_MEM_BUSY_TX = 0x52, /*!< Memory Data Transmission process is ongoing */ + HAL_I2C_STATE_MEM_BUSY_RX = 0x62, /*!< Memory Data Reception process is ongoing */ + HAL_I2C_STATE_TIMEOUT = 0x03, /*!< Timeout state */ + HAL_I2C_STATE_ERROR = 0x04 /*!< Reception process is ongoing */ +}HAL_I2C_StateTypeDef; + +/** + * @brief HAL I2C Error Code structure definition + */ +typedef enum +{ + HAL_I2C_ERROR_NONE = 0x00, /*!< No error */ + HAL_I2C_ERROR_BERR = 0x01, /*!< BERR error */ + HAL_I2C_ERROR_ARLO = 0x02, /*!< ARLO error */ + HAL_I2C_ERROR_AF = 0x04, /*!< ACKF error */ + HAL_I2C_ERROR_OVR = 0x08, /*!< OVR error */ + HAL_I2C_ERROR_DMA = 0x10, /*!< DMA transfer error */ + HAL_I2C_ERROR_TIMEOUT = 0x20, /*!< Timeout error */ + HAL_I2C_ERROR_SIZE = 0x40 /*!< Size Management error */ +}HAL_I2C_ErrorTypeDef; + +/** + * @brief I2C handle Structure definition + */ +typedef struct +{ + I2C_TypeDef *Instance; /*!< I2C registers base address */ + + I2C_InitTypeDef Init; /*!< I2C communication parameters */ + + uint8_t *pBuffPtr; /*!< Pointer to I2C transfer buffer */ + + uint16_t XferSize; /*!< I2C transfer size */ + + __IO uint16_t XferCount; /*!< I2C transfer counter */ + + DMA_HandleTypeDef *hdmatx; /*!< I2C Tx DMA handle parameters */ + + DMA_HandleTypeDef *hdmarx; /*!< I2C Rx DMA handle parameters */ + + HAL_LockTypeDef Lock; /*!< I2C locking object */ + + __IO HAL_I2C_StateTypeDef State; /*!< I2C communication state */ + + __IO HAL_I2C_ErrorTypeDef ErrorCode; /* I2C Error code */ + +}I2C_HandleTypeDef; + +/* Exported constants --------------------------------------------------------*/ + +/** @defgroup I2C_Exported_Constants + * @{ + */ + +/** @defgroup I2C_addressing_mode + * @{ + */ +#define I2C_ADDRESSINGMODE_7BIT ((uint32_t)0x00000001) +#define I2C_ADDRESSINGMODE_10BIT ((uint32_t)0x00000002) + +#define IS_I2C_ADDRESSING_MODE(MODE) (((MODE) == I2C_ADDRESSINGMODE_7BIT) || \ + ((MODE) == I2C_ADDRESSINGMODE_10BIT)) +/** + * @} + */ + +/** @defgroup I2C_dual_addressing_mode + * @{ + */ + +#define I2C_DUALADDRESS_DISABLED ((uint32_t)0x00000000) +#define I2C_DUALADDRESS_ENABLED I2C_OAR2_OA2EN + +#define IS_I2C_DUAL_ADDRESS(ADDRESS) (((ADDRESS) == I2C_DUALADDRESS_DISABLED) || \ + ((ADDRESS) == I2C_DUALADDRESS_ENABLED)) +/** + * @} + */ + +/** @defgroup I2C_own_address2_masks + * @{ + */ + +#define I2C_OA2_NOMASK ((uint8_t)0x00) +#define I2C_OA2_MASK01 ((uint8_t)0x01) +#define I2C_OA2_MASK02 ((uint8_t)0x02) +#define I2C_OA2_MASK03 ((uint8_t)0x03) +#define I2C_OA2_MASK04 ((uint8_t)0x04) +#define I2C_OA2_MASK05 ((uint8_t)0x05) +#define I2C_OA2_MASK06 ((uint8_t)0x06) +#define I2C_OA2_MASK07 ((uint8_t)0x07) + +#define IS_I2C_OWN_ADDRESS2_MASK(MASK) (((MASK) == I2C_OA2_NOMASK) || \ + ((MASK) == I2C_OA2_MASK01) || \ + ((MASK) == I2C_OA2_MASK02) || \ + ((MASK) == I2C_OA2_MASK03) || \ + ((MASK) == I2C_OA2_MASK04) || \ + ((MASK) == I2C_OA2_MASK05) || \ + ((MASK) == I2C_OA2_MASK06) || \ + ((MASK) == I2C_OA2_MASK07)) +/** + * @} + */ + +/** @defgroup I2C_general_call_addressing_mode + * @{ + */ +#define I2C_GENERALCALL_DISABLED ((uint32_t)0x00000000) +#define I2C_GENERALCALL_ENABLED I2C_CR1_GCEN + +#define IS_I2C_GENERAL_CALL(CALL) (((CALL) == I2C_GENERALCALL_DISABLED) || \ + ((CALL) == I2C_GENERALCALL_ENABLED)) +/** + * @} + */ + +/** @defgroup I2C_nostretch_mode + * @{ + */ +#define I2C_NOSTRETCH_DISABLED ((uint32_t)0x00000000) +#define I2C_NOSTRETCH_ENABLED I2C_CR1_NOSTRETCH + +#define IS_I2C_NO_STRETCH(STRETCH) (((STRETCH) == I2C_NOSTRETCH_DISABLED) || \ + ((STRETCH) == I2C_NOSTRETCH_ENABLED)) +/** + * @} + */ + +/** @defgroup I2C_Memory_Address_Size + * @{ + */ +#define I2C_MEMADD_SIZE_8BIT ((uint32_t)0x00000001) +#define I2C_MEMADD_SIZE_16BIT ((uint32_t)0x00000002) + +#define IS_I2C_MEMADD_SIZE(SIZE) (((SIZE) == I2C_MEMADD_SIZE_8BIT) || \ + ((SIZE) == I2C_MEMADD_SIZE_16BIT)) +/** + * @} + */ + +/** @defgroup I2C_ReloadEndMode_definition + * @{ + */ + +#define I2C_RELOAD_MODE I2C_CR2_RELOAD +#define I2C_AUTOEND_MODE I2C_CR2_AUTOEND +#define I2C_SOFTEND_MODE ((uint32_t)0x00000000) + +#define IS_TRANSFER_MODE(MODE) (((MODE) == I2C_RELOAD_MODE) || \ + ((MODE) == I2C_AUTOEND_MODE) || \ + ((MODE) == I2C_SOFTEND_MODE)) +/** + * @} + */ + +/** @defgroup I2C_StartStopMode_definition + * @{ + */ + +#define I2C_NO_STARTSTOP ((uint32_t)0x00000000) +#define I2C_GENERATE_STOP I2C_CR2_STOP +#define I2C_GENERATE_START_READ (uint32_t)(I2C_CR2_START | I2C_CR2_RD_WRN) +#define I2C_GENERATE_START_WRITE I2C_CR2_START + +#define IS_TRANSFER_REQUEST(REQUEST) (((REQUEST) == I2C_GENERATE_STOP) || \ + ((REQUEST) == I2C_GENERATE_START_READ) || \ + ((REQUEST) == I2C_GENERATE_START_WRITE) || \ + ((REQUEST) == I2C_NO_STARTSTOP)) + +/** + * @} + */ + +/** @defgroup I2C_Interrupt_configuration_definition + * @brief I2C Interrupt definition + * Elements values convention: 0xXXXXXXXX + * - XXXXXXXX : Interrupt control mask + * @{ + */ +#define I2C_IT_ERRI I2C_CR1_ERRIE +#define I2C_IT_TCI I2C_CR1_TCIE +#define I2C_IT_STOPI I2C_CR1_STOPIE +#define I2C_IT_NACKI I2C_CR1_NACKIE +#define I2C_IT_ADDRI I2C_CR1_ADDRIE +#define I2C_IT_RXI I2C_CR1_RXIE +#define I2C_IT_TXI I2C_CR1_TXIE + +/** + * @} + */ + + +/** @defgroup I2C_Flag_definition + * @{ + */ + +#define I2C_FLAG_TXE I2C_ISR_TXE +#define I2C_FLAG_TXIS I2C_ISR_TXIS +#define I2C_FLAG_RXNE I2C_ISR_RXNE +#define I2C_FLAG_ADDR I2C_ISR_ADDR +#define I2C_FLAG_AF I2C_ISR_NACKF +#define I2C_FLAG_STOPF I2C_ISR_STOPF +#define I2C_FLAG_TC I2C_ISR_TC +#define I2C_FLAG_TCR I2C_ISR_TCR +#define I2C_FLAG_BERR I2C_ISR_BERR +#define I2C_FLAG_ARLO I2C_ISR_ARLO +#define I2C_FLAG_OVR I2C_ISR_OVR +#define I2C_FLAG_PECERR I2C_ISR_PECERR +#define I2C_FLAG_TIMEOUT I2C_ISR_TIMEOUT +#define I2C_FLAG_ALERT I2C_ISR_ALERT +#define I2C_FLAG_BUSY I2C_ISR_BUSY +#define I2C_FLAG_DIR I2C_ISR_DIR + +/** + * @} + */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ + +/** @brief Reset I2C handle state + * @param __HANDLE__: specifies the I2C Handle. + * This parameter can be I2C where x: 1 or 2 to select the I2C peripheral. + * @retval None + */ +#define __HAL_I2C_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_I2C_STATE_RESET) + +/** @brief Enables or disables the specified I2C interrupts. + * @param __HANDLE__: specifies the I2C Handle. + * This parameter can be I2C where x: 1 or 2 to select the I2C peripheral. + * @param __INTERRUPT__: specifies the interrupt source to enable or disable. + * This parameter can be one of the following values: + * @arg I2C_IT_ERRI: Errors interrupt enable + * @arg I2C_IT_TCI: Transfer complete interrupt enable + * @arg I2C_IT_STOPI: STOP detection interrupt enable + * @arg I2C_IT_NACKI: NACK received interrupt enable + * @arg I2C_IT_ADDRI: Address match interrupt enable + * @arg I2C_IT_RXI: RX interrupt enable + * @arg I2C_IT_TXI: TX interrupt enable + * + * @retval None + */ + +#define __HAL_I2C_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR1 |= (__INTERRUPT__)) +#define __HAL_I2C_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR1 &= (~(__INTERRUPT__))) + +/** @brief Checks if the specified I2C interrupt source is enabled or disabled. + * @param __HANDLE__: specifies the I2C Handle. + * This parameter can be I2C where x: 1 or 2 to select the I2C peripheral. + * @param __INTERRUPT__: specifies the I2C interrupt source to check. + * This parameter can be one of the following values: + * @arg I2C_IT_ERRI: Errors interrupt enable + * @arg I2C_IT_TCI: Transfer complete interrupt enable + * @arg I2C_IT_STOPI: STOP detection interrupt enable + * @arg I2C_IT_NACKI: NACK received interrupt enable + * @arg I2C_IT_ADDRI: Address match interrupt enable + * @arg I2C_IT_RXI: RX interrupt enable + * @arg I2C_IT_TXI: TX interrupt enable + * + * @retval The new state of __IT__ (TRUE or FALSE). + */ +#define __HAL_I2C_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((((__HANDLE__)->Instance->CR1 & (__INTERRUPT__)) == (__INTERRUPT__)) ? SET : RESET) + +/** @brief Checks whether the specified I2C flag is set or not. + * @param __HANDLE__: specifies the I2C Handle. + * This parameter can be I2C where x: 1 or 2 to select the I2C peripheral. + * @param __FLAG__: specifies the flag to check. + * This parameter can be one of the following values: + * @arg I2C_FLAG_TXE: Transmit data register empty + * @arg I2C_FLAG_TXIS: Transmit interrupt status + * @arg I2C_FLAG_RXNE: Receive data register not empty + * @arg I2C_FLAG_ADDR: Address matched (slave mode) + * @arg I2C_FLAG_AF: Acknowledge failure received flag + * @arg I2C_FLAG_STOPF: STOP detection flag + * @arg I2C_FLAG_TC: Transfer complete (master mode) + * @arg I2C_FLAG_TCR: Transfer complete reload + * @arg I2C_FLAG_BERR: Bus error + * @arg I2C_FLAG_ARLO: Arbitration lost + * @arg I2C_FLAG_OVR: Overrun/Underrun + * @arg I2C_FLAG_PECERR: PEC error in reception + * @arg I2C_FLAG_TIMEOUT: Timeout or Tlow detection flag + * @arg I2C_FLAG_ALERT: SMBus alert + * @arg I2C_FLAG_BUSY: Bus busy + * @arg I2C_FLAG_DIR: Transfer direction (slave mode) + * + * @retval The new state of __FLAG__ (TRUE or FALSE). + */ +#define I2C_FLAG_MASK ((uint32_t)0x0001FFFF) +#define __HAL_I2C_GET_FLAG(__HANDLE__, __FLAG__) (((((__HANDLE__)->Instance->ISR) & ((__FLAG__) & I2C_FLAG_MASK)) == ((__FLAG__) & I2C_FLAG_MASK))) + +/** @brief Clears the I2C pending flags which are cleared by writing 1 in a specific bit. + * @param __HANDLE__: specifies the I2C Handle. + * This parameter can be I2C where x: 1 or 2 to select the I2C peripheral. + * @param __FLAG__: specifies the flag to clear. + * This parameter can be any combination of the following values: + * @arg I2C_FLAG_ADDR: Address matched (slave mode) + * @arg I2C_FLAG_AF: Acknowledge failure received flag + * @arg I2C_FLAG_STOPF: STOP detection flag + * @arg I2C_FLAG_BERR: Bus error + * @arg I2C_FLAG_ARLO: Arbitration lost + * @arg I2C_FLAG_OVR: Overrun/Underrun + * @arg I2C_FLAG_PECERR: PEC error in reception + * @arg I2C_FLAG_TIMEOUT: Timeout or Tlow detection flag + * @arg I2C_FLAG_ALERT: SMBus alert + * + * @retval None + */ +#define __HAL_I2C_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->ICR |= ((__FLAG__) & I2C_FLAG_MASK)) + + +#define __HAL_I2C_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 |= I2C_CR1_PE) +#define __HAL_I2C_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 &= ~I2C_CR1_PE) + +#define __HAL_I2C_RESET_CR2(__HANDLE__) ((__HANDLE__)->Instance->CR2 &= (uint32_t)~((uint32_t)(I2C_CR2_SADD | I2C_CR2_HEAD10R | I2C_CR2_NBYTES | I2C_CR2_RELOAD | I2C_CR2_RD_WRN))) + +#define __HAL_I2C_MEM_ADD_MSB(__ADDRESS__) ((uint8_t)((uint16_t)(((uint16_t)((__ADDRESS__) & (uint16_t)(0xFF00))) >> 8))) +#define __HAL_I2C_MEM_ADD_LSB(__ADDRESS__) ((uint8_t)((uint16_t)((__ADDRESS__) & (uint16_t)(0x00FF)))) + +#define __HAL_I2C_GENERATE_START(__ADDMODE__,__ADDRESS__) (((__ADDMODE__) == I2C_ADDRESSINGMODE_7BIT) ? (uint32_t)((((uint32_t)(__ADDRESS__) & (I2C_CR2_SADD)) | (I2C_CR2_START) | (I2C_CR2_AUTOEND)) & (~I2C_CR2_RD_WRN)) : \ + (uint32_t)((((uint32_t)(__ADDRESS__) & (I2C_CR2_SADD)) | (I2C_CR2_ADD10) | (I2C_CR2_START)) & (~I2C_CR2_RD_WRN))) + +#define IS_I2C_OWN_ADDRESS1(ADDRESS1) ((ADDRESS1) <= (uint32_t)0x000003FF) +#define IS_I2C_OWN_ADDRESS2(ADDRESS2) ((ADDRESS2) <= (uint16_t)0x00FF) + +/* Include I2C HAL Extension module */ +#include "stm32l0xx_hal_i2c_ex.h" + +/* Exported functions --------------------------------------------------------*/ +/* Initialization/de-initialization functions**********************************/ +HAL_StatusTypeDef HAL_I2C_Init(I2C_HandleTypeDef *hi2c); +HAL_StatusTypeDef HAL_I2C_DeInit (I2C_HandleTypeDef *hi2c); +void HAL_I2C_MspInit(I2C_HandleTypeDef *hi2c); +void HAL_I2C_MspDeInit(I2C_HandleTypeDef *hi2c); + +/* I/O operation functions ***************************************************/ + /******* Blocking mode: Polling */ +HAL_StatusTypeDef HAL_I2C_Master_Transmit(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t Timeout); +HAL_StatusTypeDef HAL_I2C_Master_Receive(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t Timeout); +HAL_StatusTypeDef HAL_I2C_Slave_Transmit(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size, uint32_t Timeout); +HAL_StatusTypeDef HAL_I2C_Slave_Receive(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size, uint32_t Timeout); +HAL_StatusTypeDef HAL_I2C_Mem_Write(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size, uint32_t Timeout); +HAL_StatusTypeDef HAL_I2C_Mem_Read(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size, uint32_t Timeout); +HAL_StatusTypeDef HAL_I2C_IsDeviceReady(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint32_t Trials, uint32_t Timeout); + + /******* Non-Blocking mode: Interrupt */ +HAL_StatusTypeDef HAL_I2C_Master_Transmit_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size); +HAL_StatusTypeDef HAL_I2C_Master_Receive_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size); +HAL_StatusTypeDef HAL_I2C_Slave_Transmit_IT(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size); +HAL_StatusTypeDef HAL_I2C_Slave_Receive_IT(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size); +HAL_StatusTypeDef HAL_I2C_Mem_Write_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size); +HAL_StatusTypeDef HAL_I2C_Mem_Read_IT(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size); + + /******* Non-Blocking mode: DMA */ +HAL_StatusTypeDef HAL_I2C_Master_Transmit_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size); +HAL_StatusTypeDef HAL_I2C_Master_Receive_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint8_t *pData, uint16_t Size); +HAL_StatusTypeDef HAL_I2C_Slave_Transmit_DMA(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size); +HAL_StatusTypeDef HAL_I2C_Slave_Receive_DMA(I2C_HandleTypeDef *hi2c, uint8_t *pData, uint16_t Size); +HAL_StatusTypeDef HAL_I2C_Mem_Write_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size); +HAL_StatusTypeDef HAL_I2C_Mem_Read_DMA(I2C_HandleTypeDef *hi2c, uint16_t DevAddress, uint16_t MemAddress, uint16_t MemAddSize, uint8_t *pData, uint16_t Size); + + /******* I2C IRQHandler and Callbacks used in non blocking modes (Interrupt and DMA) */ +void HAL_I2C_EV_IRQHandler(I2C_HandleTypeDef *hi2c); +void HAL_I2C_ER_IRQHandler(I2C_HandleTypeDef *hi2c); +void HAL_I2C_MasterTxCpltCallback(I2C_HandleTypeDef *hi2c); +void HAL_I2C_MasterRxCpltCallback(I2C_HandleTypeDef *hi2c); +void HAL_I2C_SlaveTxCpltCallback(I2C_HandleTypeDef *hi2c); +void HAL_I2C_SlaveRxCpltCallback(I2C_HandleTypeDef *hi2c); +void HAL_I2C_MemTxCpltCallback(I2C_HandleTypeDef *hi2c); +void HAL_I2C_MemRxCpltCallback(I2C_HandleTypeDef *hi2c); +void HAL_I2C_ErrorCallback(I2C_HandleTypeDef *hi2c); + +/* Peripheral State functions ************************************************/ +HAL_I2C_StateTypeDef HAL_I2C_GetState(I2C_HandleTypeDef *hi2c); +uint32_t HAL_I2C_GetError(I2C_HandleTypeDef *hi2c); + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + + +#endif /* __STM32L0xx_HAL_I2C_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_i2c_ex.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_i2c_ex.c new file mode 100644 index 0000000000..ab8a8b968a --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_i2c_ex.c @@ -0,0 +1,288 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_i2c_ex.c + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief Extended I2C HAL module driver. + * + * This file provides firmware functions to manage the following + * functionalities of the Inter Integrated Circuit (I2C) peripheral: + * + Extended Control methods + * + @verbatim + ============================================================================== + ##### I2C peripheral extended features ##### + ============================================================================== + + [..] Comparing to other previous devices, the I2C interface for STM32L0XX + devices contains the following additional features + + (+) Possibility to disable or enable Analog Noise Filter + (+) Use of a configured Digital Noise Filter + (+) Disable or enable wakeup from Stop mode + + ##### How to use this driver ##### + ============================================================================== + [..] This driver provides functions to configure Noise Filter + + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @defgroup I2CEx + * @brief I2C HAL module driver + * @{ + */ + +#ifdef HAL_I2C_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup I2CEX_Private_Functions + * @{ + */ + + +/** @defgroup I2CEX_Group1 Peripheral Control methods + * @brief management functions + * +@verbatim + =============================================================================== + ##### Peripheral Control methods ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Configure Noise Filters + +@endverbatim + * @{ + */ + +/** + * @brief Configures I2C Analog noise filter. + * @param hi2c : pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2Cx peripheral. + * @param AnalogFilter : new state of the Analog filter. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2CEx_AnalogFilter_Config(I2C_HandleTypeDef *hi2c, uint32_t AnalogFilter) +{ + /* Check the parameters */ + assert_param(IS_I2C_ALL_INSTANCE(hi2c->Instance)); + assert_param(IS_I2C_ANALOG_FILTER(AnalogFilter)); + + if((hi2c->State == HAL_I2C_STATE_BUSY) || (hi2c->State == HAL_I2C_STATE_MASTER_BUSY_TX) || (hi2c->State == HAL_I2C_STATE_MASTER_BUSY_RX) + || (hi2c->State == HAL_I2C_STATE_SLAVE_BUSY_TX) || (hi2c->State == HAL_I2C_STATE_SLAVE_BUSY_RX)) + { + return HAL_BUSY; + } + + /* Process Locked */ + __HAL_LOCK(hi2c); + + hi2c->State = HAL_I2C_STATE_BUSY; + + /* Disable the selected I2C peripheral */ + __HAL_I2C_DISABLE(hi2c); + + /* Reset I2Cx ANOFF bit */ + hi2c->Instance->CR1 &= ~(I2C_CR1_ANFOFF); + + /* Set analog filter bit*/ + hi2c->Instance->CR1 |= AnalogFilter; + + __HAL_I2C_ENABLE(hi2c); + + hi2c->State = HAL_I2C_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_OK; +} + +/** + * @brief Configures I2C Digital noise filter. + * @param hi2c : pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2Cx peripheral. + * @param DigitalFilter : Coefficient of digital noise filter between 0x00 and 0x0F. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2CEx_DigitalFilter_Config(I2C_HandleTypeDef *hi2c, uint32_t DigitalFilter) +{ + uint32_t tmpreg = 0; + + /* Check the parameters */ + assert_param(IS_I2C_ALL_INSTANCE(hi2c->Instance)); + assert_param(IS_I2C_DIGITAL_FILTER(DigitalFilter)); + + if((hi2c->State == HAL_I2C_STATE_BUSY) || (hi2c->State == HAL_I2C_STATE_MASTER_BUSY_TX) || (hi2c->State == HAL_I2C_STATE_MASTER_BUSY_RX) + || (hi2c->State == HAL_I2C_STATE_SLAVE_BUSY_TX) || (hi2c->State == HAL_I2C_STATE_SLAVE_BUSY_RX)) + { + return HAL_BUSY; + } + + /* Process Locked */ + __HAL_LOCK(hi2c); + + hi2c->State = HAL_I2C_STATE_BUSY; + + /* Disable the selected I2C peripheral */ + __HAL_I2C_DISABLE(hi2c); + + /* Get the old register value */ + tmpreg = hi2c->Instance->CR1; + + /* Reset I2Cx DNF bits [11:8] */ + tmpreg &= ~(I2C_CR1_DFN); + + /* Set I2Cx DNF coefficient */ + tmpreg |= DigitalFilter << 8; + + /* Store the new register value */ + hi2c->Instance->CR1 = tmpreg; + + __HAL_I2C_ENABLE(hi2c); + + hi2c->State = HAL_I2C_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_OK; +} + +/** + * @brief Enables I2C wakeup from stop mode. + * @param hi2c : pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2Cx peripheral. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2CEx_EnableWakeUp (I2C_HandleTypeDef *hi2c) +{ + /* Check the parameters */ + assert_param(IS_I2C_ALL_INSTANCE(hi2c->Instance)); + + if((hi2c->State == HAL_I2C_STATE_BUSY) || (hi2c->State == HAL_I2C_STATE_MASTER_BUSY_TX) || (hi2c->State == HAL_I2C_STATE_MASTER_BUSY_RX) + || (hi2c->State == HAL_I2C_STATE_SLAVE_BUSY_TX) || (hi2c->State == HAL_I2C_STATE_SLAVE_BUSY_RX)) + { + return HAL_BUSY; + } + + /* Process Locked */ + __HAL_LOCK(hi2c); + + hi2c->State = HAL_I2C_STATE_BUSY; + + /* Disable the selected I2C peripheral */ + __HAL_I2C_DISABLE(hi2c); + + /* Enable wakeup from stop mode */ + hi2c->Instance->CR1 |= I2C_CR1_WUPEN; + + __HAL_I2C_ENABLE(hi2c); + + hi2c->State = HAL_I2C_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_OK; +} + + +/** + * @brief Disables I2C wakeup from stop mode. + * @param hi2c : pointer to a I2C_HandleTypeDef structure that contains + * the configuration information for the specified I2Cx peripheral. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2CEx_DisableWakeUp (I2C_HandleTypeDef *hi2c) +{ + /* Check the parameters */ + assert_param(IS_I2C_ALL_INSTANCE(hi2c->Instance)); + + if((hi2c->State == HAL_I2C_STATE_BUSY) || (hi2c->State == HAL_I2C_STATE_MASTER_BUSY_TX) || (hi2c->State == HAL_I2C_STATE_MASTER_BUSY_RX) + || (hi2c->State == HAL_I2C_STATE_SLAVE_BUSY_TX) || (hi2c->State == HAL_I2C_STATE_SLAVE_BUSY_RX)) + { + return HAL_BUSY; + } + + /* Process Locked */ + __HAL_LOCK(hi2c); + + hi2c->State = HAL_I2C_STATE_BUSY; + + /* Disable the selected I2C peripheral */ + __HAL_I2C_DISABLE(hi2c); + + /* Enable wakeup from stop mode */ + hi2c->Instance->CR1 &= ~(I2C_CR1_WUPEN); + + __HAL_I2C_ENABLE(hi2c); + + hi2c->State = HAL_I2C_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2c); + + return HAL_OK; +} + +/** + * @} + */ + +/** + * @} + */ + +#endif /* HAL_I2C_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_i2c_ex.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_i2c_ex.h new file mode 100644 index 0000000000..8402ffadfb --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_i2c_ex.h @@ -0,0 +1,112 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_i2c_ex.h + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief Header file of I2C HAL Extension module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32L0xx_HAL_I2C_EX_H +#define __STM32L0xx_HAL_I2C_EX_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal_def.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @addtogroup I2CEx + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/* Exported constants --------------------------------------------------------*/ + +/** @defgroup I2CEx_Exported_Constants + * @{ + */ + +/** @defgroup I2CEx_Analog_Filter + * @{ + */ +#define I2C_ANALOGFILTER_ENABLED ((uint32_t)0x00000000) +#define I2C_ANALOGFILTER_DISABLED I2C_CR1_ANFOFF + +#define IS_I2C_ANALOG_FILTER(FILTER) (((FILTER) == I2C_ANALOGFILTER_ENABLED) || \ + ((FILTER) == I2C_ANALOGFILTER_DISABLED)) +/** + * @} + */ + +/** @defgroup I2CEx_Digital_Filter + * @{ + */ +#define IS_I2C_DIGITAL_FILTER(FILTER) ((FILTER) <= 0x0000000F) +/** + * @} + */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ +/* Exported functions --------------------------------------------------------*/ + +/* Peripheral Control methods ************************************************/ +HAL_StatusTypeDef HAL_I2CEx_AnalogFilter_Config(I2C_HandleTypeDef *hi2c, uint32_t AnalogFilter); +HAL_StatusTypeDef HAL_I2CEx_DigitalFilter_Config(I2C_HandleTypeDef *hi2c, uint32_t DigitalFilter); +HAL_StatusTypeDef HAL_I2CEx_EnableWakeUp (I2C_HandleTypeDef *hi2c); +HAL_StatusTypeDef HAL_I2CEx_DisableWakeUp (I2C_HandleTypeDef *hi2c); + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __STM32L0xx_HAL_I2C_EX_H */ + + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_i2s.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_i2s.c new file mode 100644 index 0000000000..9d76b7a2f0 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_i2s.c @@ -0,0 +1,1366 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_i2s.c + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief I2S HAL module driver. + * + * This file provides firmware functions to manage the following + * functionalities of the Integrated Interchip Sound (I2S) peripheral: + * + Initialization and de-initialization functions + * + IO operation functions + * + Peripheral State and Errors functions + @verbatim + =============================================================================== + ##### How to use this driver ##### + =============================================================================== + [..] + The I2S HAL driver can be used as follow: + + (#) Declare a I2S_HandleTypeDef handle structure. + (#) Initialize the I2S low level resources by implement the HAL_I2S_MspInit() API: + (##) Enable the SPIx interface clock. + (##) I2S pins configuration: + (+++) Enable the clock for the I2S GPIOs. + (+++) Configure these I2S pins as alternate function pull-up. + (##) NVIC configuration if you need to use interrupt process (HAL_I2S_Transmit_IT() + and HAL_I2S_Receive_IT() APIs). + (+++) Configure the I2Sx interrupt priority. + (+++) Enable the NVIC I2S IRQ handle. + (##) DMA Configuration if you need to use DMA process (HAL_I2S_Transmit_DMA() + and HAL_I2S_Receive_DMA() APIs: + (+++) Declare a DMA handle structure for the Tx/Rx stream. + (+++) Enable the DMAx interface clock. + (+++) Configure the declared DMA handle structure with the required Tx/Rx parameters. + (+++) Configure the DMA Tx/Rx Stream. + (+++) Associate the initilalized DMA handle to the I2S DMA Tx/Rx handle. + (+++) Configure the priority and enable the NVIC for the transfer complete interrupt on the + DMA Tx/Rx Stream. + + (#) Program the Mode, Standard, Data Format, MCLK Output, Audio frequency and Polarity + using HAL_I2S_Init() function. + + -@- The specific I2S interrupts (Transmission complete interrupt, + RXNE interrupt and Error Interrupts) will be managed using the macros + __I2S_ENABLE_IT() and __I2S_DISABLE_IT() inside the transmit and receive process. + (#) Three mode of operations are available within this driver : + + *** Polling mode IO operation *** + ================================= + [..] + (+) Send an amount of data in blocking mode using HAL_I2S_Transmit() + (+) Receive an amount of data in blocking mode using HAL_I2S_Receive() + + *** Interrupt mode IO operation *** + =================================== + [..] + (+) Send an amount of data in non blocking mode using HAL_I2S_Transmit_IT() + (+) At transmission end of transfer HAL_I2S_TxCpltCallback is executed and user can + add his own code by customization of function pointer HAL_I2S_TxCpltCallback + (+) Receive an amount of data in non blocking mode using HAL_I2S_Receive_IT() + (+) At reception end of transfer HAL_I2S_RxCpltCallback is executed and user can + add his own code by customization of function pointer HAL_I2S_RxCpltCallback + (+) In case of transfer Error, HAL_I2S_ErrorCallback() function is executed and user can + add his own code by customization of function pointer HAL_I2S_ErrorCallback + + *** DMA mode IO operation *** + ============================== + [..] + (+) Send an amount of data in non blocking mode (DMA) using HAL_I2S_Transmit_DMA() + (+) At transmission end of half transfer HAL_I2S_TxHalfCpltCallback is executed and user can + add his own code by customization of function pointer HAL_I2S_TxHalfCpltCallback + (+) At transmission end of transfer HAL_I2S_TxCpltCallback is executed and user can + add his own code by customization of function pointer HAL_I2S_TxCpltCallback + (+) Receive an amount of data in non blocking mode (DMA) using HAL_I2S_Receive_DMA() + (+) At reception end of half transfer HAL_I2S_RxHalfCpltCallback is executed and user can + add his own code by customization of function pointer HAL_I2S_RxHalfCpltCallback + (+) At reception end of transfer HAL_I2S_RxCpltCallback is executed and user can + add his own code by customization of function pointer HAL_I2S_RxCpltCallback + (+) In case of transfer Error, HAL_I2S_ErrorCallback() function is executed and user can + add his own code by customization of function pointer HAL_I2S_ErrorCallback + (+) Pause the DMA Transfer using HAL_I2S_DMAPause() + (+) Resume the DMA Transfer using HAL_I2S_DMAResume() + (+) Stop the DMA Transfer using HAL_I2S_DMAStop() + + *** I2S HAL driver macros list *** + =================================== + [..] + Below the list of most used macros in USART HAL driver. + + (+) __HAL_I2S_ENABLE: Enable the specified SPI peripheral (in I2S mode) + (+) __HAL_I2S_DISABLE: Disable the specified SPI peripheral (in I2S mode) + (+) __HAL_I2S_ENABLE_IT : Enable the specified I2S interrupts + (+) __HAL_I2S_DISABLE_IT : Disable the specified I2S interrupts + (+) __HAL_I2S_GET_FLAG: Check whether the specified I2S flag is set or not + + [..] + (@) You can refer to the I2S HAL driver header file for more useful macros + + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @defgroup I2S + * @brief I2S HAL module driver + * @{ + */ + +#ifdef HAL_I2S_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +static HAL_StatusTypeDef I2S_Transmit_IT(I2S_HandleTypeDef *hi2s); +static HAL_StatusTypeDef I2S_Receive_IT(I2S_HandleTypeDef *hi2s); +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup I2S_Private_Functions + * @{ + */ + +/** @defgroup I2S_Group1 Initialization and de-initialization functions + * @brief Initialization and Configuration functions + * +@verbatim + =============================================================================== + ##### Initialization and de-initialization functions ##### + =============================================================================== + [..] This subsection provides a set of functions allowing to initialize and + de-initialiaze the I2Sx peripheral in simplex mode: + + (+) User must Implement HAL_I2S_MspInit() function in which he configures + all related peripherals resources (CLOCK, GPIO, DMA, IT and NVIC ). + + (+) Call the function HAL_I2S_Init() to configure the selected device with + the selected configuration: + (++) Mode + (++) Standard + (++) Data Format + (++) MCLK Output + (++) Audio frequency + (++) Polarity + + (+) Call the function HAL_I2S_DeInit() to restore the default configuration + of the selected I2Sx periperal. +@endverbatim + * @{ + */ + +/** + * @brief Initializes the I2S according to the specified parameters + * in the I2S_InitTypeDef and create the associated handle. + * @param hi2s: pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2S_Init(I2S_HandleTypeDef *hi2s) +{ + uint32_t tmpreg = 0, i2sdiv = 2, i2sodd = 0, packetlength = 1; + uint32_t tmp = 0, i2sclk = 0; + + /* Check the I2S handle allocation */ + if(hi2s == NULL) + { + return HAL_ERROR; + } + + /* Check the I2S parameters */ + assert_param(IS_I2S_MODE(hi2s->Init.Mode)); + assert_param(IS_I2S_STANDARD(hi2s->Init.Standard)); + assert_param(IS_I2S_DATA_FORMAT(hi2s->Init.DataFormat)); + assert_param(IS_I2S_MCLK_OUTPUT(hi2s->Init.MCLKOutput)); + assert_param(IS_I2S_AUDIO_FREQ(hi2s->Init.AudioFreq)); + assert_param(IS_I2S_CPOL(hi2s->Init.CPOL)); + + if(hi2s->State == HAL_I2S_STATE_RESET) + { + /* Init the low level hardware : GPIO, CLOCK, CORTEX...etc */ + HAL_I2S_MspInit(hi2s); + } + + hi2s->State = HAL_I2S_STATE_BUSY; + + /*----------------------- SPIx I2SCFGR & I2SPR Configuration ---------------*/ + /* Clear I2SMOD, I2SE, I2SCFG, PCMSYNC, I2SSTD, CKPOL, DATLEN and CHLEN bits */ + hi2s->Instance->I2SCFGR &= (uint32_t)~((uint32_t)SPI_I2SCFGR_CHLEN | SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CKPOL | \ + SPI_I2SCFGR_I2SSTD | SPI_I2SCFGR_PCMSYNC | SPI_I2SCFGR_I2SCFG | \ + SPI_I2SCFGR_I2SE | SPI_I2SCFGR_I2SMOD); + hi2s->Instance->I2SPR = 0x0002; + + /* Get the I2SCFGR register value */ + tmpreg = hi2s->Instance->I2SCFGR; + + /* If the default frequency value has to be written, reinitialize i2sdiv and i2sodd */ + /* If the requested audio frequency is not the default, compute the prescaler */ + if(hi2s->Init.AudioFreq != I2S_AUDIOFREQ_DEFAULT) + { + /* Check the frame length (For the Prescaler computing) *******************/ + if(hi2s->Init.DataFormat != I2S_DATAFORMAT_16B) + { + /* Packet length is 32 bits */ + packetlength = 2; + } + + /* Get I2S source Clock frequency ****************************************/ + /* I2S clock source is SystemClock for stm32l0xx devices */ + + i2sclk = HAL_RCC_GetSysClockFreq(); + + /* Compute the Real divider depending on the MCLK output state, with a floating point */ + if(hi2s->Init.MCLKOutput == I2S_MCLKOUTPUT_ENABLE) + { + /* MCLK output is enabled */ + tmp = (uint32_t)(((((i2sclk / 256) * 10) / hi2s->Init.AudioFreq)) + 5); + } + else + { + /* MCLK output is disabled */ + tmp = (uint32_t)(((((i2sclk / (32 * packetlength)) *10 ) / hi2s->Init.AudioFreq)) + 5); + } + + /* Remove the flatting point */ + tmp = tmp / 10; + + /* Check the parity of the divider */ + i2sodd = (uint32_t)(tmp & (uint32_t)1); + + /* Compute the i2sdiv prescaler */ + i2sdiv = (uint32_t)((tmp - i2sodd) / 2); + + /* Get the Mask for the Odd bit (SPI_I2SPR[8]) register */ + i2sodd = (uint32_t) (i2sodd << 8); + } + + /* Test if the divider is 1 or 0 or greater than 0xFF */ + if((i2sdiv < 2) || (i2sdiv > 0xFF)) + { + /* Set the default values */ + i2sdiv = 2; + i2sodd = 0; + } + + /* Write to SPIx I2SPR register the computed value */ + hi2s->Instance->I2SPR = (uint32_t)((uint32_t)i2sdiv | (uint32_t)(i2sodd | (uint32_t)hi2s->Init.MCLKOutput)); + + /* Configure the I2S with the I2S_InitStruct values */ + tmpreg |= (uint32_t)(SPI_I2SCFGR_I2SMOD | hi2s->Init.Mode | hi2s->Init.Standard | hi2s->Init.DataFormat | hi2s->Init.CPOL); + + /* Write to SPIx I2SCFGR */ + hi2s->Instance->I2SCFGR = tmpreg; + + hi2s->ErrorCode = HAL_I2S_ERROR_NONE; + hi2s->State= HAL_I2S_STATE_READY; + + return HAL_OK; +} + +/** + * @brief DeInitializes the I2S peripheral + * @param hi2s: pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2S_DeInit(I2S_HandleTypeDef *hi2s) +{ + /* Check the I2S handle allocation */ + if(hi2s == NULL) + { + return HAL_ERROR; + } + + hi2s->State = HAL_I2S_STATE_BUSY; + + /* DeInit the low level hardware: GPIO, CLOCK, NVIC... */ + HAL_I2S_MspDeInit(hi2s); + + hi2s->ErrorCode = HAL_I2S_ERROR_NONE; + hi2s->State = HAL_I2S_STATE_RESET; + + /* Release Lock */ + __HAL_UNLOCK(hi2s); + + return HAL_OK; +} + +/** + * @brief I2S MSP Init + * @param hi2s: pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @retval None + */ + __weak void HAL_I2S_MspInit(I2S_HandleTypeDef *hi2s) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_I2S_MspInit could be implenetd in the user file + */ +} + +/** + * @brief I2S MSP DeInit + * @param hi2s: pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @retval None + */ + __weak void HAL_I2S_MspDeInit(I2S_HandleTypeDef *hi2s) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_I2S_MspDeInit could be implenetd in the user file + */ +} + +/** + * @} + */ + +/** @defgroup I2S_Group2 IO operation functions + * @brief Data transfers functions + * +@verbatim + =============================================================================== + ##### IO operation functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to manage the I2S data + transfers. + + (#) There is two mode of transfer: + (++) Blocking mode : The communication is performed in the polling mode. + The status of all data processing is returned by the same function + after finishing transfer. + (++) No-Blocking mode : The communication is performed using Interrupts + or DMA. These functions return the status of the transfer startup. + The end of the data processing will be indicated through the + dedicated I2S IRQ when using Interrupt mode or the DMA IRQ when + using DMA mode. + + (#) Blocking mode functions are : + (++) HAL_I2S_Transmit() + (++) HAL_I2S_Receive() + + (#) No-Blocking mode functions with Interrupt are : + (++) HAL_I2S_Transmit_IT() + (++) HAL_I2S_Receive_IT() + + (#) No-Blocking mode functions with DMA are : + (++) HAL_I2S_Transmit_DMA() + (++) HAL_I2S_Receive_DMA() + + (#) A set of Transfer Complete Callbacks are provided in No_Blocking mode: + (++) HAL_I2S_TxCpltCallback() + (++) HAL_I2S_RxCpltCallback() + (++) HAL_I2S_ErrorCallback() + +@endverbatim + * @{ + */ + +/** + * @brief Transmit an amount of data in blocking mode + * @param hi2s: pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @param pData: a 16-bit pointer to data buffer. + * @param Size: number of data sample to be sent: + * @note When a 16-bit data frame or a 16-bit data frame extended is selected during the I2S + * configuration phase, the Size parameter means the number of 16-bit data length + * in the transaction and when a 24-bit data frame or a 32-bit data frame is selected + * the Size parameter means the number of 16-bit data length. + * @param Timeout: Timeout duration + * @note The I2S is kept enabled at the end of transaction to avoid the clock de-synchronization + * between Master and Slave(example: audio streaming). + * @note This function can use an Audio Frequency up to 44KHz when I2S Clock Source is 32MHz + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2S_Transmit(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size, uint32_t Timeout) +{ + uint32_t tmp1 = 0, tmp2 = 0; + if((pData == NULL ) || (Size == 0)) + { + return HAL_ERROR; + } + + if(hi2s->State == HAL_I2S_STATE_READY) + { + tmp1 = hi2s->Instance->I2SCFGR & (SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN); + tmp2 = hi2s->Instance->I2SCFGR & (SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN); + if((tmp1 == I2S_DATAFORMAT_24B)|| \ + (tmp2 == I2S_DATAFORMAT_32B)) + { + hi2s->TxXferSize = Size*2; + hi2s->TxXferCount = Size*2; + } + else + { + hi2s->TxXferSize = Size; + hi2s->TxXferCount = Size; + } + + /* Process Locked */ + __HAL_LOCK(hi2s); + + hi2s->State = HAL_I2S_STATE_BUSY_TX; + + /* Check if the I2S is already enabled */ + if((hi2s->Instance->I2SCFGR &SPI_I2SCFGR_I2SE) != SPI_I2SCFGR_I2SE) + { + /* Enable I2S peripheral */ + __HAL_I2S_ENABLE(hi2s); + } + + while(hi2s->TxXferCount > 0) + { + hi2s->Instance->DR = (*pData++); + hi2s->TxXferCount--; + /* Wait until TXE flag is set */ + if (I2S_WaitFlagStateUntilTimeout(hi2s, I2S_FLAG_TXE, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + } + /* Wait until Busy flag is reset */ + if (I2S_WaitFlagStateUntilTimeout(hi2s, I2S_FLAG_BSY, SET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + hi2s->State = HAL_I2S_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2s); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive an amount of data in blocking mode + * @param hi2s: pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @param pData: a 16-bit pointer to data buffer. + * @param Size: number of data sample to be sent: + * @note When a 16-bit data frame or a 16-bit data frame extended is selected during the I2S + * configuration phase, the Size parameter means the number of 16-bit data length + * in the transaction and when a 24-bit data frame or a 32-bit data frame is selected + * the Size parameter means the number of 16-bit data length. + * @param Timeout: Timeout duration + * @note The I2S is kept enabled at the end of transaction to avoid the clock de-synchronization + * between Master and Slave(example: audio streaming). + * @note In I2S Master Receiver mode, just after enabling the peripheral the clock will be generate + * in continouse way and as the I2S is not disabled at the end of the I2S transaction. + * @note This function can use an Audio Frequency up to 44KHz when I2S Clock Source is 32MHz + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2S_Receive(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size, uint32_t Timeout) +{ + uint32_t tmp1 = 0, tmp2 = 0; + if((pData == NULL ) || (Size == 0)) + { + return HAL_ERROR; + } + + if(hi2s->State == HAL_I2S_STATE_READY) + { + tmp1 = hi2s->Instance->I2SCFGR & (SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN); + tmp2 = hi2s->Instance->I2SCFGR & (SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN); + if((tmp1 == I2S_DATAFORMAT_24B)|| \ + (tmp2 == I2S_DATAFORMAT_32B)) + { + hi2s->RxXferSize = Size*2; + hi2s->RxXferCount = Size*2; + } + else + { + hi2s->RxXferSize = Size; + hi2s->RxXferCount = Size; + } + /* Process Locked */ + __HAL_LOCK(hi2s); + + hi2s->State = HAL_I2S_STATE_BUSY_RX; + + /* Check if the I2S is already enabled */ + if((hi2s->Instance->I2SCFGR & SPI_I2SCFGR_I2SE) != SPI_I2SCFGR_I2SE) + { + /* Enable I2S peripheral */ + __HAL_I2S_ENABLE(hi2s); + } + + /* Check if Master Receiver mode is selected */ + if((hi2s->Instance->I2SCFGR & SPI_I2SCFGR_I2SCFG) == I2S_MODE_MASTER_RX) + { + /* Clear the Overrun Flag by a read operation on the SPI_DR register followed by a read + access to the SPI_SR register. */ + __HAL_I2S_CLEAR_OVRFLAG(hi2s); + } + + /* Receive data */ + while(hi2s->RxXferCount > 0) + { + /* Wait until RXNE flag is set */ + if (I2S_WaitFlagStateUntilTimeout(hi2s, I2S_FLAG_RXNE, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + (*pData++) = hi2s->Instance->DR; + hi2s->RxXferCount--; + } + + hi2s->State = HAL_I2S_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2s); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Transmit an amount of data in non-blocking mode with Interrupt + * @param hi2s: pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @param pData: a 16-bit pointer to data buffer. + * @param Size: number of data sample to be sent: + * @note When a 16-bit data frame or a 16-bit data frame extended is selected during the I2S + * configuration phase, the Size parameter means the number of 16-bit data length + * in the transaction and when a 24-bit data frame or a 32-bit data frame is selected + * the Size parameter means the number of 16-bit data length. + * @note The I2S is kept enabled at the end of transaction to avoid the clock de-synchronization + * between Master and Slave(example: audio streaming). + * @note This function can use an Audio Frequency up to 32KHz when I2S Clock Source is 32MHz + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2S_Transmit_IT(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size) +{ + uint32_t tmp1 = 0, tmp2 = 0; + if(hi2s->State == HAL_I2S_STATE_READY) + { + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + hi2s->pTxBuffPtr = pData; + tmp1 = hi2s->Instance->I2SCFGR & (SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN); + tmp2 = hi2s->Instance->I2SCFGR & (SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN); + if((tmp1 == I2S_DATAFORMAT_24B)|| \ + (tmp2 == I2S_DATAFORMAT_32B)) + { + hi2s->TxXferSize = Size*2; + hi2s->TxXferCount = Size*2; + } + else + { + hi2s->TxXferSize = Size; + hi2s->TxXferCount = Size; + } + + /* Process Locked */ + __HAL_LOCK(hi2s); + + hi2s->State = HAL_I2S_STATE_BUSY_TX; + hi2s->ErrorCode = HAL_I2S_ERROR_NONE; + + /* Enable TXE and ERR interrupt */ + __HAL_I2S_ENABLE_IT(hi2s, (I2S_IT_TXE | I2S_IT_ERR)); + + /* Check if the I2S is already enabled */ + if((hi2s->Instance->I2SCFGR &SPI_I2SCFGR_I2SE) != SPI_I2SCFGR_I2SE) + { + /* Enable I2S peripheral */ + __HAL_I2S_ENABLE(hi2s); + } + + /* Process Unlocked */ + __HAL_UNLOCK(hi2s); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive an amount of data in non-blocking mode with Interrupt + * @param hi2s: pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @param pData: a 16-bit pointer to the Receive data buffer. + * @param Size: number of data sample to be sent: + * @note When a 16-bit data frame or a 16-bit data frame extended is selected during the I2S + * configuration phase, the Size parameter means the number of 16-bit data length + * in the transaction and when a 24-bit data frame or a 32-bit data frame is selected + * the Size parameter means the number of 16-bit data length. + * @note The I2S is kept enabled at the end of transaction to avoid the clock de-synchronization + * between Master and Slave(example: audio streaming). + * @note It is recommended to use DMA for the I2S receiver to avoid de-synchronisation + * between Master and Slave otherwise the I2S interrupt should be optimized. + * @note This function can use an Audio Frequency up to 32KHz when I2S Clock Source is 32MHz + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2S_Receive_IT(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size) +{ + uint32_t tmp1 = 0, tmp2 = 0; + if(hi2s->State == HAL_I2S_STATE_READY) + { + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + hi2s->pRxBuffPtr = pData; + tmp1 = hi2s->Instance->I2SCFGR & (SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN); + tmp2 = hi2s->Instance->I2SCFGR & (SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN); + if((tmp1 == I2S_DATAFORMAT_24B)||\ + (tmp2 == I2S_DATAFORMAT_32B)) + { + hi2s->RxXferSize = Size*2; + hi2s->RxXferCount = Size*2; + } + else + { + hi2s->RxXferSize = Size; + hi2s->RxXferCount = Size; + } + /* Process Locked */ + __HAL_LOCK(hi2s); + + hi2s->State = HAL_I2S_STATE_BUSY_RX; + hi2s->ErrorCode = HAL_I2S_ERROR_NONE; + + /* Enable TXE and ERR interrupt */ + __HAL_I2S_ENABLE_IT(hi2s, (I2S_IT_RXNE | I2S_IT_ERR)); + + /* Check if the I2S is already enabled */ + if((hi2s->Instance->I2SCFGR &SPI_I2SCFGR_I2SE) != SPI_I2SCFGR_I2SE) + { + /* Enable I2S peripheral */ + __HAL_I2S_ENABLE(hi2s); + } + + /* Process Unlocked */ + __HAL_UNLOCK(hi2s); + + return HAL_OK; + } + + else + { + return HAL_BUSY; + } +} + +/** + * @brief Transmit an amount of data in non-blocking mode with DMA + * @param hi2s: pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @param pData: a 16-bit pointer to the Transmit data buffer. + * @param Size: number of data sample to be sent: + * @note When a 16-bit data frame or a 16-bit data frame extended is selected during the I2S + * configuration phase, the Size parameter means the number of 16-bit data length + * in the transaction and when a 24-bit data frame or a 32-bit data frame is selected + * the Size parameter means the number of 16-bit data length. + * @note The I2S is kept enabled at the end of transaction to avoid the clock de-synchronization + * between Master and Slave(example: audio streaming). + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2S_Transmit_DMA(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size) +{ + uint32_t *tmp; + uint32_t tmp1 = 0, tmp2 = 0; + + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + if(hi2s->State == HAL_I2S_STATE_READY) + { + hi2s->pTxBuffPtr = pData; + tmp1 = hi2s->Instance->I2SCFGR & (SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN); + tmp2 = hi2s->Instance->I2SCFGR & (SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN); + if((tmp1 == I2S_DATAFORMAT_24B)|| \ + (tmp2 == I2S_DATAFORMAT_32B)) + { + hi2s->TxXferSize = Size*2; + hi2s->TxXferCount = Size*2; + } + else + { + hi2s->TxXferSize = Size; + hi2s->TxXferCount = Size; + } + + /* Process Locked */ + __HAL_LOCK(hi2s); + + hi2s->State = HAL_I2S_STATE_BUSY_TX; + hi2s->ErrorCode = HAL_I2S_ERROR_NONE; + + /* Set the I2S Tx DMA Half transfert complete callback */ + hi2s->hdmatx->XferHalfCpltCallback = I2S_DMATxHalfCplt; + + /* Set the I2S Tx DMA transfert complete callback */ + hi2s->hdmatx->XferCpltCallback = I2S_DMATxCplt; + + /* Set the DMA error callback */ + hi2s->hdmatx->XferErrorCallback = I2S_DMAError; + + /* Enable the Tx DMA Stream */ + tmp = (uint32_t*)&pData; + HAL_DMA_Start_IT(hi2s->hdmatx, *(uint32_t*)tmp, (uint32_t)&hi2s->Instance->DR, hi2s->TxXferSize); + + /* Check if the I2S is already enabled */ + if((hi2s->Instance->I2SCFGR &SPI_I2SCFGR_I2SE) != SPI_I2SCFGR_I2SE) + { + /* Enable I2S peripheral */ + __HAL_I2S_ENABLE(hi2s); + } + + /* Check if the I2S Tx request is already enabled */ + if((hi2s->Instance->CR2 & SPI_CR2_TXDMAEN) != SPI_CR2_TXDMAEN) + { + /* Enable Tx DMA Request */ + hi2s->Instance->CR2 |= SPI_CR2_TXDMAEN; + } + + /* Process Unlocked */ + __HAL_UNLOCK(hi2s); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive an amount of data in non-blocking mode with DMA + * @param hi2s: pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @param pData: a 16-bit pointer to the Receive data buffer. + * @param Size: number of data sample to be sent: + * @note When a 16-bit data frame or a 16-bit data frame extended is selected during the I2S + * configuration phase, the Size parameter means the number of 16-bit data length + * in the transaction and when a 24-bit data frame or a 32-bit data frame is selected + * the Size parameter means the number of 16-bit data length. + * @note The I2S is kept enabled at the end of transaction to avoid the clock de-synchronization + * between Master and Slave(example: audio streaming). + * @retval HAL status + */ +HAL_StatusTypeDef HAL_I2S_Receive_DMA(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size) +{ + uint32_t *tmp; + uint32_t tmp1 = 0, tmp2 = 0; + + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + if(hi2s->State == HAL_I2S_STATE_READY) + { + hi2s->pRxBuffPtr = pData; + tmp1 = hi2s->Instance->I2SCFGR & (SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN); + tmp2 = hi2s->Instance->I2SCFGR & (SPI_I2SCFGR_DATLEN | SPI_I2SCFGR_CHLEN); + if((tmp1 == I2S_DATAFORMAT_24B)|| \ + (tmp2 == I2S_DATAFORMAT_32B)) + { + hi2s->RxXferSize = Size*2; + hi2s->RxXferCount = Size*2; + } + else + { + hi2s->RxXferSize = Size; + hi2s->RxXferCount = Size; + } + /* Process Locked */ + __HAL_LOCK(hi2s); + + hi2s->State = HAL_I2S_STATE_BUSY_RX; + hi2s->ErrorCode = HAL_I2S_ERROR_NONE; + + /* Set the I2S Rx DMA Half transfert complete callback */ + hi2s->hdmarx->XferHalfCpltCallback = I2S_DMARxHalfCplt; + + /* Set the I2S Rx DMA transfert complete callback */ + hi2s->hdmarx->XferCpltCallback = I2S_DMARxCplt; + + /* Set the DMA error callback */ + hi2s->hdmarx->XferErrorCallback = I2S_DMAError; + + /* Check if Master Receiver mode is selected */ + if((hi2s->Instance->I2SCFGR & SPI_I2SCFGR_I2SCFG) == I2S_MODE_MASTER_RX) + { + /* Clear the Overrun Flag by a read operation to the SPI_DR register followed by a read + access to the SPI_SR register. */ + __HAL_I2S_CLEAR_OVRFLAG(hi2s); + } + + /* Enable the Rx DMA Stream */ + tmp = (uint32_t*)&pData; + HAL_DMA_Start_IT(hi2s->hdmarx, (uint32_t)&hi2s->Instance->DR, *(uint32_t*)tmp, hi2s->RxXferSize); + + /* Check if the I2S is already enabled */ + if((hi2s->Instance->I2SCFGR &SPI_I2SCFGR_I2SE) != SPI_I2SCFGR_I2SE) + { + /* Enable I2S peripheral */ + __HAL_I2S_ENABLE(hi2s); + } + + /* Check if the I2S Rx request is already enabled */ + if((hi2s->Instance->CR2 &SPI_CR2_RXDMAEN) != SPI_CR2_RXDMAEN) + { + /* Enable Rx DMA Request */ + hi2s->Instance->CR2 |= SPI_CR2_RXDMAEN; + } + + /* Process Unlocked */ + __HAL_UNLOCK(hi2s); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Pauses the audio stream playing from the Media. + * @param hi2s: pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @retval None + */ +HAL_StatusTypeDef HAL_I2S_DMAPause(I2S_HandleTypeDef *hi2s) +{ + /* Process Locked */ + __HAL_LOCK(hi2s); + + if(hi2s->State == HAL_I2S_STATE_BUSY_TX) + { + /* Disable the I2S DMA Tx request */ + hi2s->Instance->CR2 &= (uint32_t)~((uint32_t)SPI_CR2_TXDMAEN); + } + else if(hi2s->State == HAL_I2S_STATE_BUSY_RX) + { + /* Disable the I2S DMA Rx request */ + hi2s->Instance->CR2 &= (uint32_t)~((uint32_t)SPI_CR2_RXDMAEN); + } + + /* Process Unlocked */ + __HAL_UNLOCK(hi2s); + + return HAL_OK; +} + +/** + * @brief Resumes the audio stream playing from the Media. + * @param hi2s: pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @retval None + */ +HAL_StatusTypeDef HAL_I2S_DMAResume(I2S_HandleTypeDef *hi2s) +{ + /* Process Locked */ + __HAL_LOCK(hi2s); + + if(hi2s->State == HAL_I2S_STATE_BUSY_TX) + { + /* Enable the I2S DMA Tx request */ + hi2s->Instance->CR2 |= SPI_CR2_TXDMAEN; + } + else if(hi2s->State == HAL_I2S_STATE_BUSY_RX) + { + /* Enable the I2S DMA Rx request */ + hi2s->Instance->CR2 |= SPI_CR2_RXDMAEN; + } + + /* If the I2S peripheral is still not enabled, enable it */ + if ((hi2s->Instance->I2SCFGR & SPI_I2SCFGR_I2SE) == 0) + { + /* Enable I2S peripheral */ + __HAL_I2S_ENABLE(hi2s); + } + + /* Process Unlocked */ + __HAL_UNLOCK(hi2s); + + return HAL_OK; +} + +/** + * @brief Resumes the audio stream playing from the Media. + * @param hi2s: pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @retval None + */ +HAL_StatusTypeDef HAL_I2S_DMAStop(I2S_HandleTypeDef *hi2s) +{ + /* Process Locked */ + __HAL_LOCK(hi2s); + + /* Disable the I2S Tx/Rx DMA requests */ + hi2s->Instance->CR2 &= (uint32_t)~((uint32_t)SPI_CR2_TXDMAEN); + hi2s->Instance->CR2 &= (uint32_t)~((uint32_t)SPI_CR2_RXDMAEN); + + /* Abort the I2S DMA Stream tx */ + if(hi2s->hdmatx != NULL) + { + HAL_DMA_Abort(hi2s->hdmatx); + } + /* Abort the I2S DMA Stream rx */ + if(hi2s->hdmarx != NULL) + { + HAL_DMA_Abort(hi2s->hdmarx); + } + + /* Disable I2S peripheral */ + __HAL_I2S_DISABLE(hi2s); + + hi2s->State = HAL_I2S_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hi2s); + + return HAL_OK; +} + +/** + * @brief This function handles I2S interrupt request. + * @param hi2s: pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @retval HAL status + */ +void HAL_I2S_IRQHandler(I2S_HandleTypeDef *hi2s) +{ + uint32_t tmp1 = 0, tmp2 = 0; + if(hi2s->State == HAL_I2S_STATE_BUSY_RX) + { + tmp1 = __HAL_I2S_GET_FLAG(hi2s, I2S_FLAG_RXNE); + tmp2 = __HAL_I2S_GET_IT_SOURCE(hi2s, I2S_IT_RXNE); + /* I2S in mode Receiver --------------------------------------------------*/ + if((tmp1 != RESET) && (tmp2 != RESET)) + { + I2S_Receive_IT(hi2s); + } + tmp1 = __HAL_I2S_GET_FLAG(hi2s, I2S_FLAG_OVR); + tmp2 = __HAL_I2S_GET_IT_SOURCE(hi2s, I2S_IT_ERR); + /* I2S Overrun error interrupt occured -----------------------------------*/ + if((tmp1 != RESET) && (tmp2 != RESET)) + { + __HAL_I2S_CLEAR_OVRFLAG(hi2s); + hi2s->ErrorCode |= HAL_I2S_ERROR_OVR; + } + } + + if(hi2s->State == HAL_I2S_STATE_BUSY_TX) + { + tmp1 = __HAL_I2S_GET_FLAG(hi2s, I2S_FLAG_TXE); + tmp2 = __HAL_I2S_GET_IT_SOURCE(hi2s, I2S_IT_TXE); + /* I2S in mode Tramitter -------------------------------------------------*/ + if((tmp1 != RESET) && (tmp2 != RESET)) + { + I2S_Transmit_IT(hi2s); + } + + tmp1 = __HAL_I2S_GET_FLAG(hi2s, I2S_FLAG_UDR); + tmp2 = __HAL_I2S_GET_IT_SOURCE(hi2s, I2S_IT_ERR); + /* I2S Underrun error interrupt occured ----------------------------------*/ + if((tmp1 != RESET) && (tmp2 != RESET)) + { + __HAL_I2S_CLEAR_UDRFLAG(hi2s); + hi2s->ErrorCode |= HAL_I2S_ERROR_UDR; + } + } + + /* Call the Error call Back in case of Errors */ + if(hi2s->ErrorCode != HAL_I2S_ERROR_NONE) + { + /* Set the I2S state ready to be able to start again the process */ + hi2s->State= HAL_I2S_STATE_READY; + HAL_I2S_ErrorCallback(hi2s); + } +} + +/** + * @brief Tx Transfer Half completed callbacks + * @param hi2s: pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @retval None + */ + __weak void HAL_I2S_TxHalfCpltCallback(I2S_HandleTypeDef *hi2s) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_I2S_TxHalfCpltCallback could be implenetd in the user file + */ +} + +/** + * @brief Tx Transfer completed callbacks + * @param hi2s: pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @retval None + */ + __weak void HAL_I2S_TxCpltCallback(I2S_HandleTypeDef *hi2s) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_I2S_TxCpltCallback could be implenetd in the user file + */ +} + +/** + * @brief Rx Transfer half completed callbacks + * @param hi2s: pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @retval None + */ +__weak void HAL_I2S_RxHalfCpltCallback(I2S_HandleTypeDef *hi2s) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_I2S_RxCpltCallback could be implenetd in the user file + */ +} + +/** + * @brief Rx Transfer completed callbacks + * @param hi2s: pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @retval None + */ +__weak void HAL_I2S_RxCpltCallback(I2S_HandleTypeDef *hi2s) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_I2S_RxCpltCallback could be implenetd in the user file + */ +} + +/** + * @brief I2S error callbacks + * @param hi2s: pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @retval None + */ + __weak void HAL_I2S_ErrorCallback(I2S_HandleTypeDef *hi2s) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_I2S_ErrorCallback could be implenetd in the user file + */ +} + +/** + * @} + */ + +/** @defgroup I2S_Group3 Peripheral State and Errors functions + * @brief Peripheral State functions + * +@verbatim + =============================================================================== + ##### Peripheral State and Errors functions ##### + =============================================================================== + [..] + This subsection permit to get in run-time the status of the peripheral + and the data flow. + +@endverbatim + * @{ + */ + +/** + * @brief Return the I2S state + * @param hi2s: pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @retval HAL state + */ +HAL_I2S_StateTypeDef HAL_I2S_GetState(I2S_HandleTypeDef *hi2s) +{ + return hi2s->State; +} + +/** + * @brief Return the I2S error code + * @param hi2s: pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @retval I2S Error Code + */ +HAL_I2S_ErrorTypeDef HAL_I2S_GetError(I2S_HandleTypeDef *hi2s) +{ + return hi2s->ErrorCode; +} + +/** + * @} + */ + +/** + * @brief DMA I2S transmit process complete callback + * @param hdma : DMA handle + * @retval None + */ +void I2S_DMATxCplt(DMA_HandleTypeDef *hdma) +{ + I2S_HandleTypeDef* hi2s = (I2S_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent; + + if((hdma->Instance->CCR & DMA_CCR_CIRC) == 0) + { + hi2s->TxXferCount = 0; + + /* Disable Tx DMA Request */ + hi2s->Instance->CR2 &= (uint32_t)~((uint32_t)SPI_CR2_TXDMAEN); + + hi2s->State = HAL_I2S_STATE_READY; + } + HAL_I2S_TxCpltCallback(hi2s); +} + +/** + * @brief DMA I2S transmit process half complete callback + * @param hdma : DMA handle + * @retval None + */ +void I2S_DMATxHalfCplt(DMA_HandleTypeDef *hdma) +{ + I2S_HandleTypeDef* hi2s = (I2S_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent; + + HAL_I2S_TxHalfCpltCallback(hi2s); +} + +/** + * @brief DMA I2S receive process complete callback + * @param hdma : DMA handle + * @retval None + */ +void I2S_DMARxCplt(DMA_HandleTypeDef *hdma) +{ + I2S_HandleTypeDef* hi2s = (I2S_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent; + + if((hdma->Instance->CCR & DMA_CCR_CIRC) == 0) + { + /* Disable Rx DMA Request */ + hi2s->Instance->CR2 &= (uint32_t)~((uint32_t)SPI_CR2_RXDMAEN); + + hi2s->RxXferCount = 0; + + hi2s->State = HAL_I2S_STATE_READY; + } + HAL_I2S_RxCpltCallback(hi2s); +} + +/** + * @brief DMA I2S receive process half complete callback + * @param hdma : DMA handle + * @retval None + */ +void I2S_DMARxHalfCplt(DMA_HandleTypeDef *hdma) +{ + I2S_HandleTypeDef* hi2s = (I2S_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent; + + HAL_I2S_RxHalfCpltCallback(hi2s); +} + +/** + * @brief DMA I2S communication error callback + * @param hdma : DMA handle + * @retval None + */ +void I2S_DMAError(DMA_HandleTypeDef *hdma) +{ + I2S_HandleTypeDef* hi2s = (I2S_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent; + + hi2s->TxXferCount = 0; + hi2s->RxXferCount = 0; + + hi2s->State= HAL_I2S_STATE_READY; + + hi2s->ErrorCode |= HAL_I2S_ERROR_DMA; + HAL_I2S_ErrorCallback(hi2s); +} + +/** + * @brief Transmit an amount of data in non-blocking mode with Interrupt + * @param hi2s: pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @retval HAL status + */ +static HAL_StatusTypeDef I2S_Transmit_IT(I2S_HandleTypeDef *hi2s) +{ + if(hi2s->State == HAL_I2S_STATE_BUSY_TX) + { + /* Transmit data */ + hi2s->Instance->DR = (*hi2s->pTxBuffPtr++); + + hi2s->TxXferCount--; + + if(hi2s->TxXferCount == 0) + { + /* Disable TXE and ERR interrupt */ + __HAL_I2S_DISABLE_IT(hi2s, (uint32_t)(I2S_IT_TXE | I2S_IT_ERR)); + + hi2s->State = HAL_I2S_STATE_READY; + + HAL_I2S_TxCpltCallback(hi2s); + } + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive an amount of data in non-blocking mode with Interrupt + * @param hi2s: pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @retval HAL status + */ +static HAL_StatusTypeDef I2S_Receive_IT(I2S_HandleTypeDef *hi2s) +{ + if(hi2s->State == HAL_I2S_STATE_BUSY_RX) + { + /* Receive data */ + (*hi2s->pRxBuffPtr++) = hi2s->Instance->DR; + + hi2s->RxXferCount--; + + /* Check if Master Receiver mode is selected */ + if((hi2s->Instance->I2SCFGR & SPI_I2SCFGR_I2SCFG) == I2S_MODE_MASTER_RX) + { + /* Clear the Overrun Flag by a read operation on the SPI_DR register followed by a read + access to the SPI_SR register. */ + __HAL_I2S_CLEAR_OVRFLAG(hi2s); + } + + if(hi2s->RxXferCount == 0) + { + /* Disable RXNE and ERR interrupt */ + __HAL_I2S_DISABLE_IT(hi2s, (uint32_t)(I2S_IT_RXNE | I2S_IT_ERR)); + + hi2s->State = HAL_I2S_STATE_READY; + + HAL_I2S_RxCpltCallback(hi2s); + } + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief This function handles I2S Communication Timeout. + * @param hi2s: pointer to a I2S_HandleTypeDef structure that contains + * the configuration information for I2S module + * @param Flag: Flag checked + * @param State: Value of the flag expected + * @param Timeout: Duration of the timeout + * @retval HAL status + */ +HAL_StatusTypeDef I2S_WaitFlagStateUntilTimeout(I2S_HandleTypeDef *hi2s, uint32_t Flag, uint32_t Status, uint32_t Timeout) +{ + uint32_t tickstart = 0x00; + tickstart = HAL_GetTick(); + + /* Wait until flag is set */ + if(Status == RESET) + { + while(__HAL_I2S_GET_FLAG(hi2s, Flag) == RESET) + { + /* Check for the Timeout */ + if(Timeout != HAL_MAX_DELAY) + { + if((HAL_GetTick() - tickstart ) > Timeout) + { + /* Set the I2S State ready */ + hi2s->State= HAL_I2S_STATE_READY; + /* Process Unlocked */ + __HAL_UNLOCK(hi2s); + return HAL_TIMEOUT; + } + } + } + } + else + { + while(__HAL_I2S_GET_FLAG(hi2s, Flag) != RESET) + { + /* Check for the Timeout */ + if(Timeout != HAL_MAX_DELAY) + { + if((HAL_GetTick() - tickstart ) > Timeout) + { + /* Set the I2S State ready */ + hi2s->State= HAL_I2S_STATE_READY; + /* Process Unlocked */ + __HAL_UNLOCK(hi2s); + return HAL_TIMEOUT; + } + } + } + } + return HAL_OK; +} + +/** + * @} + */ + +#endif /* HAL_I2S_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_i2s.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_i2s.h new file mode 100644 index 0000000000..0acda0145a --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_i2s.h @@ -0,0 +1,399 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_i2s.h + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief Header file of I2S HAL module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32L0xx_HAL_I2S_H +#define __STM32L0xx_HAL_I2S_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal_def.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @addtogroup I2S + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/** + * @brief I2S Init structure definition + */ +typedef struct +{ + uint32_t Mode; /*!< Specifies the I2S operating mode. + This parameter can be a value of @ref I2S_Mode */ + + uint32_t Standard; /*!< Specifies the standard used for the I2S communication. + This parameter can be a value of @ref I2S_Standard */ + + uint32_t DataFormat; /*!< Specifies the data format for the I2S communication. + This parameter can be a value of @ref I2S_Data_Format */ + + uint32_t MCLKOutput; /*!< Specifies whether the I2S MCLK output is enabled or not. + This parameter can be a value of @ref I2S_MCLK_Output */ + + uint32_t AudioFreq; /*!< Specifies the frequency selected for the I2S communication. + This parameter can be a value of @ref I2S_Audio_Frequency */ + + uint32_t CPOL; /*!< Specifies the idle state of the I2S clock. + This parameter can be a value of @ref I2S_Clock_Polarity */ + +}I2S_InitTypeDef; + +/** + * @brief HAL State structures definition + */ +typedef enum +{ + HAL_I2S_STATE_RESET = 0x00, /*!< I2S not yet initialized or disabled */ + HAL_I2S_STATE_READY = 0x01, /*!< I2S initialized and ready for use */ + HAL_I2S_STATE_BUSY = 0x02, /*!< I2S internal process is ongoing */ + HAL_I2S_STATE_BUSY_TX = 0x12, /*!< Data Transmission process is ongoing */ + HAL_I2S_STATE_BUSY_RX = 0x22, /*!< Data Reception process is ongoing */ + HAL_I2S_STATE_TIMEOUT = 0x03, /*!< I2S timeout state */ + HAL_I2S_STATE_ERROR = 0x04 /*!< I2S error state */ + +}HAL_I2S_StateTypeDef; + +/** + * @brief HAL I2S Error Code structure definition + */ +typedef enum +{ + HAL_I2S_ERROR_NONE = 0x00, /*!< No error */ + HAL_I2S_ERROR_UDR = 0x01, /*!< I2S Underrun error */ + HAL_I2S_ERROR_OVR = 0x02, /*!< I2S Overrun error */ + HAL_I2S_ERROR_FRE = 0x10, /*!< I2S Frame format error */ + HAL_I2S_ERROR_DMA = 0x20 /*!< DMA transfer error */ +}HAL_I2S_ErrorTypeDef; + +/** + * @brief I2S handle Structure definition + */ +typedef struct +{ + SPI_TypeDef *Instance; /* I2S registers base address */ + + I2S_InitTypeDef Init; /* I2S communication parameters */ + + uint16_t *pTxBuffPtr; /* Pointer to I2S Tx transfer buffer*/ + + __IO uint16_t TxXferSize; /* I2S Tx transfer size */ + + __IO uint16_t TxXferCount; /* I2S Tx transfer Counter */ + + uint16_t *pRxBuffPtr; /* Pointer to I2S Rx transfer buffer*/ + + __IO uint16_t RxXferSize; /* I2S Rx transfer size */ + + __IO uint16_t RxXferCount; /* I2S Rx transfer counter */ + + DMA_HandleTypeDef *hdmatx; /* I2S Tx DMA handle parameters */ + + DMA_HandleTypeDef *hdmarx; /* I2S Rx DMA handle parameters */ + + __IO HAL_LockTypeDef Lock; /* I2S locking object */ + + __IO HAL_I2S_StateTypeDef State; /* I2S communication state */ + + __IO HAL_I2S_ErrorTypeDef ErrorCode; /* I2S Error code */ + +}I2S_HandleTypeDef; + +/* Exported constants --------------------------------------------------------*/ + +/** @defgroup I2S_Exported_Constants + * @{ + */ + +/** @defgroup I2S_Mode + * @{ + */ +#define I2S_MODE_SLAVE_TX ((uint32_t)0x00000000) +#define I2S_MODE_SLAVE_RX ((uint32_t)0x00000100) +#define I2S_MODE_MASTER_TX ((uint32_t)0x00000200) +#define I2S_MODE_MASTER_RX ((uint32_t)0x00000300) + +#define IS_I2S_MODE(MODE) (((MODE) == I2S_MODE_SLAVE_TX) || \ + ((MODE) == I2S_MODE_SLAVE_RX) || \ + ((MODE) == I2S_MODE_MASTER_TX) || \ + ((MODE) == I2S_MODE_MASTER_RX)) +/** + * @} + */ + +/** @defgroup I2S_Standard + * @{ + */ +#define I2S_STANDARD_PHILIPS ((uint32_t)0x00000000) +#define I2S_STANDARD_MSB ((uint32_t)0x00000010) +#define I2S_STANDARD_LSB ((uint32_t)0x00000020) +#define I2S_STANDARD_PCM_SHORT ((uint32_t)0x00000030) +#define I2S_STANDARD_PCM_LONG ((uint32_t)0x000000B0) + +#define IS_I2S_STANDARD(STANDARD) (((STANDARD) == I2S_STANDARD_PHILIPS) || \ + ((STANDARD) == I2S_STANDARD_MSB) || \ + ((STANDARD) == I2S_STANDARD_LSB) || \ + ((STANDARD) == I2S_STANDARD_PCM_SHORT) || \ + ((STANDARD) == I2S_STANDARD_PCM_LONG)) +/** + * @} + */ + +/** @defgroup I2S_Data_Format + * @{ + */ +#define I2S_DATAFORMAT_16B ((uint32_t)0x00000000) +#define I2S_DATAFORMAT_16B_EXTENDED ((uint32_t)0x00000001) +#define I2S_DATAFORMAT_24B ((uint32_t)0x00000003) +#define I2S_DATAFORMAT_32B ((uint32_t)0x00000005) + +#define IS_I2S_DATA_FORMAT(FORMAT) (((FORMAT) == I2S_DATAFORMAT_16B) || \ + ((FORMAT) == I2S_DATAFORMAT_16B_EXTENDED) || \ + ((FORMAT) == I2S_DATAFORMAT_24B) || \ + ((FORMAT) == I2S_DATAFORMAT_32B)) +/** + * @} + */ + +/** @defgroup I2S_MCLK_Output + * @{ + */ +#define I2S_MCLKOUTPUT_ENABLE ((uint32_t)SPI_I2SPR_MCKOE) +#define I2S_MCLKOUTPUT_DISABLE ((uint32_t)0x00000000) + +#define IS_I2S_MCLK_OUTPUT(OUTPUT) (((OUTPUT) == I2S_MCLKOUTPUT_ENABLE) || \ + ((OUTPUT) == I2S_MCLKOUTPUT_DISABLE)) +/** + * @} + */ + +/** @defgroup I2S_Audio_Frequency + * @{ + */ +#define I2S_AUDIOFREQ_192K ((uint32_t)192000) +#define I2S_AUDIOFREQ_96K ((uint32_t)96000) +#define I2S_AUDIOFREQ_48K ((uint32_t)48000) +#define I2S_AUDIOFREQ_44K ((uint32_t)44100) +#define I2S_AUDIOFREQ_32K ((uint32_t)32000) +#define I2S_AUDIOFREQ_22K ((uint32_t)22050) +#define I2S_AUDIOFREQ_16K ((uint32_t)16000) +#define I2S_AUDIOFREQ_11K ((uint32_t)11025) +#define I2S_AUDIOFREQ_8K ((uint32_t)8000) +#define I2S_AUDIOFREQ_DEFAULT ((uint32_t)2) + +#define IS_I2S_AUDIO_FREQ(FREQ) ((((FREQ) >= I2S_AUDIOFREQ_8K) && \ + ((FREQ) <= I2S_AUDIOFREQ_192K)) || \ + ((FREQ) == I2S_AUDIOFREQ_DEFAULT)) +/** + * @} + */ + +/** @defgroup I2S_Clock_Polarity + * @{ + */ +#define I2S_CPOL_LOW ((uint32_t)0x00000000) +#define I2S_CPOL_HIGH ((uint32_t)SPI_I2SCFGR_CKPOL) + +#define IS_I2S_CPOL(CPOL) (((CPOL) == I2S_CPOL_LOW) || \ + ((CPOL) == I2S_CPOL_HIGH)) +/** + * @} + */ + +/** @defgroup I2S_Interrupt_configuration_definition + * @{ + */ +#define I2S_IT_TXE SPI_CR2_TXEIE +#define I2S_IT_RXNE SPI_CR2_RXNEIE +#define I2S_IT_ERR SPI_CR2_ERRIE +/** + * @} + */ + +/** @defgroup I2S_Flag_definition + * @{ + */ +#define I2S_FLAG_TXE SPI_SR_TXE +#define I2S_FLAG_RXNE SPI_SR_RXNE + +#define I2S_FLAG_UDR SPI_SR_UDR +#define I2S_FLAG_OVR SPI_SR_OVR +#define I2S_FLAG_FRE SPI_SR_FRE + +#define I2S_FLAG_CHSIDE SPI_SR_CHSIDE +#define I2S_FLAG_BSY SPI_SR_BSY +/** + * @} + */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ + +/** @brief Reset I2S handle state + * @param __HANDLE__: specifies the I2S Handle. + * @retval None + */ +#define __HAL_I2S_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_I2S_STATE_RESET) + +/** @brief Enable or disable the specified SPI peripheral (in I2S mode). + * @param __HANDLE__: specifies the I2S Handle. + * @retval None + */ +#define __HAL_I2S_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->I2SCFGR |= SPI_I2SCFGR_I2SE) +#define __HAL_I2S_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->I2SCFGR &= (uint32_t)~((uint32_t)SPI_I2SCFGR_I2SE)) + +/** @brief Enable or disable the specified I2S interrupts. + * @param __HANDLE__: specifies the I2S Handle. + * @param __INTERRUPT__: specifies the interrupt source to enable or disable. + * This parameter can be one of the following values: + * @arg I2S_IT_TXE: Tx buffer empty interrupt enable + * @arg I2S_IT_RXNE: RX buffer not empty interrupt enable + * @arg I2S_IT_ERR: Error interrupt enable + * @retval None + */ +#define __HAL_I2S_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR2 |= (__INTERRUPT__)) +#define __HAL_I2S_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR2 &= ~(__INTERRUPT__)) + +/** @brief Checks if the specified I2S interrupt source is enabled or disabled. + * @param __HANDLE__: specifies the I2S Handle. + * This parameter can be I2S where x: 1, 2, or 3 to select the I2S peripheral. + * @param __INTERRUPT__: specifies the I2S interrupt source to check. + * This parameter can be one of the following values: + * @arg I2S_IT_TXE: Tx buffer empty interrupt enable + * @arg I2S_IT_RXNE: RX buffer not empty interrupt enable + * @arg I2S_IT_ERR: Error interrupt enable + * @retval The new state of __IT__ (TRUE or FALSE). + */ +#define __HAL_I2S_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((((__HANDLE__)->Instance->CR2 & (__INTERRUPT__)) == (__INTERRUPT__)) ? SET : RESET) + +/** @brief Checks whether the specified I2S flag is set or not. + * @param __HANDLE__: specifies the I2S Handle. + * @param __FLAG__: specifies the flag to check. + * This parameter can be one of the following values: + * @arg I2S_FLAG_RXNE: Receive buffer not empty flag + * @arg I2S_FLAG_TXE: Transmit buffer empty flag + * @arg I2S_FLAG_UDR: Underrun flag + * @arg I2S_FLAG_OVR: Overrun flag + * @arg I2S_FLAG_FRE: Frame error flag + * @arg I2S_FLAG_CHSIDE: Channel Side flag + * @arg I2S_FLAG_BSY: Busy flag + * @retval The new state of __FLAG__ (TRUE or FALSE). + */ +#define __HAL_I2S_GET_FLAG(__HANDLE__, __FLAG__) ((((__HANDLE__)->Instance->SR) & (__FLAG__)) == (__FLAG__)) + +/** @brief Clears the I2S OVR pending flag. + * @param __HANDLE__: specifies the I2S Handle. + * @retval None + */ +#define __HAL_I2S_CLEAR_OVRFLAG(__HANDLE__) do{(__HANDLE__)->Instance->DR;\ + (__HANDLE__)->Instance->SR;}while(0) +/** @brief Clears the I2S UDR pending flag. + * @param __HANDLE__: specifies the I2S Handle. + * @retval None + */ +#define __HAL_I2S_CLEAR_UDRFLAG(__HANDLE__)((__HANDLE__)->Instance->SR) + +/* Exported functions --------------------------------------------------------*/ + +/* Initialization/de-initialization functions **********************************/ +HAL_StatusTypeDef HAL_I2S_Init(I2S_HandleTypeDef *hi2s); +HAL_StatusTypeDef HAL_I2S_DeInit (I2S_HandleTypeDef *hi2s); +void HAL_I2S_MspInit(I2S_HandleTypeDef *hi2s); +void HAL_I2S_MspDeInit(I2S_HandleTypeDef *hi2s); + +/* I/O operation functions *****************************************************/ + /* Blocking mode: Polling */ +HAL_StatusTypeDef HAL_I2S_Transmit(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size, uint32_t Timeout); +HAL_StatusTypeDef HAL_I2S_Receive(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size, uint32_t Timeout); + + /* Non-Blocking mode: Interrupt */ +HAL_StatusTypeDef HAL_I2S_Transmit_IT(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size); +HAL_StatusTypeDef HAL_I2S_Receive_IT(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size); +void HAL_I2S_IRQHandler(I2S_HandleTypeDef *hi2s); + +/* Non-Blocking mode: DMA */ +HAL_StatusTypeDef HAL_I2S_Transmit_DMA(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size); +HAL_StatusTypeDef HAL_I2S_Receive_DMA(I2S_HandleTypeDef *hi2s, uint16_t *pData, uint16_t Size); + +HAL_StatusTypeDef HAL_I2S_DMAPause(I2S_HandleTypeDef *hi2s); +HAL_StatusTypeDef HAL_I2S_DMAResume(I2S_HandleTypeDef *hi2s); +HAL_StatusTypeDef HAL_I2S_DMAStop(I2S_HandleTypeDef *hi2s); + +/* Peripheral Control and State functions **************************************/ +HAL_I2S_StateTypeDef HAL_I2S_GetState(I2S_HandleTypeDef *hi2s); +HAL_I2S_ErrorTypeDef HAL_I2S_GetError(I2S_HandleTypeDef *hi2s); + +/* Callbacks used in non blocking modes (Interrupt and DMA) *******************/ +void HAL_I2S_TxHalfCpltCallback(I2S_HandleTypeDef *hi2s); +void HAL_I2S_TxCpltCallback(I2S_HandleTypeDef *hi2s); +void HAL_I2S_RxHalfCpltCallback(I2S_HandleTypeDef *hi2s); +void HAL_I2S_RxCpltCallback(I2S_HandleTypeDef *hi2s); +void HAL_I2S_ErrorCallback(I2S_HandleTypeDef *hi2s); + +void I2S_DMATxCplt(DMA_HandleTypeDef *hdma); +void I2S_DMATxHalfCplt(DMA_HandleTypeDef *hdma); +void I2S_DMARxCplt(DMA_HandleTypeDef *hdma); +void I2S_DMARxHalfCplt(DMA_HandleTypeDef *hdma); +void I2S_DMAError(DMA_HandleTypeDef *hdma); +HAL_StatusTypeDef I2S_WaitFlagStateUntilTimeout(I2S_HandleTypeDef *hi2s, uint32_t Flag, uint32_t Status, uint32_t Timeout); + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + + +#endif /* __STM32L0xx_HAL_I2S_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_irda.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_irda.c new file mode 100644 index 0000000000..4a465f2e9b --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_irda.c @@ -0,0 +1,1275 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_irda.c + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief IRDA HAL module driver. + * + * This file provides firmware functions to manage the following + * functionalities of the IrDA (Infrared Data Association) Peripheral + * (IRDA) + * + Initialization and de-initialization functions + * + IO operation functions + * + Peripheral Control functions + * + * + @verbatim + =============================================================================== + ##### How to use this driver ##### + =============================================================================== + [..] + The IRDA HAL driver can be used as follows: + + + (#) Declare a IRDA_HandleTypeDef handle structure. + (#) Initialize the IRDA low level resources by implementing the HAL_IRDA_MspInit() API: + (##) Enable the USARTx interface clock. + (##) IRDA pins configuration: + (+) Enable the clock for the IRDA GPIOs. + (+) Configure these IRDA pins as alternate function pull-up. + (##) NVIC configuration if you need to use interrupt process (HAL_IRDA_Transmit_IT() + and HAL_IRDA_Receive_IT() APIs): + (+) Configure the USARTx interrupt priority. + (+) Enable the NVIC USART IRQ handle. + (##) DMA Configuration if you need to use DMA process (HAL_IRDA_Transmit_DMA() + and HAL_IRDA_Receive_DMA() APIs): + (+) Declare a DMA handle structure for the Tx/Rx stream. + (+) Enable the DMAx interface clock. + (+) Configure the declared DMA handle structure with the required Tx/Rx parameters. + (+) Configure the DMA Tx/Rx Stream. + (+) Associate the initilalized DMA handle to the IRDA DMA Tx/Rx handle. + (+) Configure the priority and enable the NVIC for the transfer complete interrupt on the DMA Tx/Rx Stream. + + (#) Program the Baud Rate, Word Length, Parity, IrDA Mode, Prescaler + and Mode(Receiver/Transmitter) in the hirda Init structure. + + (#) Initialize the IRDA registers by calling the HAL_IRDA_Init() API: + (++) This API configures also the low level Hardware GPIO, CLOCK, CORTEX...etc) + by calling the customed HAL_IRDA_MspInit() API. + -@@- The specific IRDA interrupts (Transmission complete interrupt, + RXNE interrupt and Error Interrupts) will be managed using the macros + __HAL_IRDA_ENABLE_IT() and __HAL_IRDA_DISABLE_IT() inside the transmit and receive process. + + (#) Three operation modes are available within this driver : + + *** Polling mode IO operation *** + ================================= + [..] + (+) Send an amount of data in blocking mode using HAL_IRDA_Transmit() + (+) Receive an amount of data in blocking mode using HAL_IRDA_Receive() + + *** Interrupt mode IO operation *** + =================================== + [..] + (+) Send an amount of data in non blocking mode using HAL_IRDA_Transmit_IT() + (+) At transmission end of transfer HAL_IRDA_TxCpltCallback is executed and user can + add his own code by customization of function pointer HAL_IRDA_TxCpltCallback + (+) Receive an amount of data in non blocking mode using HAL_IRDA_Receive_IT() + (+) At reception end of transfer HAL_IRDA_RxCpltCallback is executed and user can + add his own code by customization of function pointer HAL_IRDA_RxCpltCallback + (+) In case of transfer Error, HAL_IRDA_ErrorCallback() function is executed and user can + add his own code by customization of function pointer HAL_IRDA_ErrorCallback + + *** DMA mode IO operation *** + ============================= + [..] + (+) Send an amount of data in non blocking mode (DMA) using HAL_IRDA_Transmit_DMA() + (+) At transmission end of transfer HAL_IRDA_TxCpltCallback is executed and user can + add his own code by customization of function pointer HAL_IRDA_TxCpltCallback + (+) Receive an amount of data in non blocking mode (DMA) using HAL_IRDA_Receive_DMA() + (+) At reception end of transfer HAL_IRDA_RxCpltCallback is executed and user can + add his own code by customization of function pointer HAL_IRDA_RxCpltCallback + (+) In case of transfer Error, HAL_IRDA_ErrorCallback() function is executed and user can + add his own code by customization of function pointer HAL_IRDA_ErrorCallback + + *** IRDA HAL driver macros list *** + =================================== + [..] + Below the list of most used macros in IRDA HAL driver. + + (+) __HAL_IRDA_ENABLE: Enable the IRDA peripheral + (+) __HAL_IRDA_DISABLE: Disable the IRDA peripheral + (+) __HAL_IRDA_GET_FLAG : Checks whether the specified IRDA flag is set or not + (+) __HAL_IRDA_CLEAR_FLAG : Clears the specified IRDA pending flag + (+) __HAL_IRDA_ENABLE_IT: Enables the specified IRDA interrupt + (+) __HAL_IRDA_DISABLE_IT: Disables the specified IRDA interrupt + + (@) You can refer to the IRDA HAL driver header file for more useful macros + + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @defgroup IRDA + * @brief HAL IRDA module driver + * @{ + */ +#ifdef HAL_IRDA_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +#define TEACK_REACK_TIMEOUT 1000 +#define HAL_IRDA_TXDMA_TIMEOUTVALUE 22000 +#define IRDA_CR1_FIELDS ((uint32_t)(USART_CR1_M | USART_CR1_PCE \ + | USART_CR1_PS | USART_CR1_TE | USART_CR1_RE)) +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +static void IRDA_DMATransmitCplt(DMA_HandleTypeDef *hdma); +static void IRDA_DMAReceiveCplt(DMA_HandleTypeDef *hdma); +static void IRDA_DMAError(DMA_HandleTypeDef *hdma); +static void IRDA_SetConfig (IRDA_HandleTypeDef *hirda); +static HAL_StatusTypeDef IRDA_CheckIdleState(IRDA_HandleTypeDef *hirda); +static HAL_StatusTypeDef IRDA_WaitOnFlagUntilTimeout(IRDA_HandleTypeDef *hirda, uint32_t Flag, FlagStatus Status, uint32_t Timeout); +static HAL_StatusTypeDef IRDA_Transmit_IT(IRDA_HandleTypeDef *hirda); +static HAL_StatusTypeDef IRDA_Receive_IT(IRDA_HandleTypeDef *hirda); +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup IRDA_Private_Functions + * @{ + */ + +/** @defgroup HAL_IRDA_Group1 Initialization/de-initialization functions + * @brief Initialization and Configuration functions + * +@verbatim +=============================================================================== + ##### Initialization and Configuration functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to initialize the USARTx + in asynchronous IRDA mode. + (+) For the asynchronous mode only these parameters can be configured: + (++) Baud Rate + (++) Word Length + (++) Parity: If the parity is enabled, then the MSB bit of the data written + in the data register is transmitted but is changed by the parity bit. + Depending on the frame length defined by the M bit (8-bits or 9-bits) + or by the M1 and M0 bits (7-bit, 8-bit or 9-bit), + the possible IRDA frame formats are as listed in the following table: + +---------------------------------------------------------------+ + | M1M0 bits | PCE bit | IRDA frame | + |-----------|-----------|---------------------------------------| + | 00 | 0 | | SB | 8-bit data | STB | | + |-----------|-----------|---------------------------------------| + | 00 | 1 | | SB | 7-bit data | PB | STB | | + |-----------|-----------|---------------------------------------| + | 01 | 0 | | SB | 9-bit data | STB | | + |-----------|-----------|---------------------------------------| + | 01 | 1 | | SB | 8-bit data | PB | STB | | + |-----------------------|---------------------------------------| + | 10 | 0 | | SB | 7-bit data | STB | | + |-----------|-----------|---------------------------------------| + | 10 | 1 | | SB | 6-bit data | PB | STB | | + +---------------------------------------------------------------+ + + (++) Power mode + (++) Prescaler setting + (++) Receiver/transmitter modes + + [..] + The HAL_IRDA_Init() API follows the USART asynchronous configuration procedures + (details for the procedures are available in reference manual). + +@endverbatim + * @{ + */ + +/** + * @brief Initializes the IRDA mode according to the specified + * parameters in the IRDA_InitTypeDef and creates the associated handle . + * @param hirda: IRDA handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_IRDA_Init(IRDA_HandleTypeDef *hirda) +{ + /* Check the IRDA handle allocation */ + if(hirda == NULL) + { + return HAL_ERROR; + } + + /* Check the USART/UART associated to the IRDA handle */ + assert_param(IS_IRDA_INSTANCE(hirda->Instance)); + + if(hirda->State == HAL_IRDA_STATE_RESET) + { + /* Init the low level hardware : GPIO, CLOCK, CORTEX */ + HAL_IRDA_MspInit(hirda); + } + + hirda->State = HAL_IRDA_STATE_BUSY; + + /* Disable the Peripheral to update the configuration registers */ + __HAL_IRDA_DISABLE(hirda); + + /* Set the IRDA Communication parameters */ + IRDA_SetConfig(hirda); + + /* In IRDA mode, the following bits must be kept cleared: + - LINEN, STOP and CLKEN bits in the USART_CR2 register, + - SCEN and HDSEL bits in the USART_CR3 register.*/ + hirda->Instance->CR2 &= ~(USART_CR2_LINEN | USART_CR2_CLKEN | USART_CR2_STOP); + hirda->Instance->CR3 &= ~(USART_CR3_SCEN | USART_CR3_HDSEL); + + /* set the UART/USART in IRDA mode */ + hirda->Instance->CR3 |= USART_CR3_IREN; + + /* Enable the Peripheral */ + __HAL_IRDA_ENABLE(hirda); + + /* TEACK and/or REACK to check before moving hirda->State to Ready */ + return (IRDA_CheckIdleState(hirda)); +} + +/** + * @brief DeInitializes the IRDA peripheral + * @param hirda: IRDA handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_IRDA_DeInit(IRDA_HandleTypeDef *hirda) +{ + /* Check the IRDA handle allocation */ + if(hirda == NULL) + { + return HAL_ERROR; + } + + /* Check the USART/UART associated to the IRDA handle */ + assert_param(IS_IRDA_INSTANCE(hirda->Instance)); + + hirda->State = HAL_IRDA_STATE_BUSY; + + /* DeInit the low level hardware */ + HAL_IRDA_MspDeInit(hirda); + /* Disable the Peripheral */ + __HAL_IRDA_DISABLE(hirda); + + hirda->ErrorCode = HAL_IRDA_ERROR_NONE; + hirda->State = HAL_IRDA_STATE_RESET; + + /* Release Lock */ + __HAL_UNLOCK(hirda); + + return HAL_OK; +} + +/** + * @brief IRDA MSP Init + * @param hirda: IRDA handle + * @retval None + */ + __weak void HAL_IRDA_MspInit(IRDA_HandleTypeDef *hirda) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_IRDA_MspInit could be implented in the user file + */ +} + +/** + * @brief IRDA MSP DeInit + * @param hirda: IRDA handle + * @retval None + */ + __weak void HAL_IRDA_MspDeInit(IRDA_HandleTypeDef *hirda) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_IRDA_MspDeInit could be implented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup HAL_IRDA_Group2 IO operation functions + * @brief IRDA Transmit/Receive functions + * +@verbatim + =============================================================================== + ##### I/O operation functions ##### + =============================================================================== + This subsection provides a set of functions allowing to manage the IRDA asynchronous + data transfers. + + (#) There are two modes of transfer: + (+) Blocking mode: the communication is performed in polling mode. + The HAL status of all data processing is returned by the same function + after finishing transfer. + (+) No-Blocking mode: the communication is performed using Interrupts + or DMA, these API's return the HAL status. + The end of the data processing will be indicated through the + dedicated IRDA IRQ when using Interrupt mode or the DMA IRQ when + using DMA mode. + The HAL_IRDA_TxCpltCallback(), HAL_IRDA_RxCpltCallback() user callbacks + will be executed respectivelly at the end of the Transmit or Receive process + The HAL_IRDA_ErrorCallback() user callback will be executed when a communication error is detected + + (#) Blocking mode API's are : + (+) HAL_IRDA_Transmit() + (+) HAL_IRDA_Receive() + + (#) Non-Blocking mode API's with Interrupt are : + (+) HAL_IRDA_Transmit_IT() + (+) HAL_IRDA_Receive_IT() + (+) HAL_IRDA_IRQHandler() + (+) IRDA_Transmit_IT() + (+) IRDA_Receive_IT() + + (#) Non-Blocking mode functions with DMA are : + (+) HAL_IRDA_Transmit_DMA() + (+) HAL_IRDA_Receive_DMA() + + (#) A set of Transfer Complete Callbacks are provided in No_Blocking mode: + (+) HAL_IRDA_TxCpltCallback() + (+) HAL_IRDA_RxCpltCallback() + (+) HAL_IRDA_ErrorCallback() + +@endverbatim + * @{ + */ + +/** + * @brief Send an amount of data in blocking mode + * @param hirda: IRDA handle + * @param pData: pointer to data buffer + * @param Size: amount of data to be sent + * @param Timeout: Duration of the timeout + * @retval HAL status + */ +HAL_StatusTypeDef HAL_IRDA_Transmit(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size, uint32_t Timeout) +{ + uint16_t* tmp; + + if ((hirda->State == HAL_IRDA_STATE_READY) || (hirda->State == HAL_IRDA_STATE_BUSY_RX)) + { + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(hirda); + hirda->ErrorCode = HAL_IRDA_ERROR_NONE; + + if(hirda->State == HAL_IRDA_STATE_BUSY_RX) + { + hirda->State = HAL_IRDA_STATE_BUSY_TX_RX; + } + else + { + hirda->State = HAL_IRDA_STATE_BUSY_TX; + } + + hirda->TxXferSize = Size; + hirda->TxXferCount = Size; + while(hirda->TxXferCount > 0) + { + hirda->TxXferCount--; + + if(IRDA_WaitOnFlagUntilTimeout(hirda, IRDA_FLAG_TXE, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + if ((hirda->Init.WordLength == IRDA_WORDLENGTH_9B) && (hirda->Init.Parity == IRDA_PARITY_NONE)) + { + tmp = (uint16_t*) pData; + hirda->Instance->TDR = (*tmp & (uint16_t)0x01FF); + pData +=2; + } + else + { + hirda->Instance->TDR = (*pData++ & (uint8_t)0xFF); + } + } + + if(IRDA_WaitOnFlagUntilTimeout(hirda, IRDA_FLAG_TC, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + if(hirda->State == HAL_IRDA_STATE_BUSY_TX_RX) + { + hirda->State = HAL_IRDA_STATE_BUSY_RX; + } + else + { + hirda->State = HAL_IRDA_STATE_READY; + } + + /* Process Unlocked */ + __HAL_UNLOCK(hirda); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive an amount of data in blocking mode + * @param hirda: IRDA handle + * @param pData: pointer to data buffer + * @param Size: amount of data to be received + * @param Timeout: Duration of the timeout + * @retval HAL status + */ +HAL_StatusTypeDef HAL_IRDA_Receive(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size, uint32_t Timeout) +{ + uint16_t* tmp; + uint16_t uhMask; + + if ((hirda->State == HAL_IRDA_STATE_READY) || (hirda->State == HAL_IRDA_STATE_BUSY_TX)) + { + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(hirda); + hirda->ErrorCode = HAL_IRDA_ERROR_NONE; + + if(hirda->State == HAL_IRDA_STATE_BUSY_TX) + { + hirda->State = HAL_IRDA_STATE_BUSY_TX_RX; + } + else + { + hirda->State = HAL_IRDA_STATE_BUSY_RX; + } + + hirda->RxXferSize = Size; + hirda->RxXferCount = Size; + + /* Computation of the mask to apply to the RDR register + of the UART associated to the IRDA */ + __HAL_IRDA_MASK_COMPUTATION(hirda); + uhMask = hirda->Mask; + + /* Check data remaining to be received */ + while(hirda->RxXferCount > 0) + { + hirda->RxXferCount--; + + if(IRDA_WaitOnFlagUntilTimeout(hirda, IRDA_FLAG_RXNE, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + if ((hirda->Init.WordLength == IRDA_WORDLENGTH_9B) && (hirda->Init.Parity == IRDA_PARITY_NONE)) + { + tmp = (uint16_t*) pData ; + *tmp = (uint16_t)(hirda->Instance->RDR & uhMask); + pData +=2; + } + else + { + *pData++ = (uint8_t)(hirda->Instance->RDR & (uint8_t)uhMask); + } + } + + if(hirda->State == HAL_IRDA_STATE_BUSY_TX_RX) + { + hirda->State = HAL_IRDA_STATE_BUSY_TX; + } + else + { + hirda->State = HAL_IRDA_STATE_READY; + } + + /* Process Unlocked */ + __HAL_UNLOCK(hirda); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Send an amount of data in interrupt mode + * @param hirda: IRDA handle + * @param pData: pointer to data buffer + * @param Size: amount of data to be sent + * @retval HAL status + */ +HAL_StatusTypeDef HAL_IRDA_Transmit_IT(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size) +{ + if ((hirda->State == HAL_IRDA_STATE_READY) || (hirda->State == HAL_IRDA_STATE_BUSY_RX)) + { + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(hirda); + + hirda->pTxBuffPtr = pData; + hirda->TxXferSize = Size; + hirda->TxXferCount = Size; + + hirda->ErrorCode = HAL_IRDA_ERROR_NONE; + if(hirda->State == HAL_IRDA_STATE_BUSY_RX) + { + hirda->State = HAL_IRDA_STATE_BUSY_TX_RX; + } + else + { + hirda->State = HAL_IRDA_STATE_BUSY_TX; + } + + /* Enable the IRDA Error Interrupt: (Frame error, noise error, overrun error) */ + __HAL_IRDA_ENABLE_IT(hirda, IRDA_IT_ERR); + + /* Process Unlocked */ + __HAL_UNLOCK(hirda); + + /* Enable the IRDA Transmit Complete Interrupt */ + __HAL_IRDA_ENABLE_IT(hirda, IRDA_IT_TC); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive an amount of data in interrupt mode + * @param hirda: IRDA handle + * @param pData: pointer to data buffer + * @param Size: amount of data to be received + * @retval HAL status + */ +HAL_StatusTypeDef HAL_IRDA_Receive_IT(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size) +{ + if ((hirda->State == HAL_IRDA_STATE_READY) || (hirda->State == HAL_IRDA_STATE_BUSY_TX)) + { + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(hirda); + + hirda->pRxBuffPtr = pData; + hirda->RxXferSize = Size; + hirda->RxXferCount = Size; + + /* Computation of the mask to apply to the RDR register + of the UART associated to the IRDA */ + __HAL_IRDA_MASK_COMPUTATION(hirda); + + hirda->ErrorCode = HAL_IRDA_ERROR_NONE; + if(hirda->State == HAL_IRDA_STATE_BUSY_TX) + { + hirda->State = HAL_IRDA_STATE_BUSY_TX_RX; + } + else + { + hirda->State = HAL_IRDA_STATE_BUSY_RX; + } + + /* Enable the IRDA Parity Error Interrupt */ + __HAL_IRDA_ENABLE_IT(hirda, IRDA_IT_PE); + + /* Enable the IRDA Error Interrupt: (Frame error, noise error, overrun error) */ + __HAL_IRDA_ENABLE_IT(hirda, IRDA_IT_ERR); + + /* Process Unlocked */ + __HAL_UNLOCK(hirda); + + /* Enable the IRDA Data Register not empty Interrupt */ + __HAL_IRDA_ENABLE_IT(hirda, IRDA_IT_RXNE); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Send an amount of data in DMA mode + * @param hirda: IRDA handle + * @param pData: pointer to data buffer + * @param Size: amount of data to be sent + * @retval HAL status + */ +HAL_StatusTypeDef HAL_IRDA_Transmit_DMA(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size) +{ + uint32_t *tmp; + + if ((hirda->State == HAL_IRDA_STATE_READY) || (hirda->State == HAL_IRDA_STATE_BUSY_RX)) + { + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(hirda); + + hirda->pTxBuffPtr = pData; + hirda->TxXferSize = Size; + hirda->TxXferCount = Size; + + hirda->ErrorCode = HAL_IRDA_ERROR_NONE; + + if(hirda->State == HAL_IRDA_STATE_BUSY_RX) + { + hirda->State = HAL_IRDA_STATE_BUSY_TX_RX; + } + else + { + hirda->State = HAL_IRDA_STATE_BUSY_TX; + } + + /* Set the IRDA DMA transfert complete callback */ + hirda->hdmatx->XferCpltCallback = IRDA_DMATransmitCplt; + + /* Set the DMA error callback */ + hirda->hdmatx->XferErrorCallback = IRDA_DMAError; + + /* Enable the IRDA transmit DMA Stream */ + tmp = (uint32_t*)&pData; + HAL_DMA_Start_IT(hirda->hdmatx, *(uint32_t*)tmp, (uint32_t)&hirda->Instance->TDR, Size); + + /* Enable the DMA transfer for transmit request by setting the DMAT bit + in the IRDA CR3 register */ + hirda->Instance->CR3 |= USART_CR3_DMAT; + + /* Process Unlocked */ + __HAL_UNLOCK(hirda); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive an amount of data in DMA mode + * @param hirda: IRDA handle + * @param pData: pointer to data buffer + * @param Size: amount of data to be received + * @note When the IRDA parity is enabled (PCE = 1), the received data contain + * the parity bit (MSB position) + * @retval HAL status + */ +HAL_StatusTypeDef HAL_IRDA_Receive_DMA(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size) +{ + uint32_t *tmp; + + if ((hirda->State == HAL_IRDA_STATE_READY) || (hirda->State == HAL_IRDA_STATE_BUSY_TX)) + { + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(hirda); + + hirda->pRxBuffPtr = pData; + hirda->RxXferSize = Size; + + hirda->ErrorCode = HAL_IRDA_ERROR_NONE; + if(hirda->State == HAL_IRDA_STATE_BUSY_TX) + { + hirda->State = HAL_IRDA_STATE_BUSY_TX_RX; + } + else + { + hirda->State = HAL_IRDA_STATE_BUSY_RX; + } + + /* Set the IRDA DMA transfert complete callback */ + hirda->hdmarx->XferCpltCallback = IRDA_DMAReceiveCplt; + + /* Set the DMA error callback */ + hirda->hdmarx->XferErrorCallback = IRDA_DMAError; + + /* Enable the DMA Stream */ + tmp = (uint32_t*)&pData; + HAL_DMA_Start_IT(hirda->hdmarx, (uint32_t)&hirda->Instance->RDR, *(uint32_t*)tmp, Size); + + /* Enable the DMA transfer for the receiver request by setting the DMAR bit + in the IRDA CR3 register */ + hirda->Instance->CR3 |= USART_CR3_DMAR; + + /* Process Unlocked */ + __HAL_UNLOCK(hirda); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief This function handles IRDA interrupt request. + * @param hirda: IRDA handle + * @retval None + */ +void HAL_IRDA_IRQHandler(IRDA_HandleTypeDef *hirda) +{ + /* IRDA parity error interrupt occurred -------------------------------------*/ + if((__HAL_IRDA_GET_IT(hirda, IRDA_IT_PE) != RESET) && (__HAL_IRDA_GET_IT_SOURCE(hirda, IRDA_IT_PE) != RESET)) + { + __HAL_IRDA_CLEAR_IT(hirda, IRDA_CLEAR_PEF); + + hirda->ErrorCode |= HAL_IRDA_ERROR_PE; + /* Set the IRDA state ready to be able to start again the process */ + hirda->State = HAL_IRDA_STATE_READY; + } + + /* IRDA frame error interrupt occured --------------------------------------*/ + if((__HAL_IRDA_GET_IT(hirda, IRDA_IT_FE) != RESET) && (__HAL_IRDA_GET_IT_SOURCE(hirda, IRDA_IT_ERR) != RESET)) + { + __HAL_IRDA_CLEAR_IT(hirda, IRDA_CLEAR_FEF); + + hirda->ErrorCode |= HAL_IRDA_ERROR_FE; + /* Set the IRDA state ready to be able to start again the process */ + hirda->State = HAL_IRDA_STATE_READY; + } + + /* IRDA noise error interrupt occured --------------------------------------*/ + if((__HAL_IRDA_GET_IT(hirda, IRDA_IT_NE) != RESET) && (__HAL_IRDA_GET_IT_SOURCE(hirda, IRDA_IT_ERR) != RESET)) + { + __HAL_IRDA_CLEAR_IT(hirda, IRDA_CLEAR_NEF); + + hirda->ErrorCode |= HAL_IRDA_ERROR_NE; + /* Set the IRDA state ready to be able to start again the process */ + hirda->State = HAL_IRDA_STATE_READY; + } + + /* IRDA Over-Run interrupt occured -----------------------------------------*/ + if((__HAL_IRDA_GET_IT(hirda, IRDA_IT_ORE) != RESET) && (__HAL_IRDA_GET_IT_SOURCE(hirda, IRDA_IT_ERR) != RESET)) + { + __HAL_IRDA_CLEAR_IT(hirda, IRDA_CLEAR_OREF); + + hirda->ErrorCode |= HAL_IRDA_ERROR_ORE; + /* Set the IRDA state ready to be able to start again the process */ + hirda->State = HAL_IRDA_STATE_READY; + } + + /* Call IRDA Error Call back function if need be --------------------------*/ + if(hirda->ErrorCode != HAL_IRDA_ERROR_NONE) + { + HAL_IRDA_ErrorCallback(hirda); + } + + /* IRDA in mode Receiver ---------------------------------------------------*/ + if((__HAL_IRDA_GET_IT(hirda, IRDA_IT_RXNE) != RESET) && (__HAL_IRDA_GET_IT_SOURCE(hirda, IRDA_IT_RXNE) != RESET)) + { + IRDA_Receive_IT(hirda); + /* Clear RXNE interrupt flag */ + __HAL_IRDA_SEND_REQ(hirda, IRDA_RXDATA_FLUSH_REQUEST); + } + + + /* IRDA in mode Transmitter ------------------------------------------------*/ + if((__HAL_IRDA_GET_IT(hirda, IRDA_IT_TC) != RESET) &&(__HAL_IRDA_GET_IT_SOURCE(hirda, IRDA_IT_TC) != RESET)) + { + IRDA_Transmit_IT(hirda); + } + +} + +/** + * @brief DMA IRDA Tx transfer completed callback + * @param hdma: DMA handle + * @retval None + */ +static void IRDA_DMATransmitCplt(DMA_HandleTypeDef *hdma) +{ + IRDA_HandleTypeDef* hirda = ( IRDA_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + hirda->TxXferCount = 0; + + /* Disable the DMA transfer for transmit request by setting the DMAT bit + in the IRDA CR3 register */ + hirda->Instance->CR3 &= (uint16_t)~((uint16_t)USART_CR3_DMAT); + + /* Wait for IRDA TC Flag */ + if(IRDA_WaitOnFlagUntilTimeout(hirda, IRDA_FLAG_TC, RESET, HAL_IRDA_TXDMA_TIMEOUTVALUE) != HAL_OK) + { + /* Timeout Occured */ + hirda->State = HAL_IRDA_STATE_TIMEOUT; + HAL_IRDA_ErrorCallback(hirda); + } + else + { + /* No Timeout */ + + if(hirda->State == HAL_IRDA_STATE_BUSY_TX_RX) + { + hirda->State = HAL_IRDA_STATE_BUSY_RX; + } + else + { + hirda->State = HAL_IRDA_STATE_READY; + } + HAL_IRDA_TxCpltCallback(hirda); + } +} + +/** + * @brief DMA IRDA Rx Transfer completed callback + * @param hdma: DMA handle + * @retval None + */ +static void IRDA_DMAReceiveCplt(DMA_HandleTypeDef *hdma) +{ + IRDA_HandleTypeDef* hirda = ( IRDA_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + hirda->RxXferCount = 0; + + /* Disable the DMA transfer for the receiver request by setting the DMAR bit + in the IRDA CR3 register */ + hirda->Instance->CR3 &= (uint16_t)~((uint16_t)USART_CR3_DMAR); + + if(hirda->State == HAL_IRDA_STATE_BUSY_TX_RX) + { + hirda->State = HAL_IRDA_STATE_BUSY_TX; + } + else + { + hirda->State = HAL_IRDA_STATE_READY; + } + + HAL_IRDA_RxCpltCallback(hirda); +} + +/** + * @brief DMA IRDA communication error callback + * @param hdma: DMA handle + * @retval None + */ +static void IRDA_DMAError(DMA_HandleTypeDef *hdma) +{ + IRDA_HandleTypeDef* hirda = ( IRDA_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + hirda->RxXferCount = 0; + hirda->TxXferCount = 0; + hirda->State= HAL_IRDA_STATE_READY; + hirda->ErrorCode |= HAL_IRDA_ERROR_DMA; + HAL_IRDA_ErrorCallback(hirda); +} + +/** + * @brief Tx Transfer completed callback + * @param hirda: irda handle + * @retval None + */ + __weak void HAL_IRDA_TxCpltCallback(IRDA_HandleTypeDef *hirda) +{ + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_IRDA_TxCpltCallback can be implemented in the user file + */ +} + +/** + * @brief Rx Transfer completed callback + * @param hirda: irda handle + * @retval None + */ +__weak void HAL_IRDA_RxCpltCallback(IRDA_HandleTypeDef *hirda) +{ + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_IRDA_TxCpltCallback can be implemented in the user file + */ +} + +/** + * @brief IRDA error callback + * @param hirda: IRDA handle + * @retval None + */ + __weak void HAL_IRDA_ErrorCallback(IRDA_HandleTypeDef *hirda) +{ + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_IRDA_ErrorCallback can be implemented in the user file + */ +} + +/** + * @brief Receive an amount of data in non blocking mode. + * Function called under interruption only, once + * interruptions have been enabled by HAL_IRDA_Transmit_IT() + * @param hirda: IRDA handle + * @retval HAL status + */ +static HAL_StatusTypeDef IRDA_Transmit_IT(IRDA_HandleTypeDef *hirda) +{ + uint16_t* tmp; + + if((hirda->State == HAL_IRDA_STATE_BUSY_TX) || (hirda->State == HAL_IRDA_STATE_BUSY_TX_RX)) + { + if(hirda->TxXferCount == 0) + { + /* Disable the IRDA Transmit Complete Interrupt */ + __HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_TC); + + if(hirda->State == HAL_IRDA_STATE_BUSY_TX_RX) + { + hirda->State = HAL_IRDA_STATE_BUSY_RX; + } + else + { + /* Disable the IRDA Error Interrupt: (Frame error, noise error, overrun error) */ + __HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_ERR); + + hirda->State = HAL_IRDA_STATE_READY; + } + + HAL_IRDA_TxCpltCallback(hirda); + + return HAL_OK; + } + else + { + if ((hirda->Init.WordLength == IRDA_WORDLENGTH_9B) && (hirda->Init.Parity == IRDA_PARITY_NONE)) + { + tmp = (uint16_t*) hirda->pTxBuffPtr; + hirda->Instance->TDR = (*tmp & (uint16_t)0x01FF); + hirda->pTxBuffPtr += 2; + } + else + { + hirda->Instance->TDR = (uint8_t)(*hirda->pTxBuffPtr++ & (uint8_t)0xFF); + } + hirda->TxXferCount--; + return HAL_OK; + } + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive an amount of data in non blocking mode. + * Function called under interruption only, once + * interruptions have been enabled by HAL_IRDA_Receive_IT() + * @param hirda: IRDA handle + * @retval HAL status + */ +static HAL_StatusTypeDef IRDA_Receive_IT(IRDA_HandleTypeDef *hirda) +{ + uint16_t* tmp; + uint16_t uhMask = hirda->Mask; + + if ((hirda->State == HAL_IRDA_STATE_BUSY_RX) || (hirda->State == HAL_IRDA_STATE_BUSY_TX_RX)) + { + if ((hirda->Init.WordLength == IRDA_WORDLENGTH_9B) && (hirda->Init.Parity == IRDA_PARITY_NONE)) + { + tmp = (uint16_t*) hirda->pRxBuffPtr ; + *tmp = (uint16_t)(hirda->Instance->RDR & uhMask); + hirda->pRxBuffPtr +=2; + } + else + { + *hirda->pRxBuffPtr++ = (uint8_t)(hirda->Instance->RDR & (uint8_t)uhMask); + } + + if(--hirda->RxXferCount == 0) + { + while(HAL_IS_BIT_SET(hirda->Instance->ISR, IRDA_FLAG_RXNE)) + { + } + __HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_RXNE); + + if(hirda->State == HAL_IRDA_STATE_BUSY_TX_RX) + { + hirda->State = HAL_IRDA_STATE_BUSY_TX; + } + else + { + /* Disable the IRDA Parity Error Interrupt */ + __HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_PE); + + /* Disable the IRDA Error Interrupt: (Frame error, noise error, overrun error) */ + __HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_ERR); + + hirda->State = HAL_IRDA_STATE_READY; + } + + HAL_IRDA_RxCpltCallback(hirda); + + return HAL_OK; + } + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @} + */ + +/** @defgroup HAL_IRDA_Group3 Peripheral Control functions + * @brief IRDA control functions + * +@verbatim + =============================================================================== + ##### Peripheral Control functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to control the IRDA. + (+) HAL_IRDA_GetState() API can be helpful to check in run-time the state of the IRDA peripheral. + (+) IRDA_SetConfig() API is used to configure the IRDA communications parameters. +@endverbatim + * @{ + */ + +/** + * @brief return the IRDA state + * @param hirda: irda handle + * @retval HAL state + */ +HAL_IRDA_StateTypeDef HAL_IRDA_GetState(IRDA_HandleTypeDef *hirda) +{ + return hirda->State; +} + +/** +* @brief Return the IRDA error code +* @param hirda : pointer to a IRDA_HandleTypeDef structure that contains + * the configuration information for the specified IRDA. +* @retval IRDA Error Code +*/ +uint32_t HAL_IRDA_GetError(IRDA_HandleTypeDef *hirda) +{ + return hirda->ErrorCode; +} + +/** + * @} + */ + +/** + * @brief Configure the IRDA peripheral + * @param hirda: irda handle + * @retval None + */ +static void IRDA_SetConfig(IRDA_HandleTypeDef *hirda) +{ + uint32_t tmpreg = 0x00000000; + uint32_t clocksource = 0x00000000; + + /* Check the communication parameters */ + assert_param(IS_IRDA_BAUDRATE(hirda->Init.BaudRate)); + assert_param(IS_IRDA_WORD_LENGTH(hirda->Init.WordLength)); + assert_param(IS_IRDA_PARITY(hirda->Init.Parity)); + assert_param(IS_IRDA_TX_RX_MODE(hirda->Init.Mode)); + assert_param(IS_IRDA_PRESCALER(hirda->Init.Prescaler)); + assert_param(IS_IRDA_POWERMODE(hirda->Init.PowerMode)); + /*-------------------------- USART CR1 Configuration -----------------------*/ + /* Configure the IRDA Word Length, Parity and transfer Mode: + Set the M bits according to hirda->Init.WordLength value + Set PCE and PS bits according to hirda->Init.Parity value + Set TE and RE bits according to hirda->Init.Mode value */ + tmpreg = (uint32_t)hirda->Init.WordLength | hirda->Init.Parity | hirda->Init.Mode ; + + MODIFY_REG(hirda->Instance->CR1, IRDA_CR1_FIELDS, tmpreg); + + /*-------------------------- USART CR3 Configuration -----------------------*/ + MODIFY_REG(hirda->Instance->CR3, USART_CR3_IRLP, hirda->Init.PowerMode); + + /*-------------------------- USART GTPR Configuration ----------------------*/ + MODIFY_REG(hirda->Instance->GTPR, (uint32_t)USART_GTPR_PSC, hirda->Init.Prescaler); + + /*-------------------------- USART BRR Configuration -----------------------*/ + __HAL_IRDA_GETCLOCKSOURCE(hirda, clocksource); + switch (clocksource) + { + case IRDA_CLOCKSOURCE_PCLK1: + hirda->Instance->BRR = (uint16_t)(HAL_RCC_GetPCLK1Freq() / hirda->Init.BaudRate); + break; + case IRDA_CLOCKSOURCE_PCLK2: + hirda->Instance->BRR = (uint16_t)(HAL_RCC_GetPCLK2Freq() / hirda->Init.BaudRate); + break; + case IRDA_CLOCKSOURCE_HSI: + hirda->Instance->BRR = (uint16_t)(HSI_VALUE / hirda->Init.BaudRate); + break; + case IRDA_CLOCKSOURCE_SYSCLK: + hirda->Instance->BRR = (uint16_t)(HAL_RCC_GetSysClockFreq() / hirda->Init.BaudRate); + break; + case IRDA_CLOCKSOURCE_LSE: + hirda->Instance->BRR = (uint16_t)(LSE_VALUE / hirda->Init.BaudRate); + break; + default: + break; + } +} + +/** + * @brief Check the IRDA Idle State + * @param hirda: IRDA handle + * @retval HAL status + */ +static HAL_StatusTypeDef IRDA_CheckIdleState(IRDA_HandleTypeDef *hirda) +{ + /* Initialize the IRDA ErrorCode */ + hirda->ErrorCode = HAL_IRDA_ERROR_NONE; + + /* Check if the Transmitter is enabled */ + if((hirda->Instance->CR1 & USART_CR1_TE) == USART_CR1_TE) + { + /* Wait until TEACK flag is set */ + if(IRDA_WaitOnFlagUntilTimeout(hirda, USART_ISR_TEACK, RESET, TEACK_REACK_TIMEOUT) != HAL_OK) + { + hirda->State= HAL_IRDA_STATE_TIMEOUT; + return HAL_TIMEOUT; + } + } + /* Check if the Receiver is enabled */ + if((hirda->Instance->CR1 & USART_CR1_RE) == USART_CR1_RE) + { + if(IRDA_WaitOnFlagUntilTimeout(hirda, USART_ISR_REACK, RESET, TEACK_REACK_TIMEOUT) != HAL_OK) + { + hirda->State= HAL_IRDA_STATE_TIMEOUT; + return HAL_TIMEOUT; + } + } + /* Process Unlocked */ + __HAL_UNLOCK(hirda); + + /* Initialize the IRDA state*/ + hirda->State= HAL_IRDA_STATE_READY; + + return HAL_OK; +} + +/** + * @brief Handle IRDA Communication Timeout. + * @param hirda: IRDA handle + * @param Flag: specifies the IRDA flag to check. + * @param Status: the flag status (SET or RESET). The function is locked in a while loop as long as the flag remains set to Status. + * @param Timeout: Timeout duration + * @retval HAL status + */ +static HAL_StatusTypeDef IRDA_WaitOnFlagUntilTimeout(IRDA_HandleTypeDef *hirda, uint32_t Flag, FlagStatus Status, uint32_t Timeout) +{ + uint32_t tickstart = 0x00; + tickstart = HAL_GetTick(); + + /* Wait until flag is set */ + if(Status == RESET) + { + while(__HAL_IRDA_GET_FLAG(hirda, Flag) == RESET) + { + /* Check for the Timeout */ + if(Timeout != HAL_MAX_DELAY) + { + if((HAL_GetTick() - tickstart ) > Timeout) + { + /* Disable TXE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts for the interrupt process */ + __HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_TXE); + __HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_RXNE); + __HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_PE); + __HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_ERR); + + hirda->State= HAL_IRDA_STATE_TIMEOUT; + + /* Process Unlocked */ + __HAL_UNLOCK(hirda); + + return HAL_TIMEOUT; + } + } + } + } + else + { + while(__HAL_IRDA_GET_FLAG(hirda, Flag) != RESET) + { + /* Check for the Timeout */ + if(Timeout != HAL_MAX_DELAY) + { + if((HAL_GetTick() - tickstart ) > Timeout) + { + /* Disable TXE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts for the interrupt process */ + __HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_TXE); + __HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_RXNE); + __HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_PE); + __HAL_IRDA_DISABLE_IT(hirda, IRDA_IT_ERR); + + hirda->State= HAL_IRDA_STATE_TIMEOUT; + + /* Process Unlocked */ + __HAL_UNLOCK(hirda); + + return HAL_TIMEOUT; + } + } + } + } + return HAL_OK; +} + +/** + * @} + */ + +#endif /* HAL_IRDA_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_irda.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_irda.h new file mode 100644 index 0000000000..968a2bfaff --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_irda.h @@ -0,0 +1,567 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_irda.h + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief Header file of IRDA HAL module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32L0xx_HAL_IRDA_H +#define __STM32L0xx_HAL_IRDA_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal_def.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @addtogroup IRDA + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ + +/** + * @brief IRDA Init Structure definition + */ +typedef struct +{ + uint32_t BaudRate; /*!< This member configures the IRDA communication baud rate. + The baud rate register is computed using the following formula: + Baud Rate Register = ((PCLKx) / ((hirda->Init.BaudRate))) */ + + uint32_t WordLength; /*!< Specifies the number of data bits transmitted or received in a frame. + This parameter can be a value of @ref IRDA_Word_Length */ + + uint32_t Parity; /*!< Specifies the parity mode. + This parameter can be a value of @ref IRDA_Parity + @note When parity is enabled, the computed parity is inserted + at the MSB position of the transmitted data (9th bit when + the word length is set to 9 data bits; 8th bit when the + word length is set to 8 data bits). */ + + uint16_t Mode; /*!< Specifies wether the Receive or Transmit mode is enabled or disabled. + This parameter can be a value of @ref IRDA_Mode */ + + uint8_t Prescaler; /*!< Specifies the Prescaler value for dividing the UART/USART source clock + to achieve low-power frequency. + @note Prescaler value 0 is forbidden */ + + uint16_t PowerMode; /*!< Specifies the IRDA power mode. + This parameter can be a value of @ref IRDA_Low_Power */ +}IRDA_InitTypeDef; + +/** + * @brief HAL IRDA State structures definition + */ +typedef enum +{ + HAL_IRDA_STATE_RESET = 0x00, /*!< Peripheral is not yet Initialized */ + HAL_IRDA_STATE_READY = 0x01, /*!< Peripheral Initialized and ready for use */ + HAL_IRDA_STATE_BUSY = 0x02, /*!< an internal process is ongoing */ + HAL_IRDA_STATE_BUSY_TX = 0x12, /*!< Data Transmission process is ongoing */ + HAL_IRDA_STATE_BUSY_RX = 0x22, /*!< Data Reception process is ongoing */ + HAL_IRDA_STATE_BUSY_TX_RX = 0x32, /*!< Data Transmission and Reception process is ongoing */ + HAL_IRDA_STATE_TIMEOUT = 0x03, /*!< Timeout state */ + HAL_IRDA_STATE_ERROR = 0x04 /*!< Error */ +}HAL_IRDA_StateTypeDef; + +/** + * @brief HAL IRDA Error Code structure definition + */ +typedef enum +{ + HAL_IRDA_ERROR_NONE = 0x00, /*!< No error */ + HAL_IRDA_ERROR_PE = 0x01, /*!< Parity error */ + HAL_IRDA_ERROR_NE = 0x02, /*!< Noise error */ + HAL_IRDA_ERROR_FE = 0x04, /*!< frame error */ + HAL_IRDA_ERROR_ORE = 0x08, /*!< Overrun error */ + HAL_IRDA_ERROR_DMA = 0x10 /*!< DMA transfer error */ +}HAL_IRDA_ErrorTypeDef; + +/** + * @brief IRDA clock sources definition + */ +typedef enum +{ + IRDA_CLOCKSOURCE_PCLK1 = 0x00, /*!< PCLK1 clock source */ + IRDA_CLOCKSOURCE_PCLK2 = 0x01, /*!< PCLK2 clock source */ + IRDA_CLOCKSOURCE_HSI = 0x02, /*!< HSI clock source */ + IRDA_CLOCKSOURCE_SYSCLK = 0x04, /*!< SYSCLK clock source */ + IRDA_CLOCKSOURCE_LSE = 0x08 /*!< LSE clock source */ +}IRDA_ClockSourceTypeDef; + +/** + * @brief IRDA handle Structure definition + */ +typedef struct +{ + USART_TypeDef *Instance; /* IRDA registers base address */ + + IRDA_InitTypeDef Init; /* IRDA communication parameters */ + + uint8_t *pTxBuffPtr; /* Pointer to IRDA Tx transfer Buffer */ + + uint16_t TxXferSize; /* IRDA Tx Transfer size */ + + uint16_t TxXferCount; /* IRDA Tx Transfer Counter */ + + uint8_t *pRxBuffPtr; /* Pointer to IRDA Rx transfer Buffer */ + + uint16_t RxXferSize; /* IRDA Rx Transfer size */ + + uint16_t RxXferCount; /* IRDA Rx Transfer Counter */ + + uint16_t Mask; /* IRDA RX RDR register mask */ + + DMA_HandleTypeDef *hdmatx; /* IRDA Tx DMA Handle parameters */ + + DMA_HandleTypeDef *hdmarx; /* IRDA Rx DMA Handle parameters */ + + HAL_LockTypeDef Lock; /* Locking object */ + + __IO HAL_IRDA_StateTypeDef State; /* IRDA communication state */ + + __IO HAL_IRDA_ErrorTypeDef ErrorCode; /* IRDA Error code */ + +}IRDA_HandleTypeDef; + +/** + * @brief IRDA Configuration enumeration values definition + */ + +/* Exported constants --------------------------------------------------------*/ +/** @defgroup IRDA_Exported_Constants IRDA Exported Constants + * @{ + */ + +/** @defgroup IRDA_Parity IRDA Parity + * @{ + */ +#define IRDA_PARITY_NONE ((uint32_t)0x0000) +#define IRDA_PARITY_EVEN ((uint32_t)USART_CR1_PCE) +#define IRDA_PARITY_ODD ((uint32_t)(USART_CR1_PCE | USART_CR1_PS)) +#define IS_IRDA_PARITY(PARITY) (((PARITY) == IRDA_PARITY_NONE) || \ + ((PARITY) == IRDA_PARITY_EVEN) || \ + ((PARITY) == IRDA_PARITY_ODD)) +/** + * @} + */ + + +/** @defgroup IRDA_Transfer_Mode IRDA Transfer Mode + * @{ + */ +#define IRDA_MODE_RX ((uint32_t)USART_CR1_RE) +#define IRDA_MODE_TX ((uint32_t)USART_CR1_TE) +#define IRDA_MODE_TX_RX ((uint32_t)(USART_CR1_TE |USART_CR1_RE)) +#define IS_IRDA_TX_RX_MODE(MODE) ((((MODE) & (~((uint32_t)(IRDA_MODE_TX_RX)))) == (uint32_t)0x00) && ((MODE) != (uint32_t)0x00)) +/** + * @} + */ + +/** @defgroup IRDA_Low_Power IRDA Low Power + * @{ + */ +#define IRDA_POWERMODE_NORMAL ((uint32_t)0x0000) +#define IRDA_POWERMODE_LOWPOWER ((uint32_t)USART_CR3_IRLP) +#define IS_IRDA_POWERMODE(MODE) (((MODE) == IRDA_POWERMODE_LOWPOWER) || \ + ((MODE) == IRDA_POWERMODE_NORMAL)) +/** + * @} + */ + + /** @defgroup IRDA_State IRDA State + * @{ + */ +#define IRDA_STATE_DISABLE ((uint32_t)0x0000) +#define IRDA_STATE_ENABLE ((uint32_t)USART_CR1_UE) +#define IS_IRDA_STATE(STATE) (((STATE) == IRDA_STATE_DISABLE) || \ + ((STATE) == IRDA_STATE_ENABLE)) +/** + * @} + */ + + /** @defgroup IRDA_Mode IRDA Mode + * @{ + */ +#define IRDA_MODE_DISABLE ((uint32_t)0x0000) +#define IRDA_MODE_ENABLE ((uint32_t)USART_CR3_IREN) +#define IS_IRDA_MODE(STATE) (((STATE) == IRDA_MODE_DISABLE) || \ + ((STATE) == IRDA_MODE_ENABLE)) +/** + * @} + */ + +/** @defgroup IRDA_One_Bit IRDA One Bit Sampling + * @{ + */ +#define IRDA_ONE_BIT_SAMPLE_DISABLED ((uint32_t)0x00000000) +#define IRDA_ONE_BIT_SAMPLE_ENABLED ((uint32_t)USART_CR3_ONEBIT) +#define IS_IRDA_ONEBIT_SAMPLE(ONEBIT) (((ONEBIT) == IRDA_ONE_BIT_SAMPLE_DISABLED) || \ + ((ONEBIT) == IRDA_ONE_BIT_SAMPLE_ENABLED)) +/** + * @} + */ + +/** @defgroup IRDA_DMA_Tx IRDA DMA Tx + * @{ + */ +#define IRDA_DMA_TX_DISABLE ((uint32_t)0x00000000) +#define IRDA_DMA_TX_ENABLE ((uint32_t)USART_CR3_DMAT) +#define IS_IRDA_DMA_TX(DMATX) (((DMATX) == IRDA_DMA_TX_DISABLE) || \ + ((DMATX) == IRDA_DMA_TX_ENABLE)) +/** + * @} + */ + +/** @defgroup IRDA_DMA_Rx IRDA DMA Rx + * @{ + */ +#define IRDA_DMA_RX_DISABLE ((uint32_t)0x0000) +#define IRDA_DMA_RX_ENABLE ((uint32_t)USART_CR3_DMAR) +#define IS_IRDA_DMA_RX(DMARX) (((DMARX) == IRDA_DMA_RX_DISABLE) || \ + ((DMARX) == IRDA_DMA_RX_ENABLE)) +/** + * @} + */ + +/** @defgroup IRDA_Flags IRDA Flags + * Elements values convention: 0xXXXX + * - 0xXXXX : Flag mask in the ISR register + * @{ + */ +#define IRDA_FLAG_REACK ((uint32_t)0x00400000) +#define IRDA_FLAG_TEACK ((uint32_t)0x00200000) +#define IRDA_FLAG_BUSY ((uint32_t)0x00010000) +#define IRDA_FLAG_ABRF ((uint32_t)0x00008000) +#define IRDA_FLAG_ABRE ((uint32_t)0x00004000) +#define IRDA_FLAG_TXE ((uint32_t)0x00000080) +#define IRDA_FLAG_TC ((uint32_t)0x00000040) +#define IRDA_FLAG_RXNE ((uint32_t)0x00000020) +#define IRDA_FLAG_ORE ((uint32_t)0x00000008) +#define IRDA_FLAG_NE ((uint32_t)0x00000004) +#define IRDA_FLAG_FE ((uint32_t)0x00000002) +#define IRDA_FLAG_PE ((uint32_t)0x00000001) +/** + * @} + */ + +/** @defgroup IRDA_Interrupt_definition IRDA Interrupts Definition + * Elements values convention: 0000ZZZZ0XXYYYYYb + * - YYYYY : Interrupt source position in the XX register (5bits) + * - XX : Interrupt source register (2bits) + * - 01: CR1 register + * - 10: CR2 register + * - 11: CR3 register + * - ZZZZ : Flag position in the ISR register(4bits) + * @{ + */ +#define IRDA_IT_PE ((uint16_t)0x0028) +#define IRDA_IT_TXE ((uint16_t)0x0727) +#define IRDA_IT_TC ((uint16_t)0x0626) +#define IRDA_IT_RXNE ((uint16_t)0x0525) +#define IRDA_IT_IDLE ((uint16_t)0x0424) + + + +/** Elements values convention: 000000000XXYYYYYb + * - YYYYY : Interrupt source position in the XX register (5bits) + * - XX : Interrupt source register (2bits) + * - 01: CR1 register + * - 10: CR2 register + * - 11: CR3 register + */ +#define IRDA_IT_ERR ((uint16_t)0x0060) + +/** Elements values convention: 0000ZZZZ00000000b + * - ZZZZ : Flag position in the ISR register(4bits) + */ +#define IRDA_IT_ORE ((uint16_t)0x0300) +#define IRDA_IT_NE ((uint16_t)0x0200) +#define IRDA_IT_FE ((uint16_t)0x0100) +/** + * @} + */ + +/** @defgroup IRDA_IT_CLEAR_Flags IRDA Interruption Clear Flags + * @{ + */ +#define IRDA_CLEAR_PEF USART_ICR_PECF /*!< Parity Error Clear Flag */ +#define IRDA_CLEAR_FEF USART_ICR_FECF /*!< Framing Error Clear Flag */ +#define IRDA_CLEAR_NEF USART_ICR_NCF /*!< Noise detected Clear Flag */ +#define IRDA_CLEAR_OREF USART_ICR_ORECF /*!< OverRun Error Clear Flag */ +#define IRDA_CLEAR_TCF USART_ICR_TCCF /*!< Transmission Complete Clear Flag */ +/** + * @} + */ + + + +/** @defgroup IRDA_Request_Parameters IRDA Request Parameters + * @{ + */ +#define IRDA_AUTOBAUD_REQUEST ((uint16_t)USART_RQR_ABRRQ) /*!< Auto-Baud Rate Request */ +#define IRDA_RXDATA_FLUSH_REQUEST ((uint16_t)USART_RQR_RXFRQ) /*!< Receive Data flush Request */ +#define IRDA_TXDATA_FLUSH_REQUEST ((uint16_t)USART_RQR_TXFRQ) /*!< Transmit data flush Request */ +#define IS_IRDA_REQUEST_PARAMETER(PARAM) (((PARAM) == IRDA_AUTOBAUD_REQUEST) || \ + ((PARAM) == IRDA_SENDBREAK_REQUEST) || \ + ((PARAM) == IRDA_MUTE_MODE_REQUEST) || \ + ((PARAM) == IRDA_RXDATA_FLUSH_REQUEST) || \ + ((PARAM) == IRDA_TXDATA_FLUSH_REQUEST)) +/** + * @} + */ + +/** @defgroup IRDA_Interruption_Mask IRDA interruptions flag mask + * @{ + */ +#define IRDA_IT_MASK ((uint16_t)0x001F) +/** + * @} + */ + +/** + * @} + */ + + +/* Exported macro ------------------------------------------------------------*/ +/** @defgroup IRDA_Exported_Macros + * @{ + */ + +/** @brief Reset IRDA handle state + * @param __HANDLE__: specifies the IRDA Handle. + * The Handle Instance which can be USART1 or USART2. + * @retval None + */ +#define __HAL_IRDA_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_IRDA_STATE_RESET) + +/** @brief Check whether the specified IRDA flag is set or not. + * @param __HANDLE__: specifies the IRDA Handle. + * The Handle Instance which can be USART1 or USART2. + * UART peripheral + * @param __FLAG__: specifies the flag to check. + * This parameter can be one of the following values: + * @arg IRDA_FLAG_REACK: Receive enable ackowledge flag + * @arg IRDA_FLAG_TEACK: Transmit enable ackowledge flag + * @arg IRDA_FLAG_BUSY: Busy flag + * @arg IRDA_FLAG_ABRF: Auto Baud rate detection flag + * @arg IRDA_FLAG_ABRE: Auto Baud rate detection error flag + * @arg IRDA_FLAG_TXE: Transmit data register empty flag + * @arg IRDA_FLAG_TC: Transmission Complete flag + * @arg IRDA_FLAG_RXNE: Receive data register not empty flag + * @arg IRDA_FLAG_IDLE: Idle Line detection flag + * @arg IRDA_FLAG_ORE: OverRun Error flag + * @arg IRDA_FLAG_NE: Noise Error flag + * @arg IRDA_FLAG_FE: Framing Error flag + * @arg IRDA_FLAG_PE: Parity Error flag + * @retval The new state of __FLAG__ (TRUE or FALSE). + */ +#define __HAL_IRDA_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->ISR & (__FLAG__)) == (__FLAG__)) + +/** @brief Enable the specified IRDA interrupt. + * @param __HANDLE__: specifies the IRDA Handle. + * The Handle Instance which can be USART1 or USART2. + * UART peripheral + * @param __INTERRUPT__: specifies the IRDA interrupt source to enable. + * This parameter can be one of the following values: + * @arg IRDA_IT_TXE: Transmit Data Register empty interrupt + * @arg IRDA_IT_TC: Transmission complete interrupt + * @arg IRDA_IT_RXNE: Receive Data register not empty interrupt + * @arg IRDA_IT_IDLE: Idle line detection interrupt + * @arg IRDA_IT_PE: Parity Error interrupt + * @arg IRDA_IT_ERR: Error interrupt(Frame error, noise error, overrun error) + * @retval None + */ +#define __HAL_IRDA_ENABLE_IT(__HANDLE__, __INTERRUPT__) (((((uint8_t)(__INTERRUPT__)) >> 5) == 1)? ((__HANDLE__)->Instance->CR1 |= (1 << ((__INTERRUPT__) & IRDA_IT_MASK))): \ + ((((uint8_t)(__INTERRUPT__)) >> 5) == 2)? ((__HANDLE__)->Instance->CR2 |= (1 << ((__INTERRUPT__) & IRDA_IT_MASK))): \ + ((__HANDLE__)->Instance->CR3 |= (1 << ((__INTERRUPT__) & IRDA_IT_MASK)))) + +/** @brief Disable the specified IRDA interrupt. + * @param __HANDLE__: specifies the IRDA Handle. + * The Handle Instance which can be USART1 or USART2. + * @param __INTERRUPT__: specifies the IRDA interrupt source to disable. + * This parameter can be one of the following values: + * @arg IRDA_IT_TXE: Transmit Data Register empty interrupt + * @arg IRDA_IT_TC: Transmission complete interrupt + * @arg IRDA_IT_RXNE: Receive Data register not empty interrupt + * @arg IRDA_IT_IDLE: Idle line detection interrupt + * @arg IRDA_IT_PE: Parity Error interrupt + * @arg IRDA_IT_ERR: Error interrupt(Frame error, noise error, overrun error) + * @retval None + */ +#define __HAL_IRDA_DISABLE_IT(__HANDLE__, __INTERRUPT__) (((((uint8_t)(__INTERRUPT__)) >> 5) == 1)? ((__HANDLE__)->Instance->CR1 &= ~ ((uint32_t)1 << ((__INTERRUPT__) & IRDA_IT_MASK))): \ + ((((uint8_t)(__INTERRUPT__)) >> 5) == 2)? ((__HANDLE__)->Instance->CR2 &= ~ ((uint32_t)1 << ((__INTERRUPT__) & IRDA_IT_MASK))): \ + ((__HANDLE__)->Instance->CR3 &= ~ ((uint32_t)1 << ((__INTERRUPT__) & IRDA_IT_MASK)))) + +/** @brief Check whether the specified IRDA interrupt has occurred or not. + * @param __HANDLE__: specifies the IRDA Handle. + * The Handle Instance which can be USART1 or USART2. + * @param __IT__: specifies the IRDA interrupt source to check. + * This parameter can be one of the following values: + * @arg IRDA_IT_TXE: Transmit Data Register empty interrupt + * @arg IRDA_IT_TC: Transmission complete interrupt + * @arg IRDA_IT_RXNE: Receive Data register not empty interrupt + * @arg IRDA_IT_IDLE: Idle line detection interrupt + * @arg IRDA_IT_ORE: OverRun Error interrupt + * @arg IRDA_IT_NE: Noise Error interrupt + * @arg IRDA_IT_FE: Framing Error interrupt + * @arg IRDA_IT_PE: Parity Error interrupt + * @retval The new state of __IT__ (TRUE or FALSE). + */ +#define __HAL_IRDA_GET_IT(__HANDLE__, __IT__) ((__HANDLE__)->Instance->ISR & ((uint32_t)1 << ((__IT__)>> 0x08))) + +/** @brief Check whether the specified IRDA interrupt source is enabled. + * @param __HANDLE__: specifies the IRDA Handle. + * The Handle Instance which can be USART1 or USART2. + * @param __IT__: specifies the IRDA interrupt source to check. + * This parameter can be one of the following values: + * @arg IRDA_IT_TXE: Transmit Data Register empty interrupt + * @arg IRDA_IT_TC: Transmission complete interrupt + * @arg IRDA_IT_RXNE: Receive Data register not empty interrupt + * @arg IRDA_IT_IDLE: Idle line detection interrupt + * @arg IRDA_IT_ORE: OverRun Error interrupt + * @arg IRDA_IT_NE: Noise Error interrupt + * @arg IRDA_IT_FE: Framing Error interrupt + * @arg IRDA_IT_PE: Parity Error interrupt + * @retval The new state of __IT__ (TRUE or FALSE). + */ +#define __HAL_IRDA_GET_IT_SOURCE(__HANDLE__, __IT__) ((((((uint8_t)(__IT__)) >> 5) == 1)? (__HANDLE__)->Instance->CR1:(((((uint8_t)(__IT__)) >> 5) == 2)? \ + (__HANDLE__)->Instance->CR2 : (__HANDLE__)->Instance->CR3)) & ((uint32_t)1 << (((uint16_t)(__IT__)) & IRDA_IT_MASK))) + +/** @brief Clear the specified IRDA ISR flag, in setting the proper ICR register flag. + * @param __HANDLE__: specifies the IRDA Handle. + * The Handle Instance which can be USART1 or USART2. + * @param __IT_CLEAR__: specifies the interrupt clear register flag that needs to be set + * to clear the corresponding interrupt + * This parameter can be one of the following values: + * @arg IRDA_CLEAR_PEF: Parity Error Clear Flag + * @arg IRDA_CLEAR_FEF: Framing Error Clear Flag + * @arg IRDA_CLEAR_NEF: Noise detected Clear Flag + * @arg IRDA_CLEAR_OREF: OverRun Error Clear Flag + * @arg IRDA_CLEAR_TCF: Transmission Complete Clear Flag + * @retval None + */ +#define __HAL_IRDA_CLEAR_IT(__HANDLE__, __IT_CLEAR__) ((__HANDLE__)->Instance->ICR |= (uint32_t)(__IT_CLEAR__)) + +/** @brief Set a specific IRDA request flag. + * @param __HANDLE__: specifies the IRDA Handle. + * The Handle Instance which can be USART1 or USART2. + * @param __REQ__: specifies the request flag to set + * This parameter can be one of the following values: + * @arg IRDA_AUTOBAUD_REQUEST: Auto-Baud Rate Request + * @arg IRDA_RXDATA_FLUSH_REQUEST: Receive Data flush Request + * @arg IRDA_TXDATA_FLUSH_REQUEST: Transmit data flush Request + * + * @retval None + */ +#define __HAL_IRDA_SEND_REQ(__HANDLE__, __REQ__) ((__HANDLE__)->Instance->RQR |= (uint16_t)(__REQ__)) + +/** @brief Enable UART/USART associated to IRDA Handle + * @param __HANDLE__: specifies the IRDA Handle. + * The Handle Instance which can be USART1 or USART2. + * @retval None + */ +#define __HAL_IRDA_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 |= USART_CR1_UE) + +/** @brief Disable UART/USART associated to IRDA Handle + * @param __HANDLE__: specifies the IRDA Handle. + * The Handle Instance which can be USART1 or USART2. + * @retval None + */ +#define __HAL_IRDA_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 &= ~USART_CR1_UE) + +/** @brief Ensure that IRDA Baud rate is less or equal to maximum value + * @param __BAUDRATE__: specifies the IRDA Baudrate set by the user. + * @retval True or False + */ +#define IS_IRDA_BAUDRATE(__BAUDRATE__) ((__BAUDRATE__) < 115201) + +/** @brief Ensure that IRDA prescaler value is strictly larger than 0 + * @param __PRESCALER__: specifies the IRDA prescaler value set by the user. + * @retval True or False + */ +#define IS_IRDA_PRESCALER(__PRESCALER__) ((__PRESCALER__) > 0) + +/** + * @} + */ + +/* Include IRDA HAL Extension module */ +#include "stm32l0xx_hal_irda_ex.h" + +/* Exported functions --------------------------------------------------------*/ +/* Initialization/de-initialization methods **********************************/ +HAL_StatusTypeDef HAL_IRDA_Init(IRDA_HandleTypeDef *hirda); +HAL_StatusTypeDef HAL_IRDA_DeInit(IRDA_HandleTypeDef *hirda); +void HAL_IRDA_MspInit(IRDA_HandleTypeDef *hirda); +void HAL_IRDA_MspDeInit(IRDA_HandleTypeDef *hirda); + +/* IO operation methods *******************************************************/ +HAL_StatusTypeDef HAL_IRDA_Transmit(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size, uint32_t Timeout); +HAL_StatusTypeDef HAL_IRDA_Receive(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size, uint32_t Timeout); +HAL_StatusTypeDef HAL_IRDA_Transmit_IT(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size); +HAL_StatusTypeDef HAL_IRDA_Receive_IT(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size); +HAL_StatusTypeDef HAL_IRDA_Transmit_DMA(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size); +HAL_StatusTypeDef HAL_IRDA_Receive_DMA(IRDA_HandleTypeDef *hirda, uint8_t *pData, uint16_t Size); +void HAL_IRDA_IRQHandler(IRDA_HandleTypeDef *hirda); +void HAL_IRDA_TxCpltCallback(IRDA_HandleTypeDef *hirda); +void HAL_IRDA_RxCpltCallback(IRDA_HandleTypeDef *hirda); +void HAL_IRDA_ErrorCallback(IRDA_HandleTypeDef *hirda); + +/* Peripheral State methods **************************************************/ +HAL_IRDA_StateTypeDef HAL_IRDA_GetState(IRDA_HandleTypeDef *hirda); +uint32_t HAL_IRDA_GetError(IRDA_HandleTypeDef *hirda); + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __STM32L0xx_HAL_IRDA_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_irda_ex.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_irda_ex.h new file mode 100644 index 0000000000..a6173c33cb --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_irda_ex.h @@ -0,0 +1,221 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_irda_ex.h + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief Header file of IRDA HAL Extension module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2013 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32L0xx_HAL_IRDA_EX_H +#define __STM32L0xx_HAL_IRDA_EX_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal_def.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @addtogroup IRDAEx + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/* Exported constants --------------------------------------------------------*/ +/** @defgroup IRDAEx_Extended_Exported_Constants + * @{ + */ + +/** @defgroup IRDAEx_Word_Length IRDA Word Length + * @{ + */ +#define IRDA_WORDLENGTH_7B ((uint32_t)USART_CR1_M_1) +#define IRDA_WORDLENGTH_8B ((uint32_t)0x00000000) +#define IRDA_WORDLENGTH_9B ((uint32_t)USART_CR1_M_0) +#define IS_IRDA_WORD_LENGTH(LENGTH) (((LENGTH) == IRDA_WORDLENGTH_7B) || \ + ((LENGTH) == IRDA_WORDLENGTH_8B) || \ + ((LENGTH) == IRDA_WORDLENGTH_9B)) +/** + * @} + */ + + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ + +/** @defgroup IRDAEx_Extended_Exported_Macros + * @{ + */ +/** @brief Reports the IRDA clock source. + * @param __HANDLE__: specifies the UART Handle + * @param __CLOCKSOURCE__ : output variable + * @retval IRDA clocking source, written in __CLOCKSOURCE__. + */ +#define __HAL_IRDA_GETCLOCKSOURCE(__HANDLE__,__CLOCKSOURCE__) \ + do { \ + if((__HANDLE__)->Instance == USART1) \ + { \ + switch(__HAL_RCC_GET_USART1_SOURCE()) \ + { \ + case RCC_USART1CLKSOURCE_PCLK2: \ + (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_PCLK2; \ + break; \ + case RCC_USART1CLKSOURCE_HSI: \ + (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_HSI; \ + break; \ + case RCC_USART1CLKSOURCE_SYSCLK: \ + (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_SYSCLK; \ + break; \ + case RCC_USART1CLKSOURCE_LSE: \ + (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_LSE; \ + break; \ + default: \ + break; \ + } \ + } \ + else if((__HANDLE__)->Instance == USART2) \ + { \ + switch(__HAL_RCC_GET_USART2_SOURCE()) \ + { \ + case RCC_USART2CLKSOURCE_PCLK1: \ + (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_PCLK1; \ + break; \ + case RCC_USART2CLKSOURCE_HSI: \ + (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_HSI; \ + break; \ + case RCC_USART2CLKSOURCE_SYSCLK: \ + (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_SYSCLK; \ + break; \ + case RCC_USART2CLKSOURCE_LSE: \ + (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_LSE; \ + break; \ + default: \ + break; \ + } \ + } \ + else if((__HANDLE__)->Instance == LPUART1) \ + { \ + switch(__HAL_RCC_GET_LPUART1_SOURCE()) \ + { \ + case RCC_LPUART1CLKSOURCE_PCLK1: \ + (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_PCLK1; \ + break; \ + case RCC_LPUART1CLKSOURCE_HSI: \ + (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_HSI; \ + break; \ + case RCC_LPUART1CLKSOURCE_SYSCLK: \ + (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_SYSCLK; \ + break; \ + case RCC_LPUART1CLKSOURCE_LSE: \ + (__CLOCKSOURCE__) = IRDA_CLOCKSOURCE_LSE; \ + break; \ + default: \ + break; \ + } \ + } \ + } while(0) + +/** @brief Reports the mask to apply to retrieve the received data + * according to the word length and to the parity bits activation. + * @param __HANDLE__: specifies the IRDA Handle + * @retval mask to apply to USART RDR register value. + */ +#define __HAL_IRDA_MASK_COMPUTATION(__HANDLE__) \ + do { \ + if ((__HANDLE__)->Init.WordLength == IRDA_WORDLENGTH_9B) \ + { \ + if ((__HANDLE__)->Init.Parity == IRDA_PARITY_NONE) \ + { \ + (__HANDLE__)->Mask = 0x01FF ; \ + } \ + else \ + { \ + (__HANDLE__)->Mask = 0x00FF ; \ + } \ + } \ + else if ((__HANDLE__)->Init.WordLength == IRDA_WORDLENGTH_8B) \ + { \ + if ((__HANDLE__)->Init.Parity == IRDA_PARITY_NONE) \ + { \ + (__HANDLE__)->Mask = 0x00FF ; \ + } \ + else \ + { \ + (__HANDLE__)->Mask = 0x007F ; \ + } \ + } \ + else if ((__HANDLE__)->Init.WordLength == IRDA_WORDLENGTH_7B) \ + { \ + if ((__HANDLE__)->Init.Parity == IRDA_PARITY_NONE) \ + { \ + (__HANDLE__)->Mask = 0x007F ; \ + } \ + else \ + { \ + (__HANDLE__)->Mask = 0x003F ; \ + } \ + } \ +} while(0) +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/* Initialization/de-initialization methods **********************************/ +/* IO operation methods *******************************************************/ +/* Peripheral Control methods ************************************************/ +/* Peripheral State methods **************************************************/ + + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __STM32L0xx_HAL_IRDA_EX_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_iwdg.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_iwdg.c new file mode 100644 index 0000000000..27dc0108b4 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_iwdg.c @@ -0,0 +1,407 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_iwdg.c + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief IWDG HAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the Independent Watchdog (IWDG) peripheral: + * + Initialization and de-initialization functions + * + IO operation functions + * + Peripheral State functions + * + @verbatim + ============================================================================== + ##### IWDG Generic features ##### + ============================================================================== + [..] + (+) The IWDG can be started by either software or hardware (configurable + through option byte). + + (+) The IWDG is clocked by its own dedicated Low-Speed clock (LSI) and + thus stays active even if the main clock fails. + Once the IWDG is started, the LSI is forced ON and cannot be disabled + (LSI cannot be disabled too), and the counter starts counting down from + the reset value of 0xFFF. When it reaches the end of count value (0x000) + a system reset is generated. + + (+) The IWDG counter should be refreshed at regular intervals, otherwise the + watchdog generates an MCU reset when the counter reaches 0. + + (+) The IWDG is implemented in the VDD voltage domain that is still functional + in STOP and STANDBY mode (IWDG reset can wake-up from STANDBY). + IWDGRST flag in RCC_CSR register can be used to inform when an IWDG + reset occurs. + + [..] Min-max timeout value @32KHz (LSI): ~0.512ms / ~32.0s + The IWDG timeout may vary due to LSI frequency dispersion. STM32L0xx + devices provide the capability to measure the LSI frequency (LSI clock + connected internally to TIM5 CH4 input capture). The measured value + can be used to have an IWDG timeout with an acceptable accuracy. + + + ##### How to use this driver ##### + ============================================================================== + [..] + (#) if Window option is disabled + (+) Use IWDG using HAL_IWDG_Init() function to : + (++) Enable write access to IWDG_PR, IWDG_RLR. + (++) Configure the IWDG prescaler, counter reload value. + This reload value will be loaded in the IWDG counter each time the counter + is reloaded, then the IWDG will start counting down from this value. + (+) Use IWDG using HAL_IWDG_Start() function to : + (++) Reload IWDG counter with value defined in the IWDG_RLR register. + (++) Start the IWDG, when the IWDG is used in software mode (no need + to enable the LSI, it will be enabled by hardware). + (+) Then the application program must refresh the IWDG counter at regular + intervals during normal operation to prevent an MCU reset, using + HAL_IWDG_Refresh() function. + (#) if Window option is enabled: + (+) Use IWDG using HAL_IWDG_Start() function to enable IWDG downcounter + (+) Use IWDG using HAL_IWDG_Init() function to : + (++) Enable write access to IWDG_PR, IWDG_RLR and IWDG_WINR registers. + (++) Configure the IWDG prescaler, reload value and window value. + (+) Then the application program must refresh the IWDG counter at regular + intervals during normal operation to prevent an MCU reset, using + HAL_IWDG_Refresh() function. + + *** IWDG HAL driver macros list *** + ==================================== + [..] + Below the list of most used macros in IWDG HAL driver. + + (+) __HAL_IWDG_START: Enable the IWDG peripheral + (+) __HAL_IWDG_RELOAD_COUNTER: Reloads IWDG counter with value defined in the reload register + (+) __HAL_IWDG_ENABLE_WRITE_ACCESS : Enable write access to IWDG_PR and IWDG_RLR registers + (+) __HAL_IWDG_DISABLE_WRITE_ACCESS : Disable write access to IWDG_PR and IWDG_RLR registers + (+) __HAL_IWDG_GET_FLAG: Get the selected IWDG's flag status + + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @defgroup IWDG + * @brief IWDG HAL module driver. + * @{ + */ + +#ifdef HAL_IWDG_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup IWDG_Private_Functions + * @{ + */ + +/** @defgroup IWDG_Group1 Initialization and de-initialization functions + * @brief Initialization and Configuration functions. + * +@verbatim + =============================================================================== + ##### Initialization and de-initialization functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Initialize the IWDG according to the specified parameters + in the IWDG_InitTypeDef and create the associated handle + (+) Manage Window option + (+) Initialize the IWDG MSP + +@endverbatim + * @{ + */ + +/** + * @brief Initializes the IWDG according to the specified + * parameters in the IWDG_InitTypeDef and creates the associated handle. + * @param hiwdg: pointer to a IWDG_HandleTypeDef structure that contains + * the configuration information for the specified IWDG module. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_IWDG_Init(IWDG_HandleTypeDef *hiwdg) +{ + uint32_t tickstart = 0; + + /* Check the IWDG handle allocation */ + if(hiwdg == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_IWDG_PRESCALER(hiwdg->Init.Prescaler)); + assert_param(IS_IWDG_RELOAD(hiwdg->Init.Reload)); + assert_param(IS_IWDG_WINDOW(hiwdg->Init.Window)); + + /* Check pending flag, if previous update not done, return error */ + if((__HAL_IWDG_GET_FLAG(hiwdg, IWDG_FLAG_PVU) != RESET) + &&(__HAL_IWDG_GET_FLAG(hiwdg, IWDG_FLAG_RVU) != RESET) + &&(__HAL_IWDG_GET_FLAG(hiwdg, IWDG_FLAG_WVU) != RESET)) + { + return HAL_ERROR; + } + + if(hiwdg->State == HAL_IWDG_STATE_RESET) + { + /* Init the low level hardware */ + HAL_IWDG_MspInit(hiwdg); + } + + /* Change IWDG peripheral state */ + hiwdg->State = HAL_IWDG_STATE_BUSY; + + /* Enable write access to IWDG_PR, IWDG_RLR and IWDG_WINR registers */ + /* by writing 0x5555 in KR */ + __HAL_IWDG_ENABLE_WRITE_ACCESS(hiwdg); + + /* Write to IWDG registers the IWDG_Prescaler & IWDG_Reload values to work with */ + MODIFY_REG(hiwdg->Instance->PR, (uint32_t)IWDG_PR_PR, hiwdg->Init.Prescaler); + MODIFY_REG(hiwdg->Instance->RLR, (uint32_t)IWDG_RLR_RL, hiwdg->Init.Reload); + + /* check if window option is enabled */ + if (((hiwdg->Init.Window) != IWDG_WINDOW_DISABLE) || ((hiwdg->Instance->WINR) != IWDG_WINDOW_DISABLE)) + { + tickstart = HAL_GetTick(); + + /* Wait for register to be updated */ + while((uint32_t)(hiwdg->Instance->SR) != RESET) + { + if((HAL_GetTick() - tickstart ) > 1000) + { + /* Set IWDG state */ + hiwdg->State = HAL_IWDG_STATE_TIMEOUT; + return HAL_TIMEOUT; + } + } + + /* Write to IWDG WINR the IWDG_Window value to compare with */ + MODIFY_REG(hiwdg->Instance->WINR, (uint32_t)IWDG_WINR_WIN, hiwdg->Init.Window); + + } + /* Change IWDG peripheral state */ + hiwdg->State = HAL_IWDG_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Initializes the IWDG MSP. + * @param hiwdg: pointer to a IWDG_HandleTypeDef structure that contains + * the configuration information for the specified IWDG module. + * @retval None + */ +__weak void HAL_IWDG_MspInit(IWDG_HandleTypeDef *hiwdg) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_IWDG_MspInit could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup IWDG_Group2 IO operation functions + * @brief IO operation functions + * +@verbatim + =============================================================================== + ##### IO operation functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Start the IWDG. + (+) Refresh the IWDG. + +@endverbatim + * @{ + */ + +/** + * @brief Starts the IWDG. + * @param hiwdg: pointer to a IWDG_HandleTypeDef structure that contains + * the configuration information for the specified IWDG module. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_IWDG_Start(IWDG_HandleTypeDef *hiwdg) +{ + uint32_t tickstart = 0; + + /* Process locked */ + __HAL_LOCK(hiwdg); + + /* Change IWDG peripheral state */ + hiwdg->State = HAL_IWDG_STATE_BUSY; + + /* Reload IWDG counter with value defined in the RLR register */ + if ((hiwdg->Init.Window) == IWDG_WINDOW_DISABLE) + { + __HAL_IWDG_RELOAD_COUNTER(hiwdg); + } + + /* Enable the IWDG peripheral */ + __HAL_IWDG_START(hiwdg); + + tickstart = HAL_GetTick(); + + /* Wait until PVU, RVU, WVU flag are RESET */ + while( (__HAL_IWDG_GET_FLAG(hiwdg, IWDG_FLAG_PVU) != RESET) + &&(__HAL_IWDG_GET_FLAG(hiwdg, IWDG_FLAG_RVU) != RESET) + &&(__HAL_IWDG_GET_FLAG(hiwdg, IWDG_FLAG_WVU) != RESET) ) + { + + if((HAL_GetTick() - tickstart ) > 1000) + { + /* Set IWDG state */ + hiwdg->State = HAL_IWDG_STATE_TIMEOUT; + + /* Process unlocked */ + __HAL_UNLOCK(hiwdg); + + return HAL_TIMEOUT; + } + } + + /* Change IWDG peripheral state */ + hiwdg->State = HAL_IWDG_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hiwdg); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Refreshes the IWDG. + * @param hiwdg: pointer to a IWDG_HandleTypeDef structure that contains + * the configuration information for the specified IWDG module. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_IWDG_Refresh(IWDG_HandleTypeDef *hiwdg) +{ + uint32_t tickstart = 0; + + /* Process Locked */ + __HAL_LOCK(hiwdg); + + /* Change IWDG peripheral state */ + hiwdg->State = HAL_IWDG_STATE_BUSY; + + tickstart = HAL_GetTick(); + + /* Wait until RVU flag is RESET */ + while(__HAL_IWDG_GET_FLAG(hiwdg, IWDG_FLAG_RVU) != RESET) + { + if((HAL_GetTick() - tickstart ) > 1000) + { + /* Set IWDG state */ + hiwdg->State = HAL_IWDG_STATE_TIMEOUT; + + /* Process unlocked */ + __HAL_UNLOCK(hiwdg); + + return HAL_TIMEOUT; + } + } + + /* Reload IWDG counter with value defined in the reload register */ + __HAL_IWDG_RELOAD_COUNTER(hiwdg); + + /* Change IWDG peripheral state */ + hiwdg->State = HAL_IWDG_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hiwdg); + + /* Return function status */ + return HAL_OK; +} + +/** + * @} + */ + +/** @defgroup IWDG_Group3 Peripheral State functions + * @brief Peripheral State functions. + * +@verbatim + =============================================================================== + ##### Peripheral State functions ##### + =============================================================================== + [..] + This subsection permits to get in run-time the status of the peripheral + and the data flow. + +@endverbatim + * @{ + */ + +/** + * @brief Returns the IWDG state. + * @param hiwdg: pointer to a IWDG_HandleTypeDef structure that contains + * the configuration information for the specified IWDG module. + * @retval HAL state + */ +HAL_IWDG_StateTypeDef HAL_IWDG_GetState(IWDG_HandleTypeDef *hiwdg) +{ + return hiwdg->State; +} + +/** + * @} + */ + +/** + * @} + */ + +#endif /* HAL_IWDG_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_iwdg.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_iwdg.h new file mode 100644 index 0000000000..10f5bd355d --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_iwdg.h @@ -0,0 +1,276 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_iwdg.h + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief Header file of IWDG HAL module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32L0xx_HAL_IWDG_H +#define __STM32L0xx_HAL_IWDG_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal_def.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @addtogroup IWDG + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ + +/** + * @brief IWDG HAL State Structure definition + */ +typedef enum +{ + HAL_IWDG_STATE_RESET = 0x00, /*!< IWDG not yet initialized or disabled */ + HAL_IWDG_STATE_READY = 0x01, /*!< IWDG initialized and ready for use */ + HAL_IWDG_STATE_BUSY = 0x02, /*!< IWDG internal process is ongoing */ + HAL_IWDG_STATE_TIMEOUT = 0x03, /*!< IWDG timeout state */ + HAL_IWDG_STATE_ERROR = 0x04 /*!< IWDG error state */ + +}HAL_IWDG_StateTypeDef; + +/** + * @brief IWDG Init structure definition + */ +typedef struct +{ + uint32_t Prescaler; /*!< Select the prescaler of the IWDG. + This parameter can be a value of @ref IWDG_Prescaler */ + + uint32_t Reload; /*!< Specifies the IWDG down-counter reload value. + This parameter must be a number between Min_Data = 0 and Max_Data = 0x0FFF */ + + uint32_t Window; /*!< Specifies the window value to be compared to the down-counter. + This parameter must be a number between Min_Data = 0 and Max_Data = 0x0FFF */ + +} IWDG_InitTypeDef; + +/** + * @brief IWDG handle Structure definition + */ +typedef struct +{ + IWDG_TypeDef *Instance; /*!< Register base address */ + + IWDG_InitTypeDef Init; /*!< IWDG required parameters */ + + HAL_LockTypeDef Lock; /*!< IWDG locking object */ + + __IO HAL_IWDG_StateTypeDef State; /*!< IWDG communication state */ + +}IWDG_HandleTypeDef; + +/* Exported constants --------------------------------------------------------*/ +/** @defgroup IWDG_Exported_Constants + * @{ + */ + +/** @defgroup IWDG_Registers_BitMask + * @brief IWDG registers bit mask + * @{ + */ +/* --- KR Register ---*/ +/* KR register bit mask */ +#define KR_KEY_RELOAD ((uint32_t)0xAAAA) /*!< IWDG reload counter enable */ +#define KR_KEY_ENABLE ((uint32_t)0xCCCC) /*!< IWDG peripheral enable */ +#define KR_KEY_EWA ((uint32_t)0x5555) /*!< IWDG KR write Access enable */ +#define KR_KEY_DWA ((uint32_t)0x0000) /*!< IWDG KR write Access disable */ + +/** + * @} + */ + +/** @defgroup IWDG_Flag_definition + * @{ + */ +#define IWDG_FLAG_PVU ((uint32_t)0x0001) /*!< Watchdog counter prescaler value update flag */ +#define IWDG_FLAG_RVU ((uint32_t)0x0002) /*!< Watchdog counter reload value update flag */ +#define IWDG_FLAG_WVU ((uint32_t)0x0004) /*!< Watchdog counter window value update Flag */ + +#define IS_IWDG_FLAG(FLAG) (((FLAG) == IWDG_FLAG_PVU) || \ + ((FLAG) == IWDG_FLAG_RVU) || \ + ((FLAG) == IWDG_FLAG_WVU)) + +/** + * @} + */ + +/** @defgroup IWDG_Prescaler + * @{ + */ +#define IWDG_PRESCALER_4 ((uint8_t)0x00) /*!< IWDG prescaler set to 4 */ +#define IWDG_PRESCALER_8 ((uint8_t)0x01) /*!< IWDG prescaler set to 8 */ +#define IWDG_PRESCALER_16 ((uint8_t)0x02) /*!< IWDG prescaler set to 16 */ +#define IWDG_PRESCALER_32 ((uint8_t)0x03) /*!< IWDG prescaler set to 32 */ +#define IWDG_PRESCALER_64 ((uint8_t)0x04) /*!< IWDG prescaler set to 64 */ +#define IWDG_PRESCALER_128 ((uint8_t)0x05) /*!< IWDG prescaler set to 128 */ +#define IWDG_PRESCALER_256 ((uint8_t)0x06) /*!< IWDG prescaler set to 256 */ + +#define IS_IWDG_PRESCALER(PRESCALER) (((PRESCALER) == IWDG_PRESCALER_4) || \ + ((PRESCALER) == IWDG_PRESCALER_8) || \ + ((PRESCALER) == IWDG_PRESCALER_16) || \ + ((PRESCALER) == IWDG_PRESCALER_32) || \ + ((PRESCALER) == IWDG_PRESCALER_64) || \ + ((PRESCALER) == IWDG_PRESCALER_128)|| \ + ((PRESCALER) == IWDG_PRESCALER_256)) + +/** + * @} + */ + +/** @defgroup IWDG_Reload_Value + * @{ + */ +#define IS_IWDG_RELOAD(RELOAD) ((RELOAD) <= 0xFFF) + +/** + * @} + */ + +/** @defgroup IWDG_CounterWindow_Value + * @{ + */ +#define IS_IWDG_WINDOW(VALUE) ((VALUE) <= 0xFFF) + +/** + * @} + */ + +/** @defgroup IWDG_Window option disable + * @{ + */ + +#define IWDG_WINDOW_DISABLE 0xFFF +/** + * @} + */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ +/** @defgroup IWDG_Exported_Macro + * @{ + */ + +/** @brief Reset IWDG handle state + * @param __HANDLE__: IWDG handle + * @retval None + */ +#define __HAL_IWDG_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_IWDG_STATE_RESET) + +/** + * @brief Enables the IWDG peripheral. + * @param __HANDLE__: IWDG handle + * @retval None + */ +#define __HAL_IWDG_START(__HANDLE__) ((__HANDLE__)->Instance->KR |= KR_KEY_ENABLE) + +/** + * @brief Reloads IWDG counter with value defined in the reload register + * (write access to IWDG_PR and IWDG_RLR registers disabled). + * @param __HANDLE__: IWDG handle + * @retval None + */ +#define __HAL_IWDG_RELOAD_COUNTER(__HANDLE__) (((__HANDLE__)->Instance->KR) |= KR_KEY_RELOAD) + +/** + * @brief Enables write access to IWDG_PR, IWDG_RLR and IWDG_WINR registers. + * @param __HANDLE__: IWDG handle + * @retval None + */ +#define __HAL_IWDG_ENABLE_WRITE_ACCESS(__HANDLE__) (((__HANDLE__)->Instance->KR) |= KR_KEY_EWA) + +/** + * @brief Disables write access to IWDG_PR, IWDG_RLR and IWDG_WINR registers. + * @param __HANDLE__: IWDG handle + * @retval None + */ +#define __HAL_IWDG_DISABLE_WRITE_ACCESS(__HANDLE__) (((__HANDLE__)->Instance->KR) |= KR_KEY_DWA) + +/** + * @brief Gets the selected IWDG's flag status. + * @param __HANDLE__: IWDG handle + * @param __FLAG__: specifies the flag to check. + * This parameter can be one of the following values: + * @arg IWDG_FLAG_PVU: Watchdog counter reload value update flag + * @arg IWDG_FLAG_RVU: Watchdog counter prescaler value flag + * @arg IWDG_FLAG_WVU: Watchdog counter window value flag + * @retval The new state of __FLAG__ (TRUE or FALSE) . + */ +#define __HAL_IWDG_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->SR & (__FLAG__)) == (__FLAG__)) + +/** + * @} + */ + + +/* Exported functions --------------------------------------------------------*/ + +/* Initialization/de-initialization functions ********************************/ +HAL_StatusTypeDef HAL_IWDG_Init(IWDG_HandleTypeDef *hiwdg); +void HAL_IWDG_MspInit(IWDG_HandleTypeDef *hiwdg); + +/* I/O operation functions ****************************************************/ +HAL_StatusTypeDef HAL_IWDG_Start(IWDG_HandleTypeDef *hiwdg); +HAL_StatusTypeDef HAL_IWDG_Refresh(IWDG_HandleTypeDef *hiwdg); + +/* Peripheral State functions ************************************************/ +HAL_IWDG_StateTypeDef HAL_IWDG_GetState(IWDG_HandleTypeDef *hiwdg); + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __STM32L0xx_HAL_IWDG_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_lcd.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_lcd.c new file mode 100644 index 0000000000..a4722477b2 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_lcd.c @@ -0,0 +1,576 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_lcd.c + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief LCD Controller HAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the LCD Controller (LCD) peripheral: + * + Initialization/de-initialization methods + * + I/O operation methods + * + Peripheral State methods + * + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] The LCD HAL driver can be used as follows: + + (#) Declare a LCD_HandleTypeDef handle structure. + + (#) Initialize the LCD low level resources by implement the HAL_LCD_MspInit() API: + (##) Enable the LCDCLK (same as RTCCLK): to configure the RTCCLK/LCDCLK, proceed as follows: + (+) Enable the Power Controller (PWR) APB1 interface clock using the + __PWR_CLK_ENABLE() macro. + (+) Enable access to RTC domain using the HAL_PWR_EnableBkUpAccess() function. + (+) Select the RTC clock source using the __HAL_RCC_RTC_CONFIG() function. + + (@) The frequency generator allows you to achieve various LCD frame rates + starting from an LCD input clock frequency (LCDCLK) which can vary + from 32 kHz up to 1 MHz. + (##) LCD pins configuration: + (+) Enable the clock for the LCD GPIOs. + (+) Configure these LCD pins as alternate function no-pull. + (##) Enable the LCD interface clock. + + (#) Program the Prescaler, Divider, Blink mode, Blink Frequency Duty, Bias, + Voltage Source, Dead Time, Pulse On Duration and Contrast in the hlcd Init structure. + + (#) Initialize the LCD registers by calling the HAL_LCD_Init() API. + + (@) The HAL_LCD_Init() API configures also the low level Hardware GPIO, CLOCK, ...etc) + by calling the custumed HAL_LCD_MspInit() API. + (@) After calling the HAL_LCD_Init() the LCD RAM memory is cleared + + (#) Optionally you can update the LCD configuration using these macros: + - LCD High Drive using the __HAL_LCD_HIGHDRIVER_ENABLE() and __HAL_LCD_HIGHDRIVER_DISABLE() macros + - LCD Pulse ON Duration using the __HAL_LCD_PULSEONDURATION_CONFIG() macro + - LCD Dead Time using the __HAL_LCD_DEADTIME_CONFIG() macro + - The LCD Blink mode and frequency using the __HAL_LCD_BLINK_CONFIG() macro + - The LCD Contrast using the __HAL_LCD_CONTRAST_CONFIG() macro + + (#) Write to the LCD RAM memory using the HAL_LCD_Write() API, this API can be called + more time to update the different LCD RAM registers before calling + HAL_LCD_UpdateDisplayRequest() API. + + (#) The HAL_LCD_Clear() API can be used to clear the LCD RAM memory. + + (#) When LCD RAM memory is updated enable the update display request using + the HAL_LCD_UpdateDisplayRequest() API. + + [..] LCD and low power modes: + (#) The LCD still active during STOP mode. + + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @defgroup LCD + * @brief LCD HAL module driver + * @{ + */ +#ifdef HAL_LCD_MODULE_ENABLED +#if !defined (STM32L051xx) && !defined (STM32L052xx) && !defined (STM32L062xx) && !defined (STM32L061xx) + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +#define LCD_TIMEOUT_VALUE 1000 +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ +/** @defgroup LCD_Private_Functions + * @{ + */ + +/** @defgroup HAL_LCD_Group1 Initialization/de-initialization methods + * @brief Initialization and Configuration functions + * +@verbatim +=============================================================================== + ##### Initialization and Configuration functions ##### + =============================================================================== + [..] + +@endverbatim + * @{ + */ + +/** + * @brief DeInitializes the LCD peripheral. + * @param hlcd: LCD handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LCD_DeInit(LCD_HandleTypeDef *hlcd) +{ + /* Check the LCD handle allocation */ + if(hlcd == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_LCD_ALL_INSTANCE(hlcd->Instance)); + + hlcd->State = HAL_LCD_STATE_BUSY; + + /* DeInit the low level hardware */ + HAL_LCD_MspDeInit(hlcd); + + hlcd->ErrorCode = HAL_LCD_ERROR_NONE; + hlcd->State = HAL_LCD_STATE_RESET; + + /* Release Lock */ + __HAL_UNLOCK(hlcd); + + return HAL_OK; +} + +/** + * @brief Initializes the LCD peripheral according to the specified parameters + * in the LCD_InitStruct. + * @note This function can be used only when the LCD is disabled. + * @param hlcd: LCD handle + * @retval None + */ +HAL_StatusTypeDef HAL_LCD_Init(LCD_HandleTypeDef *hlcd) +{ + uint32_t tickstart = 0x00; + uint8_t counter = 0; + + /* Check the LCD handle allocation */ + if(hlcd == NULL) + { + return HAL_ERROR; + } + + /* Check function parameters */ + assert_param(IS_LCD_ALL_INSTANCE(hlcd->Instance)); + assert_param(IS_LCD_PRESCALER(hlcd->Init.Prescaler)); + assert_param(IS_LCD_DIVIDER(hlcd->Init.Divider)); + assert_param(IS_LCD_DUTY(hlcd->Init.Duty)); + assert_param(IS_LCD_BIAS(hlcd->Init.Bias)); + assert_param(IS_LCD_VOLTAGE_SOURCE(hlcd->Init.VoltageSource)); + assert_param(IS_LCD_PULSE_ON_DURATION(hlcd->Init.PulseOnDuration)); + assert_param(IS_LCD_DEAD_TIME(hlcd->Init.DeadTime)); + assert_param(IS_LCD_CONTRAST(hlcd->Init.Contrast)); + assert_param(IS_LCD_BLINK_FREQUENCY(hlcd->Init.BlinkFrequency)); + assert_param(IS_LCD_BLINK_MODE(hlcd->Init.BlinkMode)); + + + if(hlcd->State == HAL_LCD_STATE_RESET) + { + /* Initialize the low level hardware (MSP) */ + HAL_LCD_MspInit(hlcd); + } + + hlcd->State = HAL_LCD_STATE_BUSY; + + /* Disable the peripheral */ + __HAL_LCD_DISABLE(hlcd); + + /* Clear the LCD_RAM registers and enable the display request by setting the UDR bit + in the LCD_SR register */ + for(counter = LCD_RAM_REGISTER0; counter <= LCD_RAM_REGISTER15; counter++) + { + hlcd->Instance->RAM[counter] = 0; + } + /* Enable the display request */ + hlcd->Instance->SR |= LCD_SR_UDR; + + /* Configure the LCD Prescaler, Divider, Blink mode and Blink Frequency: + Set PS[3:0] bits according to hlcd->Init.Prescaler value + Set DIV[3:0] bits according to hlcd->Init.Divider value + Set BLINK[1:0] bits according to hlcd->Init.BlinkMode value + Set BLINKF[2:0] bits according to hlcd->Init.BlinkFrequency value + Set DEAD[2:0] bits according to hlcd->Init.DeadTime value + Set PON[2:0] bits according to hlcd->Init.PulseOnDuration value + Set CC[2:0] bits according to hlcd->Init.Contrast value */ + hlcd->Instance->FCR = (uint32_t)(hlcd->Init.Prescaler | hlcd->Init.Divider | \ + hlcd->Init.BlinkMode | hlcd->Init.BlinkFrequency | \ + hlcd->Init.DeadTime | hlcd->Init.PulseOnDuration | \ + hlcd->Init.Contrast); + /* Wait until LCD Frame Control Register Synchronization flag (FCRSF) is set in the LCD_SR register + This bit is set by hardware each time the LCD_FCR register is updated in the LCDCLK + domain. It is cleared by hardware when writing to the LCD_FCR register.*/ + LCD_WaitForSynchro(hlcd); + + /* Configure the LCD Duty, Bias, Voltage Source, Dead Time, Pulse On Duration and Contrast: + Set DUTY[2:0] bits according to hlcd->Init.Duty value + Set BIAS[1:0] bits according to hlcd->Init.Bias value + Set VSEL bits according to hlcd->Init.VoltageSource value */ + hlcd->Instance->CR = (uint32_t)(hlcd->Init.Duty | hlcd->Init.Bias | \ + hlcd->Init.VoltageSource); + + /* Enable the peripheral */ + __HAL_LCD_ENABLE(hlcd); + + /* Get timeout */ + tickstart = HAL_GetTick(); + + /* Wait Until the LCD is enabled */ + while((hlcd->Instance->SR & LCD_FLAG_ENS) == (uint32_t)RESET) + { + if((HAL_GetTick() - tickstart ) > LCD_TIMEOUT_VALUE) + { + hlcd->ErrorCode = HAL_LCD_ERROR_ENS; + return HAL_TIMEOUT; + } + } + + /* Get timeout */ + tickstart = HAL_GetTick(); + + /*!< Wait Until the LCD Booster is ready */ + while((hlcd->Instance->SR & LCD_FLAG_RDY) == (uint32_t)RESET) + { + if((HAL_GetTick() - tickstart ) > LCD_TIMEOUT_VALUE) + { + hlcd->ErrorCode = HAL_LCD_ERROR_RDY; + return HAL_TIMEOUT; + } + } + + /* Initialize the LCD state */ + hlcd->ErrorCode = HAL_LCD_ERROR_NONE; + hlcd->State= HAL_LCD_STATE_READY; + + return HAL_OK; +} + +/** + * @brief LCD MSP DeInit. + * @param hlcd: LCD handle + * @retval None + */ + __weak void HAL_LCD_MspDeInit(LCD_HandleTypeDef *hlcd) +{ + /* NOTE: This function Should not be modified, when the callback is needed, + the HAL_LCD_MspDeInit could be implemented in the user file + */ +} + +/** + * @brief LCD MSP Init. + * @param hlcd: LCD handle + * @retval None + */ + __weak void HAL_LCD_MspInit(LCD_HandleTypeDef *hlcd) +{ + /* NOTE: This function Should not be modified, when the callback is needed, + the HAL_LCD_MspInit could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup HAL_LCD_Group2 IO operation methods + * @brief LCD RAM functions + * +@verbatim + =============================================================================== + ##### I/O operation methods ##### + =============================================================================== + [..] Using its double buffer memory the LCD controller ensures the coherency of the + displayed information without having to use interrupts to control LCD_RAM + modification. + The application software can access the first buffer level (LCD_RAM) through + the APB interface. Once it has modified the LCD_RAM using the HAL_LCD_Write() API, + it sets the UDR flag in the LCD_SR register using the HAL_LCD_UpdateDisplayRequest() API. + This UDR flag (update display request) requests the updated information to be + moved into the second buffer level (LCD_DISPLAY). + This operation is done synchronously with the frame (at the beginning of the + next frame), until the update is completed, the LCD_RAM is write protected and + the UDR flag stays high. + Once the update is completed another flag (UDD - Update Display Done) is set and + generates an interrupt if the UDDIE bit in the LCD_FCR register is set. + The time it takes to update LCD_DISPLAY is, in the worst case, one odd and one + even frame. + The update will not occur (UDR = 1 and UDD = 0) until the display is + enabled (LCDEN = 1). + +@endverbatim + * @{ + */ + +/** + * @brief Writes a word in the specific LCD RAM. + * @param hlcd: LCD handle + * @param RAMRegisterIndex: specifies the LCD RAM Register. + * This parameter can be one of the following values: + * @arg LCD_RAM_REGISTER0: LCD RAM Register 0 + * @arg LCD_RAM_REGISTER1: LCD RAM Register 1 + * @arg LCD_RAM_REGISTER2: LCD RAM Register 2 + * @arg LCD_RAM_REGISTER3: LCD RAM Register 3 + * @arg LCD_RAM_REGISTER4: LCD RAM Register 4 + * @arg LCD_RAM_REGISTER5: LCD RAM Register 5 + * @arg LCD_RAM_REGISTER6: LCD RAM Register 6 + * @arg LCD_RAM_REGISTER7: LCD RAM Register 7 + * @arg LCD_RAM_REGISTER8: LCD RAM Register 8 + * @arg LCD_RAM_REGISTER9: LCD RAM Register 9 + * @arg LCD_RAM_REGISTER10: LCD RAM Register 10 + * @arg LCD_RAM_REGISTER11: LCD RAM Register 11 + * @arg LCD_RAM_REGISTER12: LCD RAM Register 12 + * @arg LCD_RAM_REGISTER13: LCD RAM Register 13 + * @arg LCD_RAM_REGISTER14: LCD RAM Register 14 + * @arg LCD_RAM_REGISTER15: LCD RAM Register 15 + * @param RAMRegisterMask: specifies the LCD RAM Register Data Mask. + * @param Data: specifies LCD Data Value to be written. + * @retval None + */ +HAL_StatusTypeDef HAL_LCD_Write(LCD_HandleTypeDef *hlcd, uint32_t RAMRegisterIndex, uint32_t RAMRegisterMask, uint32_t Data) +{ + uint32_t tickstart = 0x00; + + if((hlcd->State == HAL_LCD_STATE_READY) || (hlcd->State == HAL_LCD_STATE_BUSY)) + { + /* Check the parameters */ + assert_param(IS_LCD_RAM_REGISTER(RAMRegisterIndex)); + + if(hlcd->State == HAL_LCD_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hlcd); + hlcd->State = HAL_LCD_STATE_BUSY; + + /* Get timeout */ + tickstart = HAL_GetTick(); + + /*!< Wait Until the LCD is ready */ + while((hlcd->Instance->SR & LCD_FLAG_UDR) != (uint32_t)RESET) + { + if((int32_t) (HAL_GetTick() - tickstart) > LCD_TIMEOUT_VALUE) + { + hlcd->ErrorCode = HAL_LCD_ERROR_UDR; + return HAL_TIMEOUT; + } + } + } + + /* Clear the data bytes position into LCD RAM register */ + hlcd->Instance->RAM[RAMRegisterIndex] &= (uint32_t)RAMRegisterMask; + + /* Copy the new Data bytes to LCD RAM register */ + hlcd->Instance->RAM[RAMRegisterIndex] |= (uint32_t)Data; + + return HAL_OK; + } + else + { + return HAL_ERROR; + } +} + +/** + * @brief Clears the LCD RAM registers. + * @param hlcd: LCD handle + * @retval None + */ +HAL_StatusTypeDef HAL_LCD_Clear(LCD_HandleTypeDef *hlcd) +{ + uint32_t tickstart = 0x00; + uint32_t counter = 0; + + if((hlcd->State == HAL_LCD_STATE_READY) || (hlcd->State == HAL_LCD_STATE_BUSY)) + { + /* Process Locked */ + __HAL_LOCK(hlcd); + + hlcd->State = HAL_LCD_STATE_BUSY; + + /* Get timeout */ + tickstart = HAL_GetTick(); + + /*!< Wait Until the LCD is ready */ + while((hlcd->Instance->SR & LCD_FLAG_UDR) != (uint32_t)RESET) + { + if((int32_t) (HAL_GetTick() - tickstart) > LCD_TIMEOUT_VALUE) + { + hlcd->ErrorCode = HAL_LCD_ERROR_UDR; + return HAL_TIMEOUT; + } + } + /* Clear the LCD_RAM registers */ + for(counter = LCD_RAM_REGISTER0; counter <= LCD_RAM_REGISTER15; counter++) + { + hlcd->Instance->RAM[counter] = 0; + } + + /* Update the LCD display */ + HAL_LCD_UpdateDisplayRequest(hlcd); + + return HAL_OK; + } + else + { + return HAL_ERROR; + } +} + +/** + * @brief Enables the Update Display Request. + * @param hlcd: LCD handle + * @note Each time software modifies the LCD_RAM it must set the UDR bit to + * transfer the updated data to the second level buffer. + * The UDR bit stays set until the end of the update and during this + * time the LCD_RAM is write protected. + * @note When the display is disabled, the update is performed for all + * LCD_DISPLAY locations. + * When the display is enabled, the update is performed only for locations + * for which commons are active (depending on DUTY). For example if + * DUTY = 1/2, only the LCD_DISPLAY of COM0 and COM1 will be updated. + * @retval None + */ +HAL_StatusTypeDef HAL_LCD_UpdateDisplayRequest(LCD_HandleTypeDef *hlcd) +{ + uint32_t tickstart = 0x00; + + /* Clear the Update Display Done flag before starting the update display request */ + __HAL_LCD_CLEAR_FLAG(hlcd, LCD_FLAG_UDD); + + /* Enable the display request */ + hlcd->Instance->SR |= LCD_SR_UDR; + + /* Get timeout */ + tickstart = HAL_GetTick(); + + /*!< Wait Until the LCD display is done */ + while((hlcd->Instance->SR & LCD_FLAG_UDD) == (uint32_t)RESET) + { + if((int32_t) (HAL_GetTick() - tickstart) > LCD_TIMEOUT_VALUE) + { + hlcd->ErrorCode = HAL_LCD_ERROR_UDD; + return HAL_TIMEOUT; + } + } + + hlcd->State = HAL_LCD_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hlcd); + + return HAL_OK; +} + +/** + * @} + */ + +/** @defgroup HAL_LCD_Group3 Peripheral State methods + * @brief LCD State functions + * +@verbatim + =============================================================================== + ##### Peripheral State methods ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to control the LCD: + (+) HAL_LCD_GetState() API can be helpful to check in run-time the state of the LCD peripheral State. + (+) HAL_LCD_GetError() API to return the LCD error code. +@endverbatim + * @{ + */ + +/** + * @brief Returns the LCD state. + * @param hlcd: LCD handle + * @retval HAL state + */ +HAL_LCD_StateTypeDef HAL_LCD_GetState(LCD_HandleTypeDef *hlcd) +{ + return hlcd->State; +} + +/** + * @brief Return the LCD error code + * @param hlcd: LCD handle + * @retval LCD Error Code + */ +uint32_t HAL_LCD_GetError(LCD_HandleTypeDef *hlcd) +{ + return hlcd->ErrorCode; +} + +/** + * @} + */ + +/** + * @brief Waits until the LCD FCR register is synchronized in the LCDCLK domain. + * This function must be called after any write operation to LCD_FCR register. + * @param None + * @retval None + */ +HAL_StatusTypeDef LCD_WaitForSynchro(LCD_HandleTypeDef *hlcd) +{ + uint32_t tickstart = 0x00; + + /* Get timeout */ + tickstart = HAL_GetTick(); + + /* Loop until FCRSF flag is set */ + while((hlcd->Instance->SR & LCD_FLAG_FCRSF) == (uint32_t)RESET) + { + if((int32_t) (HAL_GetTick() - tickstart) > LCD_TIMEOUT_VALUE) + { + hlcd->ErrorCode = HAL_LCD_ERROR_FCRSF; + return HAL_TIMEOUT; + } + } + + return HAL_OK; +} + +/** + * @} + */ +#endif /* STM32L051xx && STM32L052xx && STM32L062xx && STM32L061xx*/ +#endif /* HAL_LCD_MODULE_ENABLED */ + +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ + diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_lcd.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_lcd.h new file mode 100644 index 0000000000..396269f141 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_lcd.h @@ -0,0 +1,699 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_lcd.h + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief Header file of LCD Controller HAL module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32L0xx_HAL_LCD_H +#define __STM32L0xx_HAL_LCD_H + +#ifdef __cplusplus + extern "C" { +#endif + +#if !defined (STM32L051xx) && !defined (STM32L052xx) && !defined (STM32L062xx) && !defined (STM32L061xx) + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal_def.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @addtogroup LCD + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ + +/** + * @brief LCD Init structure definition + */ + +typedef struct +{ + uint32_t Prescaler; /*!< Configures the LCD Prescaler. + This parameter can be one value of @ref LCD_Prescaler */ + uint32_t Divider; /*!< Configures the LCD Divider. + This parameter can be one value of @ref LCD_Divider */ + uint32_t Duty; /*!< Configures the LCD Duty. + This parameter can be one value of @ref LCD_Duty */ + uint32_t Bias; /*!< Configures the LCD Bias. + This parameter can be one value of @ref LCD_Bias */ + uint32_t VoltageSource; /*!< Selects the LCD Voltage source. + This parameter can be one value of @ref LCD_Voltage_Source */ + uint32_t Contrast; /*!< Configures the LCD Contrast. + This parameter can be one value of @ref LCD_Contrast */ + uint32_t DeadTime; /*!< Configures the LCD Dead Time. + This parameter can be one value of @ref LCD_DeadTime */ + uint32_t PulseOnDuration; /*!< Configures the LCD Pulse On Duration. + This parameter can be one value of @ref LCD_PulseOnDuration */ + uint32_t HighDrive; /*!< Enable or disable the low resistance divider. + This parameter can be set to ENABLE or DISABLE. */ + uint32_t BlinkMode; /*!< Configures the LCD Blink Mode. + This parameter can be one value of @ref LCD_BlinkMode */ + uint32_t BlinkFrequency; /*!< Configures the LCD Blink frequency. + This parameter can be one value of @ref LCD_BlinkFrequency */ +}LCD_InitTypeDef; + +/** + * @brief HAL LCD State structures definition + */ +typedef enum +{ + HAL_LCD_STATE_RESET = 0x00, /*!< Peripheral is not yet Initialized */ + HAL_LCD_STATE_READY = 0x01, /*!< Peripheral Initialized and ready for use */ + HAL_LCD_STATE_BUSY = 0x02, /*!< an internal process is ongoing */ + HAL_LCD_STATE_TIMEOUT = 0x03, /*!< Timeout state */ + HAL_LCD_STATE_ERROR = 0x04 /*!< Error */ +}HAL_LCD_StateTypeDef; + +/** + * @brief HAL LCD Error Code structure definition + */ +typedef enum +{ + HAL_LCD_ERROR_NONE = 0x00, /*!< No error */ + HAL_LCD_ERROR_FCRSF = 0x01, /*!< Synchro flag timeout error */ + HAL_LCD_ERROR_UDR = 0x02, /*!< Update display request flag timeout error */ + HAL_LCD_ERROR_UDD = 0x04, /*!< Update display done flag timeout error */ + HAL_LCD_ERROR_ENS = 0x08, /*!< LCD enabled status flag timeout error */ + HAL_LCD_ERROR_RDY = 0x10 /*!< LCD Booster ready timeout error */ +}HAL_LCD_ErrorTypeDef; + +/** + * @brief UART handle Structure definition + */ +typedef struct +{ + LCD_TypeDef *Instance; /* LCD registers base address */ + + LCD_InitTypeDef Init; /* LCD communication parameters */ + + HAL_LockTypeDef Lock; /* Locking object */ + + __IO HAL_LCD_StateTypeDef State; /* LCD communication state */ + + __IO HAL_LCD_ErrorTypeDef ErrorCode; /* LCD Error code */ + +}LCD_HandleTypeDef; + +/* Exported constants --------------------------------------------------------*/ + +/** @defgroup LCD_Exported_Constants + * @{ + */ + +#define IS_LCD_ALL_INSTANCE(INSTANCE) ((INSTANCE) == LCD) + +/** @defgroup LCD_Prescaler + * @{ + */ + +#define LCD_PRESCALER_1 ((uint32_t)0x00000000) /*!< CLKPS = LCDCLK */ +#define LCD_PRESCALER_2 ((uint32_t)0x00400000) /*!< CLKPS = LCDCLK/2 */ +#define LCD_PRESCALER_4 ((uint32_t)0x00800000) /*!< CLKPS = LCDCLK/4 */ +#define LCD_PRESCALER_8 ((uint32_t)0x00C00000) /*!< CLKPS = LCDCLK/8 */ +#define LCD_PRESCALER_16 ((uint32_t)0x01000000) /*!< CLKPS = LCDCLK/16 */ +#define LCD_PRESCALER_32 ((uint32_t)0x01400000) /*!< CLKPS = LCDCLK/32 */ +#define LCD_PRESCALER_64 ((uint32_t)0x01800000) /*!< CLKPS = LCDCLK/64 */ +#define LCD_PRESCALER_128 ((uint32_t)0x01C00000) /*!< CLKPS = LCDCLK/128 */ +#define LCD_PRESCALER_256 ((uint32_t)0x02000000) /*!< CLKPS = LCDCLK/256 */ +#define LCD_PRESCALER_512 ((uint32_t)0x02400000) /*!< CLKPS = LCDCLK/512 */ +#define LCD_PRESCALER_1024 ((uint32_t)0x02800000) /*!< CLKPS = LCDCLK/1024 */ +#define LCD_PRESCALER_2048 ((uint32_t)0x02C00000) /*!< CLKPS = LCDCLK/2048 */ +#define LCD_PRESCALER_4096 ((uint32_t)0x03000000) /*!< CLKPS = LCDCLK/4096 */ +#define LCD_PRESCALER_8192 ((uint32_t)0x03400000) /*!< CLKPS = LCDCLK/8192 */ +#define LCD_PRESCALER_16384 ((uint32_t)0x03800000) /*!< CLKPS = LCDCLK/16384 */ +#define LCD_PRESCALER_32768 ((uint32_t)0x03C00000) /*!< CLKPS = LCDCLK/32768 */ + +#define IS_LCD_PRESCALER(PRESCALER) (((PRESCALER) == LCD_PRESCALER_1) || \ + ((PRESCALER) == LCD_PRESCALER_2) || \ + ((PRESCALER) == LCD_PRESCALER_4) || \ + ((PRESCALER) == LCD_PRESCALER_8) || \ + ((PRESCALER) == LCD_PRESCALER_16) || \ + ((PRESCALER) == LCD_PRESCALER_32) || \ + ((PRESCALER) == LCD_PRESCALER_64) || \ + ((PRESCALER) == LCD_PRESCALER_128) || \ + ((PRESCALER) == LCD_PRESCALER_256) || \ + ((PRESCALER) == LCD_PRESCALER_512) || \ + ((PRESCALER) == LCD_PRESCALER_1024) || \ + ((PRESCALER) == LCD_PRESCALER_2048) || \ + ((PRESCALER) == LCD_PRESCALER_4096) || \ + ((PRESCALER) == LCD_PRESCALER_8192) || \ + ((PRESCALER) == LCD_PRESCALER_16384) || \ + ((PRESCALER) == LCD_PRESCALER_32768)) + +/** + * @} + */ + +/** @defgroup LCD_Divider + * @{ + */ + +#define LCD_DIVIDER_16 ((uint32_t)0x00000000) /*!< LCD frequency = CLKPS/16 */ +#define LCD_DIVIDER_17 ((uint32_t)0x00040000) /*!< LCD frequency = CLKPS/17 */ +#define LCD_DIVIDER_18 ((uint32_t)0x00080000) /*!< LCD frequency = CLKPS/18 */ +#define LCD_DIVIDER_19 ((uint32_t)0x000C0000) /*!< LCD frequency = CLKPS/19 */ +#define LCD_DIVIDER_20 ((uint32_t)0x00100000) /*!< LCD frequency = CLKPS/20 */ +#define LCD_DIVIDER_21 ((uint32_t)0x00140000) /*!< LCD frequency = CLKPS/21 */ +#define LCD_DIVIDER_22 ((uint32_t)0x00180000) /*!< LCD frequency = CLKPS/22 */ +#define LCD_DIVIDER_23 ((uint32_t)0x001C0000) /*!< LCD frequency = CLKPS/23 */ +#define LCD_DIVIDER_24 ((uint32_t)0x00200000) /*!< LCD frequency = CLKPS/24 */ +#define LCD_DIVIDER_25 ((uint32_t)0x00240000) /*!< LCD frequency = CLKPS/25 */ +#define LCD_DIVIDER_26 ((uint32_t)0x00280000) /*!< LCD frequency = CLKPS/26 */ +#define LCD_DIVIDER_27 ((uint32_t)0x002C0000) /*!< LCD frequency = CLKPS/27 */ +#define LCD_DIVIDER_28 ((uint32_t)0x00300000) /*!< LCD frequency = CLKPS/28 */ +#define LCD_DIVIDER_29 ((uint32_t)0x00340000) /*!< LCD frequency = CLKPS/29 */ +#define LCD_DIVIDER_30 ((uint32_t)0x00380000) /*!< LCD frequency = CLKPS/30 */ +#define LCD_DIVIDER_31 ((uint32_t)0x003C0000) /*!< LCD frequency = CLKPS/31 */ + +#define IS_LCD_DIVIDER(DIVIDER) (((DIVIDER) == LCD_DIVIDER_16) || \ + ((DIVIDER) == LCD_DIVIDER_17) || \ + ((DIVIDER) == LCD_DIVIDER_18) || \ + ((DIVIDER) == LCD_DIVIDER_19) || \ + ((DIVIDER) == LCD_DIVIDER_20) || \ + ((DIVIDER) == LCD_DIVIDER_21) || \ + ((DIVIDER) == LCD_DIVIDER_22) || \ + ((DIVIDER) == LCD_DIVIDER_23) || \ + ((DIVIDER) == LCD_DIVIDER_24) || \ + ((DIVIDER) == LCD_DIVIDER_25) || \ + ((DIVIDER) == LCD_DIVIDER_26) || \ + ((DIVIDER) == LCD_DIVIDER_27) || \ + ((DIVIDER) == LCD_DIVIDER_28) || \ + ((DIVIDER) == LCD_DIVIDER_29) || \ + ((DIVIDER) == LCD_DIVIDER_30) || \ + ((DIVIDER) == LCD_DIVIDER_31)) + +/** + * @} + */ + + +/** @defgroup LCD_Duty + * @{ + */ + +#define LCD_DUTY_STATIC ((uint32_t)0x00000000) /*!< Static duty */ +#define LCD_DUTY_1_2 ((uint32_t)0x00000004) /*!< 1/2 duty */ +#define LCD_DUTY_1_3 ((uint32_t)0x00000008) /*!< 1/3 duty */ +#define LCD_DUTY_1_4 ((uint32_t)0x0000000C) /*!< 1/4 duty */ +#define LCD_DUTY_1_8 ((uint32_t)0x00000010) /*!< 1/4 duty */ + +#define IS_LCD_DUTY(DUTY) (((DUTY) == LCD_DUTY_STATIC) || \ + ((DUTY) == LCD_DUTY_1_2) || \ + ((DUTY) == LCD_DUTY_1_3) || \ + ((DUTY) == LCD_DUTY_1_4) || \ + ((DUTY) == LCD_DUTY_1_8)) + +/** + * @} + */ + + +/** @defgroup LCD_Bias + * @{ + */ + +#define LCD_BIAS_1_4 ((uint32_t)0x00000000) /*!< 1/4 Bias */ +#define LCD_BIAS_1_2 LCD_CR_BIAS_0 /*!< 1/2 Bias */ +#define LCD_BIAS_1_3 LCD_CR_BIAS_1 /*!< 1/3 Bias */ + +#define IS_LCD_BIAS(BIAS) (((BIAS) == LCD_BIAS_1_4) || \ + ((BIAS) == LCD_BIAS_1_2) || \ + ((BIAS) == LCD_BIAS_1_3)) +/** + * @} + */ + +/** @defgroup LCD_Voltage_Source + * @{ + */ + +#define LCD_VOLTAGESOURCE_INTERNAL ((uint32_t)0x00000000) /*!< Internal voltage source for the LCD */ +#define LCD_VOLTAGESOURCE_EXTERNAL LCD_CR_VSEL /*!< External voltage source for the LCD */ + +#define IS_LCD_VOLTAGE_SOURCE(SOURCE) (((SOURCE) == LCD_VOLTAGESOURCE_INTERNAL) || \ + ((SOURCE) == LCD_VOLTAGESOURCE_EXTERNAL)) + +/** + * @} + */ + +/** @defgroup LCD_Interrupts + * @{ + */ +#define LCD_IT_SOF LCD_FCR_SOFIE +#define LCD_IT_UDD LCD_FCR_UDDIE + +#define IS_LCD_IT(IT) ((((IT) & (uint32_t)0xFFFFFFF5) == 0x00) && ((IT) != 0x00)) + +#define IS_LCD_GET_IT(IT) (((IT) == LCD_IT_SOF) || ((IT) == LCD_IT_UDD)) + +/** + * @} + */ + +/** @defgroup LCD_PulseOnDuration + * @{ + */ + +#define LCD_PULSEONDURATION_0 ((uint32_t)0x00000000) /*!< Pulse ON duration = 0 pulse */ +#define LCD_PULSEONDURATION_1 ((uint32_t)0x00000010) /*!< Pulse ON duration = 1/CK_PS */ +#define LCD_PULSEONDURATION_2 ((uint32_t)0x00000020) /*!< Pulse ON duration = 2/CK_PS */ +#define LCD_PULSEONDURATION_3 ((uint32_t)0x00000030) /*!< Pulse ON duration = 3/CK_PS */ +#define LCD_PULSEONDURATION_4 ((uint32_t)0x00000040) /*!< Pulse ON duration = 4/CK_PS */ +#define LCD_PULSEONDURATION_5 ((uint32_t)0x00000050) /*!< Pulse ON duration = 5/CK_PS */ +#define LCD_PULSEONDURATION_6 ((uint32_t)0x00000060) /*!< Pulse ON duration = 6/CK_PS */ +#define LCD_PULSEONDURATION_7 ((uint32_t)0x00000070) /*!< Pulse ON duration = 7/CK_PS */ + +#define IS_LCD_PULSE_ON_DURATION(DURATION) (((DURATION) == LCD_PULSEONDURATION_0) || \ + ((DURATION) == LCD_PULSEONDURATION_1) || \ + ((DURATION) == LCD_PULSEONDURATION_2) || \ + ((DURATION) == LCD_PULSEONDURATION_3) || \ + ((DURATION) == LCD_PULSEONDURATION_4) || \ + ((DURATION) == LCD_PULSEONDURATION_5) || \ + ((DURATION) == LCD_PULSEONDURATION_6) || \ + ((DURATION) == LCD_PULSEONDURATION_7)) +/** + * @} + */ + + +/** @defgroup LCD_DeadTime + * @{ + */ + +#define LCD_DEADTIME_0 ((uint32_t)0x00000000) /*!< No dead Time */ +#define LCD_DEADTIME_1 ((uint32_t)0x00000080) /*!< One Phase between different couple of Frame */ +#define LCD_DEADTIME_2 ((uint32_t)0x00000100) /*!< Two Phase between different couple of Frame */ +#define LCD_DEADTIME_3 ((uint32_t)0x00000180) /*!< Three Phase between different couple of Frame */ +#define LCD_DEADTIME_4 ((uint32_t)0x00000200) /*!< Four Phase between different couple of Frame */ +#define LCD_DEADTIME_5 ((uint32_t)0x00000280) /*!< Five Phase between different couple of Frame */ +#define LCD_DEADTIME_6 ((uint32_t)0x00000300) /*!< Six Phase between different couple of Frame */ +#define LCD_DEADTIME_7 ((uint32_t)0x00000380) /*!< Seven Phase between different couple of Frame */ + +#define IS_LCD_DEAD_TIME(TIME) (((TIME) == LCD_DEADTIME_0) || \ + ((TIME) == LCD_DEADTIME_1) || \ + ((TIME) == LCD_DEADTIME_2) || \ + ((TIME) == LCD_DEADTIME_3) || \ + ((TIME) == LCD_DEADTIME_4) || \ + ((TIME) == LCD_DEADTIME_5) || \ + ((TIME) == LCD_DEADTIME_6) || \ + ((TIME) == LCD_DEADTIME_7)) +/** + * @} + */ + +/** @defgroup LCD_BlinkMode + * @{ + */ + +#define LCD_BLINKMODE_OFF ((uint32_t)0x00000000) /*!< Blink disabled */ +#define LCD_BLINKMODE_SEG0_COM0 ((uint32_t)0x00010000) /*!< Blink enabled on SEG[0], COM[0] (1 pixel) */ +#define LCD_BLINKMODE_SEG0_ALLCOM ((uint32_t)0x00020000) /*!< Blink enabled on SEG[0], all COM (up to + 8 pixels according to the programmed duty) */ +#define LCD_BLINKMODE_ALLSEG_ALLCOM ((uint32_t)0x00030000) /*!< Blink enabled on all SEG and all COM (all pixels) */ + +#define IS_LCD_BLINK_MODE(MODE) (((MODE) == LCD_BLINKMODE_OFF) || \ + ((MODE) == LCD_BLINKMODE_SEG0_COM0) || \ + ((MODE) == LCD_BLINKMODE_SEG0_ALLCOM) || \ + ((MODE) == LCD_BLINKMODE_ALLSEG_ALLCOM)) +/** + * @} + */ + +/** @defgroup LCD_BlinkFrequency + * @{ + */ + +#define LCD_BLINKFREQUENCY_DIV8 ((uint32_t)0x00000000) /*!< The Blink frequency = fLCD/8 */ +#define LCD_BLINKFREQUENCY_DIV16 ((uint32_t)0x00002000) /*!< The Blink frequency = fLCD/16 */ +#define LCD_BLINKFREQUENCY_DIV32 ((uint32_t)0x00004000) /*!< The Blink frequency = fLCD/32 */ +#define LCD_BLINKFREQUENCY_DIV64 ((uint32_t)0x00006000) /*!< The Blink frequency = fLCD/64 */ +#define LCD_BLINKFREQUENCY_DIV128 ((uint32_t)0x00008000) /*!< The Blink frequency = fLCD/128 */ +#define LCD_BLINKFREQUENCY_DIV256 ((uint32_t)0x0000A000) /*!< The Blink frequency = fLCD/256 */ +#define LCD_BLINKFREQUENCY_DIV512 ((uint32_t)0x0000C000) /*!< The Blink frequency = fLCD/512 */ +#define LCD_BLINKFREQUENCY_DIV1024 ((uint32_t)0x0000E000) /*!< The Blink frequency = fLCD/1024 */ + +#define IS_LCD_BLINK_FREQUENCY(FREQUENCY) (((FREQUENCY) == LCD_BLINKFREQUENCY_DIV8) || \ + ((FREQUENCY) == LCD_BLINKFREQUENCY_DIV16) || \ + ((FREQUENCY) == LCD_BLINKFREQUENCY_DIV32) || \ + ((FREQUENCY) == LCD_BLINKFREQUENCY_DIV64) || \ + ((FREQUENCY) == LCD_BLINKFREQUENCY_DIV128) || \ + ((FREQUENCY) == LCD_BLINKFREQUENCY_DIV256) || \ + ((FREQUENCY) == LCD_BLINKFREQUENCY_DIV512) || \ + ((FREQUENCY) == LCD_BLINKFREQUENCY_DIV1024)) +/** + * @} + */ + +/** @defgroup LCD_Contrast + * @{ + */ + +#define LCD_CONTRASTLEVEL_0 ((uint32_t)0x00000000) /*!< Maximum Voltage = 2.60V */ +#define LCD_CONTRASTLEVEL_1 ((uint32_t)0x00000400) /*!< Maximum Voltage = 2.73V */ +#define LCD_CONTRASTLEVEL_2 ((uint32_t)0x00000800) /*!< Maximum Voltage = 2.86V */ +#define LCD_CONTRASTLEVEL_3 ((uint32_t)0x00000C00) /*!< Maximum Voltage = 2.99V */ +#define LCD_CONTRASTLEVEL_4 ((uint32_t)0x00001000) /*!< Maximum Voltage = 3.12V */ +#define LCD_CONTRASTLEVEL_5 ((uint32_t)0x00001400) /*!< Maximum Voltage = 3.25V */ +#define LCD_CONTRASTLEVEL_6 ((uint32_t)0x00001800) /*!< Maximum Voltage = 3.38V */ +#define LCD_CONTRASTLEVEL_7 ((uint32_t)0x00001C00) /*!< Maximum Voltage = 3.51V */ + +#define IS_LCD_CONTRAST(CONTRAST) (((CONTRAST) == LCD_CONTRASTLEVEL_0) || \ + ((CONTRAST) == LCD_CONTRASTLEVEL_1) || \ + ((CONTRAST) == LCD_CONTRASTLEVEL_2) || \ + ((CONTRAST) == LCD_CONTRASTLEVEL_3) || \ + ((CONTRAST) == LCD_CONTRASTLEVEL_4) || \ + ((CONTRAST) == LCD_CONTRASTLEVEL_5) || \ + ((CONTRAST) == LCD_CONTRASTLEVEL_6) || \ + ((CONTRAST) == LCD_CONTRASTLEVEL_7)) +/** + * @} + */ + +/** @defgroup LCD_Flag + * @{ + */ + +#define LCD_FLAG_ENS LCD_SR_ENS +#define LCD_FLAG_SOF LCD_SR_SOF +#define LCD_FLAG_UDR LCD_SR_UDR +#define LCD_FLAG_UDD LCD_SR_UDD +#define LCD_FLAG_RDY LCD_SR_RDY +#define LCD_FLAG_FCRSF LCD_SR_FCRSR + +#define IS_LCD_GET_FLAG(FLAG) (((FLAG) == LCD_FLAG_ENS) || ((FLAG) == LCD_FLAG_SOF) || \ + ((FLAG) == LCD_FLAG_UDR) || ((FLAG) == LCD_FLAG_UDD) || \ + ((FLAG) == LCD_FLAG_RDY) || ((FLAG) == LCD_FLAG_FCRSF)) + +#define IS_LCD_CLEAR_FLAG(FLAG) ((((FLAG) & (uint32_t)0xFFFFFFF5) == 0x00) && ((FLAG) != 0x00)) +/** + * @} + */ + +/** @defgroup LCD_RAMRegister + * @{ + */ + +#define LCD_RAM_REGISTER0 ((uint32_t)0x00000000) /*!< LCD RAM Register 0 */ +#define LCD_RAM_REGISTER1 ((uint32_t)0x00000001) /*!< LCD RAM Register 1 */ +#define LCD_RAM_REGISTER2 ((uint32_t)0x00000002) /*!< LCD RAM Register 2 */ +#define LCD_RAM_REGISTER3 ((uint32_t)0x00000003) /*!< LCD RAM Register 3 */ +#define LCD_RAM_REGISTER4 ((uint32_t)0x00000004) /*!< LCD RAM Register 4 */ +#define LCD_RAM_REGISTER5 ((uint32_t)0x00000005) /*!< LCD RAM Register 5 */ +#define LCD_RAM_REGISTER6 ((uint32_t)0x00000006) /*!< LCD RAM Register 6 */ +#define LCD_RAM_REGISTER7 ((uint32_t)0x00000007) /*!< LCD RAM Register 7 */ +#define LCD_RAM_REGISTER8 ((uint32_t)0x00000008) /*!< LCD RAM Register 8 */ +#define LCD_RAM_REGISTER9 ((uint32_t)0x00000009) /*!< LCD RAM Register 9 */ +#define LCD_RAM_REGISTER10 ((uint32_t)0x0000000A) /*!< LCD RAM Register 10 */ +#define LCD_RAM_REGISTER11 ((uint32_t)0x0000000B) /*!< LCD RAM Register 11 */ +#define LCD_RAM_REGISTER12 ((uint32_t)0x0000000C) /*!< LCD RAM Register 12 */ +#define LCD_RAM_REGISTER13 ((uint32_t)0x0000000D) /*!< LCD RAM Register 13 */ +#define LCD_RAM_REGISTER14 ((uint32_t)0x0000000E) /*!< LCD RAM Register 14 */ +#define LCD_RAM_REGISTER15 ((uint32_t)0x0000000F) /*!< LCD RAM Register 15 */ + +#define IS_LCD_RAM_REGISTER(REGISTER) (((REGISTER) == LCD_RAM_REGISTER0) || \ + ((REGISTER) == LCD_RAM_REGISTER1) || \ + ((REGISTER) == LCD_RAM_REGISTER2) || \ + ((REGISTER) == LCD_RAM_REGISTER3) || \ + ((REGISTER) == LCD_RAM_REGISTER4) || \ + ((REGISTER) == LCD_RAM_REGISTER5) || \ + ((REGISTER) == LCD_RAM_REGISTER6) || \ + ((REGISTER) == LCD_RAM_REGISTER7) || \ + ((REGISTER) == LCD_RAM_REGISTER8) || \ + ((REGISTER) == LCD_RAM_REGISTER9) || \ + ((REGISTER) == LCD_RAM_REGISTER10) || \ + ((REGISTER) == LCD_RAM_REGISTER11) || \ + ((REGISTER) == LCD_RAM_REGISTER12) || \ + ((REGISTER) == LCD_RAM_REGISTER13) || \ + ((REGISTER) == LCD_RAM_REGISTER14) || \ + ((REGISTER) == LCD_RAM_REGISTER15)) + +/** + * @} + */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ + +/** @brief Reset LCD handle state + * @param __HANDLE__: specifies the LCD Handle. + * @retval None + */ +#define __HAL_LCD_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_LCD_STATE_RESET) + +/** @brief macros to enables or disables the LCD + * @param __HANDLE__: specifies the LCD Handle. + * @retval None + */ +#define __HAL_LCD_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= LCD_CR_LCDEN) +#define __HAL_LCD_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~LCD_CR_LCDEN) + +/** @brief Macros to enable or disable the low resistance divider. Displays with high + * internal resistance may need a longer drive time to achieve + * satisfactory contrast. This function is useful in this case if some + * additional power consumption can be tolerated. + * @param __HANDLE__: specifies the LCD Handle. + * @note When this mode is enabled, the PulseOn Duration (PON) have to be + * programmed to 1/CK_PS (LCD_PULSEONDURATION_1). + * @retval None + */ +#define __HAL_LCD_HIGHDRIVER_ENABLE(__HANDLE__) \ + do{ \ + ((__HANDLE__)->Instance->FCR |= LCD_FCR_HD); \ + LCD_WaitForSynchro(__HANDLE__); \ + }while(0) + +#define __HAL_LCD_HIGHDRIVER_DISABLE(__HANDLE__) \ + do{ \ + ((__HANDLE__)->Instance->FCR &= ~LCD_FCR_HD); \ + LCD_WaitForSynchro(__HANDLE__); \ + }while(0) +/** + * @brief Macro to configure the LCD pulses on duration. + * @param __HANDLE__: specifies the LCD Handle. + * @param __DURATION__: specifies the LCD pulse on duration in terms of + * CK_PS (prescaled LCD clock period) pulses. + * This parameter can be one of the following values: + * @arg LCD_PULSEONDURATION_0: 0 pulse + * @arg LCD_PULSEONDURATION_1: Pulse ON duration = 1/CK_PS + * @arg LCD_PULSEONDURATION_2: Pulse ON duration = 2/CK_PS + * @arg LCD_PULSEONDURATION_3: Pulse ON duration = 3/CK_PS + * @arg LCD_PULSEONDURATION_4: Pulse ON duration = 4/CK_PS + * @arg LCD_PULSEONDURATION_5: Pulse ON duration = 5/CK_PS + * @arg LCD_PULSEONDURATION_6: Pulse ON duration = 6/CK_PS + * @arg LCD_PULSEONDURATION_7: Pulse ON duration = 7/CK_PS + * @retval None + */ +#define __HAL_LCD_PULSEONDURATION_CONFIG(__HANDLE__, __DURATION__) \ + do{ \ + MODIFY_REG((__HANDLE__)->Instance->FCR, LCD_FCR_PON, (__DURATION__)); \ + LCD_WaitForSynchro(__HANDLE__); \ + }while(0) + +/** + * @brief Macro to configure the LCD dead time. + * @param __HANDLE__: specifies the LCD Handle. + * @param __DEADTIME__: specifies the LCD dead time. + * This parameter can be one of the following values: + * @arg LCD_DEADTIME_0: No dead Time + * @arg LCD_DEADTIME_1: One Phase between different couple of Frame + * @arg LCD_DEADTIME_2: Two Phase between different couple of Frame + * @arg LCD_DEADTIME_3: Three Phase between different couple of Frame + * @arg LCD_DEADTIME_4: Four Phase between different couple of Frame + * @arg LCD_DEADTIME_5: Five Phase between different couple of Frame + * @arg LCD_DEADTIME_6: Six Phase between different couple of Frame + * @arg LCD_DEADTIME_7: Seven Phase between different couple of Frame + * @retval None + */ +#define __HAL_LCD_DEADTIME_CONFIG(__HANDLE__, __DEADTIME__) \ + do{ \ + MODIFY_REG((__HANDLE__)->Instance->FCR, LCD_FCR_DEAD, (__DEADTIME__)); \ + LCD_WaitForSynchro(__HANDLE__); \ + }while(0) + +/** + * @brief Macro to configure the LCD Contrast. + * @param __HANDLE__: specifies the LCD Handle. + * @param __CONTRAST__: specifies the LCD Contrast. + * This parameter can be one of the following values: + * @arg LCD_CONTRASTLEVEL_0: Maximum Voltage = 2.60V + * @arg LCD_CONTRASTLEVEL_1: Maximum Voltage = 2.73V + * @arg LCD_CONTRASTLEVEL_2: Maximum Voltage = 2.86V + * @arg LCD_CONTRASTLEVEL_3: Maximum Voltage = 2.99V + * @arg LCD_CONTRASTLEVEL_4: Maximum Voltage = 3.12V + * @arg LCD_CONTRASTLEVEL_5: Maximum Voltage = 3.25V + * @arg LCD_CONTRASTLEVEL_6: Maximum Voltage = 3.38V + * @arg LCD_CONTRASTLEVEL_7: Maximum Voltage = 3.51V + * @retval None + */ +#define __HAL_LCD_CONTRAST_CONFIG(__HANDLE__, __CONTRAST__) \ + do{ \ + MODIFY_REG((__HANDLE__)->Instance->FCR, LCD_FCR_CC, (__CONTRAST__)); \ + LCD_WaitForSynchro(__HANDLE__); \ + } while(0) +/** + * @brief Macro to configure the LCD Blink mode and Blink frequency. + * @param __HANDLE__: specifies the LCD Handle. + * @param __BLINKMODE__: specifies the LCD blink mode. + * This parameter can be one of the following values: + * @arg LCD_BLINKMODE_OFF: Blink disabled + * @arg LCD_BLINKMODE_SEG0_COM0: Blink enabled on SEG[0], COM[0] (1 pixel) + * @arg LCD_BLINKMODE_SEG0_ALLCOM: Blink enabled on SEG[0], all COM (up to 8 + * pixels according to the programmed duty) + * @arg LCD_BLINKMODE_ALLSEG_ALLCOM: Blink enabled on all SEG and all COM + * (all pixels) + * @param __BLINKFREQUENCY__: specifies the LCD blink frequency. + * @arg LCD_BLINKFREQUENCY_DIV8: The Blink frequency = fLcd/8 + * @arg LCD_BLINKFREQUENCY_DIV16: The Blink frequency = fLcd/16 + * @arg LCD_BLINKFREQUENCY_DIV32: The Blink frequency = fLcd/32 + * @arg LCD_BLINKFREQUENCY_DIV64: The Blink frequency = fLcd/64 + * @arg LCD_BLINKFREQUENCY_DIV128: The Blink frequency = fLcd/128 + * @arg LCD_BLINKFREQUENCY_DIV256: The Blink frequency = fLcd/256 + * @arg LCD_BLINKFREQUENCY_DIV512: The Blink frequency = fLcd/512 + * @arg LCD_BLINKFREQUENCY_DIV1024: The Blink frequency = fLcd/1024 + * @retval None + */ +#define __HAL_LCD_BLINK_CONFIG(__HANDLE__, __BLINKMODE__, __BLINKFREQUENCY__) \ + do{ \ + MODIFY_REG((__HANDLE__)->Instance->FCR, (LCD_FCR_BLINKF | LCD_FCR_BLINK), ((__BLINKMODE__) | (__BLINKFREQUENCY__))); \ + LCD_WaitForSynchro(__HANDLE__); \ + }while(0) + +/** @brief Enables or disables the specified LCD interrupt. + * @param __HANDLE__: specifies the LCD Handle. + * @param __INTERRUPT__: specifies the LCD interrupt source to be enabled or disabled. + * This parameter can be one of the following values: + * @arg LCD_IT_SOF: Start of Frame Interrupt + * @arg LCD_IT_UDD: Update Display Done Interrupt + * @retval None + */ +#define __HAL_LCD_ENABLE_IT(__HANDLE__, __INTERRUPT__) \ + do{ \ + ((__HANDLE__)->Instance->FCR |= (__INTERRUPT__)); \ + LCD_WaitForSynchro(__HANDLE__); \ + }while(0) +#define __HAL_LCD_DISABLE_IT(__HANDLE__, __INTERRUPT__) \ + do{ \ + ((__HANDLE__)->Instance->FCR &= ~(__INTERRUPT__));\ + LCD_WaitForSynchro(__HANDLE__); \ + }while(0) +/** @brief Checks whether the specified LCD interrupt is enabled or not. + * @param __HANDLE__: specifies the LCD Handle. + * @param __IT__: specifies the LCD interrupt source to check. + * This parameter can be one of the following values: + * @arg LCD_IT_SOF: Start of Frame Interrupt + * @arg LCD_IT_UDD: Update Display Done Interrupt. + * @note If the device is in STOP mode (PCLK not provided) UDD will not + * generate an interrupt even if UDDIE = 1. + * If the display is not enabled the UDD interrupt will never occur. + * @retval The state of __IT__ (TRUE or FALSE). + */ +#define __HAL_LCD_GET_IT_SOURCE(__HANDLE__, __IT__) (((__HANDLE__)->Instance->FCR) & (__IT__)) + +/** @brief Checks whether the specified LCD flag is set or not. + * @param __HANDLE__: specifies the LCD Handle. + * @param __FLAG__: specifies the flag to check. + * This parameter can be one of the following values: + * @arg LCD_FLAG_ENS: LCD Enabled flag. It indicates the LCD controller status. + * @note The ENS bit is set immediately when the LCDEN bit in the LCD_CR + * goes from 0 to 1. On deactivation it reflects the real status of + * LCD so it becomes 0 at the end of the last displayed frame. + * @arg LCD_FLAG_SOF: Start of Frame flag. This flag is set by hardware at + * the beginning of a new frame, at the same time as the display data is + * updated. + * @arg LCD_FLAG_UDR: Update Display Request flag. + * @arg LCD_FLAG_UDD: Update Display Done flag. + * @arg LCD_FLAG_RDY: Step_up converter Ready flag. It indicates the status + * of the step-up converter. + * @arg LCD_FLAG_FCRSF: LCD Frame Control Register Synchronization Flag. + * This flag is set by hardware each time the LCD_FCR register is updated + * in the LCDCLK domain. + * @retval The new state of __FLAG__ (TRUE or FALSE). + */ +#define __HAL_LCD_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->SR & (__FLAG__)) == (__FLAG__)) + +/** @brief Clears the specified LCD pending flag. + * @param __HANDLE__: specifies the LCD Handle. + * @param __FLAG__: specifies the flag to check. + * This parameter can be any combination of the following values: + * @arg LCD_FLAG_SOF: Start of Frame Interrupt + * @arg LCD_FLAG_UDD: Update Display Done Interrupt + * @retval None + */ +#define __HAL_LCD_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->CLR = (__FLAG__)) + +/* Exported functions ------------------------------------------------------- */ +/* Initialization/de-initialization methods **********************************/ +HAL_StatusTypeDef HAL_LCD_DeInit(LCD_HandleTypeDef *hlcd); +HAL_StatusTypeDef HAL_LCD_Init(LCD_HandleTypeDef *hlcd); +void HAL_LCD_MspInit(LCD_HandleTypeDef *hlcd); +void HAL_LCD_MspDeInit(LCD_HandleTypeDef *hlcd); + +/* IO operation methods *******************************************************/ +HAL_StatusTypeDef HAL_LCD_Write(LCD_HandleTypeDef *hlcd, uint32_t RAMRegisterIndex, uint32_t RAMRegisterMask, uint32_t Data); +HAL_StatusTypeDef HAL_LCD_Clear(LCD_HandleTypeDef *hlcd); +HAL_StatusTypeDef HAL_LCD_UpdateDisplayRequest(LCD_HandleTypeDef *hlcd); + +/* Peripheral State methods **************************************************/ +HAL_LCD_StateTypeDef HAL_LCD_GetState(LCD_HandleTypeDef *hlcd); +uint32_t HAL_LCD_GetError(LCD_HandleTypeDef *hlcd); + +/* Private functions ---------------------------------------------------------*/ +HAL_StatusTypeDef LCD_WaitForSynchro(LCD_HandleTypeDef *hlcd); + +#endif /* STM32L051xx && STM32L052xx && STM32L062xx && STM32L061xx*/ + +#ifdef __cplusplus +} +#endif + +#endif /* __STM32L0xx_HAL_LCD_H */ + +/** + * @} + */ + +/** + * @} + */ + +/******************* (C) COPYRIGHT 2014 STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_lptim.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_lptim.c new file mode 100644 index 0000000000..bd9c120095 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_lptim.c @@ -0,0 +1,1585 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_lptim.c + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief LPTIM HAL module driver. + * + * This file provides firmware functions to manage the following + * functionalities of the Low Power Timer (LPTIM) peripheral: + * + Initialization and de-initialization functions. + * + Start/Stop operation functions in polling mode. + * + Start/Stop operation functions in interrupt mode. + * + Reading operation functions. + * + Peripheral State functions. + * + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + The LPTIM HAL driver can be used as follows: + + (#)Initialize the LPTIM low level resources by implementing the + HAL_LPTIM_MspInit(): + (##) Enable the LPTIM interface clock using __LPTIM1_CLK_ENABLE(). + (##) In case of using interrupts (e.g. HAL_LPTIM_PWM_Start_IT()): + (+) Configure the LPTIM interrupt priority using HAL_NVIC_SetPriority(). + (+) Enable the LPTIM IRQ handler using HAL_NVIC_EnableIRQ(). + (+) In LPTIM IRQ handler, call HAL_LPTIM_IRQHandler(). + + (#)Initialize the LPTIM HAL using HAL_LPTIM_Init(). This function + configures mainly: + (##) The instance: Only LPTIM1 is present in STM32L053xx. + (##) Clock: the counter clock. + - Source : it can be either the ULPTIM input (IN1) or one of + the internal clock; (APB, LSE, LSI or MSI). + - Prescaler: select the clock divider. + (##) UltraLowPowerClock : To be used only if the ULPTIM is selected + as counter clock source. + - Polarity: polarity of the active edge for the counter unit + if the ULPTIM input is selected. + - SampleTime: clock sampling time to configure the clock glitch + filter. + (##) Trigger: How the counter start. + - Source: trigger can be software or one of the hardware triggers. + - ActiveEdge : only for hardware trigger. + - SampleTime : trigger sampling time to configure the trigger + glitch filter. + (##) OutputPolarity : 2 opposite polarities are possibles. + (##) UpdateMode: specifies whether the update of the autoreload and + the compare values is done immediately or after the end of current + period. + + (#)Six modes are available: + + (##) PWM Mode: To generate a PWM signal with specified period and pulse, + call HAL_LPTIM_PWM_Start() or HAL_LPTIM_PWM_Start_IT() for interruption + mode. + + (##) One Pulse Mode: To generate pulse with specified width in response + to a stimulus, call HAL_LPTIM_OnePulse_Start() or + HAL_LPTIM_OnePulse_Start_IT() for interruption mode. + + (##) Set once Mode: In this mode, the output changes the level (from + low level to high level if the output polarity is configured high, else + the opposite) when a compare match occurs. To start this mode, call + HAL_LPTIM_SetOnce_Start() or HAL_LPTIM_SetOnce_Start_IT() for + interruption mode. + + (##) Encoder Mode: To use the encoder interface call + HAL_LPTIM_Encoder_Start() or HAL_LPTIM_Encoder_Start_IT() for + interruption mode. + + (##) Time out Mode: an active edge on one selected trigger input rests + the counter. The first trigger event will start the timer, any + successive trigger event will reset the counter and the timer will + restart. To start this mode call HAL_LPTIM_TimeOut_Start_IT() or + HAL_LPTIM_TimeOut_Start_IT() for interruption mode. + + (##) Counter Mode: counter can be used to count external events on + the LPTIM Input1 or it can be used to count internal clock cycles. + To start this mode, call HAL_LPTIM_Counter_Start() or + HAL_LPTIM_Counter_Start_IT() for interruption mode. + + + (#) User can stop any process by calling the corresponding API: + HAL_LPTIM_Xxx_Stop() or HAL_LPTIM_Xxx_Stop_IT() if the process is + already started in interruption mode. + + (#)Call HAL_LPTIM_DeInit() to deinitialize the LPTIM peripheral. + + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @defgroup LPTIM + * @brief LPTIM HAL module driver. + * @{ + */ + +#ifdef HAL_LPTIM_MODULE_ENABLED +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup LPTIM_Private_Functions + * @{ + */ + +/** @defgroup HAL_LPTIM_Group1 Initialization/de-initialization functions + * @brief Initialization and Configuration functions. + * +@verbatim + ============================================================================== + ##### Initialization and de-initialization functions ##### + ============================================================================== + [..] This section provides functions allowing to: + (+) Initialize the LPTIM according to the specified parameters in the + LPTIM_InitTypeDef and creates the associated handle. + (+) DeInitialize the LPTIM peripheral. + (+) Initialize the LPTIM MSP. + (+) DeInitialize LPTIM MSP. + +@endverbatim + * @{ + */ + +/** + * @brief Initializes the LPTIM according to the specified parameters in the + * LPTIM_InitTypeDef and creates the associated handle. + * @param hlptim: LPTIM handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LPTIM_Init(LPTIM_HandleTypeDef *hlptim) +{ + uint32_t tmpcfgr = 0; + + /* Check the parameters */ + assert_param(IS_LPTIM_INSTANCE(hlptim->Instance)); + + assert_param(IS_LPTIM_CLOCK_SOURCE(hlptim->Init.Clock.Source)); + assert_param(IS_LPTIM_CLOCK_PRESCALER(hlptim->Init.Clock.Prescaler)); + if ((hlptim->Init.Clock.Source) == LPTIM_CLOCKSOURCE_ULPTIM) + { + assert_param(IS_LPTIM_CLOCK_POLARITY(hlptim->Init.UltraLowPowerClock.Polarity)); + assert_param(IS_LPTIM_CLOCK_SAMPLE_TIME(hlptim->Init.UltraLowPowerClock.SampleTime)); + } + assert_param(IS_LPTIM_TRG_SOURCE(hlptim->Init.Trigger.Source)); + if ((hlptim->Init.Trigger.Source) != LPTIM_TRIGSOURCE_SOFTWARE) + { + assert_param(IS_LPTIM_TRIG_SAMPLE_TIME(hlptim->Init.Trigger.SampleTime)); + assert_param(IS_LPTIM_EXT_TRG_POLARITY(hlptim->Init.Trigger.ActiveEdge)); + } + assert_param(IS_LPTIM_OUTPUT_POLARITY(hlptim->Init.OutputPolarity)); + assert_param(IS_LPTIM_UPDATE_MODE(hlptim->Init.UpdateMode)); + assert_param(IS_LPTIM_COUNTER_SOURCE(hlptim->Init.CounterSource)); + + /* Check the LPTIM handle allocation */ + if(hlptim == NULL) + { + return HAL_ERROR; + } + + if(hlptim->State == HAL_LPTIM_STATE_RESET) + { + /* Init the low level hardware */ + HAL_LPTIM_MspInit(hlptim); + } + + /* Change the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_BUSY; + + /* Get the LPTIMx CFGR value */ + tmpcfgr = hlptim->Instance->CFGR; + + if ((hlptim->Init.Clock.Source) == LPTIM_CLOCKSOURCE_ULPTIM) + { + tmpcfgr &= (uint32_t)(~(LPTIM_CFGR_CKPOL | LPTIM_CFGR_CKFLT)); + } + if ((hlptim->Init.Trigger.Source) != LPTIM_TRIGSOURCE_SOFTWARE) + { + tmpcfgr &= (uint32_t)(~ (LPTIM_CFGR_TRGFLT | LPTIM_CFGR_TRIGSEL)); + } + + /* Clear CKSEL, PRESC, TRIGEN, TRGFLT, WAVPOL, PRELOAD & COUNTMODE bits */ + tmpcfgr &= (uint32_t)(~(LPTIM_CFGR_CKSEL | LPTIM_CFGR_TRIGEN | LPTIM_CFGR_PRELOAD | + LPTIM_CFGR_WAVPOL | LPTIM_CFGR_PRESC | LPTIM_CFGR_COUNTMODE )); + + /* Set initialization parameters */ + tmpcfgr |= (hlptim->Init.Clock.Source | + hlptim->Init.Clock.Prescaler | + hlptim->Init.OutputPolarity | + hlptim->Init.UpdateMode | + hlptim->Init.CounterSource); + + if ((hlptim->Init.Clock.Source) == LPTIM_CLOCKSOURCE_ULPTIM) + { + tmpcfgr |= (hlptim->Init.UltraLowPowerClock.Polarity | + hlptim->Init.UltraLowPowerClock.SampleTime); + } + + if ((hlptim->Init.Trigger.Source) != LPTIM_TRIGSOURCE_SOFTWARE) + { + /* Enable External trigger and set the trigger source */ + tmpcfgr |= (hlptim->Init.Trigger.Source | + hlptim->Init.Trigger.ActiveEdge | + hlptim->Init.Trigger.SampleTime); + } + + /* Write to LPTIMx CFGR */ + hlptim->Instance->CFGR = tmpcfgr; + + /* Change the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief DeInitializes the LPTIM peripheral. + * @param hlptim: LPTIM handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LPTIM_DeInit(LPTIM_HandleTypeDef *hlptim) +{ + /* Check the LPTIM handle allocation */ + if(hlptim == NULL) + { + return HAL_ERROR; + } + + /* Change the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_BUSY; + + /* Disable the LPTIM Peripheral Clock */ + __HAL_LPTIM_DISABLE(hlptim); + + /* DeInit the low level hardware: CLOCK, NVIC.*/ + HAL_LPTIM_MspDeInit(hlptim); + + /* Change the LPTIM state */ + hlptim->State = HAL_LPTIM_STATE_RESET; + + /* Release Lock */ + __HAL_UNLOCK(hlptim); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Initializes the LPTIM MSP. + * @param hlptim: LPTIM handle + * @retval None + */ +__weak void HAL_LPTIM_MspInit(LPTIM_HandleTypeDef *hlptim) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_LPTIM_MspInit could be implemented in the user file + */ +} + +/** + * @brief DeInitializes LPTIM MSP. + * @param hlptim: LPTIM handle + * @retval None + */ +__weak void HAL_LPTIM_MspDeInit(LPTIM_HandleTypeDef *hlptim) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_LPTIM_MspDeInit could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup HAL_LPTIM_Group2 LPTIM Start/Stop operation functions + * @brief I/O operation functions. + * +@verbatim + ============================================================================== + ##### LPTIM Start/Stop operation functions ##### + ============================================================================== + [..] This section provides functions allowing to: + (+) Start the PWM mode. + (+) Stop the PWM mode. + (+) Start the One pulse mode. + (+) Stop the One pulse mode. + (+) Start the Set once mode. + (+) Stop the Set once mode. + (+) Start the Encoder mode. + (+) Stop the Encoder mode. + (+) Start the Timeout mode. + (+) Stop the Timeout mode. + (+) Start the Counter mode. + (+) Stop the Counter mode. + + +@endverbatim + * @{ + */ + +/** + * @brief Starts the LPTIM PWM generation. + * @param hlptim : LPTIM handle + * @param Period : Specifies the Autoreload value. + * This parameter must be a value between 0x0000 and 0xFFFF. + * @param Pulse : Specifies the compare value. + * This parameter must be a value between 0x0000 and 0xFFFF. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LPTIM_PWM_Start(LPTIM_HandleTypeDef *hlptim, uint32_t Period, uint32_t Pulse) +{ + /* Check the parameters */ + assert_param(IS_LPTIM_INSTANCE(hlptim->Instance)); + assert_param(IS_LPTIM_PERIOD(Period)); + assert_param(IS_LPTIM_PULSE(Pulse)); + + /* Set the LPTIM state */ + hlptim->State= HAL_LPTIM_STATE_BUSY; + + /* Reset WAVE bit to set PWM mode */ + hlptim->Instance->CFGR &= ~LPTIM_CFGR_WAVE; + + /* Enable the Peripheral */ + __HAL_LPTIM_ENABLE(hlptim); + + /* Load the period value in the autoreload register */ + __HAL_LPTIM_AUTORELOAD_SET(hlptim, Period); + + /* Load the pulse value in the compare register */ + __HAL_LPTIM_COMPARE_SET(hlptim, Pulse); + + /* Start timer in continuous mode */ + __HAL_LPTIM_START_CONTINUOUS(hlptim); + + /* Change the TIM state*/ + hlptim->State= HAL_LPTIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the LPTIM PWM generation. + * @param hlptim : LPTIM handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LPTIM_PWM_Stop(LPTIM_HandleTypeDef *hlptim) +{ + /* Check the parameters */ + assert_param(IS_LPTIM_INSTANCE(hlptim->Instance)); + + /* Set the LPTIM state */ + hlptim->State= HAL_LPTIM_STATE_BUSY; + + /* Disable the Peripheral */ + __HAL_LPTIM_DISABLE(hlptim); + + /* Change the TIM state*/ + hlptim->State= HAL_LPTIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Starts the LPTIM PWM generation in interrupt mode. + * @param hlptim : LPTIM handle + * @param Period : Specifies the Autoreload value. + * This parameter must be a value between 0x0000 and 0xFFFF + * @param Pulse : Specifies the compare value. + * This parameter must be a value between 0x0000 and 0xFFFF + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LPTIM_PWM_Start_IT(LPTIM_HandleTypeDef *hlptim, uint32_t Period, uint32_t Pulse) +{ + /* Check the parameters */ + assert_param(IS_LPTIM_INSTANCE(hlptim->Instance)); + assert_param(IS_LPTIM_PERIOD(Period)); + assert_param(IS_LPTIM_PULSE(Pulse)); + + /* Set the LPTIM state */ + hlptim->State= HAL_LPTIM_STATE_BUSY; + + /* Reset WAVE bit to set PWM mode */ + hlptim->Instance->CFGR &= ~LPTIM_CFGR_WAVE; + + /* Enable Autoreload write complete interrupt */ + __HAL_LPTIM_ENABLE_INTERRUPT(hlptim, LPTIM_IT_ARROK); + + /* Enable Compare write complete interrupt */ + __HAL_LPTIM_ENABLE_INTERRUPT(hlptim, LPTIM_IT_CMPOK); + + /* Enable Autoreload match interrupt */ + __HAL_LPTIM_ENABLE_INTERRUPT(hlptim, LPTIM_IT_ARRM); + + /* Enable Compare match interrupt */ + __HAL_LPTIM_ENABLE_INTERRUPT(hlptim, LPTIM_IT_CMPM); + + /* If external trigger source is used, then enable external trigger interrupt */ + if ((hlptim->Init.Trigger.Source) != LPTIM_TRIGSOURCE_SOFTWARE) + { + /* Enable external trigger interrupt */ + __HAL_LPTIM_ENABLE_INTERRUPT(hlptim, LPTIM_IT_EXTTRIG); + } + + /* Enable the Peripheral */ + __HAL_LPTIM_ENABLE(hlptim); + + /* Load the period value in the autoreload register */ + __HAL_LPTIM_AUTORELOAD_SET(hlptim, Period); + + /* Load the pulse value in the compare register */ + __HAL_LPTIM_COMPARE_SET(hlptim, Pulse); + + /* Start timer in continuous mode */ + __HAL_LPTIM_START_CONTINUOUS(hlptim); + + /* Change the TIM state*/ + hlptim->State= HAL_LPTIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the LPTIM PWM generation in interrupt mode. + * @param hlptim : LPTIM handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LPTIM_PWM_Stop_IT(LPTIM_HandleTypeDef *hlptim) +{ + /* Check the parameters */ + assert_param(IS_LPTIM_INSTANCE(hlptim->Instance)); + + /* Set the LPTIM state */ + hlptim->State= HAL_LPTIM_STATE_BUSY; + + /* Disable the Peripheral */ + __HAL_LPTIM_DISABLE(hlptim); + + /* Disable Autoreload write complete interrupt */ + __HAL_LPTIM_DISABLE_INTERRUPT(hlptim, LPTIM_IT_ARROK); + + /* Disable Compare write complete interrupt */ + __HAL_LPTIM_DISABLE_INTERRUPT(hlptim, LPTIM_IT_CMPOK); + + /* Disable Autoreload match interrupt */ + __HAL_LPTIM_DISABLE_INTERRUPT(hlptim, LPTIM_IT_ARRM); + + /* Disable Compare match interrupt */ + __HAL_LPTIM_DISABLE_INTERRUPT(hlptim, LPTIM_IT_CMPM); + + /* If external trigger source is used, then disable external trigger interrupt */ + if ((hlptim->Init.Trigger.Source) != LPTIM_TRIGSOURCE_SOFTWARE) + { + /* Disable external trigger interrupt */ + __HAL_LPTIM_DISABLE_INTERRUPT(hlptim, LPTIM_IT_EXTTRIG); + } + + /* Change the TIM state*/ + hlptim->State= HAL_LPTIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Starts the LPTIM One pulse generation. + * @param hlptim : LPTIM handle + * @param Period : Specifies the Autoreload value. + * This parameter must be a value between 0x0000 and 0xFFFF. + * @param Pulse : Specifies the compare value. + * This parameter must be a value between 0x0000 and 0xFFFF. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LPTIM_OnePulse_Start(LPTIM_HandleTypeDef *hlptim, uint32_t Period, uint32_t Pulse) +{ + /* Check the parameters */ + assert_param(IS_LPTIM_INSTANCE(hlptim->Instance)); + assert_param(IS_LPTIM_PERIOD(Period)); + assert_param(IS_LPTIM_PULSE(Pulse)); + + /* Set the LPTIM state */ + hlptim->State= HAL_LPTIM_STATE_BUSY; + + /* Reset WAVE bit to set one pulse mode */ + hlptim->Instance->CFGR &= ~LPTIM_CFGR_WAVE; + + /* Enable the Peripheral */ + __HAL_LPTIM_ENABLE(hlptim); + + /* Load the period value in the autoreload register */ + __HAL_LPTIM_AUTORELOAD_SET(hlptim, Period); + + /* Load the pulse value in the compare register */ + __HAL_LPTIM_COMPARE_SET(hlptim, Pulse); + + /* Start timer in continuous mode */ + __HAL_LPTIM_START_SINGLE(hlptim); + + /* Change the TIM state*/ + hlptim->State= HAL_LPTIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the LPTIM One pulse generation. + * @param hlptim : LPTIM handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LPTIM_OnePulse_Stop(LPTIM_HandleTypeDef *hlptim) +{ + /* Check the parameters */ + assert_param(IS_LPTIM_INSTANCE(hlptim->Instance)); + + /* Set the LPTIM state */ + hlptim->State= HAL_LPTIM_STATE_BUSY; + + /* Disable the Peripheral */ + __HAL_LPTIM_DISABLE(hlptim); + + /* Change the TIM state*/ + hlptim->State= HAL_LPTIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Starts the LPTIM One pulse generation in interrupt mode. + * @param hlptim : LPTIM handle + * @param Period : Specifies the Autoreload value. + * This parameter must be a value between 0x0000 and 0xFFFF. + * @param Pulse : Specifies the compare value. + * This parameter must be a value between 0x0000 and 0xFFFF. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LPTIM_OnePulse_Start_IT(LPTIM_HandleTypeDef *hlptim, uint32_t Period, uint32_t Pulse) +{ + /* Check the parameters */ + assert_param(IS_LPTIM_INSTANCE(hlptim->Instance)); + assert_param(IS_LPTIM_PERIOD(Period)); + assert_param(IS_LPTIM_PULSE(Pulse)); + + /* Set the LPTIM state */ + hlptim->State= HAL_LPTIM_STATE_BUSY; + + /* Reset WAVE bit to set one pulse mode */ + hlptim->Instance->CFGR &= ~LPTIM_CFGR_WAVE; + + /* Enable Autoreload write complete interrupt */ + __HAL_LPTIM_ENABLE_INTERRUPT(hlptim, LPTIM_IT_ARROK); + + /* Enable Compare write complete interrupt */ + __HAL_LPTIM_ENABLE_INTERRUPT(hlptim, LPTIM_IT_CMPOK); + + /* Enable Autoreload match interrupt */ + __HAL_LPTIM_ENABLE_INTERRUPT(hlptim, LPTIM_IT_ARRM); + + /* Enable Compare match interrupt */ + __HAL_LPTIM_ENABLE_INTERRUPT(hlptim, LPTIM_IT_CMPM); + + /* If external trigger source is used, then enable external trigger interrupt */ + if ((hlptim->Init.Trigger.Source) != LPTIM_TRIGSOURCE_SOFTWARE) + { + /* Enable external trigger interrupt */ + __HAL_LPTIM_ENABLE_INTERRUPT(hlptim, LPTIM_IT_EXTTRIG); + } + + /* Enable the Peripheral */ + __HAL_LPTIM_ENABLE(hlptim); + + /* Load the period value in the autoreload register */ + __HAL_LPTIM_AUTORELOAD_SET(hlptim, Period); + + /* Load the pulse value in the compare register */ + __HAL_LPTIM_COMPARE_SET(hlptim, Pulse); + + /* Start timer in continuous mode */ + __HAL_LPTIM_START_SINGLE(hlptim); + + /* Change the TIM state*/ + hlptim->State= HAL_LPTIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the LPTIM One pulse generation in interrupt mode. + * @param hlptim : LPTIM handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LPTIM_OnePulse_Stop_IT(LPTIM_HandleTypeDef *hlptim) +{ + /* Check the parameters */ + assert_param(IS_LPTIM_INSTANCE(hlptim->Instance)); + + /* Set the LPTIM state */ + hlptim->State= HAL_LPTIM_STATE_BUSY; + + /* Disable the Peripheral */ + __HAL_LPTIM_DISABLE(hlptim); + + /* Disable Autoreload write complete interrupt */ + __HAL_LPTIM_DISABLE_INTERRUPT(hlptim, LPTIM_IT_ARROK); + + /* Disable Compare write complete interrupt */ + __HAL_LPTIM_DISABLE_INTERRUPT(hlptim, LPTIM_IT_CMPOK); + + /* Disable Autoreload match interrupt */ + __HAL_LPTIM_DISABLE_INTERRUPT(hlptim, LPTIM_IT_ARRM); + + /* Disable Compare match interrupt */ + __HAL_LPTIM_DISABLE_INTERRUPT(hlptim, LPTIM_IT_CMPM); + + /* If external trigger source is used, then disable external trigger interrupt */ + if ((hlptim->Init.Trigger.Source) != LPTIM_TRIGSOURCE_SOFTWARE) + { + /* Disable external trigger interrupt */ + __HAL_LPTIM_DISABLE_INTERRUPT(hlptim, LPTIM_IT_EXTTRIG); + } + + /* Change the TIM state*/ + hlptim->State= HAL_LPTIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Starts the LPTIM in Set once mode. + * @param hlptim : LPTIM handle + * @param Period : Specifies the Autoreload value. + * This parameter must be a value between 0x0000 and 0xFFFF. + * @param Pulse : Specifies the compare value. + * This parameter must be a value between 0x0000 and 0xFFFF. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LPTIM_SetOnce_Start(LPTIM_HandleTypeDef *hlptim, uint32_t Period, uint32_t Pulse) +{ + /* Check the parameters */ + assert_param(IS_LPTIM_INSTANCE(hlptim->Instance)); + assert_param(IS_LPTIM_PERIOD(Period)); + assert_param(IS_LPTIM_PULSE(Pulse)); + + /* Set the LPTIM state */ + hlptim->State= HAL_LPTIM_STATE_BUSY; + + /* Set WAVE bit to enable the set once mode */ + hlptim->Instance->CFGR |= LPTIM_CFGR_WAVE; + + /* Enable the Peripheral */ + __HAL_LPTIM_ENABLE(hlptim); + + /* Load the period value in the autoreload register */ + __HAL_LPTIM_AUTORELOAD_SET(hlptim, Period); + + /* Load the pulse value in the compare register */ + __HAL_LPTIM_COMPARE_SET(hlptim, Pulse); + + /* Start timer in continuous mode */ + __HAL_LPTIM_START_SINGLE(hlptim); + + /* Change the TIM state*/ + hlptim->State= HAL_LPTIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the LPTIM Set once mode. + * @param hlptim : LPTIM handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LPTIM_SetOnce_Stop(LPTIM_HandleTypeDef *hlptim) +{ + /* Check the parameters */ + assert_param(IS_LPTIM_INSTANCE(hlptim->Instance)); + + /* Set the LPTIM state */ + hlptim->State= HAL_LPTIM_STATE_BUSY; + + /* Disable the Peripheral */ + __HAL_LPTIM_DISABLE(hlptim); + + /* Change the TIM state*/ + hlptim->State= HAL_LPTIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Starts the LPTIM Set once mode in interrupt mode. + * @param hlptim : LPTIM handle + * @param Period : Specifies the Autoreload value. + * This parameter must be a value between 0x0000 and 0xFFFF. + * @param Pulse : Specifies the compare value. + * This parameter must be a value between 0x0000 and 0xFFFF. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LPTIM_SetOnce_Start_IT(LPTIM_HandleTypeDef *hlptim, uint32_t Period, uint32_t Pulse) +{ + /* Check the parameters */ + assert_param(IS_LPTIM_INSTANCE(hlptim->Instance)); + assert_param(IS_LPTIM_PERIOD(Period)); + assert_param(IS_LPTIM_PULSE(Pulse)); + + /* Set the LPTIM state */ + hlptim->State= HAL_LPTIM_STATE_BUSY; + + /* Set WAVE bit to enable the set once mode */ + hlptim->Instance->CFGR |= LPTIM_CFGR_WAVE; + + /* Enable Autoreload write complete interrupt */ + __HAL_LPTIM_ENABLE_INTERRUPT(hlptim, LPTIM_IT_ARROK); + + /* Enable Compare write complete interrupt */ + __HAL_LPTIM_ENABLE_INTERRUPT(hlptim, LPTIM_IT_CMPOK); + + /* Enable Autoreload match interrupt */ + __HAL_LPTIM_ENABLE_INTERRUPT(hlptim, LPTIM_IT_ARRM); + + /* Enable Compare match interrupt */ + __HAL_LPTIM_ENABLE_INTERRUPT(hlptim, LPTIM_IT_CMPM); + + /* If external trigger source is used, then enable external trigger interrupt */ + if ((hlptim->Init.Trigger.Source) != LPTIM_TRIGSOURCE_SOFTWARE) + { + /* Enable external trigger interrupt */ + __HAL_LPTIM_ENABLE_INTERRUPT(hlptim, LPTIM_IT_EXTTRIG); + } + + /* Enable the Peripheral */ + __HAL_LPTIM_ENABLE(hlptim); + + /* Load the period value in the autoreload register */ + __HAL_LPTIM_AUTORELOAD_SET(hlptim, Period); + + /* Load the pulse value in the compare register */ + __HAL_LPTIM_COMPARE_SET(hlptim, Pulse); + + /* Start timer in continuous mode */ + __HAL_LPTIM_START_SINGLE(hlptim); + + /* Change the TIM state*/ + hlptim->State= HAL_LPTIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the LPTIM Set once mode in interrupt mode. + * @param hlptim : LPTIM handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LPTIM_SetOnce_Stop_IT(LPTIM_HandleTypeDef *hlptim) +{ + /* Check the parameters */ + assert_param(IS_LPTIM_INSTANCE(hlptim->Instance)); + + /* Set the LPTIM state */ + hlptim->State= HAL_LPTIM_STATE_BUSY; + + /* Disable the Peripheral */ + __HAL_LPTIM_DISABLE(hlptim); + + /* Disable Autoreload write complete interrupt */ + __HAL_LPTIM_DISABLE_INTERRUPT(hlptim, LPTIM_IT_ARROK); + + /* Disable Compare write complete interrupt */ + __HAL_LPTIM_DISABLE_INTERRUPT(hlptim, LPTIM_IT_CMPOK); + + /* Disable Autoreload match interrupt */ + __HAL_LPTIM_DISABLE_INTERRUPT(hlptim, LPTIM_IT_ARRM); + + /* Disable Compare match interrupt */ + __HAL_LPTIM_DISABLE_INTERRUPT(hlptim, LPTIM_IT_CMPM); + + /* If external trigger source is used, then disable external trigger interrupt */ + if ((hlptim->Init.Trigger.Source) != LPTIM_TRIGSOURCE_SOFTWARE) + { + /* Disable external trigger interrupt */ + __HAL_LPTIM_DISABLE_INTERRUPT(hlptim, LPTIM_IT_EXTTRIG); + } + + /* Change the TIM state*/ + hlptim->State= HAL_LPTIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Starts the Encoder interface. + * @param hlptim : LPTIM handle + * @param Period : Specifies the Autoreload value. + * This parameter must be a value between 0x0000 and 0xFFFF. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LPTIM_Encoder_Start(LPTIM_HandleTypeDef *hlptim, uint32_t Period) +{ + /* Check the parameters */ + assert_param(IS_LPTIM_INSTANCE(hlptim->Instance)); + assert_param(IS_LPTIM_PERIOD(Period)); + + /* Set the LPTIM state */ + hlptim->State= HAL_LPTIM_STATE_BUSY; + + /* Set ENC bit to enable the encoder interface */ + hlptim->Instance->CFGR |= LPTIM_CFGR_ENC; + + /* Enable the Peripheral */ + __HAL_LPTIM_ENABLE(hlptim); + + /* Load the period value in the autoreload register */ + __HAL_LPTIM_AUTORELOAD_SET(hlptim, Period); + + /* Start timer in continuous mode */ + __HAL_LPTIM_START_CONTINUOUS(hlptim); + + /* Change the TIM state*/ + hlptim->State= HAL_LPTIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the Encoder interface. + * @param hlptim : LPTIM handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LPTIM_Encoder_Stop(LPTIM_HandleTypeDef *hlptim) +{ + /* Check the parameters */ + assert_param(IS_LPTIM_INSTANCE(hlptim->Instance)); + + /* Set the LPTIM state */ + hlptim->State= HAL_LPTIM_STATE_BUSY; + + /* Disable the Peripheral */ + __HAL_LPTIM_DISABLE(hlptim); + + /* Reset ENC bit to disable the encoder interface */ + hlptim->Instance->CFGR &= ~LPTIM_CFGR_ENC; + + /* Change the TIM state*/ + hlptim->State= HAL_LPTIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Starts the Encoder interface in interrupt mode. + * @param hlptim : LPTIM handle + * @param Period : Specifies the Autoreload value. + * This parameter must be a value between 0x0000 and 0xFFFF. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LPTIM_Encoder_Start_IT(LPTIM_HandleTypeDef *hlptim, uint32_t Period) +{ + /* Check the parameters */ + assert_param(IS_LPTIM_INSTANCE(hlptim->Instance)); + assert_param(IS_LPTIM_PERIOD(Period)); + + /* Set the LPTIM state */ + hlptim->State= HAL_LPTIM_STATE_BUSY; + + /* Set ENC bit to enable the encoder interface */ + hlptim->Instance->CFGR |= LPTIM_CFGR_ENC; + + /* Enable "switch to down direction" interrupt */ + __HAL_LPTIM_ENABLE_INTERRUPT(hlptim, LPTIM_IT_DOWN); + + /* Enable "switch to up direction" interrupt */ + __HAL_LPTIM_ENABLE_INTERRUPT(hlptim, LPTIM_IT_UP); + + /* Enable the Peripheral */ + __HAL_LPTIM_ENABLE(hlptim); + + /* Load the period value in the autoreload register */ + __HAL_LPTIM_AUTORELOAD_SET(hlptim, Period); + + /* Start timer in continuous mode */ + __HAL_LPTIM_START_CONTINUOUS(hlptim); + + /* Change the TIM state*/ + hlptim->State= HAL_LPTIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the Encoder interface in nterrupt mode. + * @param hlptim : LPTIM handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LPTIM_Encoder_Stop_IT(LPTIM_HandleTypeDef *hlptim) +{ + /* Check the parameters */ + assert_param(IS_LPTIM_INSTANCE(hlptim->Instance)); + + /* Set the LPTIM state */ + hlptim->State= HAL_LPTIM_STATE_BUSY; + + /* Disable the Peripheral */ + __HAL_LPTIM_DISABLE(hlptim); + + /* Reset ENC bit to disable the encoder interface */ + hlptim->Instance->CFGR &= ~LPTIM_CFGR_ENC; + + /* Disable "switch to down direction" interrupt */ + __HAL_LPTIM_DISABLE_INTERRUPT(hlptim, LPTIM_IT_DOWN); + + /* Disable "switch to up direction" interrupt */ + __HAL_LPTIM_DISABLE_INTERRUPT(hlptim, LPTIM_IT_UP); + + /* Change the TIM state*/ + hlptim->State= HAL_LPTIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Starts the Timeout function. The first trigger event will start the + * timer, any successive trigger event will reset the counter and + * the timer restarts. + * @param hlptim : LPTIM handle + * @param Period : Specifies the Autoreload value. + * This parameter must be a value between 0x0000 and 0xFFFF. + * @param Timeout : Specifies the TimeOut value to rest the counter. + * This parameter must be a value between 0x0000 and 0xFFFF. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LPTIM_TimeOut_Start(LPTIM_HandleTypeDef *hlptim, uint32_t Period, uint32_t Timeout) +{ + /* Check the parameters */ + assert_param(IS_LPTIM_INSTANCE(hlptim->Instance)); + assert_param(IS_LPTIM_PERIOD(Period)); + assert_param(IS_LPTIM_PULSE(Timeout)); + + /* Set the LPTIM state */ + hlptim->State= HAL_LPTIM_STATE_BUSY; + + /* Reset WAVE bit to set PWM mode */ + hlptim->Instance->CFGR &= ~LPTIM_CFGR_WAVE; + + /* Set TIMOUT bit to enable the timeout function */ + hlptim->Instance->CFGR |= LPTIM_CFGR_TIMOUT; + + /* Enable the Peripheral */ + __HAL_LPTIM_ENABLE(hlptim); + + /* Load the period value in the autoreload register */ + __HAL_LPTIM_AUTORELOAD_SET(hlptim, Period); + + /* Load the Timeout value in the compare register */ + __HAL_LPTIM_COMPARE_SET(hlptim, Timeout); + + /* Start timer in continuous mode */ + __HAL_LPTIM_START_CONTINUOUS(hlptim); + + /* Change the TIM state*/ + hlptim->State= HAL_LPTIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the Timeout function. + * @param hlptim : LPTIM handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LPTIM_TimeOut_Stop(LPTIM_HandleTypeDef *hlptim) +{ + /* Check the parameters */ + assert_param(IS_LPTIM_INSTANCE(hlptim->Instance)); + + /* Set the LPTIM state */ + hlptim->State= HAL_LPTIM_STATE_BUSY; + + /* Disable the Peripheral */ + __HAL_LPTIM_DISABLE(hlptim); + + /* Reset TIMOUT bit to enable the timeout function */ + hlptim->Instance->CFGR &= ~LPTIM_CFGR_TIMOUT; + + /* Change the TIM state*/ + hlptim->State= HAL_LPTIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Starts the Timeout function in interrupt mode. The first trigger + * event will start the timer, any successive trigger event will reset + * the counter and the timer restarts. + * @param hlptim : LPTIM handle + * @param Period : Specifies the Autoreload value. + * This parameter must be a value between 0x0000 and 0xFFFF. + * @param Timeout : Specifies the TimeOut value to rest the counter. + * This parameter must be a value between 0x0000 and 0xFFFF. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LPTIM_TimeOut_Start_IT(LPTIM_HandleTypeDef *hlptim, uint32_t Period, uint32_t Timeout) +{ + /* Check the parameters */ + assert_param(IS_LPTIM_INSTANCE(hlptim->Instance)); + assert_param(IS_LPTIM_PERIOD(Period)); + assert_param(IS_LPTIM_PULSE(Timeout)); + + /* Set the LPTIM state */ + hlptim->State= HAL_LPTIM_STATE_BUSY; + + /* Reset WAVE bit to set PWM mode */ + hlptim->Instance->CFGR &= ~LPTIM_CFGR_WAVE; + + /* Set TIMOUT bit to enable the timeout function */ + hlptim->Instance->CFGR |= LPTIM_CFGR_TIMOUT; + + + /* Enable Compare match interrupt */ + __HAL_LPTIM_ENABLE_INTERRUPT(hlptim, LPTIM_IT_CMPM); + + /* Enable the Peripheral */ + __HAL_LPTIM_ENABLE(hlptim); + + /* Load the period value in the autoreload register */ + __HAL_LPTIM_AUTORELOAD_SET(hlptim, Period); + + /* Load the Timeout value in the compare register */ + __HAL_LPTIM_COMPARE_SET(hlptim, Timeout); + + /* Start timer in continuous mode */ + __HAL_LPTIM_START_CONTINUOUS(hlptim); + + /* Change the TIM state*/ + hlptim->State= HAL_LPTIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the Timeout function in interrupt mode. + * @param hlptim : LPTIM handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LPTIM_TimeOut_Stop_IT(LPTIM_HandleTypeDef *hlptim) +{ + /* Check the parameters */ + assert_param(IS_LPTIM_INSTANCE(hlptim->Instance)); + + /* Set the LPTIM state */ + hlptim->State= HAL_LPTIM_STATE_BUSY; + + /* Disable the Peripheral */ + __HAL_LPTIM_DISABLE(hlptim); + + /* Reset TIMOUT bit to enable the timeout function */ + hlptim->Instance->CFGR &= ~LPTIM_CFGR_TIMOUT; + + /* Disable Autoreload write complete interrupt */ + __HAL_LPTIM_DISABLE_INTERRUPT(hlptim, LPTIM_IT_ARROK); + + /* Disable Compare write complete interrupt */ + __HAL_LPTIM_DISABLE_INTERRUPT(hlptim, LPTIM_IT_CMPOK); + + /* Disable Autoreload match interrupt */ + __HAL_LPTIM_DISABLE_INTERRUPT(hlptim, LPTIM_IT_ARRM); + + /* Disable Compare match interrupt */ + __HAL_LPTIM_DISABLE_INTERRUPT(hlptim, LPTIM_IT_CMPM); + + /* Disable external trigger interrupt */ + __HAL_LPTIM_DISABLE_INTERRUPT(hlptim, LPTIM_IT_EXTTRIG); + + /* Change the TIM state*/ + hlptim->State= HAL_LPTIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Starts the Counter mode. + * @param hlptim : LPTIM handle + * @param Period : Specifies the Autoreload value. + * This parameter must be a value between 0x0000 and 0xFFFF. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LPTIM_Counter_Start(LPTIM_HandleTypeDef *hlptim, uint32_t Period) +{ + /* Check the parameters */ + assert_param(IS_LPTIM_INSTANCE(hlptim->Instance)); + assert_param(IS_LPTIM_PERIOD(Period)); + + /* Set the LPTIM state */ + hlptim->State= HAL_LPTIM_STATE_BUSY; + + /* If clock source is not ULPTIM clock, then it must not be prescaled */ + if (hlptim->Init.Clock.Source != LPTIM_CLOCKSOURCE_ULPTIM) + { + /* Check if clock is prescaled */ + assert_param(IS_LPTIM_CLOCK_PRESCALERDIV1(hlptim->Init.Clock.Prescaler)); + /* Set clock prescaler to 0 */ + hlptim->Instance->CFGR &= ~LPTIM_CFGR_PRESC; + } + + /* Enable the Peripheral */ + __HAL_LPTIM_ENABLE(hlptim); + + /* Load the period value in the autoreload register */ + __HAL_LPTIM_AUTORELOAD_SET(hlptim, Period); + + /* Start timer in continuous mode */ + __HAL_LPTIM_START_CONTINUOUS(hlptim); + + /* Change the TIM state*/ + hlptim->State= HAL_LPTIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the Counter mode. + * @param hlptim : LPTIM handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LPTIM_Counter_Stop(LPTIM_HandleTypeDef *hlptim) +{ + /* Check the parameters */ + assert_param(IS_LPTIM_INSTANCE(hlptim->Instance)); + + /* Set the LPTIM state */ + hlptim->State= HAL_LPTIM_STATE_BUSY; + + /* Disable the Peripheral */ + __HAL_LPTIM_DISABLE(hlptim); + + /* Change the TIM state*/ + hlptim->State= HAL_LPTIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Starts the Counter mode in interrupt mode. + * @param hlptim : LPTIM handle + * @param Period : Specifies the Autoreload value. + * This parameter must be a value between 0x0000 and 0xFFFF. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LPTIM_Counter_Start_IT(LPTIM_HandleTypeDef *hlptim, uint32_t Period) +{ + /* Check the parameters */ + assert_param(IS_LPTIM_INSTANCE(hlptim->Instance)); + assert_param(IS_LPTIM_PERIOD(Period)); + + /* Set the LPTIM state */ + hlptim->State= HAL_LPTIM_STATE_BUSY; + + /* If clock source is not ULPTIM clock, then it must not be prescaled */ + if (hlptim->Init.Clock.Source != LPTIM_CLOCKSOURCE_ULPTIM) + { + /* Check if clock is prescaled */ + assert_param(IS_LPTIM_CLOCK_PRESCALERDIV1(hlptim->Init.Clock.Prescaler)); + /* Set clock prescaler to 0 */ + hlptim->Instance->CFGR &= ~LPTIM_CFGR_PRESC; + } + + /* Enable Autoreload write complete interrupt */ + __HAL_LPTIM_ENABLE_INTERRUPT(hlptim, LPTIM_IT_ARROK); + + /* Enable Autoreload match interrupt */ + __HAL_LPTIM_ENABLE_INTERRUPT(hlptim, LPTIM_IT_ARRM); + + /* Enable the Peripheral */ + __HAL_LPTIM_ENABLE(hlptim); + + /* Load the period value in the autoreload register */ + __HAL_LPTIM_AUTORELOAD_SET(hlptim, Period); + + /* Start timer in continuous mode */ + __HAL_LPTIM_START_CONTINUOUS(hlptim); + + /* Change the TIM state*/ + hlptim->State= HAL_LPTIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the Counter mode in interrupt mode. + * @param hlptim : LPTIM handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LPTIM_Counter_Stop_IT(LPTIM_HandleTypeDef *hlptim) +{ + /* Check the parameters */ + assert_param(IS_LPTIM_INSTANCE(hlptim->Instance)); + + /* Set the LPTIM state */ + hlptim->State= HAL_LPTIM_STATE_BUSY; + + /* Disable the Peripheral */ + __HAL_LPTIM_DISABLE(hlptim); + + /* Disable Autoreload write complete interrupt */ + __HAL_LPTIM_DISABLE_INTERRUPT(hlptim, LPTIM_IT_ARROK); + + /* Disable Autoreload match interrupt */ + __HAL_LPTIM_DISABLE_INTERRUPT(hlptim, LPTIM_IT_ARRM); + + /* Change the TIM state*/ + hlptim->State= HAL_LPTIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @} + */ + +/** @defgroup HAL_LPTIM_Group3 LPTIM Read operation functions + * @brief Read operation functions. + * +@verbatim + ============================================================================== + ##### LPTIM Reading operation functions ##### + ============================================================================== +[..] This section provides LPTIM Reading functions. + (+) Read the counter value. + (+) Read the period (Auto-reload) value. + (+) Read the pulse (Compare)value. +@endverbatim + * @{ + */ + +/** + * @brief This function returns the current counter value. + * @param hlptim: LPTIM handle + * @retval Counter value. + */ +uint32_t HAL_LPTIM_ReadCounter(LPTIM_HandleTypeDef *hlptim) +{ + /* Check the parameters */ + assert_param(IS_LPTIM_INSTANCE(hlptim->Instance)); + + return (hlptim->Instance->CNT); +} + +/** + * @brief This function return the current Autoreload (Period) value. + * @param hlptim: LPTIM handle + * @retval Autoreload value. + */ +uint32_t HAL_LPTIM_ReadAutoReload(LPTIM_HandleTypeDef *hlptim) +{ + /* Check the parameters */ + assert_param(IS_LPTIM_INSTANCE(hlptim->Instance)); + + return (hlptim->Instance->ARR); +} + +/** + * @brief This function return the current Compare (Pulse) value. + * @param hlptim: LPTIM handle + * @retval Compare value. + */ +uint32_t HAL_LPTIM_ReadCompare(LPTIM_HandleTypeDef *hlptim) +{ + /* Check the parameters */ + assert_param(IS_LPTIM_INSTANCE(hlptim->Instance)); + + return (hlptim->Instance->CMP); +} + +/** + * @} + */ + + + +/** @defgroup HAL_LPTIM_Group4 LPTIM IRQ handler + * @brief LPTIM IRQ handler. + * +@verbatim + ============================================================================== + ##### LPTIM IRQ handler ##### + ============================================================================== +[..] This section provides LPTIM IRQ handler function. + +@endverbatim + * @{ + */ + +/** + * @brief This function handles LPTIM interrupt request. + * @param hlptim: LPTIM handle + * @retval None + */ +void HAL_LPTIM_IRQHandler(LPTIM_HandleTypeDef *hlptim) +{ + /* Compare match interrupt */ + if(__HAL_LPTIM_GET_FLAG(hlptim, LPTIM_FLAG_CMPM) != RESET) + { + if(__HAL_LPTIM_GET_ITSTATUS(hlptim, LPTIM_IT_CMPM) !=RESET) + { + /* Clear Compare match flag */ + __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_CMPM); + + /* Compare match Callback */ + HAL_LPTIM_CompareMatchCallback(hlptim); + } + } + + /* Autoreload match interrupt */ + if(__HAL_LPTIM_GET_FLAG(hlptim, LPTIM_FLAG_ARRM) != RESET) + { + if(__HAL_LPTIM_GET_ITSTATUS(hlptim, LPTIM_IT_ARRM) !=RESET) + { + /* Clear Autoreload match flag */ + __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_ARRM); + + /* Autoreload match Callback */ + HAL_LPTIM_AutoReloadMatchCallback(hlptim); + } + } + + /* Trigger detected interrupt */ + if(__HAL_LPTIM_GET_FLAG(hlptim, LPTIM_FLAG_EXTTRIG) != RESET) + { + if(__HAL_LPTIM_GET_ITSTATUS(hlptim, LPTIM_IT_EXTTRIG) !=RESET) + { + /* Clear Trigger detected flag */ + __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_EXTTRIG); + + /* Trigger detected callback */ + HAL_LPTIM_TriggerCallback(hlptim); + } + } + + /* Compare write interrupt */ + if(__HAL_LPTIM_GET_FLAG(hlptim, LPTIM_FLAG_CMPOK) != RESET) + { + if(__HAL_LPTIM_GET_ITSTATUS(hlptim, LPTIM_IT_CMPOK) !=RESET) + { + /* Clear Compare write flag */ + __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_CMPOK); + + /* Compare write Callback */ + HAL_LPTIM_CompareWriteCallback(hlptim); + } + } + + /* Autoreload write interrupt */ + if(__HAL_LPTIM_GET_FLAG(hlptim, LPTIM_FLAG_ARROK) != RESET) + { + if(__HAL_LPTIM_GET_ITSTATUS(hlptim, LPTIM_IT_ARROK) !=RESET) + { + /* Clear Autoreload write flag */ + __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_ARROK); + + /* Autoreload write Callback */ + HAL_LPTIM_AutoReloadWriteCallback(hlptim); + } + } + + /* Direction counter changed from Down to Up interrupt */ + if(__HAL_LPTIM_GET_FLAG(hlptim, LPTIM_FLAG_UP) != RESET) + { + if(__HAL_LPTIM_GET_ITSTATUS(hlptim, LPTIM_IT_UP) !=RESET) + { + /* Clear Direction counter changed from Down to Up flag */ + __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_UP); + + /* Direction counter changed from Down to Up Callback */ + HAL_LPTIM_DirectionUpCallback(hlptim); + } + } + + /* Direction counter changed from Up to Down interrupt */ + if(__HAL_LPTIM_GET_FLAG(hlptim, LPTIM_FLAG_DOWN) != RESET) + { + if(__HAL_LPTIM_GET_ITSTATUS(hlptim, LPTIM_IT_DOWN) !=RESET) + { + /* Clear Direction counter changed from Up to Down flag */ + __HAL_LPTIM_CLEAR_FLAG(hlptim, LPTIM_FLAG_DOWN); + + /* Direction counter changed from Up to Down Callback */ + HAL_LPTIM_DirectionDownCallback(hlptim); + } + } +} + +/** + * @brief Compare match callback in non blocking mode + * @param hlptim : LPTIM handle + * @retval None + */ +__weak void HAL_LPTIM_CompareMatchCallback(LPTIM_HandleTypeDef *hlptim) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_LPTIM_CompareMatchCallback could be implemented in the user file + */ +} + +/** + * @brief Autoreload match callback in non blocking mode + * @param hlptim : LPTIM handle + * @retval None + */ +__weak void HAL_LPTIM_AutoReloadMatchCallback(LPTIM_HandleTypeDef *hlptim) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_LPTIM_AutoReloadMatchCallback could be implemented in the user file + */ +} + +/** + * @brief Trigger detected callback in non blocking mode + * @param hlptim : LPTIM handle + * @retval None + */ +__weak void HAL_LPTIM_TriggerCallback(LPTIM_HandleTypeDef *hlptim) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_LPTIM_TriggerCallback could be implemented in the user file + */ +} + +/** + * @brief Compare write callback in non blocking mode + * @param hlptim : LPTIM handle + * @retval None + */ +__weak void HAL_LPTIM_CompareWriteCallback(LPTIM_HandleTypeDef *hlptim) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_LPTIM_CompareWriteCallback could be implemented in the user file + */ +} + +/** + * @brief Autoreload write callback in non blocking mode + * @param hlptim : LPTIM handle + * @retval None + */ +__weak void HAL_LPTIM_AutoReloadWriteCallback(LPTIM_HandleTypeDef *hlptim) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_LPTIM_AutoReloadWriteCallback could be implemented in the user file + */ +} + +/** + * @brief Direction counter changed from Down to Up callback in non blocking mode + * @param hlptim : LPTIM handle + * @retval None + */ +__weak void HAL_LPTIM_DirectionUpCallback(LPTIM_HandleTypeDef *hlptim) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_LPTIM_DirectionUpCallback could be implemented in the user file + */ +} + +/** + * @brief Direction counter changed from Up to Down callback in non blocking mode + * @param hlptim : LPTIM handle + * @retval None + */ +__weak void HAL_LPTIM_DirectionDownCallback(LPTIM_HandleTypeDef *hlptim) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_LPTIM_DirectionDownCallback could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup HAL_LPTIM_Group5 Peripheral State functions + * @brief Peripheral State functions. + * +@verbatim + ============================================================================== + ##### Peripheral State functions ##### + ============================================================================== + [..] + This subsection permits to get in run-time the status of the peripheral. + +@endverbatim + * @{ + */ + +/** + * @brief Returns the LPTIM state. + * @param hlptim: LPTIM handle + * @retval HAL state + */ +HAL_LPTIM_StateTypeDef HAL_LPTIM_GetState(LPTIM_HandleTypeDef *hlptim) +{ + return hlptim->State; +} + +/** + * @} + */ + + +/** + * @} + */ + +#endif /* HAL_LPTIM_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_lptim.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_lptim.h new file mode 100644 index 0000000000..f172e1727e --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_lptim.h @@ -0,0 +1,615 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_lptim.h + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief Header file of LPTIM HAL module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32L0xx_HAL_LPTIM_H +#define __STM32L0xx_HAL_LPTIM_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal_def.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @addtogroup LPTIM + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ + +/** + * @brief LPTIM Clock configuration definition + */ +typedef struct +{ + uint32_t Source; /*!< Selects the clock source. + This parameter can be a value of @ref LPTIM_Clock_Source */ + + uint32_t Prescaler; /*!< Specifies the counter clock Prescaler. + This parameter can be a value of @ref LPTIM_Clock_Prescaler */ + +}LPTIM_ClockConfigTypeDef; + +/** + * @brief LPTIM Clock configuration definition + */ +typedef struct +{ + uint32_t Polarity; /*!< Selects the polarity of the active edge for the counter unit + if the ULPTIM input is selected. + Note: This parameter is used only when Ultra low power clock source is used. + Note: If the polarity is configured on 'both edges', an auxiliary clock + (one of the Low power oscillator) must be active. + This parameter can be a value of @ref LPTIM_Clock_Polarity */ + + uint32_t SampleTime; /*!< Selects the clock sampling time to configure the clock glitch filter. + Note: This parameter is used only when Ultra low power clock source is used. + This parameter can be a value of @ref LPTIM_Clock_Sample_Time */ + +}LPTIM_ULPClockConfigTypeDef; + +/** + * @brief LPTIM Trigger configuration definition + */ +typedef struct +{ + uint32_t Source; /*!< Selects the Trigger source. + This parameter can be a value of @ref LPTIM_Trigger_Source */ + + uint32_t ActiveEdge; /*!< Selects the Trigger active edge. + Note: This parameter is used only when an external trigger is used. + This parameter can be a value of @ref LPTIM_External_Trigger_Polarity */ + + uint32_t SampleTime; /*!< Selects the trigger sampling time to configure the clock glitch filter. + Note: This parameter is used only when an external trigger is used. + This parameter can be a value of @ref LPTIM_Trigger_Sample_Time */ +}LPTIM_TriggerConfigTypeDef; + +/** + * @brief LPTIM Initialization Structure definition + */ +typedef struct +{ + LPTIM_ClockConfigTypeDef Clock; /*!< Specifies the clock parameters */ + + LPTIM_ULPClockConfigTypeDef UltraLowPowerClock; /*!< Specifies the Ultra Low Power clock parameters */ + + LPTIM_TriggerConfigTypeDef Trigger; /*!< Specifies the Trigger parameters */ + + uint32_t OutputPolarity; /*!< Specifies the Output polarity. + This parameter can be a value of @ref LPTIM_Output_Polarity */ + + uint32_t UpdateMode; /*!< Specifies whether the update of the autorelaod and the compare + values is done immediately or after the end of current period. + This parameter can be a value of @ref LPTIM_Updating_Mode */ + + uint32_t CounterSource; /*!< Specifies whether the counter is incremented each internal event + or each external event. + This parameter can be a value of @ref LPTIM_Counter_Source */ + +}LPTIM_InitTypeDef; + +/** + * @brief HAL LPTIM State structure definition + */ +typedef enum __HAL_LPTIM_StateTypeDef +{ + HAL_LPTIM_STATE_RESET = 0x00, /*!< Peripheral not yet initialized or disabled */ + HAL_LPTIM_STATE_READY = 0x01, /*!< Peripheral Initialized and ready for use */ + HAL_LPTIM_STATE_BUSY = 0x02, /*!< An internal process is ongoing */ + HAL_LPTIM_STATE_TIMEOUT = 0x03, /*!< Timeout state */ + HAL_LPTIM_STATE_ERROR = 0x04 /*!< Internal Process is ongoing */ +}HAL_LPTIM_StateTypeDef; + +/** + * @brief LPTIM handle Structure definition + */ +typedef struct +{ + LPTIM_TypeDef *Instance; /*!< Register base address */ + + LPTIM_InitTypeDef Init; /*!< LPTIM required parameters */ + + HAL_StatusTypeDef Status; /*!< LPTIM peripheral status */ + + HAL_LockTypeDef Lock; /*!< LPTIM locking object */ + + __IO HAL_LPTIM_StateTypeDef State; /*!< LPTIM peripheral state */ + +}LPTIM_HandleTypeDef; + +/* Exported constants --------------------------------------------------------*/ + +/** @defgroup LPTIM_Exported_Constants + * @{ + */ + +/** @defgroup LPTIM_Autorelaod_Value + * @{ + */ +#define IS_LPTIM_AUTORELOAD(AUTORELOAD) ((AUTORELOAD) <= 0x0000FFFF) +/** + * @} + */ + +/** @defgroup LPTIM_Compare_Value + * @{ + */ +#define IS_LPTIM_COMPARE(COMPARE) ((COMPARE) <= 0x0000FFFF) +/** + * @} + */ + +/** @defgroup LPTIM_Clock_Source + * @{ + */ +#define LPTIM_CLOCKSOURCE_APBCLOCK_LPOSC ((uint32_t)0x00) +#define LPTIM_CLOCKSOURCE_ULPTIM LPTIM_CFGR_CKSEL + +#define IS_LPTIM_CLOCK_SOURCE(SOURCE) (((SOURCE) == LPTIM_CLOCKSOURCE_ULPTIM) || \ + ((SOURCE) == LPTIM_CLOCKSOURCE_APBCLOCK_LPOSC)) +/** + * @} + */ + +/** @defgroup LPTIM_Clock_Prescaler + * @{ + */ +#define LPTIM_PRESCALER_DIV1 ((uint32_t)0x000000) +#define LPTIM_PRESCALER_DIV2 LPTIM_CFGR_PRESC_0 +#define LPTIM_PRESCALER_DIV4 LPTIM_CFGR_PRESC_1 +#define LPTIM_PRESCALER_DIV8 ((uint32_t)(LPTIM_CFGR_PRESC_0 | LPTIM_CFGR_PRESC_1)) +#define LPTIM_PRESCALER_DIV16 LPTIM_CFGR_PRESC_2 +#define LPTIM_PRESCALER_DIV32 ((uint32_t)(LPTIM_CFGR_PRESC_0 | LPTIM_CFGR_PRESC_2)) +#define LPTIM_PRESCALER_DIV64 ((uint32_t)(LPTIM_CFGR_PRESC_1 | LPTIM_CFGR_PRESC_2)) +#define LPTIM_PRESCALER_DIV128 ((uint32_t)LPTIM_CFGR_PRESC) + +#define IS_LPTIM_CLOCK_PRESCALER(PRESCALER) (((PRESCALER) == LPTIM_PRESCALER_DIV1 ) || \ + ((PRESCALER) == LPTIM_PRESCALER_DIV2 ) || \ + ((PRESCALER) == LPTIM_PRESCALER_DIV4 ) || \ + ((PRESCALER) == LPTIM_PRESCALER_DIV8 ) || \ + ((PRESCALER) == LPTIM_PRESCALER_DIV16 ) || \ + ((PRESCALER) == LPTIM_PRESCALER_DIV32 ) || \ + ((PRESCALER) == LPTIM_PRESCALER_DIV64 ) || \ + ((PRESCALER) == LPTIM_PRESCALER_DIV128)) +#define IS_LPTIM_CLOCK_PRESCALERDIV1(PRESCALER) ((PRESCALER) == LPTIM_PRESCALER_DIV1) +/** + * @} + */ + +/** @defgroup LPTIM_Output_Polarity + * @{ + */ + +#define LPTIM_OUTPUTPOLARITY_HIGH ((uint32_t)0x00000000) +#define LPTIM_OUTPUTPOLARITY_LOW (LPTIM_CFGR_WAVPOL) +#define IS_LPTIM_OUTPUT_POLARITY(POLARITY) (((POLARITY) == LPTIM_OUTPUTPOLARITY_LOW ) || \ + ((POLARITY) == LPTIM_OUTPUTPOLARITY_HIGH)) +/** + * @} + */ + +/** @defgroup LPTIM_Clock_Sample_Time + * @{ + */ +#define LPTIM_CLOCKSAMPLETIME_DIRECTTRANSISTION ((uint32_t)0x00000000) +#define LPTIM_CLOCKSAMPLETIME_2TRANSISTIONS LPTIM_CFGR_CKFLT_0 +#define LPTIM_CLOCKSAMPLETIME_4TRANSISTIONS LPTIM_CFGR_CKFLT_1 +#define LPTIM_CLOCKSAMPLETIME_8TRANSISTIONS LPTIM_CFGR_CKFLT +#define IS_LPTIM_CLOCK_SAMPLE_TIME(SAMPLETIME) (((SAMPLETIME) == LPTIM_CLOCKSAMPLETIME_DIRECTTRANSISTION) || \ + ((SAMPLETIME) == LPTIM_CLOCKSAMPLETIME_2TRANSISTIONS) || \ + ((SAMPLETIME) == LPTIM_CLOCKSAMPLETIME_4TRANSISTIONS) || \ + ((SAMPLETIME) == LPTIM_CLOCKSAMPLETIME_8TRANSISTIONS)) +/** + * @} + */ + +/** @defgroup LPTIM_Clock_Polarity + * @{ + */ + +#define LPTIM_CLOCKPOLARITY_RISINGEDGE ((uint32_t)0x00000000) +#define LPTIM_CLOCKPOLARITY_FALLINGEDGE LPTIM_CFGR_CKPOL_0 +#define LPTIM_CLOCKPOLARITY_BOTHEDGES LPTIM_CFGR_CKPOL_1 +#define IS_LPTIM_CLOCK_POLARITY(POLARITY) (((POLARITY) == LPTIM_CLOCKPOLARITY_RISINGEDGE) || \ + ((POLARITY) == LPTIM_CLOCKPOLARITY_FALLINGEDGE) || \ + ((POLARITY) == LPTIM_CLOCKPOLARITY_BOTHEDGES)) + +/** + * @} + */ + +/** @defgroup LPTIM_Trigger_Source + * @{ + */ +#define LPTIM_TRIGSOURCE_SOFTWARE ((uint32_t)0x0000FFFF) +#define LPTIM_TRIGSOURCE_0 ((uint32_t)0x00000000) +#define LPTIM_TRIGSOURCE_1 ((uint32_t)LPTIM_CFGR_TRIGSEL_0) +#define LPTIM_TRIGSOURCE_2 LPTIM_CFGR_TRIGSEL_1 +#define LPTIM_TRIGSOURCE_3 ((uint32_t)LPTIM_CFGR_TRIGSEL_0 | LPTIM_CFGR_TRIGSEL_1) +#define LPTIM_TRIGSOURCE_4 LPTIM_CFGR_TRIGSEL_2 +#define LPTIM_TRIGSOURCE_6 ((uint32_t)LPTIM_CFGR_TRIGSEL_1 | LPTIM_CFGR_TRIGSEL_2) +#define LPTIM_TRIGSOURCE_7 LPTIM_CFGR_TRIGSEL +#define IS_LPTIM_TRG_SOURCE(TRIG) (((TRIG) == LPTIM_TRIGSOURCE_SOFTWARE) || \ + ((TRIG) == LPTIM_TRIGSOURCE_0) || \ + ((TRIG) == LPTIM_TRIGSOURCE_1) || \ + ((TRIG) == LPTIM_TRIGSOURCE_2) || \ + ((TRIG) == LPTIM_TRIGSOURCE_3) || \ + ((TRIG) == LPTIM_TRIGSOURCE_4) || \ + ((TRIG) == LPTIM_TRIGSOURCE_6) || \ + ((TRIG) == LPTIM_TRIGSOURCE_7)) +/** + * @} + */ + +/** @defgroup LPTIM_External_Trigger_Polarity + * @{ + */ +#define LPTIM_ACTIVEEDGE_RISING LPTIM_CFGR_TRIGEN_0 +#define LPTIM_ACTIVEEDGE_FALLING LPTIM_CFGR_TRIGEN_1 +#define LPTIM_ACTIVEEDGE_RISING_FALLING LPTIM_CFGR_TRIGEN +#define IS_LPTIM_EXT_TRG_POLARITY(POLAR) (((POLAR) == LPTIM_ACTIVEEDGE_RISING ) || \ + ((POLAR) == LPTIM_ACTIVEEDGE_FALLING ) || \ + ((POLAR) == LPTIM_ACTIVEEDGE_RISING_FALLING )) + +/** + * @} + */ + +/** @defgroup LPTIM_Trigger_Sample_Time + * @{ + */ +#define LPTIM_TRIGSAMPLETIME_DIRECTTRANSISTION ((uint32_t)0x00000000) +#define LPTIM_TRIGSAMPLETIME_2TRANSISTIONS LPTIM_CFGR_TRGFLT_0 +#define LPTIM_TRIGSAMPLETIME_4TRANSISTIONS LPTIM_CFGR_TRGFLT_1 +#define LPTIM_TRIGSAMPLETIME_8TRANSISTIONS LPTIM_CFGR_TRGFLT +#define IS_LPTIM_TRIG_SAMPLE_TIME(SAMPLETIME) (((SAMPLETIME) == LPTIM_TRIGSAMPLETIME_DIRECTTRANSISTION) || \ + ((SAMPLETIME) == LPTIM_TRIGSAMPLETIME_2TRANSISTIONS ) || \ + ((SAMPLETIME) == LPTIM_TRIGSAMPLETIME_4TRANSISTIONS ) || \ + ((SAMPLETIME) == LPTIM_TRIGSAMPLETIME_8TRANSISTIONS )) +/** + * @} + */ + +/** @defgroup LPTIM_Updating_Mode + * @{ + */ + +#define LPTIM_UPDATE_IMMEDIATE ((uint32_t)0x00000000) +#define LPTIM_UPDATE_ENDOFPERIOD LPTIM_CFGR_PRELOAD +#define IS_LPTIM_UPDATE_MODE(MODE) (((MODE) == LPTIM_UPDATE_IMMEDIATE) || \ + ((MODE) == LPTIM_UPDATE_ENDOFPERIOD)) + +/** + * @} + */ + +/** @defgroup LPTIM_Counter_Source + * @{ + */ + +#define LPTIM_COUNTERSOURCE_INTERNAL ((uint32_t)0x00000000) +#define LPTIM_COUNTERSOURCE_EXTERNAL LPTIM_CFGR_COUNTMODE +#define IS_LPTIM_COUNTER_SOURCE(SOURCE) (((SOURCE) == LPTIM_COUNTERSOURCE_INTERNAL) || \ + ((SOURCE) == LPTIM_COUNTERSOURCE_EXTERNAL)) + +/** + * @} + */ + +/** @defgroup LPTIM_Autorelaod_Value + * @{ + */ +#define IS_LPTIM_PERIOD(PERIOD) ((PERIOD) <= 0x0000FFFF) +/** + * @} + */ + +/** @defgroup LPTIM_Compare_Value + * @{ + */ +#define IS_LPTIM_PULSE(PULSE) ((PULSE) <= 0x0000FFFF) +/** + * @} + */ + +/** @defgroup LPTIM_Flag_Definition + * @{ + */ + +#define LPTIM_FLAG_DOWN LPTIM_ISR_DOWN +#define LPTIM_FLAG_UP LPTIM_ISR_UP +#define LPTIM_FLAG_ARROK LPTIM_ISR_ARROK +#define LPTIM_FLAG_CMPOK LPTIM_ISR_CMPOK +#define LPTIM_FLAG_EXTTRIG LPTIM_ISR_EXTTRIG +#define LPTIM_FLAG_ARRM LPTIM_ISR_ARRM +#define LPTIM_FLAG_CMPM LPTIM_ISR_CMPM +#define IS_LPTIM_FLAG_(FLAG) (((FLAG) == LPTIM_FLAG_DOWN) || \ + ((FLAG) == LPTIM_FLAG_UP) || \ + ((FLAG) == LPTIM_FLAG_ARROK) || \ + ((FLAG) == LPTIM_FLAG_CMPOK) || \ + ((FLAG) == LPTIM_FLAG_EXTTRIG) || \ + ((FLAG) == LPTIM_FLAG_ARRM) || \ + ((FLAG) == LPTIM_FLAG_CMPM)) +/** + * @} + */ +/** @defgroup LPTIM_Interrupts_Definition + * @{ + */ + +#define LPTIM_IT_DOWN LPTIM_IER_DOWNIE +#define LPTIM_IT_UP LPTIM_IER_UPIE +#define LPTIM_IT_ARROK LPTIM_IER_ARROKIE +#define LPTIM_IT_CMPOK LPTIM_IER_CMPOKIE +#define LPTIM_IT_EXTTRIG LPTIM_IER_EXTTRIGIE +#define LPTIM_IT_ARRM LPTIM_IER_ARRMIE +#define LPTIM_IT_CMPM LPTIM_IER_CMPMIE +#define IS_LPTIM_IT(IT) (((IT) == LPTIM_IT_DOWN) || \ + ((IT) == LPTIM_IT_UP) || \ + ((IT) == LPTIM_IT_ARROK) || \ + ((IT) == LPTIM_IT_CMPOK) || \ + ((IT) == LPTIM_IT_EXTTRIG) || \ + ((IT) == LPTIM_IT_ARRM) || \ + ((IT) == LPTIM_IT_CMPM)) +/** + * @} + */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ + +/** @brief Reset LPTIM handle state + * @param __HANDLE__: LPTIM handle + * @retval None + */ +#define __HAL_LPTIM_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_LPTIM_STATE_RESET) + +/** + * @brief Enable/Disable the LPTIM peripheral. + * @param __HANDLE__: LPTIM handle + * @retval None + */ +#define __HAL_LPTIM_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= (LPTIM_CR_ENABLE)) +#define __HAL_LPTIM_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~(LPTIM_CR_ENABLE)) + +/** + * @brief Starts the LPTIM peripheral in Continuous or in single mode. + * @param __HANDLE__: DMA handle + * @retval None + */ +#define __HAL_LPTIM_START_CONTINUOUS(__HANDLE__) ((__HANDLE__)->Instance->CR |= LPTIM_CR_CNTSTRT) +#define __HAL_LPTIM_START_SINGLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= LPTIM_CR_SNGSTRT) + + +/** + * @brief Writes the passed parameter in the Autoreload register. + * @param __HANDLE__: LPTIM handle + * @param __VALUE__ : Autoreload value + * @retval None + */ +#define __HAL_LPTIM_AUTORELOAD_SET(__HANDLE__ , __VALUE__) ((__HANDLE__)->Instance->ARR = (__VALUE__)) + +/** + * @brief Writes the passed parameter in the Compare register. + * @param __HANDLE__: LPTIM handle + * @param __VALUE__ : Compare value + * @retval None + */ +#define __HAL_LPTIM_COMPARE_SET(__HANDLE__ , __VALUE__) ((__HANDLE__)->Instance->CMP = (__VALUE__)) + +/** + * @brief Checks whether the specified LPTIM flag is set or not. + * @param __HANDLE__: LPTIM handle + * @param __FLAG__ : LPTIM flag to check + * This parameter can be a value of: + * @arg LPTIM_FLAG_DOWN : Counter direction change up Flag. + * @arg LPTIM_FLAG_UP : Counter direction change down to up Flag. + * @arg LPTIM_FLAG_ARROK : Autoreload register update OK Flag. + * @arg LPTIM_FLAG_CMPOK : Compare register update OK Flag. + * @arg LPTIM_FLAG_EXTTRIG : External trigger edge event Flag. + * @arg LPTIM_FLAG_ARRM : Autoreload match Flag. + * @arg LPTIM_FLAG_CMPM : Compare match Flag. + * @retval The state of the specified flag (SET or RESET). + */ +#define __HAL_LPTIM_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->ISR &(__FLAG__)) == (__FLAG__)) + +/** + * @brief Clears the specified LPTIM flag. + * @param __HANDLE__: LPTIM handle. + * @param __FLAG__ : LPTIM flag to clear. + * This parameter can be a value of: + * @arg LPTIM_FLAG_DOWN : Counter direction change up Flag. + * @arg LPTIM_FLAG_UP : Counter direction change down to up Flag. + * @arg LPTIM_FLAG_ARROK : Autoreload register update OK Flag. + * @arg LPTIM_FLAG_CMPOK : Compare register update OK Flag. + * @arg LPTIM_FLAG_EXTTRIG : External trigger edge event Flag. + * @arg LPTIM_FLAG_ARRM : Autoreload match Flag. + * @arg LPTIM_FLAG_CMPM : Compare match Flag. + * @retval None. + */ +#define __HAL_LPTIM_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->ICR |= (__FLAG__)) + +/** + * @brief Enable the specified LPTIM interrupt. + * @param __HANDLE__ : LPTIM handle. + * @param __INTERRUPT__ : LPTIM interrupt to set. + * This parameter can be a value of: + * @arg LPTIM_IT_DOWN : Counter direction change up Interrupt. + * @arg LPTIM_IT_UP : Counter direction change down to up Interrupt. + * @arg LPTIM_IT_ARROK : Autoreload register update OK Interrupt. + * @arg LPTIM_IT_CMPOK : Compare register update OK Interrupt. + * @arg LPTIM_IT_EXTTRIG : External trigger edge event Interrupt. + * @arg LPTIM_IT_ARRM : Autoreload match Interrupt. + * @arg LPTIM_IT_CMPM : Compare match Interrupt. + * @retval None. + */ +#define __HAL_LPTIM_ENABLE_INTERRUPT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->IER |= (__INTERRUPT__)) + + /** + * @brief Disable the specified LPTIM interrupt. + * @param __HANDLE__ : LPTIM handle. + * @param __INTERRUPT__ : LPTIM interrupt to set. + * This parameter can be a value of: + * @arg LPTIM_IT_DOWN : Counter direction change up Interrupt. + * @arg LPTIM_IT_UP : Counter direction change down to up Interrupt. + * @arg LPTIM_IT_ARROK : Autoreload register update OK Interrupt. + * @arg LPTIM_IT_CMPOK : Compare register update OK Interrupt. + * @arg LPTIM_IT_EXTTRIG : External trigger edge event Interrupt. + * @arg LPTIM_IT_ARRM : Autoreload match Interrupt. + * @arg LPTIM_IT_CMPM : Compare match Interrupt. + * @retval None. + */ +#define __HAL_LPTIM_DISABLE_INTERRUPT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->IER &= (~(__INTERRUPT__))) + + /** + * @brief Checks whether the specified LPTIM interrupt is set or not. + * @param __HANDLE__ : LPTIM handle. + * @param __INTERRUPT__ : LPTIM interrupt to check. + * This parameter can be a value of: + * @arg LPTIM_IT_DOWN : Counter direction change up Interrupt. + * @arg LPTIM_IT_UP : Counter direction change down to up Interrupt. + * @arg LPTIM_IT_ARROK : Autoreload register update OK Interrupt. + * @arg LPTIM_IT_CMPOK : Compare register update OK Interrupt. + * @arg LPTIM_IT_EXTTRIG : External trigger edge event Interrupt. + * @arg LPTIM_IT_ARRM : Autoreload match Interrupt. + * @arg LPTIM_IT_CMPM : Compare match Interrupt. + * @retval Interrupt status. + */ + +#define __HAL_LPTIM_GET_ITSTATUS(__HANDLE__, __INTERRUPT__) ((((__HANDLE__)->Instance->IER & (__INTERRUPT__)) == (__INTERRUPT__)) ? SET : RESET) +/* Exported functions --------------------------------------------------------*/ +/* Initialization/de-initialization functions ********************************/ +HAL_StatusTypeDef HAL_LPTIM_Init(LPTIM_HandleTypeDef *hlptim); +HAL_StatusTypeDef HAL_LPTIM_DeInit(LPTIM_HandleTypeDef *hlptim); + +/* MSP functions *************************************************************/ +void HAL_LPTIM_MspInit(LPTIM_HandleTypeDef *hlptim); +void HAL_LPTIM_MspDeInit(LPTIM_HandleTypeDef *hlptim); + +/* Start/Stop operation functions *********************************************/ +/* ################################# PWM Mode ################################*/ +/* Blocking mode: Polling */ +HAL_StatusTypeDef HAL_LPTIM_PWM_Start(LPTIM_HandleTypeDef *hlptim, uint32_t Period, uint32_t Pulse); +HAL_StatusTypeDef HAL_LPTIM_PWM_Stop(LPTIM_HandleTypeDef *hlptim); +/* Non-Blocking mode: Interrupt */ +HAL_StatusTypeDef HAL_LPTIM_PWM_Start_IT(LPTIM_HandleTypeDef *hlptim, uint32_t Period, uint32_t Pulse); +HAL_StatusTypeDef HAL_LPTIM_PWM_Stop_IT(LPTIM_HandleTypeDef *hlptim); + +/* ############################# One Pulse Mode ##############################*/ +/* Blocking mode: Polling */ +HAL_StatusTypeDef HAL_LPTIM_OnePulse_Start(LPTIM_HandleTypeDef *hlptim, uint32_t Period, uint32_t Pulse); +HAL_StatusTypeDef HAL_LPTIM_OnePulse_Stop(LPTIM_HandleTypeDef *hlptim); +/* Non-Blocking mode: Interrupt */ +HAL_StatusTypeDef HAL_LPTIM_OnePulse_Start_IT(LPTIM_HandleTypeDef *hlptim, uint32_t Period, uint32_t Pulse); +HAL_StatusTypeDef HAL_LPTIM_OnePulse_Stop_IT(LPTIM_HandleTypeDef *hlptim); + +/* ############################## Set once Mode ##############################*/ +/* Blocking mode: Polling */ +HAL_StatusTypeDef HAL_LPTIM_SetOnce_Start(LPTIM_HandleTypeDef *hlptim, uint32_t Period, uint32_t Pulse); +HAL_StatusTypeDef HAL_LPTIM_SetOnce_Stop(LPTIM_HandleTypeDef *hlptim); +/* Non-Blocking mode: Interrupt */ +HAL_StatusTypeDef HAL_LPTIM_SetOnce_Start_IT(LPTIM_HandleTypeDef *hlptim, uint32_t Period, uint32_t Pulse); +HAL_StatusTypeDef HAL_LPTIM_SetOnce_Stop_IT(LPTIM_HandleTypeDef *hlptim); + +/* ############################### Encoder Mode ##############################*/ +/* Blocking mode: Polling */ +HAL_StatusTypeDef HAL_LPTIM_Encoder_Start(LPTIM_HandleTypeDef *hlptim, uint32_t Period); +HAL_StatusTypeDef HAL_LPTIM_Encoder_Stop(LPTIM_HandleTypeDef *hlptim); +/* Non-Blocking mode: Interrupt */ +HAL_StatusTypeDef HAL_LPTIM_Encoder_Start_IT(LPTIM_HandleTypeDef *hlptim, uint32_t Period); +HAL_StatusTypeDef HAL_LPTIM_Encoder_Stop_IT(LPTIM_HandleTypeDef *hlptim); + +/* ############################# Time out Mode ##############################*/ +/* Blocking mode: Polling */ +HAL_StatusTypeDef HAL_LPTIM_TimeOut_Start(LPTIM_HandleTypeDef *hlptim, uint32_t Period, uint32_t Timeout); +HAL_StatusTypeDef HAL_LPTIM_TimeOut_Stop(LPTIM_HandleTypeDef *hlptim); +/* Non-Blocking mode: Interrupt */ +HAL_StatusTypeDef HAL_LPTIM_TimeOut_Start_IT(LPTIM_HandleTypeDef *hlptim, uint32_t Period, uint32_t Timeout); +HAL_StatusTypeDef HAL_LPTIM_TimeOut_Stop_IT(LPTIM_HandleTypeDef *hlptim); + +/* ############################## Counter Mode ###############################*/ +/* Blocking mode: Polling */ +HAL_StatusTypeDef HAL_LPTIM_Counter_Start(LPTIM_HandleTypeDef *hlptim, uint32_t Period); +HAL_StatusTypeDef HAL_LPTIM_Counter_Stop(LPTIM_HandleTypeDef *hlptim); +/* Non-Blocking mode: Interrupt */ +HAL_StatusTypeDef HAL_LPTIM_Counter_Start_IT(LPTIM_HandleTypeDef *hlptim, uint32_t Period); +HAL_StatusTypeDef HAL_LPTIM_Counter_Stop_IT(LPTIM_HandleTypeDef *hlptim); + +/* Reading operation functions ************************************************/ +uint32_t HAL_LPTIM_ReadCounter(LPTIM_HandleTypeDef *hlptim); +uint32_t HAL_LPTIM_ReadAutoReload(LPTIM_HandleTypeDef *hlptim); +uint32_t HAL_LPTIM_ReadCompare(LPTIM_HandleTypeDef *hlptim); + +/* LPTIM IRQ functions *******************************************************/ +void HAL_LPTIM_IRQHandler(LPTIM_HandleTypeDef *hlptim); + +/* CallBack functions ********************************************************/ +void HAL_LPTIM_CompareMatchCallback(LPTIM_HandleTypeDef *hlptim); +void HAL_LPTIM_AutoReloadMatchCallback(LPTIM_HandleTypeDef *hlptim); +void HAL_LPTIM_TriggerCallback(LPTIM_HandleTypeDef *hlptim); +void HAL_LPTIM_CompareWriteCallback(LPTIM_HandleTypeDef *hlptim); +void HAL_LPTIM_AutoReloadWriteCallback(LPTIM_HandleTypeDef *hlptim); +void HAL_LPTIM_DirectionUpCallback(LPTIM_HandleTypeDef *hlptim); +void HAL_LPTIM_DirectionDownCallback(LPTIM_HandleTypeDef *hlptim); + +/* Peripheral State functions ************************************************/ +HAL_LPTIM_StateTypeDef HAL_LPTIM_GetState(LPTIM_HandleTypeDef *hlptim); + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __STM32L0xx_HAL_LPTIM_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_pcd.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_pcd.c new file mode 100644 index 0000000000..476745a469 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_pcd.c @@ -0,0 +1,1307 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_pcd.c + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief PCD HAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the USB Peripheral Controller: + * + Initialization and de-initialization functions + * + IO operation functions + * + Peripheral Control functions + * + Peripheral State functions + * + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + The PCD HAL driver can be used as follows: + + (#) Declare a PCD_HandleTypeDef handle structure, for example: + PCD_HandleTypeDef hpcd; + + (#) Fill parameters of Init structure in HCD handle + + (#) Call HAL_PCD_Init() API to initialize the HCD peripheral (Core, Device core, ...) + + (#) Initialize the PCD low level resources through the HAL_PCD_MspInit() API: + (##) Enable the PCD/USB Low Level interface clock using + (+++) __USB_CLK_ENABLE); + + (##) Initialize the related GPIO clocks + (##) Configure PCD pin-out + (##) Configure PCD NVIC interrupt + + (#)Associate the Upper USB device stack to the HAL PCD Driver: + (##) hpcd.pData = pdev; + + (#)Enable HCD transmission and reception: + (##) HAL_PCD_Start(); + + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @defgroup PCD + * @brief PCD HAL module driver + * @{ + */ + +#ifdef HAL_PCD_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +#define BTABLE_ADDRESS (0x000) +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +static HAL_StatusTypeDef PCD_EP_ISR_Handler(PCD_HandleTypeDef *hpcd); +void PCD_WritePMA(USB_TypeDef *USBx, uint8_t *pbUsrBuf, uint16_t wPMABufAddr, uint16_t wNBytes); +void PCD_ReadPMA(USB_TypeDef *USBx, uint8_t *pbUsrBuf, uint16_t wPMABufAddr, uint16_t wNBytes); +/* Private functions ---------------------------------------------------------*/ + + +/** @defgroup PCD_Private_Functions + * @{ + */ + +/** @defgroup PCD_Group1 Initialization and de-initialization functions + * @brief Initialization and Configuration functions + * +@verbatim + =============================================================================== + ##### Initialization and de-initialization functions ##### + =============================================================================== + [..] This section provides functions allowing to: + +@endverbatim + * @{ + */ + +/** + * @brief Initializes the PCD according to the specified + * parameters in the PCD_InitTypeDef and create the associated handle. + * @param hpcd: PCD handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_Init(PCD_HandleTypeDef *hpcd) +{ + uint32_t i = 0; + + uint32_t wInterrupt_Mask = 0; + + /* Check the PCD handle allocation */ + if(hpcd == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_PCD_ALL_INSTANCE(hpcd->Instance)); + + hpcd->State = PCD_BUSY; + + /* Init the low level hardware : GPIO, CLOCK, NVIC... */ + HAL_PCD_MspInit(hpcd); + + /* Init endpoints structures */ + for (i = 0; i < hpcd->Init.dev_endpoints ; i++) + { + /* Init ep structure */ + hpcd->IN_ep[i].is_in = 1; + hpcd->IN_ep[i].num = i; + /* Control until ep is actvated */ + hpcd->IN_ep[i].type = PCD_EP_TYPE_CTRL; + hpcd->IN_ep[i].maxpacket = 0; + hpcd->IN_ep[i].xfer_buff = 0; + hpcd->IN_ep[i].xfer_len = 0; + } + + for (i = 0; i < hpcd->Init.dev_endpoints ; i++) + { + hpcd->OUT_ep[i].is_in = 0; + hpcd->OUT_ep[i].num = i; + /* Control until ep is activated */ + hpcd->OUT_ep[i].type = PCD_EP_TYPE_CTRL; + hpcd->OUT_ep[i].maxpacket = 0; + hpcd->OUT_ep[i].xfer_buff = 0; + hpcd->OUT_ep[i].xfer_len = 0; + } + + /* Init Device */ + /*CNTR_FRES = 1*/ + hpcd->Instance->CNTR = USB_CNTR_FRES; + + /*CNTR_FRES = 0*/ + hpcd->Instance->CNTR = 0; + + /*Clear pending interrupts*/ + hpcd->Instance->ISTR = 0; + + /*Set Btable Adress*/ + hpcd->Instance->BTABLE = BTABLE_ADDRESS; + + /*set wInterrupt_Mask global variable*/ + wInterrupt_Mask = USB_CNTR_CTRM | USB_CNTR_WKUPM | USB_CNTR_SUSPM | USB_CNTR_ERRM \ + | USB_CNTR_ESOFM | USB_CNTR_RESETM; + + /*Set interrupt mask*/ + hpcd->Instance->CNTR = wInterrupt_Mask; + + hpcd->USB_Address = 0; + hpcd->State= PCD_READY; + + return HAL_OK; +} + +/** + * @brief DeInitializes the PCD peripheral + * @param hpcd: PCD handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_DeInit(PCD_HandleTypeDef *hpcd) +{ + /* Check the PCD handle allocation */ + if(hpcd == NULL) + { + return HAL_ERROR; + } + + hpcd->State = PCD_BUSY; + + /* Stop Device */ + HAL_PCD_Stop(hpcd); + + /* DeInit the low level hardware */ + HAL_PCD_MspDeInit(hpcd); + + hpcd->State = PCD_READY; + + return HAL_OK; +} + +/** + * @brief Initializes the PCD MSP. + * @param hpcd: PCD handle + * @retval None + */ +__weak void HAL_PCD_MspInit(PCD_HandleTypeDef *hpcd) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_PCD_MspInit could be implenetd in the user file + */ +} + +/** + * @brief DeInitializes PCD MSP. + * @param hpcd: PCD handle + * @retval None + */ +__weak void HAL_PCD_MspDeInit(PCD_HandleTypeDef *hpcd) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_PCD_MspDeInit could be implenetd in the user file + */ +} + +/** + * @} + */ + +/** @defgroup PCD_Group2 IO operation functions + * @brief Data transfers functions + * +@verbatim + =============================================================================== + ##### IO operation functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to manage the PCD data + transfers. + +@endverbatim + * @{ + */ + +/** + * @brief Start The USB OTG Device. + * @param hpcd: PCD handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_Start(PCD_HandleTypeDef *hpcd) +{ + /* Enabling DP Pull-Down bit to Connect internal pull-up on USB DP line */ + hpcd->Instance->BCDR |= USB_BCDR_DPPU; + + return HAL_OK; +} + +/** + * @brief Stop The USB OTG Device. + * @param hpcd: PCD handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_Stop(PCD_HandleTypeDef *hpcd) +{ + __HAL_LOCK(hpcd); + + /* disable all interrupts and force USB reset */ + hpcd->Instance->CNTR = USB_CNTR_FRES; + + /* clear interrupt status register */ + hpcd->Instance->ISTR = 0; + + /* switch-off device */ + hpcd->Instance->CNTR = (USB_CNTR_FRES | USB_CNTR_PDWN); + + __HAL_UNLOCK(hpcd); + return HAL_OK; +} + +/** + * @brief This function handles PCD Endpoint interrupt request. + * @param hpcd: PCD handle + * @retval HAL status + */ +static HAL_StatusTypeDef PCD_EP_ISR_Handler(PCD_HandleTypeDef *hpcd) +{ + PCD_EPTypeDef *ep; + uint16_t count=0; + uint8_t EPindex; + __IO uint16_t wIstr; + __IO uint16_t wEPVal = 0; + + /* stay in loop while pending interrupts */ + while (((wIstr = hpcd->Instance->ISTR) & USB_ISTR_CTR) != 0) + { + /* extract highest priority endpoint number */ + EPindex = (uint8_t)(wIstr & USB_ISTR_EP_ID); + + if (EPindex == 0) + { + /* Decode and service control endpoint interrupt */ + + /* DIR bit = origin of the interrupt */ + if ((wIstr & USB_ISTR_DIR) == 0) + { + /* DIR = 0 */ + + /* DIR = 0 => IN int */ + /* DIR = 0 implies that (EP_CTR_TX = 1) always */ + PCD_CLEAR_TX_EP_CTR(hpcd->Instance, PCD_ENDP0); + ep = &hpcd->IN_ep[0]; + + ep->xfer_count = PCD_GET_EP_TX_CNT(hpcd->Instance, ep->num); + ep->xfer_buff += ep->xfer_count; + + /* TX COMPLETE */ + HAL_PCD_DataInStageCallback(hpcd, 0); + + + if((hpcd->USB_Address > 0)&& ( ep->xfer_len == 0)) + { + hpcd->Instance->DADDR = (hpcd->USB_Address | USB_DADDR_EF); + hpcd->USB_Address = 0; + } + + } + else + { + /* DIR = 1 */ + + /* DIR = 1 & CTR_RX => SETUP or OUT int */ + /* DIR = 1 & (CTR_TX | CTR_RX) => 2 int pending */ + ep = &hpcd->OUT_ep[0]; + wEPVal = PCD_GET_ENDPOINT(hpcd->Instance, PCD_ENDP0); + + if ((wEPVal & USB_EP_SETUP) != 0) + { + /* Get SETUP Packet*/ + ep->xfer_count = PCD_GET_EP_RX_CNT(hpcd->Instance, ep->num); + PCD_ReadPMA(hpcd->Instance, (uint8_t*)hpcd->Setup ,ep->pmaadress , ep->xfer_count); + /* SETUP bit kept frozen while CTR_RX = 1*/ + PCD_CLEAR_RX_EP_CTR(hpcd->Instance, PCD_ENDP0); + + /* Process SETUP Packet*/ + HAL_PCD_SetupStageCallback(hpcd); + } + + else if ((wEPVal & USB_EP_CTR_RX) != 0) + { + PCD_CLEAR_RX_EP_CTR(hpcd->Instance, PCD_ENDP0); + /* Get Control Data OUT Packet*/ + ep->xfer_count = PCD_GET_EP_RX_CNT(hpcd->Instance, ep->num); + + if (ep->xfer_count != 0) + { + PCD_ReadPMA(hpcd->Instance, ep->xfer_buff, ep->pmaadress, ep->xfer_count); + ep->xfer_buff+=ep->xfer_count; + } + + /* Process Control Data OUT Packet*/ + HAL_PCD_DataOutStageCallback(hpcd, 0); + + PCD_SET_EP_RX_CNT(hpcd->Instance, PCD_ENDP0, ep->maxpacket); + PCD_SET_EP_RX_STATUS(hpcd->Instance, PCD_ENDP0, USB_EP_RX_VALID); + } + } + } + else + { + + /* Decode and service non control endpoints interrupt */ + + /* process related endpoint register */ + wEPVal = PCD_GET_ENDPOINT(hpcd->Instance, EPindex); + if ((wEPVal & USB_EP_CTR_RX) != 0) + { + /* clear int flag */ + PCD_CLEAR_RX_EP_CTR(hpcd->Instance, EPindex); + ep = &hpcd->OUT_ep[EPindex]; + + /* OUT double Buffering*/ + if (ep->doublebuffer == 0) + { + count = PCD_GET_EP_RX_CNT(hpcd->Instance, ep->num); + if (count != 0) + { + PCD_ReadPMA(hpcd->Instance, ep->xfer_buff, ep->pmaadress, count); + } + } + else + { + if (PCD_GET_ENDPOINT(hpcd->Instance, ep->num) & USB_EP_DTOG_RX) + { + /*read from endpoint BUF0Addr buffer*/ + count = PCD_GET_EP_DBUF0_CNT(hpcd->Instance, ep->num); + if (count != 0) + { + PCD_ReadPMA(hpcd->Instance, ep->xfer_buff, ep->pmaaddr0, count); + } + } + else + { + /*read from endpoint BUF1Addr buffer*/ + count = PCD_GET_EP_DBUF1_CNT(hpcd->Instance, ep->num); + if (count != 0) + { + PCD_ReadPMA(hpcd->Instance, ep->xfer_buff, ep->pmaaddr1, count); + } + } + PCD_FreeUserBuffer(hpcd->Instance, ep->num, PCD_EP_DBUF_OUT); + } + /*multi-packet on the NON control OUT endpoint*/ + ep->xfer_count+=count; + ep->xfer_buff+=count; + + if ((ep->xfer_len == 0) || (count < ep->maxpacket)) + { + /* RX COMPLETE */ + HAL_PCD_DataOutStageCallback(hpcd, ep->num); + } + else + { + HAL_PCD_EP_Receive(hpcd, ep->num, ep->xfer_buff, ep->xfer_len); + } + + } /* if((wEPVal & EP_CTR_RX) */ + + if ((wEPVal & USB_EP_CTR_TX) != 0) + { + ep = &hpcd->IN_ep[EPindex]; + + /* clear int flag */ + PCD_CLEAR_TX_EP_CTR(hpcd->Instance, EPindex); + + /* IN double Buffering*/ + if (ep->doublebuffer == 0) + { + ep->xfer_count = PCD_GET_EP_TX_CNT(hpcd->Instance, ep->num); + if (ep->xfer_count != 0) + { + PCD_WritePMA(hpcd->Instance, ep->xfer_buff, ep->pmaadress, ep->xfer_count); + } + } + else + { + if (PCD_GET_ENDPOINT(hpcd->Instance, ep->num) & USB_EP_DTOG_TX) + { + /*read from endpoint BUF0Addr buffer*/ + ep->xfer_count = PCD_GET_EP_DBUF0_CNT(hpcd->Instance, ep->num); + if (ep->xfer_count != 0) + { + PCD_WritePMA(hpcd->Instance, ep->xfer_buff, ep->pmaaddr0, ep->xfer_count); + } + } + else + { + /*read from endpoint BUF1Addr buffer*/ + ep->xfer_count = PCD_GET_EP_DBUF1_CNT(hpcd->Instance, ep->num); + if (ep->xfer_count != 0) + { + PCD_WritePMA(hpcd->Instance, ep->xfer_buff, ep->pmaaddr1, ep->xfer_count); + } + } + PCD_FreeUserBuffer(hpcd->Instance, ep->num, PCD_EP_DBUF_IN); + } + /*multi-packet on the NON control IN endpoint*/ + ep->xfer_count = PCD_GET_EP_TX_CNT(hpcd->Instance, ep->num); + ep->xfer_buff+=ep->xfer_count; + + /* Zero Length Packet? */ + if (ep->xfer_len == 0) + { + /* TX COMPLETE */ + HAL_PCD_DataInStageCallback(hpcd, ep->num); + } + else + { + HAL_PCD_EP_Transmit(hpcd, ep->num, ep->xfer_buff, ep->xfer_len); + } + } + } + } + return HAL_OK; +} +/** + * @brief This function handles PCD interrupt request. + * @param hpcd: PCD handle + * @retval HAL status + */ +void HAL_PCD_IRQHandler(PCD_HandleTypeDef *hpcd) +{ + uint32_t wInterrupt_Mask = 0; + + if (__HAL_PCD_GET_FLAG (hpcd, USB_ISTR_CTR)) + { + /* servicing of the endpoint correct transfer interrupt */ + /* clear of the CTR flag into the sub */ + PCD_EP_ISR_Handler(hpcd); + } + + if (__HAL_PCD_GET_FLAG (hpcd, USB_ISTR_RESET)) + { + __HAL_PCD_CLEAR_FLAG(hpcd, USB_ISTR_RESET); + HAL_PCD_ResetCallback(hpcd); + HAL_PCD_SetAddress(hpcd, 0); + } + + if (__HAL_PCD_GET_FLAG (hpcd, USB_ISTR_PMAOVR)) + { + __HAL_PCD_CLEAR_FLAG(hpcd, USB_ISTR_PMAOVR); + } + + if (__HAL_PCD_GET_FLAG (hpcd, USB_ISTR_ERR)) + { + __HAL_PCD_CLEAR_FLAG(hpcd, USB_ISTR_ERR); + } + + if (__HAL_PCD_GET_FLAG (hpcd, USB_ISTR_WKUP)) + { + + hpcd->Instance->CNTR &= ~(USB_CNTR_LPMODE); + + /*set wInterrupt_Mask global variable*/ + wInterrupt_Mask = USB_CNTR_CTRM | USB_CNTR_WKUPM | USB_CNTR_SUSPM | USB_CNTR_ERRM \ + | USB_CNTR_ESOFM | USB_CNTR_RESETM; + + /*Set interrupt mask*/ + hpcd->Instance->CNTR = wInterrupt_Mask; + + HAL_PCD_ResumeCallback(hpcd); + + __HAL_PCD_CLEAR_FLAG(hpcd, USB_ISTR_WKUP); + } + + if (__HAL_PCD_GET_FLAG (hpcd, USB_ISTR_SUSP)) + { + /* clear of the ISTR bit must be done after setting of CNTR_FSUSP */ + __HAL_PCD_CLEAR_FLAG(hpcd, USB_ISTR_SUSP); + + /* Force low-power mode in the macrocell */ + hpcd->Instance->CNTR |= USB_CNTR_FSUSP; + hpcd->Instance->CNTR |= USB_CNTR_LPMODE; + + if (__HAL_PCD_GET_FLAG (hpcd, USB_ISTR_WKUP) == 0) + { + HAL_PCD_SuspendCallback(hpcd); + } + } + + if (__HAL_PCD_GET_FLAG (hpcd, USB_ISTR_SOF)) + { + __HAL_PCD_CLEAR_FLAG(hpcd, USB_ISTR_SOF); + HAL_PCD_SOFCallback(hpcd); + } + + if (__HAL_PCD_GET_FLAG (hpcd, USB_ISTR_ESOF)) + { + /* clear ESOF flag in ISTR */ + __HAL_PCD_CLEAR_FLAG(hpcd, USB_ISTR_ESOF); + } +} + +/** + * @brief Data out stage callbacks + * @param hpcd: PCD handle + * @retval None + */ + __weak void HAL_PCD_DataOutStageCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_PCD_DataOutStageCallback could be implenetd in the user file + */ +} + +/** + * @brief Data IN stage callbacks + * @param hpcd: PCD handle + * @retval None + */ + __weak void HAL_PCD_DataInStageCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_PCD_DataOutStageCallback could be implenetd in the user file + */ +} +/** + * @brief Setup stage callback + * @param hpcd: ppp handle + * @retval None + */ + __weak void HAL_PCD_SetupStageCallback(PCD_HandleTypeDef *hpcd) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_PCD_DataOutStageCallback could be implenetd in the user file + */ +} + +/** + * @brief USB Start Of Frame callbacks + * @param hpcd: PCD handle + * @retval None + */ + __weak void HAL_PCD_SOFCallback(PCD_HandleTypeDef *hpcd) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_PCD_DataOutStageCallback could be implenetd in the user file + */ +} + +/** + * @brief USB Reset callbacks + * @param hpcd: PCD handle + * @retval None + */ + __weak void HAL_PCD_ResetCallback(PCD_HandleTypeDef *hpcd) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_PCD_DataOutStageCallback could be implenetd in the user file + */ +} + + +/** + * @brief Suspend event callbacks + * @param hpcd: PCD handle + * @retval None + */ + __weak void HAL_PCD_SuspendCallback(PCD_HandleTypeDef *hpcd) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_PCD_DataOutStageCallback could be implenetd in the user file + */ +} + +/** + * @brief Resume event callbacks + * @param hpcd: PCD handle + * @retval None + */ + __weak void HAL_PCD_ResumeCallback(PCD_HandleTypeDef *hpcd) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_PCD_DataOutStageCallback could be implenetd in the user file + */ +} + +/** + * @brief Incomplete ISO OUT callbacks + * @param hpcd: PCD handle + * @retval None + */ + __weak void HAL_PCD_ISOOUTIncompleteCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_PCD_DataOutStageCallback could be implenetd in the user file + */ +} + +/** + * @brief Incomplete ISO IN callbacks + * @param hpcd: PCD handle + * @retval None + */ + __weak void HAL_PCD_ISOINIncompleteCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_PCD_DataOutStageCallback could be implenetd in the user file + */ +} + +/** + * @brief Connection event callbacks + * @param hpcd: PCD handle + * @retval None + */ + __weak void HAL_PCD_ConnectCallback(PCD_HandleTypeDef *hpcd) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_PCD_DataOutStageCallback could be implenetd in the user file + */ +} + +/** + * @brief Disconnection event callbacks + * @param hpcd: ppp handle + * @retval None + */ + __weak void HAL_PCD_DisconnectCallback(PCD_HandleTypeDef *hpcd) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_PCD_DataOutStageCallback could be implenetd in the user file + */ +} + +/** + * @} + */ + +/** @defgroup PCD_Group3 Peripheral Control functions + * @brief management functions + * +@verbatim + =============================================================================== + ##### Peripheral Control functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to control the PCD data + transfers. + +@endverbatim + * @{ + */ + +/** + * @brief Send an amount of data in blocking mode + * @param hpcd: PCD handle + * @param pData: pointer to data buffer + * @param Size: amount of data to be sent + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_DevConnect(PCD_HandleTypeDef *hpcd) +{ + __HAL_LOCK(hpcd); + + /* Enabling DP Pull-Down bit to Connect internal pull-up on USB DP line */ + hpcd->Instance->BCDR |= USB_BCDR_DPPU; + + __HAL_UNLOCK(hpcd); + return HAL_OK; +} + +/** + * @brief Send an amount of data in blocking mode + * @param hpcd: PCD handle + * @param pData: pointer to data buffer + * @param Size: amount of data to be sent + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_DevDisconnect(PCD_HandleTypeDef *hpcd) +{ + __HAL_LOCK(hpcd); + + /* Disable DP Pull-Down bit*/ + hpcd->Instance->BCDR &= ~(USB_BCDR_DPPU); + + __HAL_UNLOCK(hpcd); + return HAL_OK; +} + +/** + * @brief Set the USB Device address + * @param hpcd: PCD handle + * @param address: new device address + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_SetAddress(PCD_HandleTypeDef *hpcd, uint8_t address) +{ + __HAL_LOCK(hpcd); + + if(address == 0) + { + /* set device address and enable function */ + hpcd->Instance->DADDR = USB_DADDR_EF; + } + else /* USB Address will be applied later */ + { + hpcd->USB_Address = address; + } + + __HAL_UNLOCK(hpcd); + return HAL_OK; +} +/** + * @brief Open and configure an endpoint + * @param hpcd: PCD handle + * @param ep_addr: endpoint address + * @param ep_mps: endpoint max packert size + * @param ep_type: endpoint type + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_EP_Open(PCD_HandleTypeDef *hpcd, uint8_t ep_addr, uint16_t ep_mps, uint8_t ep_type) +{ + HAL_StatusTypeDef ret = HAL_OK; + PCD_EPTypeDef *ep; + + if ((ep_addr & 0x80) == 0x80) + { + ep = &hpcd->IN_ep[ep_addr & 0x7F]; + } + else + { + ep = &hpcd->OUT_ep[ep_addr & 0x7F]; + } + ep->num = ep_addr & 0x7F; + + ep->is_in = (0x80 & ep_addr) != 0; + ep->maxpacket = ep_mps; + ep->type = ep_type; + + __HAL_LOCK(hpcd); + +/* initialize Endpoint */ + switch (ep->type) + { + case PCD_EP_TYPE_CTRL: + PCD_SET_EPTYPE(hpcd->Instance, ep->num, USB_EP_CONTROL); + break; + case PCD_EP_TYPE_BULK: + PCD_SET_EPTYPE(hpcd->Instance, ep->num, USB_EP_BULK); + break; + case PCD_EP_TYPE_INTR: + PCD_SET_EPTYPE(hpcd->Instance, ep->num, USB_EP_INTERRUPT); + break; + case PCD_EP_TYPE_ISOC: + PCD_SET_EPTYPE(hpcd->Instance, ep->num, USB_EP_ISOCHRONOUS); + break; + } + + PCD_SET_EP_ADDRESS(hpcd->Instance, ep->num, ep->num); + + if (ep->doublebuffer == 0) + { + if (ep->is_in) + { + /*Set the endpoint Transmit buffer address */ + PCD_SET_EP_TX_ADDRESS(hpcd->Instance, ep->num, ep->pmaadress); + PCD_CLEAR_TX_DTOG(hpcd->Instance, ep->num); + /* Configure NAK status for the Endpoint*/ + PCD_SET_EP_TX_STATUS(hpcd->Instance, ep->num, USB_EP_TX_NAK); + } + else + { + /*Set the endpoint Receive buffer address */ + PCD_SET_EP_RX_ADDRESS(hpcd->Instance, ep->num, ep->pmaadress); + /*Set the endpoint Receive buffer counter*/ + PCD_SET_EP_RX_CNT(hpcd->Instance, ep->num, ep->maxpacket); + PCD_CLEAR_RX_DTOG(hpcd->Instance, ep->num); + /* Configure VALID status for the Endpoint*/ + PCD_SET_EP_RX_STATUS(hpcd->Instance, ep->num, USB_EP_RX_VALID); + } + } + /*Double Buffer*/ + else + { + /*Set the endpoint as double buffered*/ + PCD_SET_EP_DBUF(hpcd->Instance, ep->num); + /*Set buffer address for double buffered mode*/ + PCD_SET_EP_DBUF_ADDR(hpcd->Instance, ep->num,ep->pmaaddr0, ep->pmaaddr1); + + if (ep->is_in==0) + { + /* Clear the data toggle bits for the endpoint IN/OUT*/ + PCD_CLEAR_RX_DTOG(hpcd->Instance, ep->num); + PCD_CLEAR_TX_DTOG(hpcd->Instance, ep->num); + + /* Reset value of the data toggle bits for the endpoint out*/ + PCD_TX_DTOG(hpcd->Instance, ep->num); + + PCD_SET_EP_RX_STATUS(hpcd->Instance, ep->num, USB_EP_RX_VALID); + PCD_SET_EP_TX_STATUS(hpcd->Instance, ep->num, USB_EP_TX_DIS); + } + else + { + /* Clear the data toggle bits for the endpoint IN/OUT*/ + PCD_CLEAR_RX_DTOG(hpcd->Instance, ep->num); + PCD_CLEAR_TX_DTOG(hpcd->Instance, ep->num); + PCD_RX_DTOG(hpcd->Instance, ep->num); + /* Configure DISABLE status for the Endpoint*/ + PCD_SET_EP_TX_STATUS(hpcd->Instance, ep->num, USB_EP_TX_DIS); + PCD_SET_EP_RX_STATUS(hpcd->Instance, ep->num, USB_EP_RX_DIS); + } + } + + __HAL_UNLOCK(hpcd); + return ret; +} + + +/** + * @brief Deactivate an endpoint + * @param hpcd: PCD handle + * @param ep_addr: endpoint address + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_EP_Close(PCD_HandleTypeDef *hpcd, uint8_t ep_addr) +{ + PCD_EPTypeDef *ep; + + if ((ep_addr & 0x80) == 0x80) + { + ep = &hpcd->IN_ep[ep_addr & 0x7F]; + } + else + { + ep = &hpcd->OUT_ep[ep_addr & 0x7F]; + } + ep->num = ep_addr & 0x7F; + + ep->is_in = (0x80 & ep_addr) != 0; + + __HAL_LOCK(hpcd); + + if (ep->doublebuffer == 0) + { + if (ep->is_in) + { + PCD_CLEAR_TX_DTOG(hpcd->Instance, ep->num); + /* Configure DISABLE status for the Endpoint*/ + PCD_SET_EP_TX_STATUS(hpcd->Instance, ep->num, USB_EP_TX_DIS); + } + else + { + PCD_CLEAR_RX_DTOG(hpcd->Instance, ep->num); + /* Configure DISABLE status for the Endpoint*/ + PCD_SET_EP_RX_STATUS(hpcd->Instance, ep->num, USB_EP_RX_DIS); + } + } + /*Double Buffer*/ + else + { + if (ep->is_in==0) + { + /* Clear the data toggle bits for the endpoint IN/OUT*/ + PCD_CLEAR_RX_DTOG(hpcd->Instance, ep->num); + PCD_CLEAR_TX_DTOG(hpcd->Instance, ep->num); + + /* Reset value of the data toggle bits for the endpoint out*/ + PCD_TX_DTOG(hpcd->Instance, ep->num); + + PCD_SET_EP_RX_STATUS(hpcd->Instance, ep->num, USB_EP_RX_DIS); + PCD_SET_EP_TX_STATUS(hpcd->Instance, ep->num, USB_EP_TX_DIS); + } + else + { + /* Clear the data toggle bits for the endpoint IN/OUT*/ + PCD_CLEAR_RX_DTOG(hpcd->Instance, ep->num); + PCD_CLEAR_TX_DTOG(hpcd->Instance, ep->num); + PCD_RX_DTOG(hpcd->Instance, ep->num); + /* Configure DISABLE status for the Endpoint*/ + PCD_SET_EP_TX_STATUS(hpcd->Instance, ep->num, USB_EP_TX_DIS); + PCD_SET_EP_RX_STATUS(hpcd->Instance, ep->num, USB_EP_RX_DIS); + } + } + + __HAL_UNLOCK(hpcd); + return HAL_OK; +} + + +/** + * @brief Receive an amount of data + * @param hpcd: PCD handle + * @param ep_addr: endpoint address + * @param pBuf: pointer to the reception buffer + * @param len: amount of data to be received + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_EP_Receive(PCD_HandleTypeDef *hpcd, uint8_t ep_addr, uint8_t *pBuf, uint32_t len) +{ + + PCD_EPTypeDef *ep; + + ep = &hpcd->OUT_ep[ep_addr & 0x7F]; + + /*setup and start the Xfer */ + ep->xfer_buff = pBuf; + ep->xfer_len = len; + ep->xfer_count = 0; + ep->is_in = 0; + ep->num = ep_addr & 0x7F; + + __HAL_LOCK(hpcd); + + /* Multi packet transfer*/ + if (ep->xfer_len > ep->maxpacket) + { + len=ep->maxpacket; + ep->xfer_len-=len; + } + else + { + len=ep->xfer_len; + ep->xfer_len =0; + } + + /* configure and validate Rx endpoint */ + if (ep->doublebuffer == 0) + { + /*Set RX buffer count*/ + PCD_SET_EP_RX_CNT(hpcd->Instance, ep->num, len); + } + else + { + /*Set the Double buffer counter*/ + PCD_SET_EP_DBUF1_CNT(hpcd->Instance, ep->num, ep->is_in, len); + } + + PCD_SET_EP_RX_STATUS(hpcd->Instance, ep->num, USB_EP_RX_VALID); + + __HAL_UNLOCK(hpcd); + + return HAL_OK; +} + +/** + * @brief Get Received Data Size + * @param hpcd: PCD handle + * @param ep_addr: endpoint address + * @retval Data Size + */ +uint16_t HAL_PCD_EP_GetRxCount(PCD_HandleTypeDef *hpcd, uint8_t ep_addr) +{ + return hpcd->OUT_ep[ep_addr & 0x7F].xfer_count; +} +/** + * @brief Send an amount of data + * @param hpcd: PCD handle + * @param ep_addr: endpoint address + * @param pBuf: pointer to the transmission buffer + * @param len: amount of data to be sent + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_EP_Transmit(PCD_HandleTypeDef *hpcd, uint8_t ep_addr, uint8_t *pBuf, uint32_t len) +{ + PCD_EPTypeDef *ep; + uint16_t pmabuffer = 0; + + ep = &hpcd->IN_ep[ep_addr & 0x7F]; + + /*setup and start the Xfer */ + ep->xfer_buff = pBuf; + ep->xfer_len = len; + ep->xfer_count = 0; + ep->is_in = 1; + ep->num = ep_addr & 0x7F; + + __HAL_LOCK(hpcd); + + /*Multi packet transfer*/ + if (ep->xfer_len > ep->maxpacket) + { + len=ep->maxpacket; + ep->xfer_len-=len; + } + else + { + len=ep->xfer_len; + ep->xfer_len =0; + } + + /* configure and validate Tx endpoint */ + if (ep->doublebuffer == 0) + { + PCD_WritePMA(hpcd->Instance, ep->xfer_buff, ep->pmaadress, len); + PCD_SET_EP_TX_CNT(hpcd->Instance, ep->num, len); + } + else + { + /*Set the Double buffer counter*/ + PCD_SET_EP_DBUF1_CNT(hpcd->Instance, ep->num, ep->is_in, len); + + /*Write the data to the USB endpoint*/ + if (PCD_GET_ENDPOINT(hpcd->Instance, ep->num)& USB_EP_DTOG_TX) + { + pmabuffer = ep->pmaaddr1; + } + else + { + pmabuffer = ep->pmaaddr0; + } + PCD_WritePMA(hpcd->Instance, ep->xfer_buff, pmabuffer, len); + PCD_FreeUserBuffer(hpcd->Instance, ep->num, ep->is_in); + } + + PCD_SET_EP_TX_STATUS(hpcd->Instance, ep->num, USB_EP_TX_VALID); + + __HAL_UNLOCK(hpcd); + + return HAL_OK; +} + +/** + * @brief Set a STALL condition over an endpoint + * @param hpcd: PCD handle + * @param ep_addr: endpoint address + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_EP_SetStall(PCD_HandleTypeDef *hpcd, uint8_t ep_addr) +{ + PCD_EPTypeDef *ep; + + __HAL_LOCK(hpcd); + + if ((0x80 & ep_addr) == 0x80) + { + ep = &hpcd->IN_ep[ep_addr & 0x7F]; + } + else + { + ep = &hpcd->OUT_ep[ep_addr]; + } + + ep->is_stall = 1; + ep->num = ep_addr & 0x7F; + ep->is_in = ((ep_addr & 0x80) == 0x80); + + if (ep->num == 0) + { + /* This macro sets STALL status for RX & TX*/ + PCD_SET_EP_TXRX_STATUS(hpcd->Instance, ep->num, USB_EP_RX_STALL, USB_EP_TX_STALL); + } + else + { + if (ep->is_in) + { + PCD_SET_EP_TX_STATUS(hpcd->Instance, ep->num , USB_EP_TX_STALL); + } + else + { + PCD_SET_EP_RX_STATUS(hpcd->Instance, ep->num , USB_EP_RX_STALL); + } + } + __HAL_UNLOCK(hpcd); + + return HAL_OK; +} + +/** + * @brief Clear a STALL condition over in an endpoint + * @param hpcd: PCD handle + * @param ep_addr: endpoint address + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_EP_ClrStall(PCD_HandleTypeDef *hpcd, uint8_t ep_addr) +{ + PCD_EPTypeDef *ep; + + if ((0x80 & ep_addr) == 0x80) + { + ep = &hpcd->IN_ep[ep_addr & 0x7F]; + } + else + { + ep = &hpcd->OUT_ep[ep_addr]; + } + + ep->is_stall = 0; + ep->num = ep_addr & 0x7F; + ep->is_in = ((ep_addr & 0x80) == 0x80); + + __HAL_LOCK(hpcd); + + if (ep->is_in) + { + PCD_CLEAR_TX_DTOG(hpcd->Instance, ep->num); + PCD_SET_EP_TX_STATUS(hpcd->Instance, ep->num, USB_EP_TX_VALID); + } + else + { + PCD_CLEAR_RX_DTOG(hpcd->Instance, ep->num); + PCD_SET_EP_RX_STATUS(hpcd->Instance, ep->num, USB_EP_RX_VALID); + } + __HAL_UNLOCK(hpcd); + + return HAL_OK; +} + +/** + * @brief Flush an endpoint + * @param hpcd: PCD handle + * @param ep_addr: endpoint address + * @retval HAL status + */ +HAL_StatusTypeDef HAL_PCD_EP_Flush(PCD_HandleTypeDef *hpcd, uint8_t ep_addr) +{ + return HAL_OK; +} + +/** + * @brief HAL_PCD_ActiveRemoteWakeup : active remote wakeup signalling + * @param hpcd: PCD handle + * @retval status + */ +HAL_StatusTypeDef HAL_PCD_ActiveRemoteWakeup(PCD_HandleTypeDef *hpcd) +{ + hpcd->Instance->CNTR |= USB_CNTR_RESUME; + return HAL_OK; +} + +/** + * @brief HAL_PCD_DeActiveRemoteWakeup : de-active remote wakeup signalling + * @param hpcd: PCD handle + * @retval status + */ +HAL_StatusTypeDef HAL_PCD_DeActiveRemoteWakeup(PCD_HandleTypeDef *hpcd) +{ + hpcd->Instance->CNTR &= ~(USB_CNTR_RESUME); + return HAL_OK; +} +/** + * @brief Copy a buffer from user memory area to packet memory area (PMA) + * @param pbUsrBuf: pointer to user memory area. + * @param wPMABufAddr: address into PMA. + * @param wNBytes: no. of bytes to be copied. + * @retval None + */ +void PCD_WritePMA(USB_TypeDef *USBx, uint8_t *pbUsrBuf, uint16_t wPMABufAddr, uint16_t wNBytes) +{ + uint32_t n = (wNBytes + 1) >> 1; + uint32_t i; + uint16_t temp1, temp2; + uint16_t *pdwVal; + pdwVal = (uint16_t *)(wPMABufAddr + (uint32_t)USBx + 0x400); + + for (i = n; i != 0; i--) + { + temp1 = (uint16_t) * pbUsrBuf; + pbUsrBuf++; + temp2 = temp1 | (uint16_t) * pbUsrBuf << 8; + *pdwVal++ = temp2; + pbUsrBuf++; + } +} + +/** + * @brief Copy a buffer from user memory area to packet memory area (PMA) + * @param pbUsrBuf = pointer to user memory area. + * @param wPMABufAddr: address into PMA. + * @param wNBytes: no. of bytes to be copied. + * @retval None + */ +void PCD_ReadPMA(USB_TypeDef *USBx, uint8_t *pbUsrBuf, uint16_t wPMABufAddr, uint16_t wNBytes) +{ + uint32_t n = (wNBytes + 1) >> 1; + uint32_t i; + uint16_t *pdwVal; + pdwVal = (uint16_t *)(wPMABufAddr + (uint32_t)USBx + 0x400); + for (i = n; i != 0; i--) + { + *(uint16_t*)pbUsrBuf++ = *pdwVal++; + pbUsrBuf++; + } +} +/** + * @} + */ + +/** @defgroup PCD_Group4 Peripheral State functions + * @brief Peripheral State functions + * +@verbatim + =============================================================================== + ##### Peripheral State functions ##### + =============================================================================== + [..] + This subsection permit to get in run-time the status of the peripheral + and the data flow. + +@endverbatim + * @{ + */ + +/** + * @brief Return the PCD state + * @param hpcd : PCD handle + * @retval HAL state + */ +PCD_StateTypeDef HAL_PCD_GetState(PCD_HandleTypeDef *hpcd) +{ + return hpcd->State; +} +/** + * @} + */ + + +/** + * @} + */ + +#endif /* HAL_PCD_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_pcd.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_pcd.h new file mode 100644 index 0000000000..88d3b38289 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_pcd.h @@ -0,0 +1,682 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_pcd.h + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief Header file of PCD HAL module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32L0xx_HAL_PCD_H +#define __STM32L0xx_HAL_PCD_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal_def.h" +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @addtogroup PCD + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ + + /** + * @brief PCD State structures definition + */ +typedef enum +{ + PCD_READY = 0x00, + PCD_ERROR = 0x01, + PCD_BUSY = 0x02, + PCD_TIMEOUT = 0x03 +} PCD_StateTypeDef; + +typedef enum +{ + /* double buffered endpoint direction */ + PCD_EP_DBUF_OUT, + PCD_EP_DBUF_IN, + PCD_EP_DBUF_ERR, +}PCD_EP_DBUF_DIR; + +/* endpoint buffer number */ +typedef enum +{ + PCD_EP_NOBUF, + PCD_EP_BUF0, + PCD_EP_BUF1 +}PCD_EP_BUF_NUM; + +#define PCD_EP_TYPE_CTRL 0 +#define PCD_EP_TYPE_ISOC 1 +#define PCD_EP_TYPE_BULK 2 +#define PCD_EP_TYPE_INTR 3 + +#define PCD_ENDP0 ((uint8_t)0) +#define PCD_ENDP1 ((uint8_t)1) +#define PCD_ENDP2 ((uint8_t)2) +#define PCD_ENDP3 ((uint8_t)3) +#define PCD_ENDP4 ((uint8_t)4) +#define PCD_ENDP5 ((uint8_t)5) +#define PCD_ENDP6 ((uint8_t)6) +#define PCD_ENDP7 ((uint8_t)7) + +/* Endpoint Kind */ +#define PCD_SNG_BUF 0 +#define PCD_DBL_BUF 1 + +#define IS_PCD_ALL_INSTANCE IS_USB_ALL_INSTANCE +/** + * @brief PCD Initialization Structure definition + */ +typedef struct +{ + uint32_t dev_endpoints; /*!< Device Endpoints number. + This parameter depends on the used USB core. + This parameter must be a number between Min_Data = 1 and Max_Data = 15 */ + + uint32_t speed; /*!< USB Core speed. + This parameter can be any value of @ref USB_Core_Speed_ */ + + uint32_t ep0_mps; /*!< Set the Endpoint 0 Max Packet size. + This parameter can be any value of @ref USB_EP0_MPS_ */ + + uint32_t phy_itface; /*!< Select the used PHY interface. + This parameter can be any value of @ref USB_Core_PHY_ */ + + uint32_t Sof_enable; /*!< Enable or disable the output of the SOF signal. + This parameter can be set to ENABLE or DISABLE */ + + uint32_t low_power_enable; /*!< Enable or disable Low Power mode + This parameter can be set to ENABLE or DISABLE */ + + uint32_t lpm_enable; /*!< Enable or disable Link Power Management. + This parameter can be set to ENABLE or DISABLE */ + + uint32_t battery_charging_enable; /*!< Enable or disable Battery charging. + This parameter can be set to ENABLE or DISABLE */ + +}PCD_InitTypeDef; + +typedef struct +{ + uint8_t num; /*!< Endpoint number + This parameter must be a number between Min_Data = 1 and Max_Data = 15 */ + + uint8_t is_in; /*!< Endpoint direction + This parameter must be a number between Min_Data = 0 and Max_Data = 1 */ + + uint8_t is_stall; /*!< Endpoint stall condition + This parameter must be a number between Min_Data = 0 and Max_Data = 1 */ + + uint8_t type; /*!< Endpoint type + This parameter can be any value of @ref USB_EP_Type_ */ + + uint16_t pmaadress; /*!< PMA Address + This parameter can be any value between Min_addr = 0 and Max_addr = 1K */ + + + uint16_t pmaaddr0; /*!< PMA Address0 + This parameter can be any value between Min_addr = 0 and Max_addr = 1K */ + + + uint16_t pmaaddr1; /*!< PMA Address1 + This parameter can be any value between Min_addr = 0 and Max_addr = 1K */ + + + uint8_t doublebuffer; /*!< Double buffer enable + This parameter can be 0 or 1 */ + + uint32_t maxpacket; /*!< Endpoint Max packet size + This parameter must be a number between Min_Data = 0 and Max_Data = 64KB */ + + uint8_t *xfer_buff; /*!< Pointer to transfer buffer */ + + + uint32_t xfer_len; /*!< Current transfer length */ + + uint32_t xfer_count; /*!< Partial transfer length in case of multi packet transfer */ + +}PCD_EPTypeDef; + +typedef USB_TypeDef PCD_TypeDef; + +/** + * @brief PCD Handle Structure definition + */ +typedef struct +{ + PCD_TypeDef *Instance; /*!< Register base address */ + PCD_InitTypeDef Init; /*!< PCD required parameters */ + __IO uint8_t USB_Address; /*!< USB Address */ + PCD_EPTypeDef IN_ep[5]; /*!< IN endpoint parameters */ + PCD_EPTypeDef OUT_ep[5]; /*!< OUT endpoint parameters */ + HAL_LockTypeDef Lock; /*!< PCD peripheral status */ + __IO PCD_StateTypeDef State; /*!< PCD communication state */ + uint32_t Setup[12]; /*!< Setup packet buffer */ + void *pData; /*!< Pointer to upper stack Handler */ + +} PCD_HandleTypeDef; + +#include "stm32l0xx_hal_pcd_ex.h" +/* Exported constants --------------------------------------------------------*/ +/** @defgroup PCD_Exported_Constants + * @{ + */ + +/** @defgroup PCD_Speed + * @{ + */ +#define PCD_SPEED_HIGH 0 /* Not Supported */ +#define PCD_SPEED_FULL 2 +/** + * @} + */ + + /** @defgroup USB_Core_PHY + * @{ + */ +#define PCD_PHY_EMBEDDED 2 +/** + * @} + */ + + /** @defgroup USB_EP0_MPS + * @{ + */ +#define DEP0CTL_MPS_64 0 +#define DEP0CTL_MPS_32 1 +#define DEP0CTL_MPS_16 2 +#define DEP0CTL_MPS_8 3 + +#define PCD_EP0MPS_64 DEP0CTL_MPS_64 +#define PCD_EP0MPS_32 DEP0CTL_MPS_32 +#define PCD_EP0MPS_16 DEP0CTL_MPS_16 +#define PCD_EP0MPS_08 DEP0CTL_MPS_8 +/** + * @} + */ +/** + * @} + */ + +/* Exported macros -----------------------------------------------------------*/ + +/** @defgroup PCD_Interrupt_Clock + * @brief macros to handle interrupts and specific clock configurations + * @{ + */ +#define __HAL_PCD_GET_FLAG(__HANDLE__, __INTERRUPT__) ((((__HANDLE__)->Instance->ISTR) & (__INTERRUPT__)) == (__INTERRUPT__)) +#define __HAL_PCD_CLEAR_FLAG(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->ISTR) &= ~(__INTERRUPT__)) + +#define USB_EXTI_LINE_WAKEUP ((uint32_t)0x00040000) /*!< External interrupt line 18 Connected to the USB FS EXTI Line */ + +#define __HAL_USB_EXTI_ENABLE_IT() EXTI->IMR |= USB_EXTI_LINE_WAKEUP +#define __HAL_USB_EXTI_DISABLE_IT() EXTI->IMR &= ~(USB_EXTI_LINE_WAKEUP) + +/* Internal macros -----------------------------------------------------------*/ + +/* SetENDPOINT */ +#define PCD_SET_ENDPOINT(USBx, bEpNum,wRegValue) (*(&USBx->EP0R + bEpNum * 2)= (uint16_t)wRegValue) + +/* GetENDPOINT */ +#define PCD_GET_ENDPOINT(USBx, bEpNum) (*(&USBx->EP0R + bEpNum * 2)) + + + +/** + * @brief sets the type in the endpoint register(bits EP_TYPE[1:0]) + * @param bEpNum: Endpoint Number. + * @param wType: Endpoint Type. + * @retval None + */ +#define PCD_SET_EPTYPE(USBx, bEpNum,wType) (PCD_SET_ENDPOINT(USBx, bEpNum,\ + ((PCD_GET_ENDPOINT(USBx, bEpNum) & USB_EP_T_MASK) | wType ))) + +/** + * @brief gets the type in the endpoint register(bits EP_TYPE[1:0]) + * @param bEpNum: Endpoint Number. + * @retval Endpoint Type + */ +#define PCD_GET_EPTYPE(USBx, bEpNum) (PCD_GET_ENDPOINT(USBx, bEpNum) & USB_EP_T_FIELD) + + +/** + * @brief free buffer used from the application realizing it to the line + toggles bit SW_BUF in the double buffered endpoint register + * @param bEpNum, bDir + * @retval None + */ +#define PCD_FreeUserBuffer(USBx, bEpNum, bDir)\ +{\ + if (bDir == PCD_EP_DBUF_OUT)\ + { /* OUT double buffered endpoint */\ + PCD_TX_DTOG(USBx, bEpNum);\ + }\ + else if (bDir == PCD_EP_DBUF_IN)\ + { /* IN double buffered endpoint */\ + PCD_RX_DTOG(USBx, bEpNum);\ + }\ +} + +/** + * @brief gets direction of the double buffered endpoint + * @param bEpNum: Endpoint Number. + * @retval EP_DBUF_OUT, EP_DBUF_IN, + * EP_DBUF_ERR if the endpoint counter not yet programmed. + */ +#define PCD_GET_DB_DIR(USBx, bEpNum)\ +{\ + if ((uint16_t)(*PCD_EP_RX_CNT(USBx, bEpNum) & 0xFC00) != 0)\ + return(PCD_EP_DBUF_OUT);\ + else if (((uint16_t)(*PCD_EP_TX_CNT(USBx, bEpNum)) & 0x03FF) != 0)\ + return(PCD_EP_DBUF_IN);\ + else\ + return(PCD_EP_DBUF_ERR);\ +} + +/** + * @brief sets the status for tx transfer (bits STAT_TX[1:0]). + * @param bEpNum: Endpoint Number. + * @param wState: new state + * @retval None + */ +#define PCD_SET_EP_TX_STATUS(USBx, bEpNum, wState) {\ + register uint16_t _wRegVal; \ + \ + _wRegVal = PCD_GET_ENDPOINT(USBx, bEpNum) & USB_EPTX_DTOGMASK;\ + /* toggle first bit ? */ \ + if((USB_EPTX_DTOG1 & wState)!= 0) \ + _wRegVal ^= USB_EPTX_DTOG1; \ + /* toggle second bit ? */ \ + if((USB_EPTX_DTOG2 & wState)!= 0) \ + _wRegVal ^= USB_EPTX_DTOG2; \ + PCD_SET_ENDPOINT(USBx, bEpNum, (_wRegVal | USB_EP_CTR_RX|USB_EP_CTR_TX)); \ + } /* PCD_SET_EP_TX_STATUS */ + +/** + * @brief sets the status for rx transfer (bits STAT_TX[1:0]) + * @param bEpNum: Endpoint Number. + * @param wState: new state + * @retval None + */ +#define PCD_SET_EP_RX_STATUS(USBx, bEpNum,wState) {\ + register uint16_t _wRegVal; \ + \ + _wRegVal = PCD_GET_ENDPOINT(USBx, bEpNum) & USB_EPRX_DTOGMASK;\ + /* toggle first bit ? */ \ + if((USB_EPRX_DTOG1 & wState)!= 0) \ + _wRegVal ^= USB_EPRX_DTOG1; \ + /* toggle second bit ? */ \ + if((USB_EPRX_DTOG2 & wState)!= 0) \ + _wRegVal ^= USB_EPRX_DTOG2; \ + PCD_SET_ENDPOINT(USBx, bEpNum, (_wRegVal | USB_EP_CTR_RX|USB_EP_CTR_TX)); \ + } /* PCD_SET_EP_RX_STATUS */ + +/** + * @brief sets the status for rx & tx (bits STAT_TX[1:0] & STAT_RX[1:0]) + * @param bEpNum: Endpoint Number. + * @param wStaterx: new state. + * @param wStatetx: new state. + * @retval None + */ +#define PCD_SET_EP_TXRX_STATUS(USBx,bEpNum,wStaterx,wStatetx) {\ + register uint32_t _wRegVal; \ + \ + _wRegVal = PCD_GET_ENDPOINT(USBx, bEpNum) & (USB_EPRX_DTOGMASK |USB_EPTX_STAT) ;\ + /* toggle first bit ? */ \ + if((USB_EPRX_DTOG1 & wStaterx)!= 0) \ + _wRegVal ^= USB_EPRX_DTOG1; \ + /* toggle second bit ? */ \ + if((USB_EPRX_DTOG2 & wStaterx)!= 0) \ + _wRegVal ^= USB_EPRX_DTOG2; \ + /* toggle first bit ? */ \ + if((USB_EPTX_DTOG1 & wStatetx)!= 0) \ + _wRegVal ^= USB_EPTX_DTOG1; \ + /* toggle second bit ? */ \ + if((USB_EPTX_DTOG2 & wStatetx)!= 0) \ + _wRegVal ^= USB_EPTX_DTOG2; \ + PCD_SET_ENDPOINT(USBx, bEpNum, _wRegVal | USB_EP_CTR_RX|USB_EP_CTR_TX); \ + } /* PCD_SET_EP_TXRX_STATUS */ + +/** + * @brief gets the status for tx/rx transfer (bits STAT_TX[1:0] + * /STAT_RX[1:0]) + * @param bEpNum: Endpoint Number. + * @retval status + */ +#define PCD_GET_EP_TX_STATUS(USBx, bEpNum) ((uint16_t)PCD_GET_ENDPOINT(USBx, bEpNum) & USB_EPTX_STAT) + +#define PCD_GET_EP_RX_STATUS(USBx, bEpNum) ((uint16_t)PCD_GET_ENDPOINT(USBx, bEpNum) & USB_EPRX_STAT) + +/** + * @brief sets directly the VALID tx/rx-status into the endpoint register + * @param bEpNum: Endpoint Number. + * @retval None + */ +#define PCD_SET_EP_TX_VALID(USBx, bEpNum) (PCD_SET_EP_TX_STATUS(USBx, bEpNum, USB_EP_TX_VALID)) + +#define PCD_SET_EP_RX_VALID(USBx, bEpNum) (PCD_SET_EP_RX_STATUS(USBx, bEpNum, USB_EP_RX_VALID)) + +/** + * @brief checks stall condition in an endpoint. + * @param bEpNum: Endpoint Number. + * @retval TRUE = endpoint in stall condition. + */ +#define PCD_GET_EP_TX_STALL_STATUS(USBx, bEpNum) (PCD_GET_EP_TX_STATUS(USBx, bEpNum) \ + == USB_EP_TX_STALL) +#define PCD_GET_EP_RX_STALL_STATUS(USBx, bEpNum) (PCD_GET_EP_RX_STATUS(USBx, bEpNum) \ + == USB_EP_RX_STALL) + +/** + * @brief set & clear EP_KIND bit. + * @param bEpNum: Endpoint Number. + * @retval None + */ +#define PCD_SET_EP_KIND(USBx, bEpNum) (PCD_SET_ENDPOINT(USBx, bEpNum, \ + (USB_EP_CTR_RX|USB_EP_CTR_TX|((PCD_GET_ENDPOINT(USBx, bEpNum) | USB_EP_KIND) & USB_EPREG_MASK)))) +#define PCD_CLEAR_EP_KIND(USBx, bEpNum) (PCD_SET_ENDPOINT(USBx, bEpNum, \ + (USB_EP_CTR_RX|USB_EP_CTR_TX|(PCD_GET_ENDPOINT(USBx, bEpNum) & USB_EPKIND_MASK)))) + +/** + * @brief Sets/clears directly STATUS_OUT bit in the endpoint register. + * @param bEpNum: Endpoint Number. + * @retval None + */ +#define PCD_SET_OUT_STATUS(USBx, bEpNum) PCD_SET_EP_KIND(USBx, bEpNum) +#define PCD_CLEAR_OUT_STATUS(USBx, bEpNum) PCD_CLEAR_EP_KIND(USBx, bEpNum) + +/** + * @brief Sets/clears directly EP_KIND bit in the endpoint register. + * @param bEpNum: Endpoint Number. + * @retval None + */ +#define PCD_SET_EP_DBUF(USBx, bEpNum) PCD_SET_EP_KIND(USBx, bEpNum) +#define PCD_CLEAR_EP_DBUF(USBx, bEpNum) PCD_CLEAR_EP_KIND(USBx, bEpNum) + +/** + * @brief Clears bit CTR_RX / CTR_TX in the endpoint register. + * @param bEpNum: Endpoint Number. + * @retval None + */ +#define PCD_CLEAR_RX_EP_CTR(USBx, bEpNum) (PCD_SET_ENDPOINT(USBx, bEpNum,\ + PCD_GET_ENDPOINT(USBx, bEpNum) & 0x7FFF & USB_EPREG_MASK)) +#define PCD_CLEAR_TX_EP_CTR(USBx, bEpNum) (PCD_SET_ENDPOINT(USBx, bEpNum,\ + PCD_GET_ENDPOINT(USBx, bEpNum) & 0xFF7F & USB_EPREG_MASK)) + +/** + * @brief Toggles DTOG_RX / DTOG_TX bit in the endpoint register. + * @param bEpNum: Endpoint Number. + * @retval None + */ +#define PCD_RX_DTOG(USBx, bEpNum) (PCD_SET_ENDPOINT(USBx, bEpNum, \ + USB_EP_CTR_RX|USB_EP_CTR_TX|USB_EP_DTOG_RX | (PCD_GET_ENDPOINT(USBx, bEpNum) & USB_EPREG_MASK))) +#define PCD_TX_DTOG(USBx, bEpNum) (PCD_SET_ENDPOINT(USBx, bEpNum, \ + USB_EP_CTR_RX|USB_EP_CTR_TX|USB_EP_DTOG_TX | (PCD_GET_ENDPOINT(USBx, bEpNum) & USB_EPREG_MASK))) + +/** + * @brief Clears DTOG_RX / DTOG_TX bit in the endpoint register. + * @param bEpNum: Endpoint Number. + * @retval None + */ +#define PCD_CLEAR_RX_DTOG(USBx, bEpNum) if((PCD_GET_ENDPOINT(USBx, bEpNum) & USB_EP_DTOG_RX) != 0)\ + PCD_RX_DTOG(USBx, bEpNum) +#define PCD_CLEAR_TX_DTOG(USBx, bEpNum) if((PCD_GET_ENDPOINT(USBx, bEpNum) & USB_EP_DTOG_TX) != 0)\ + PCD_TX_DTOG(USBx, bEpNum) + +/** + * @brief Sets address in an endpoint register. + * @param bEpNum: Endpoint Number. + * @param bAddr: Address. + * @retval None + */ +#define PCD_SET_EP_ADDRESS(USBx, bEpNum,bAddr) PCD_SET_ENDPOINT(USBx, bEpNum,\ + USB_EP_CTR_RX|USB_EP_CTR_TX|(PCD_GET_ENDPOINT(USBx, bEpNum) & USB_EPREG_MASK) | bAddr) + +/** + * @brief Gets address in an endpoint register. + * @param bEpNum: Endpoint Number. + * @retval None + */ +#define PCD_GET_EP_ADDRESS(USBx, bEpNum) ((uint8_t)(PCD_GET_ENDPOINT(USBx, bEpNum) & USB_EPADDR_FIELD)) +#define PCD_EP_TX_ADDRESS(USBx, bEpNum) ((uint16_t *)((USBx->BTABLE+bEpNum*8)+ ((uint32_t)USBx + 0x400))) +#define PCD_EP_TX_CNT(USBx, bEpNum) ((uint16_t *)((USBx->BTABLE+bEpNum*8+2)+ ((uint32_t)USBx + 0x400))) +#define PCD_EP_RX_ADDRESS(USBx, bEpNum) ((uint16_t *)((USBx->BTABLE+bEpNum*8+4)+ ((uint32_t)USBx + 0x400))) +#define PCD_EP_RX_CNT(USBx, bEpNum) ((uint16_t *)((USBx->BTABLE+bEpNum*8+6)+ ((uint32_t)USBx + 0x400))) + +/** + * @brief sets address of the tx/rx buffer. + * @param bEpNum: Endpoint Number. + * @param wAddr: address to be set (must be word aligned). + * @retval None + */ +#define PCD_SET_EP_TX_ADDRESS(USBx, bEpNum,wAddr) (*PCD_EP_TX_ADDRESS(USBx, bEpNum) = ((wAddr >> 1) << 1)) +#define PCD_SET_EP_RX_ADDRESS(USBx, bEpNum,wAddr) (*PCD_EP_RX_ADDRESS(USBx, bEpNum) = ((wAddr >> 1) << 1)) + +/** + * @brief Gets address of the tx/rx buffer. + * @param bEpNum: Endpoint Number. + * @retval address of the buffer. + */ +#define PCD_GET_EP_TX_ADDRESS(USBx, bEpNum) ((uint16_t)*PCD_EP_TX_ADDRESS(USBx, bEpNum)) +#define PCD_GET_EP_RX_ADDRESS(USBx, bEpNum) ((uint16_t)*PCD_EP_RX_ADDRESS(USBx, bEpNum)) + +/** + * @brief Sets counter of rx buffer with no. of blocks. + * @param bEpNum: Endpoint Number. + * @param wCount: Counter. + * @retval None + */ +#define PCD_CALC_BLK32(dwReg,wCount,wNBlocks) {\ + wNBlocks = wCount >> 5;\ + if((wCount & 0x1f) == 0)\ + wNBlocks--;\ + *pdwReg = (uint16_t)((wNBlocks << 10) | 0x8000);\ + }/* PCD_CALC_BLK32 */ + +#define PCD_CALC_BLK2(dwReg,wCount,wNBlocks) {\ + wNBlocks = wCount >> 1;\ + if((wCount & 0x1) != 0)\ + wNBlocks++;\ + *pdwReg = (uint16_t)(wNBlocks << 10);\ + }/* PCD_CALC_BLK2 */ + +#define PCD_SET_EP_CNT_RX_REG(dwReg,wCount) {\ + uint16_t wNBlocks;\ + if(wCount > 62){PCD_CALC_BLK32(dwReg,wCount,wNBlocks);}\ + else {PCD_CALC_BLK2(dwReg,wCount,wNBlocks);}\ + }/* PCD_SET_EP_CNT_RX_REG */ + +#define PCD_SET_EP_RX_DBUF0_CNT(USBx, bEpNum,wCount) {\ + uint16_t *pdwReg = PCD_EP_TX_CNT(USBx, bEpNum); \ + PCD_SET_EP_CNT_RX_REG(pdwReg, wCount);\ + } +/** + * @brief sets counter for the tx/rx buffer. + * @param bEpNum: Endpoint Number. + * @param wCount: Counter value. + * @retval None + */ +#define PCD_SET_EP_TX_CNT(USBx, bEpNum,wCount) (*PCD_EP_TX_CNT(USBx, bEpNum) = wCount) +#define PCD_SET_EP_RX_CNT(USBx, bEpNum,wCount) {\ + uint16_t *pdwReg = PCD_EP_RX_CNT(USBx, bEpNum); \ + PCD_SET_EP_CNT_RX_REG(pdwReg, wCount);\ + } + +/** + * @brief gets counter of the tx buffer. + * @param bEpNum: Endpoint Number. + * @retval Counter value + */ +#define PCD_GET_EP_TX_CNT(USBx, bEpNum)((uint16_t)(*PCD_EP_TX_CNT(USBx, bEpNum)) & 0x3ff) +#define PCD_GET_EP_RX_CNT(USBx, bEpNum)((uint16_t)(*PCD_EP_RX_CNT(USBx, bEpNum)) & 0x3ff) + +/** + * @brief Sets buffer 0/1 address in a double buffer endpoint. + * @param bEpNum: Endpoint Number. + * @param wBuf0Addr: buffer 0 address. + * @retval Counter value + */ +#define PCD_SET_EP_DBUF0_ADDR(USBx, bEpNum,wBuf0Addr) {PCD_SET_EP_TX_ADDRESS(USBx, bEpNum, wBuf0Addr);} +#define PCD_SET_EP_DBUF1_ADDR(USBx, bEpNum,wBuf1Addr) {PCD_SET_EP_RX_ADDRESS(USBx, bEpNum, wBuf1Addr);} + +/** + * @brief Sets addresses in a double buffer endpoint. + * @param bEpNum: Endpoint Number. + * @param wBuf0Addr: buffer 0 address. + * @param wBuf1Addr = buffer 1 address. + * @retval None + */ +#define PCD_SET_EP_DBUF_ADDR(USBx, bEpNum,wBuf0Addr,wBuf1Addr) { \ + PCD_SET_EP_DBUF0_ADDR(USBx, bEpNum, wBuf0Addr);\ + PCD_SET_EP_DBUF1_ADDR(USBx, bEpNum, wBuf1Addr);\ + } /* PCD_SET_EP_DBUF_ADDR */ + +/** + * @brief Gets buffer 0/1 address of a double buffer endpoint. + * @param bEpNum: Endpoint Number. + * @retval None + */ +#define PCD_GET_EP_DBUF0_ADDR(USBx, bEpNum) (PCD_GET_EP_TX_ADDRESS(USBx, bEpNum)) +#define PCD_GET_EP_DBUF1_ADDR(USBx, bEpNum) (PCD_GET_EP_RX_ADDRESS(USBx, bEpNum)) + +/** + * @brief Gets buffer 0/1 address of a double buffer endpoint. + * @param bEpNum: Endpoint Number. + * bDir: endpoint dir EP_DBUF_OUT = OUT + * EP_DBUF_IN = IN + * @param wCount: Counter value + * @retval None + */ +#define PCD_SET_EP_DBUF0_CNT(USBx, bEpNum, bDir, wCount) { \ + if(bDir == PCD_EP_DBUF_OUT)\ + /* OUT endpoint */ \ + {PCD_SET_EP_RX_DBUF0_CNT(USBx, bEpNum,wCount);} \ + else if(bDir == PCD_EP_DBUF_IN)\ + /* IN endpoint */ \ + *PCD_EP_TX_CNT(USBx, bEpNum) = (uint32_t)wCount; \ + } /* SetEPDblBuf0Count*/ + +#define PCD_SET_EP_DBUF1_CNT(USBx, bEpNum, bDir, wCount) { \ + if(bDir == PCD_EP_DBUF_OUT)\ + /* OUT endpoint */ \ + {PCD_SET_EP_RX_CNT(USBx, bEpNum,wCount);}\ + else if(bDir == PCD_EP_DBUF_IN)\ + /* IN endpoint */\ + *PCD_EP_RX_CNT(USBx, bEpNum) = (uint32_t)wCount; \ + } /* SetEPDblBuf1Count */ + +#define PCD_SET_EP_DBUF_CNT(USBx, bEpNum, bDir, wCount) {\ + PCD_SET_EP_DBUF0_CNT(USBx, bEpNum, bDir, wCount); \ + PCD_SET_EP_DBUF1_CNT(USBx, bEpNum, bDir, wCount); \ + } /* PCD_SET_EP_DBUF_CNT */ + +/** + * @brief Gets buffer 0/1 rx/tx counter for double buffering. + * @param bEpNum: Endpoint Number. + * @retval None + */ +#define PCD_GET_EP_DBUF0_CNT(USBx, bEpNum) (PCD_GET_EP_TX_CNT(USBx, bEpNum)) +#define PCD_GET_EP_DBUF1_CNT(USBx, bEpNum) (PCD_GET_EP_RX_CNT(USBx, bEpNum)) + + +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ + +/* Initialization/de-initialization functions **********************************/ +HAL_StatusTypeDef HAL_PCD_Init(PCD_HandleTypeDef *hpcd); +HAL_StatusTypeDef HAL_PCD_DeInit (PCD_HandleTypeDef *hpcd); +void HAL_PCD_MspInit(PCD_HandleTypeDef *hpcd); +void HAL_PCD_MspDeInit(PCD_HandleTypeDef *hpcd); + +/* I/O operation functions *****************************************************/ + /* Non-Blocking mode: Interrupt */ +HAL_StatusTypeDef HAL_PCD_Start(PCD_HandleTypeDef *hpcd); +HAL_StatusTypeDef HAL_PCD_Stop(PCD_HandleTypeDef *hpcd); +void HAL_PCD_IRQHandler(PCD_HandleTypeDef *hpcd); + +void HAL_PCD_DataOutStageCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum); +void HAL_PCD_DataInStageCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum); +void HAL_PCD_SetupStageCallback(PCD_HandleTypeDef *hpcd); +void HAL_PCD_SOFCallback(PCD_HandleTypeDef *hpcd); +void HAL_PCD_ResetCallback(PCD_HandleTypeDef *hpcd); +void HAL_PCD_SuspendCallback(PCD_HandleTypeDef *hpcd); +void HAL_PCD_ResumeCallback(PCD_HandleTypeDef *hpcd); +void HAL_PCD_ISOOUTIncompleteCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum); +void HAL_PCD_ISOINIncompleteCallback(PCD_HandleTypeDef *hpcd, uint8_t epnum); +void HAL_PCD_ConnectCallback(PCD_HandleTypeDef *hpcd); +void HAL_PCD_DisconnectCallback(PCD_HandleTypeDef *hpcd); + + + +/* Peripheral Control functions ************************************************/ +HAL_StatusTypeDef HAL_PCD_DevConnect(PCD_HandleTypeDef *hpcd); +HAL_StatusTypeDef HAL_PCD_DevDisconnect(PCD_HandleTypeDef *hpcd); +HAL_StatusTypeDef HAL_PCD_SetAddress(PCD_HandleTypeDef *hpcd, uint8_t address); +HAL_StatusTypeDef HAL_PCD_EP_Open(PCD_HandleTypeDef *hpcd, uint8_t ep_addr, uint16_t ep_mps, uint8_t ep_type); +HAL_StatusTypeDef HAL_PCD_EP_Close(PCD_HandleTypeDef *hpcd, uint8_t ep_addr); +HAL_StatusTypeDef HAL_PCD_EP_Receive(PCD_HandleTypeDef *hpcd, uint8_t ep_addr, uint8_t *pBuf, uint32_t len); +HAL_StatusTypeDef HAL_PCD_EP_Transmit(PCD_HandleTypeDef *hpcd, uint8_t ep_addr, uint8_t *pBuf, uint32_t len); +uint16_t HAL_PCD_EP_GetRxCount(PCD_HandleTypeDef *hpcd, uint8_t ep_addr); +HAL_StatusTypeDef HAL_PCD_EP_SetStall(PCD_HandleTypeDef *hpcd, uint8_t ep_addr); +HAL_StatusTypeDef HAL_PCD_EP_ClrStall(PCD_HandleTypeDef *hpcd, uint8_t ep_addr); +HAL_StatusTypeDef HAL_PCD_EP_Flush(PCD_HandleTypeDef *hpcd, uint8_t ep_addr); +HAL_StatusTypeDef HAL_PCD_ActiveRemoteWakeup(PCD_HandleTypeDef *hpcd); +HAL_StatusTypeDef HAL_PCD_DeActiveRemoteWakeup(PCD_HandleTypeDef *hpcd); +/* Peripheral State functions **************************************************/ +PCD_StateTypeDef HAL_PCD_GetState(PCD_HandleTypeDef *hpcd); + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + + +#endif /* __STM32L0xx_HAL_PCD_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_pcd_ex.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_pcd_ex.c new file mode 100644 index 0000000000..327e10af51 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_pcd_ex.c @@ -0,0 +1,151 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_pcd_ex.c + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief Extended PCD HAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the USB Peripheral Controller: + * + Configururation of the PMA for EP + * + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @defgroup PCDEx + * @brief PCDEx HAL module driver + * @{ + */ + +#ifdef HAL_PCD_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ + + +/** @defgroup PCDEx_Private_Functions + * @{ + */ + +/** @defgroup PCDEx_Group1 Initialization and de-initialization functions + * @brief Initialization and Configuration functions + * +@verbatim + =============================================================================== + ##### Peripheral extended features methods ##### + =============================================================================== +@endverbatim + * @{ + */ + +/** + * @brief Configure PMA for EP + * @param pdev : Device instance + * @param ep_addr: endpoint address + * @param ep_Kind: endpoint Kind + * @arg USB_SNG_BUF: Single Buffer used + * @arg USB_DBL_BUF: Double Buffer used + * @param pmaadress: EP address in The PMA: In case of single buffer endpoint + * this parameter is 16-bit value providing the address + * in PMA allocated to endpoint. + * In case of double buffer endpoint this parameter + * is a 32-bit value providing the endpoint buffer 0 address + * in the LSB part of 32-bit value and endpoint buffer 1 address + * in the MSB part of 32-bit value. + * @retval : status + */ + +HAL_StatusTypeDef HAL_PCDEx_PMAConfig(PCD_HandleTypeDef *hpcd, + uint16_t ep_addr, + uint16_t ep_kind, + uint32_t pmaadress) + +{ + PCD_EPTypeDef *ep; + + /* initialize ep structure*/ + if ((0x80 & ep_addr) == 0x80) + { + ep = &hpcd->IN_ep[ep_addr & 0x7F]; + } + else + { + ep = &hpcd->OUT_ep[ep_addr]; + } + + /* Here we check if the endpoint is single or double Buffer*/ + if (ep_kind == PCD_SNG_BUF) + { + /*Single Buffer*/ + ep->doublebuffer = 0; + /*Configure te PMA*/ + ep->pmaadress = (uint16_t)pmaadress; + } + else /*USB_DBL_BUF*/ + { + /*Double Buffer Endpoint*/ + ep->doublebuffer = 1; + /*Configure the PMA*/ + ep->pmaaddr0 = pmaadress & 0xFFFF; + ep->pmaaddr1 = (pmaadress & 0xFFFF0000) >> 16; + } + + return HAL_OK; +} +/** + * @} + */ + + +/** + * @} + */ + +#endif /* HAL_PCD_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_pcd_ex.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_pcd_ex.h new file mode 100644 index 0000000000..d5234d0fbe --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_pcd_ex.h @@ -0,0 +1,82 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_pcd.h + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief Header file of PCD HAL module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32L0xx_HAL_PCD_EX_H +#define __STM32L0xx_HAL_PCD_EX_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal_def.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @addtogroup PCDEx + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/* Exported constants --------------------------------------------------------*/ +/* Exported macros -----------------------------------------------------------*/ +/* Internal macros -----------------------------------------------------------*/ +/* Exported functions --------------------------------------------------------*/ +HAL_StatusTypeDef HAL_PCDEx_PMAConfig(PCD_HandleTypeDef *hpcd, + uint16_t ep_addr, + uint16_t ep_kind, + uint32_t pmaadress); + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + + +#endif /* __STM32L0xx_HAL_PCD_EX_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_pwr.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_pwr.c new file mode 100644 index 0000000000..76b1a0314b --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_pwr.c @@ -0,0 +1,644 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_pwr.c + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief PWR HAL module driver. + * + * This file provides firmware functions to manage the following + * functionalities of the Power Controller (PWR) peripheral: + * + Initialization/de-initialization functions + * + Peripheral Control functions + * + @verbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @defgroup PWR + * @brief PWR HAL module driver + * @{ + */ + +#ifdef HAL_PWR_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup PWR_Private_Functions + * @{ + */ + +/** @defgroup PWR_Group1 Initialization and de-initialization functions + * @brief Initialization and de-initialization functions + * +@verbatim + =============================================================================== + ##### Initialization and de-initialization functions ##### + =============================================================================== + [..] + After reset, the backup domain (RTC registers, RTC backup data + registers) is protected against possible unwanted + write accesses. + To enable access to the RTC Domain and RTC registers, proceed as follows: + (+) Enable the Power Controller (PWR) APB1 interface clock using the + __PWR_CLK_ENABLE() macro. + (+) Enable access to RTC domain using the HAL_PWR_EnableBkUpAccess() function. + +@endverbatim + * @{ + */ + +/** + * @brief Deinitializes the HAL PWR peripheral registers to their default reset values. + * @param None + * @retval None + */ +void HAL_PWR_DeInit(void) +{ + __PWR_FORCE_RESET(); + __PWR_RELEASE_RESET(); +} + +/** + * @brief Enables access to the backup domain (RTC registers, RTC + * backup data registers ). + * @note If the HSE divided by 2, 4, 8 or 16 is used as the RTC clock, the + * Backup Domain Access should be kept enabled. + * @param None + * @retval None + */ +void HAL_PWR_EnableBkUpAccess(void) +{ + /* Enable access to RTC and backup registers */ + PWR->CR |= PWR_CR_DBP; +} + +/** + * @brief Disables access to the backup domain (RTC registers, RTC + * backup data registers). + * @note If the HSE divided by 2, 4, 8 or 16 is used as the RTC clock, the + * Backup Domain Access should be kept enabled. + * @param None + * @retval None + */ +void HAL_PWR_DisableBkUpAccess(void) +{ + /* Disable access to RTC and backup registers */ + PWR->CR &= (uint32_t)~((uint32_t)PWR_CR_DBP); +} + +/** + * @} + */ + +/** @defgroup PWR_Group2 Peripheral Control functions + * @brief Low Power modes configuration functions + * +@verbatim + + =============================================================================== + ##### Peripheral Control functions ##### + =============================================================================== + + *** PVD configuration *** + ========================= + [..] + (+) The PVD is used to monitor the VDD power supply by comparing it to a + threshold selected by the PVD Level (PLS[2:0] bits in the PWR_CR). + (+) The PVD can use an external input analog voltage (PVD_IN) which is compared + internally to VREFINT. The PVD_IN (PB7) has to be configured in Analog mode + when PWR_PVDLevel_7 is selected (PLS[2:0] = 111). + + (+) A PVDO flag is available to indicate if VDD/VDDA is higher or lower + than the PVD threshold. This event is internally connected to the EXTI + line16 and can generate an interrupt if enabled. This is done through + __HAL_PVD_EXTI_ENABLE_IT() macro. + (+) The PVD is stopped in Standby mode. + + *** WakeUp pin configuration *** + ================================ + [..] + (+) WakeUp pin is used to wake up the system from Standby mode. This pin is + forced in input pull-down configuration and is active on rising edges. + (+) There are two WakeUp pins: + WakeUp Pin 1 on PA.00. + WakeUp Pin 2 on PC.13. + + [..] + *** Main and Backup Regulators configuration *** + ================================================ + + (+) The main internal regulator can be configured to have a tradeoff between + performance and power consumption when the device does not operate at + the maximum frequency. This is done through __HAL_PWR_VOLTAGESCALING_CONFIG() + macro which configure VOS bit in PWR_CR register: + (++) When this bit is set (Regulator voltage output Scale 1 mode selected) + the System frequency can go up to 32 MHz. + (++) When this bit is reset (Regulator voltage output Scale 2 mode selected) + the System frequency can go up to 16 MHz. + (++) When this bit is reset (Regulator voltage output Scale 3 mode selected) + the System frequency can go up to 4.2 MHz. + + Refer to the datasheets for more details. + + *** Low Power modes configuration *** + ===================================== + [..] + The device features 5 low-power modes: + (+) Low power run mode: regulator in low power mode, limited clock frequency, + limited number of peripherals running. + (+) Sleep mode: Cortex-M0+ core stopped, peripherals kept running. + (+) Low power sleep mode: Cortex-M0+ core stopped, limited clock frequency, + limited number of peripherals running, regulator in low power mode. + (+) Stop mode: All clocks are stopped, regulator running, regulator in low power mode. + (+) Standby mode: VCORE domain powered off + + *** Low power run mode *** + ========================= + [..] + To further reduce the consumption when the system is in Run mode, the regulator can be + configured in low power mode. In this mode, the system frequency should not exceed + MSI frequency range1. + In Low power run mode, all I/O pins keep the same state as in Run mode. + + (+) Entry: + (++) VCORE in range2 + (++) Decrease the system frequency tonot exceed the frequency of MSI frequency range1. + (++) The regulator is forced in low power mode using the HAL_PWREx_EnableLowPowerRunMode() + function. + (+) Exit: + (++) The regulator is forced in Main regulator mode using the HAL_PWREx_DisableLowPowerRunMode() + function. + (++) Increase the system frequency if needed. + + *** Sleep mode *** + ================== + [..] + (+) Entry: + The Sleep mode is entered by using the HAL_PWR_EnterSLEEPMode(PWR_MAINREGULATOR_ON, PWR_SLEEPENTRY_WFx) + functions with + (++) PWR_SLEEPENTRY_WFI: enter SLEEP mode with WFI instruction + (++) PWR_SLEEPENTRY_WFE: enter SLEEP mode with WFE instruction + + (+) Exit: + (++) Any peripheral interrupt acknowledged by the nested vectored interrupt + controller (NVIC) can wake up the device from Sleep mode. + + *** Low power sleep mode *** + ============================ + [..] + (+) Entry: + The Low power sleep mode is entered by using the HAL_PWR_EnterSLEEPMode(PWR_LOWPOWERREGULATOR_ON, PWR_SLEEPENTRY_WFx) + functions with + (++) PWR_SLEEPENTRY_WFI: enter SLEEP mode with WFI instruction + (++) PWR_SLEEPENTRY_WFE: enter SLEEP mode with WFE instruction + (+) The Flash memory can be switched off by using the control bits (SLEEP_PD in the FLASH_ACR register. + This reduces power consumption but increases the wake-up time. + + (+) Exit: + (++) If the WFI instruction was used to enter Low power sleep mode, any peripheral interrupt + acknowledged by the nested vectored interrupt controller (NVIC) can wake up the device + from Low power sleep mode. If the WFE instruction was used to enter Low power sleep mode, + the MCU exits Sleep mode as soon as an event occurs. + + *** Stop mode *** + ================= + [..] + The Stop mode is based on the Cortex™-M0+ deepsleep mode combined with peripheral + clock gating. The voltage regulator can be configured either in normal or low-power mode. + In Stop mode, all clocks in the VCORE domain are stopped, the PLL, the MSI, the HSI and + the HSE RC oscillators are disabled. Internal SRAM and register contents are preserved. + To get the lowest consumption in Stop mode, the internal Flash memory also enters low + power mode. When the Flash memory is in power-down mode, an additional startup delay is + incurred when waking up from Stop mode. + To minimize the consumption In Stop mode, VREFINT, the BOR, PVD, and temperature + sensor can be switched off before entering Stop mode. They can be switched on again by + software after exiting Stop mode using the ULP bit in the PWR_CR register. + In Stop mode, all I/O pins keep the same state as in Run mode. + + (+) Entry: + The Stop mode is entered using the HAL_PWR_EnterSTOPMode(PWR_MAINREGULATOR_ON, PWR_SLEEPENTRY_WFI ) + function with: + (++) Main regulator ON. + (++) Low Power regulator ON. + (++) PWR_SLEEPENTRY_WFI: enter SLEEP mode with WFI instruction + (++) PWR_SLEEPENTRY_WFE: enter SLEEP mode with WFE instruction + (+) Exit: + (++) By issuing an interrupt or a wakeup event, the MSI or HSI16 RC + oscillator is selected as system clock depending the bit STOPWUCK in the RCC_CFGR + register + + *** Standby mode *** + ==================== + [..] + The Standby mode allows to achieve the lowest power consumption. It is based on the + Cortex™-M0+ deepsleep mode, with the voltage regulator disabled. The VCORE domain is + consequently powered off. The PLL, the MSI, the HSI oscillator and the HSE oscillator are + also switched off. SRAM and register contents are lost except for the RTC registers, RTC + backup registers and Standby circuitry. + + To minimize the consumption In Standby mode, VREFINT, the BOR, PVD, and temperature + sensor can be switched off before entering the Standby mode. They can be switched + on again by software after exiting the Standby mode. + function. + + (+) Entry: + (++) The Standby mode is entered using the HAL_PWR_EnterSTANDBYMode() function. + (+) Exit: + (++) WKUP pin rising edge, RTC alarm (Alarm A and Alarm B), RTC wakeup, + tamper event, time-stamp event, external reset in NRST pin, IWDG reset. + + *** Auto-wakeup (AWU) from low-power mode *** + ============================================= + [..] + The MCU can be woken up from low-power mode by an RTC Alarm event, an RTC + Wakeup event, a tamper event, a time-stamp event, or a comparator event, + without depending on an external interrupt (Auto-wakeup mode). + + (+) RTC auto-wakeup (AWU) from the Stop mode + (++) To wake up from the Stop mode with an RTC alarm event, it is necessary to: + (+++) Configure the EXTI Line 17 to be sensitive to rising edges (Interrupt + or Event modes) using the EXTI_Init() function. + (+++) Enable the RTC Alarm Interrupt using the RTC_ITConfig() function + (+++) Configure the RTC to generate the RTC alarm using the RTC_SetAlarm() + and RTC_AlarmCmd() functions. + (++) To wake up from the Stop mode with an RTC Tamper or time stamp event, it + is necessary to: + (+++) Configure the EXTI Line 19 to be sensitive to rising edges (Interrupt + or Event modes) using the EXTI_Init() function. + (+++) Enable the RTC Tamper or time stamp Interrupt using the RTC_ITConfig() + function. + (+++) Configure the RTC to detect the tamper or time stamp event using the + RTC_TimeStampConfig(), RTC_TamperTriggerConfig() and RTC_TamperCmd() + functions. + (++) To wake up from the Stop mode with an RTC WakeUp event, it is necessary to: + (+++) Configure the EXTI Line 20 to be sensitive to rising edges (Interrupt + or Event modes) using the EXTI_Init() function. + (+++) Enable the RTC WakeUp Interrupt using the RTC_ITConfig() function. + (+++) Configure the RTC to generate the RTC WakeUp event using the RTC_WakeUpClockConfig(), + RTC_SetWakeUpCounter() and RTC_WakeUpCmd() functions. + + (+) RTC auto-wakeup (AWU) from the Standby mode + (++) To wake up from the Standby mode with an RTC alarm event, it is necessary to: + (+++) Enable the RTC Alarm Interrupt using the RTC_ITConfig() function. + (+++) Configure the RTC to generate the RTC alarm using the RTC_SetAlarm() + and RTC_AlarmCmd() functions. + (++) To wake up from the Standby mode with an RTC Tamper or time stamp event, it + is necessary to: + (+++) Enable the RTC Tamper or time stamp Interrupt using the RTC_ITConfig() + function. + (+++) Configure the RTC to detect the tamper or time stamp event using the + RTC_TimeStampConfig(), RTC_TamperTriggerConfig() and RTC_TamperCmd() + functions. + (++) To wake up from the Standby mode with an RTC WakeUp event, it is necessary to: + (+++) Enable the RTC WakeUp Interrupt using the RTC_ITConfig() function + (+++) Configure the RTC to generate the RTC WakeUp event using the RTC_WakeUpClockConfig(), + RTC_SetWakeUpCounter() and RTC_WakeUpCmd() functions. + + (+) Comparator auto-wakeup (AWU) from the Stop mode + (++) To wake up from the Stop mode with an comparator 1 or comparator 2 wakeup + event, it is necessary to: + (+++) Configure the EXTI Line 21 for comparator 1 or EXTI Line 22 for comparator 2 + to be sensitive to to the selected edges (falling, rising or falling + and rising) (Interrupt or Event modes) using the EXTI_Init() function. + (+++) Configure the comparator to generate the event. + + + +@endverbatim + * @{ + */ + +/** + * @brief Configures the voltage threshold detected by the Power Voltage Detector(PVD). + * @param sConfigPVD: pointer to an PWR_PVDTypeDef structure that contains the configuration + * information for the PVD. + * @note Refer to the electrical characteristics of your device datasheet for + * more details about the voltage threshold corresponding to each + * detection level. + * @retval None + */ +void HAL_PWR_PVDConfig(PWR_PVDTypeDef *sConfigPVD) +{ + uint32_t tmpreg = 0; + + /* Check the parameters */ + assert_param(IS_PWR_PVD_LEVEL(sConfigPVD->PVDLevel)); + + tmpreg = PWR->CR; + + /* Clear PLS[7:5] bits */ + tmpreg &= ~ (uint32_t)PWR_CR_PLS; + + /* Set PLS[7:5] bits according to PVDLevel value */ + tmpreg |= sConfigPVD->PVDLevel; + + /* Store the new value */ + PWR->CR = tmpreg; + + /* Configure the EXTI 16 interrupt */ + if((sConfigPVD->Mode == PWR_MODE_IT_RISING_FALLING) ||\ + (sConfigPVD->Mode == PWR_MODE_IT_FALLING) ||\ + (sConfigPVD->Mode == PWR_MODE_IT_RISING)) + { + __HAL_PVD_EXTI_ENABLE_IT(PWR_EXTI_LINE_PVD); + } + /* Configure the rising edge */ + if((sConfigPVD->Mode == PWR_MODE_IT_RISING_FALLING) ||\ + (sConfigPVD->Mode == PWR_MODE_IT_RISING)) + { + EXTI->RTSR |= PWR_EXTI_LINE_PVD; + } + /* Configure the falling edge */ + if((sConfigPVD->Mode == PWR_MODE_IT_RISING_FALLING) ||\ + (sConfigPVD->Mode == PWR_MODE_IT_FALLING)) + { + EXTI->FTSR |= PWR_EXTI_LINE_PVD; + } +} + +/** + * @brief Enables the Power Voltage Detector(PVD). + * @param None + * @retval None + */ +void HAL_PWR_EnablePVD(void) +{ + /* Enable the power voltage detector */ + PWR->CR |= PWR_CR_PVDE; +} + +/** + * @brief Disables the Power Voltage Detector(PVD). + * @param None + * @retval None + */ +void HAL_PWR_DisablePVD(void) +{ + /* Disable the power voltage detector */ + PWR->CR &= (uint32_t)~((uint32_t)PWR_CR_PVDE); +} + +/** + * @brief Enables the WakeUp PINx functionality. + * @param WakeUpPinx: Specifies the Power Wake-Up pin to enable. + * This parameter can be one of the following values: + * @arg PWR_WAKEUP_PIN1 + * @arg PWR_WAKEUP_PIN2 + * @retval None + */ +void HAL_PWR_EnableWakeUpPin(uint32_t WakeUpPinx) +{ + /* Check the parameter */ + assert_param(IS_PWR_WAKEUP_PIN(WakeUpPinx)); + /* Enable the EWUPx pin */ + PWR->CSR |= WakeUpPinx; +} + +/** + * @brief Disables the WakeUp PINx functionality. + * @param WakeUpPinx: Specifies the Power Wake-Up pin to disable. + * This parameter can be one of the following values: + * @arg PWR_WAKEUP_PIN1 + * @arg PWR_WAKEUP_PIN2 + * @retval None + */ +void HAL_PWR_DisableWakeUpPin(uint32_t WakeUpPinx) +{ + /* Check the parameter */ + assert_param(IS_PWR_WAKEUP_PIN(WakeUpPinx)); + /* Disable the EWUPx pin */ + PWR->CSR &= ~WakeUpPinx; +} + +/** + * @brief Enters Sleep mode. + * @note In Sleep mode, all I/O pins keep the same state as in Run mode. + * @param Regulator: Specifies the regulator state in SLEEP mode. + * This parameter can be one of the following values: + * @arg PWR_MAINREGULATOR_ON: SLEEP mode with regulator ON + * @arg PWR_LOWPOWERREGULATOR_ON: SLEEP mode with low power regulator ON + * @param SLEEPEntry: Specifies if SLEEP mode is entered with WFI or WFE instruction. + * When WFI entry is used, tick interrupt have to be disabled if not desired as + * the interrupt wake up source. + * This parameter can be one of the following values: + * @arg PWR_SLEEPENTRY_WFI: enter SLEEP mode with WFI instruction + * @arg PWR_SLEEPENTRY_WFE: enter SLEEP mode with WFE instruction + * @retval None + */ +void HAL_PWR_EnterSLEEPMode(uint32_t Regulator, uint8_t SLEEPEntry) +{ + uint32_t tmpreg = 0; + /* Check the parameters */ + assert_param(IS_PWR_REGULATOR(Regulator)); + assert_param(IS_PWR_SLEEP_ENTRY(SLEEPEntry)); + + /* Select the regulator state in Sleep mode ---------------------------------*/ + tmpreg = PWR->CR; + /* Clear PDDS and LPDS bits */ + tmpreg &= (uint32_t)~(PWR_CR_PDDS | PWR_CR_LPSDSR); + + /* Set LPSDSR bit according to PWR_Regulator value */ + tmpreg |= Regulator; + + /* Store the new value */ + PWR->CR = tmpreg; + + /* Clear SLEEPDEEP bit of Cortex System Control Register */ + SCB->SCR &= (uint32_t)~((uint32_t)SCB_SCR_SLEEPDEEP_Msk); + + /* Select SLEEP mode entry -------------------------------------------------*/ + if(SLEEPEntry == PWR_SLEEPENTRY_WFI) + { + /* Request Wait For Interrupt */ + __WFI(); + } + else + { + /* Request Wait For Event */ + __SEV(); + __WFE(); + __WFE(); + } + +} + +/** + * @brief Enters Stop mode. + * @note In Stop mode, all I/O pins keep the same state as in Run mode. + * @note When exiting Stop mode by issuing an interrupt or a wakeup event, + * MSI or HSI16 RCoscillator is selected as system clock depending + * the bit STOPWUCK in the RCC_CFGR register. + * @note When the voltage regulator operates in low power mode, an additional + * startup delay is incurred when waking up from Stop mode. + * By keeping the internal regulator ON during Stop mode, the consumption + * is higher although the startup time is reduced. + * @param Regulator: Specifies the regulator state in Stop mode. + * This parameter can be one of the following values: + * @arg PWR_MAINREGULATOR_ON: Stop mode with regulator ON + * @arg PWR_LOWPOWERREGULATOR_ON: Stop mode with low power regulator ON + * @param STOPEntry: Specifies if Stop mode in entered with WFI or WFE instruction. + * This parameter can be one of the following values: + * @arg PWR_STOPENTRY_WFI: Enter Stop mode with WFI instruction + * @arg PWR_STOPENTRY_WFE: Enter Stop mode with WFE instruction + * @retval None + */ +void HAL_PWR_EnterSTOPMode(uint32_t Regulator, uint8_t STOPEntry) +{ + uint32_t tmpreg = 0; + + /* Check the parameters */ + assert_param(IS_PWR_REGULATOR(Regulator)); + assert_param(IS_PWR_STOP_ENTRY(STOPEntry)); + + /* Select the regulator state in Stop mode ---------------------------------*/ + tmpreg = PWR->CR; + /* Clear PDDS and LPDS bits */ + tmpreg &= (uint32_t)~(PWR_CR_PDDS | PWR_CR_LPSDSR); + + /* Set LPSDSR bit according to PWR_Regulator value */ + tmpreg |= Regulator; + + /* Store the new value */ + PWR->CR = tmpreg; + + /* Set SLEEPDEEP bit of Cortex System Control Register */ + SCB->SCR |= SCB_SCR_SLEEPDEEP_Msk; + + /* Select Stop mode entry --------------------------------------------------*/ + if(STOPEntry == PWR_STOPENTRY_WFI) + { + /* Request Wait For Interrupt */ + __WFI(); + } + else + { + /* Request Wait For Event */ + __SEV(); + __WFE(); + __WFE(); + } + + /* Reset SLEEPDEEP bit of Cortex System Control Register */ + SCB->SCR &= (uint32_t)~((uint32_t)SCB_SCR_SLEEPDEEP_Msk); +} + +/** + * @brief Enters Standby mode. + * @note In Standby mode, all I/O pins are high impedance except for: + * - Reset pad (still available) + * - RTC_AF1 pin (PC13) if configured for tamper, time-stamp, RTC + * Alarm out, or RTC clock calibration out. + * - RTC_AF2 pin (PC13) if configured for tamper. + * - WKUP pin 1 (PA0) if enabled. + * - WKUP pin 2 (PC13) if enabled. + * @param None + * @retval None + */ +void HAL_PWR_EnterSTANDBYMode(void) +{ + /* Clear Wakeup flag */ + PWR->CR |= PWR_CR_CWUF; + + /* Select Standby mode */ + PWR->CR |= PWR_CR_PDDS; + + /* Set SLEEPDEEP bit of Cortex System Control Register */ + SCB->SCR |= SCB_SCR_SLEEPDEEP_Msk; + + /* This option is used to ensure that store operations are completed */ +#if defined ( __CC_ARM) + __force_stores(); +#endif + /* Request Wait For Interrupt */ + __WFI(); +} + +/** + * @brief This function handles the PWR PVD interrupt request. + * @note This API should be called under the PVD_IRQHandler(). + * @param None + * @retval None + */ +void HAL_PWR_PVD_IRQHandler(void) +{ + /* Check PWR exti flag */ + if(__HAL_PVD_EXTI_GET_FLAG(PWR_EXTI_LINE_PVD) != RESET) + { + /* PWR PVD interrupt user callback */ + HAL_PWR_PVDCallback(); + + /* Clear PWR Exti pending bit */ + __HAL_PVD_EXTI_CLEAR_FLAG(PWR_EXTI_LINE_PVD); + } +} + +/** + * @brief PWR PVD interrupt callback + * @param None + * @retval None + */ +__weak void HAL_PWR_PVDCallback(void) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_PWR_PVDCallback could be implemented in the user file + */ +} + +/** + * @} + */ + +/** + * @} + */ + +#endif /* HAL_PWR_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_pwr.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_pwr.h new file mode 100644 index 0000000000..2a4d10d622 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_pwr.h @@ -0,0 +1,334 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_pwr.h + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief Header file of PWR HAL module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32L0xx_HAL_PWR_H +#define __STM32L0xx_HAL_PWR_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal_def.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @addtogroup PWR + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/** + * @brief PWR PVD configuration structure definition + */ +typedef struct +{ + uint32_t PVDLevel; /*!< PVDLevel: Specifies the PVD detection level. + This parameter can be a value of @ref PWR_PVD_detection_level */ + + uint32_t Mode; /*!< Mode: Specifies the operating mode for the selected pins. + This parameter can be a value of @ref PWR_PVD_Mode */ +}PWR_PVDTypeDef; + +/* Exported constants --------------------------------------------------------*/ + +/** @defgroup PWR_Exported_Constants + * @{ + */ + +/** @defgroup PWR_WakeUp_Pins + * @{ + */ + +#define PWR_WAKEUP_PIN1 PWR_CSR_EWUP1 +#define PWR_WAKEUP_PIN2 PWR_CSR_EWUP2 +#define IS_PWR_WAKEUP_PIN(PIN) (((PIN) == PWR_WAKEUP_PIN1) || \ + ((PIN) == PWR_WAKEUP_PIN2)) +/** + * @} + */ + +/** @defgroup PWR_PVD_detection_level + * @{ + */ +#define PWR_PVDLEVEL_0 PWR_CR_PLS_LEV0 +#define PWR_PVDLEVEL_1 PWR_CR_PLS_LEV1 +#define PWR_PVDLEVEL_2 PWR_CR_PLS_LEV2 +#define PWR_PVDLEVEL_3 PWR_CR_PLS_LEV3 +#define PWR_PVDLEVEL_4 PWR_CR_PLS_LEV4 +#define PWR_PVDLEVEL_5 PWR_CR_PLS_LEV5 +#define PWR_PVDLEVEL_6 PWR_CR_PLS_LEV6 +#define PWR_PVDLEVEL_7 PWR_CR_PLS_LEV7 /* External input analog voltage + (Compare internally to VREFINT) */ +#define IS_PWR_PVD_LEVEL(LEVEL) (((LEVEL) == PWR_PVDLEVEL_0) || ((LEVEL) == PWR_PVDLEVEL_1)|| \ + ((LEVEL) == PWR_PVDLEVEL_2) || ((LEVEL) == PWR_PVDLEVEL_3)|| \ + ((LEVEL) == PWR_PVDLEVEL_4) || ((LEVEL) == PWR_PVDLEVEL_5)|| \ + ((LEVEL) == PWR_PVDLEVEL_6) || ((LEVEL) == PWR_PVDLEVEL_7)) +/** + * @} + */ + +/** @defgroup PWR_PVD_Mode + * @{ + */ +#define PWR_MODE_EVT ((uint32_t)0x00000000) /*!< No Interrupt */ +#define PWR_MODE_IT_RISING ((uint32_t)0x00000001) /*!< External Interrupt Mode with Rising edge trigger detection */ +#define PWR_MODE_IT_FALLING ((uint32_t)0x00000002) /*!< External Interrupt Mode with Falling edge trigger detection */ +#define PWR_MODE_IT_RISING_FALLING ((uint32_t)0x00000003) /*!< External Interrupt Mode with Rising/Falling edge trigger detection */ +#define IS_PWR_PVD_MODE(MODE) (((MODE) == PWR_MODE_EVT) || ((MODE) == PWR_MODE_IT_RISING)|| \ + ((MODE) == PWR_MODE_IT_FALLING) || ((MODE) == PWR_MODE_IT_RISING_FALLING)) +/** + * @} + */ + +/** @defgroup PWR_Regulator_state_in_SLEEP_STOP_mode + * @{ + */ +#define PWR_MAINREGULATOR_ON ((uint32_t)0x00000000) +#define PWR_LOWPOWERREGULATOR_ON PWR_CR_LPSDSR + +#define IS_PWR_REGULATOR(REGULATOR) (((REGULATOR) == PWR_MAINREGULATOR_ON) || \ + ((REGULATOR) == PWR_LOWPOWERREGULATOR_ON)) +/** + * @} + */ + +/** @defgroup PWR_SLEEP_mode_entry + * @{ + */ +#define PWR_SLEEPENTRY_WFI ((uint8_t)0x01) +#define PWR_SLEEPENTRY_WFE ((uint8_t)0x02) +#define IS_PWR_SLEEP_ENTRY(ENTRY) (((ENTRY) == PWR_SLEEPENTRY_WFI) || ((ENTRY) == PWR_SLEEPENTRY_WFE)) +/** + * @} + */ + +/** @defgroup PWR_STOP_mode_entry + * @{ + */ +#define PWR_STOPENTRY_WFI ((uint8_t)0x01) +#define PWR_STOPENTRY_WFE ((uint8_t)0x02) +#define IS_PWR_STOP_ENTRY(ENTRY) (((ENTRY) == PWR_STOPENTRY_WFI) || ((ENTRY) == PWR_STOPENTRY_WFE) ) +/** + * @} + */ + +/** @defgroup PWR_Regulator_Voltage_Scale + * @{ + */ + +#define PWR_REGULATOR_VOLTAGE_SCALE1 PWR_CR_VOS_0 +#define PWR_REGULATOR_VOLTAGE_SCALE2 PWR_CR_VOS_1 +#define PWR_REGULATOR_VOLTAGE_SCALE3 PWR_CR_VOS + +#define IS_PWR_VOLTAGE_SCALING_RANGE(RANGE) (((RANGE) == PWR_REGULATOR_VOLTAGE_SCALE1) || \ + ((RANGE) == PWR_REGULATOR_VOLTAGE_SCALE2) || \ + ((RANGE) == PWR_REGULATOR_VOLTAGE_SCALE3)) +/** + * @} + */ + +/** @defgroup PWR_Flag + * @{ + */ +#define PWR_FLAG_WU PWR_CSR_WUF +#define PWR_FLAG_SB PWR_CSR_SBF +#define PWR_FLAG_PVDO PWR_CSR_PVDO +#define PWR_FLAG_VREFINTRDY PWR_CSR_VREFINTRDYF +#define PWR_FLAG_VOS PWR_CSR_VOSF +#define PWR_FLAG_REGLP PWR_CSR_REGLPF + +/** + * @} + */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ +/** @defgroup PWR_Exported_Macro + * @{ + */ + +/** @brief macros configure the main internal regulator output voltage. + * @param __REGULATOR__: specifies the regulator output voltage to achieve + * a tradeoff between performance and power consumption when the device does + * not operate at the maximum frequency (refer to the datasheets for more details). + * This parameter can be one of the following values: + * @arg PWR_REGULATOR_VOLTAGE_SCALE1: Regulator voltage output Scale 1 mode, + * System frequency up to 32 MHz. + * @arg PWR_REGULATOR_VOLTAGE_SCALE2: Regulator voltage output Scale 2 mode, + * System frequency up to 16 MHz. + * @arg PWR_REGULATOR_VOLTAGE_SCALE3: Regulator voltage output Scale 3 mode, + * System frequency up to 4.2 MHz + * @retval None + */ +#define __HAL_PWR_VOLTAGESCALING_CONFIG(__REGULATOR__) (MODIFY_REG(PWR->CR, PWR_CR_VOS, (__REGULATOR__))) + +/** @brief Check PWR flag is set or not. + * @param __FLAG__: specifies the flag to check. + * This parameter can be one of the following values: + * @arg PWR_FLAG_WU: Wake Up flag. This flag indicates that a wakeup event + * was received from the WKUP pin or from the RTC alarm (Alarm B), + * RTC Tamper event, RTC TimeStamp event or RTC Wakeup. + * An additional wakeup event is detected if the WKUP pin is enabled + * (by setting the EWUP bit) when the WKUP pin level is already high. + * @arg PWR_FLAG_SB: StandBy flag. This flag indicates that the system was + * resumed from StandBy mode. + * @arg PWR_FLAG_PVDO: PVD Output. This flag is valid only if PVD is enabled + * by the HAL_PWR_EnablePVD() function. The PVD is stopped by Standby mode + * For this reason, this bit is equal to 0 after Standby or reset + * until the PVDE bit is set. + * @arg PWR_FLAG_VREFINTRDY: Internal voltage reference (VREFINT) ready flag. + * This bit indicates the state of the internal voltage reference, VREFINT. + * @arg PWR_FLAG_VOS: Voltage Scaling select flag. A delay is required for + * the internal regulator to be ready after the voltage range is changed. + * The VOSF bit indicates that the regulator has reached the voltage level + * defined with bits VOS of PWR_CR register. + * @arg PWR_FLAG_REGLP: Regulator LP flag. When the MCU exits from Low power run + * mode, this bit stays at 1 until the regulator is ready in main mode. + * A polling on this bit is recommended to wait for the regulator main mode. + * This bit is reset by hardware when the regulator is ready. + * @retval The new state of __FLAG__ (TRUE or FALSE). + */ +#define __HAL_PWR_GET_FLAG(__FLAG__) ((PWR->CSR & (__FLAG__)) == (__FLAG__)) + +/** @brief Clear the PWR's pending flags. + * @param __FLAG__: specifies the flag to clear. + * This parameter can be one of the following values: + * @arg PWR_FLAG_WU: Wake Up flag + * @arg PWR_FLAG_SB: StandBy flag + */ +#define __HAL_PWR_CLEAR_FLAG(__FLAG__) (PWR->CR |= (__FLAG__) << 2) + +#define PWR_EXTI_LINE_PVD ((uint32_t)0x00010000) /*!< External interrupt line 16 Connected to the PVD EXTI Line */ +/** + * @brief Enable the PVD Exti Line. + * @param __EXTILINE__: specifies the PVD Exti sources to be enabled. + * This parameter can be: + * @arg PWR_EXTI_LINE_PVD + * @retval None. + */ +#define __HAL_PVD_EXTI_ENABLE_IT(__EXTILINE__) (EXTI->IMR |= (__EXTILINE__)) + +/** + * @brief Disable the PVD EXTI Line. + * @param __EXTILINE__: specifies the PVD EXTI sources to be disabled. + * This parameter can be: + * @arg PWR_EXTI_LINE_PVD + * @retval None. + */ +#define __HAL_PVD_EXTI_DISABLE_IT(__EXTILINE__) (EXTI->IMR &= ~(__EXTILINE__)) + +/** + * @brief Generates a Software interrupt on selected EXTI line. + * @param __EXTILINE__: specifies the PVD EXTI sources to be disabled. + * This parameter can be: + * @arg PWR_EXTI_LINE_PVD + * @retval None + */ +#define __HAL_PVD_EXTI_GENERATE_SWIT(__EXTI_LINE__) (EXTI->SWIER |= (__EXTI_LINE__)) + +/** + * @brief checks whether the specified PVD Exti interrupt flag is set or not. + * @param __EXTILINE__: specifies the PVD Exti sources to be cleared. + * This parameter can be: + * @arg PWR_EXTI_LINE_PVD + * @retval EXTI PVD Line Status. + */ +#define __HAL_PVD_EXTI_GET_FLAG(__EXTILINE__) (EXTI->PR & (__EXTILINE__)) + +/** + * @brief Clear the PVD Exti flag. + * @param __EXTILINE__: specifies the PVD Exti sources to be cleared. + * This parameter can be: + * @arg PWR_EXTI_LINE_PVD + * @retval None. + */ +#define __HAL_PVD_EXTI_CLEAR_FLAG(__EXTILINE__) (EXTI->PR = (__EXTILINE__)) + +/** + * @} + */ + +/* Include PWR HAL Extension module */ +#include "stm32l0xx_hal_pwr_ex.h" + +/* Exported functions --------------------------------------------------------*/ + +/* Initialization and de-initialization functions *******************************/ +void HAL_PWR_DeInit(void); +void HAL_PWR_EnableBkUpAccess(void); +void HAL_PWR_DisableBkUpAccess(void); + +/* Peripheral Control functions ************************************************/ +void HAL_PWR_PVDConfig(PWR_PVDTypeDef *sConfigPVD); +void HAL_PWR_EnablePVD(void); +void HAL_PWR_DisablePVD(void); + +/* WakeUp pins configuration functions ****************************************/ +void HAL_PWR_EnableWakeUpPin(uint32_t WakeUpPinx); +void HAL_PWR_DisableWakeUpPin(uint32_t WakeUpPinx); + +/* Low Power modes configuration functions ************************************/ +void HAL_PWR_EnterSTOPMode(uint32_t Regulator, uint8_t STOPEntry); +void HAL_PWR_EnterSLEEPMode(uint32_t Regulator, uint8_t SLEEPEntry); +void HAL_PWR_EnterSTANDBYMode(void); + +void HAL_PWR_PVD_IRQHandler(void); +void HAL_PWR_PVDCallback(void); + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + + +#endif /* __STM32L0xx_HAL_PWR_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_pwr_ex.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_pwr_ex.c new file mode 100644 index 0000000000..491d4db3a5 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_pwr_ex.c @@ -0,0 +1,174 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_pwr_ex.c + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief Extended PWR HAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the Power Controller (PWR) peripheral: + * + Extended Initialization and de-initialization functions + * + Extended Peripheral Control functions + * + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @defgroup PWREx + * @brief PWR HAL module driver + * @{ + */ + +#ifdef HAL_PWR_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup PWREx_Private_Functions + * @{ + */ + +/** @defgroup PWREx_Group1 Peripheral Extended features functions + * @brief Low Power modes configuration functions + * +@verbatim + + =============================================================================== + ##### Peripheral extended features functions ##### + =============================================================================== +@endverbatim + * @{ + */ + +/** + * @brief Enables the Fast WakeUp from Ultra Low Power mode. + * @note This bit works in conjunction with ULP bit. + * Means, when ULP = 1 and FWU = 1 :VREFINT startup time is ignored when + * exiting from low power mode. + * @param None + * @retval None + */ +void HAL_PWREx_EnableFastWakeUp(void) +{ + /* Enable the fast wake up */ + PWR->CR |= PWR_CR_FWU; +} + +/** + * @brief Disables the Fast WakeUp from Ultra Low Power mode. + * @param None + * @retval None + */ +void HAL_PWREx_DisableFastWakeUp(void) +{ + /* Disable the fast wake up */ + PWR->CR &= (uint32_t)~((uint32_t)PWR_CR_FWU); +} + +/** + * @brief Enables the Ultra Low Power mode + * @param None + * @retval None + */ +void HAL_PWREx_EnableUltraLowPower(void) +{ + /* Enable the Ultra Low Power mode */ + PWR->CR |= PWR_CR_ULP; +} + +/** + * @brief Disables the Ultra Low Power mode + * @param None + * @retval None + */ +void HAL_PWREx_DisableUltraLowPower(void) +{ + /* Disable the Ultra Low Power mode */ + PWR->CR &= (uint32_t)~((uint32_t)PWR_CR_ULP); +} + +/** + * @brief Enters the Low Power Run mode. + * @note Low power run mode can only be entered when VCORE is in range 2. + * In addition, the dynamic voltage scaling must not be used when Low + * power run mode is selected. Only Stop and Sleep modes with regulator + * configured in Low power mode is allowed when Low power run mode is + * selected. + * @note In Low power run mode, all I/O pins keep the same state as in Run mode. + * @param None + * @retval None + */ +void HAL_PWREx_EnableLowPowerRunMode(void) +{ + /* Enters the Low Power Run mode */ + PWR->CR |= PWR_CR_LPSDSR; + PWR->CR |= PWR_CR_LPRUN; +} + +/** + * @brief Exits the Low Power Run mode. + * @param None + * @retval None + */ +void HAL_PWREx_DisableLowPowerRunMode(void) +{ + /* Exits the Low Power Run mode */ + PWR->CR &= (uint32_t)~((uint32_t)PWR_CR_LPRUN); + PWR->CR &= (uint32_t)~((uint32_t)PWR_CR_LPSDSR); +} + +/** + * @} + */ + +/** + * @} + */ + +#endif /* HAL_PWR_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_pwr_ex.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_pwr_ex.h new file mode 100644 index 0000000000..649d879243 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_pwr_ex.h @@ -0,0 +1,102 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_pwr_ex.h + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief Header file of PWR HAL Extension module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32L0xx_HAL_PWR_EX_H +#define __STM32L0xx_HAL_PWR_EX_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal_def.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @addtogroup PWREx + * @{ + */ + + +/* Exported types ------------------------------------------------------------*/ +/* Exported constants --------------------------------------------------------*/ +/* Exported macro ------------------------------------------------------------*/ +/** @defgroup PWREx_Exported macro + * @{ + */ + +/** @brief Macros to enable or disable the Deep-sleep mode with Flash memory kept off. + * @note When entering low power mode (stop or standby only), if DS_EE_KOFF and RUN_PD of + * FLASH_ACR register are both set , the Flash memory will not be woken up + * when exiting from deep-sleep mode. + */ +#define __HAL_PWR_FLASHWAKEUP_ENABLE() CLEAR_BIT(PWR->CR, PWR_CR_DSEEKOFF) +#define __HAL_PWR_FLASHWAKEUP_DISABLE() SET_BIT(PWR->CR, PWR_CR_DSEEKOFF) +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ + +/* Peripheral Control methods ************************************************/ +void HAL_PWREx_EnableFastWakeUp(void); +void HAL_PWREx_DisableFastWakeUp(void); +void HAL_PWREx_EnableUltraLowPower(void); +void HAL_PWREx_DisableUltraLowPower(void); +void HAL_PWREx_EnableLowPowerRunMode(void); +void HAL_PWREx_DisableLowPowerRunMode(void); + + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + + +#endif /* __STM32L0xx_HAL_PWR_EX_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_rcc.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_rcc.c new file mode 100644 index 0000000000..d160605c95 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_rcc.c @@ -0,0 +1,1326 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_rcc.c + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief RCC HAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the Reset and Clock Control (RCC) peripheral: + * + Initialization and de-initialization functions + * + Peripheral Control functions + * + @verbatim + ============================================================================== + ##### RCC specific features ##### + ============================================================================== + [..] After reset the device is running from MSI (2 MHz) with Flash 0 WS, + all peripherals are off except internal SRAM, Flash and SW-DP. + (+) There is no prescaler on High speed (AHB) and Low speed (APB) busses; + all peripherals mapped on these busses are running at MSI speed. + (+) The clock for all peripherals is switched off, except the SRAM and + FLASH. + (+) All GPIOs are in input floating state, except the SW-DP pins which + are assigned to be used for debug purpose. + [..] Once the device started from reset, the user application has to: + (+) Configure the clock source to be used to drive the System clock + (if the application needs higher frequency/performance) + (+) Configure the System clock frequency and Flash settings + (+) Configure the AHB and APB busses prescalers + (+) Enable the clock for the peripheral(s) to be used + (+) Configure the clock source(s) for peripherals whose clocks are not + derived from the System clock (ADC, RTC/LCD, RNG and IWDG) + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @defgroup RCC + * @brief RCC HAL module driver + * @{ + */ + +#ifdef HAL_RCC_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +#define HSE_TIMEOUT_VALUE HSE_STARTUP_TIMEOUT +#define HSI_TIMEOUT_VALUE ((uint32_t)100) /* 100 ms */ +#define LSI_TIMEOUT_VALUE ((uint32_t)100) /* 100 ms */ +#define PLL_TIMEOUT_VALUE ((uint32_t)100) /* 100 ms */ +#define HSI48_TIMEOUT_VALUE ((uint32_t)100) /* 100 ms */ +#define MSI_TIMEOUT_VALUE ((uint32_t)100) /* 100 ms */ +#define CLOCKSWITCH_TIMEOUT_VALUE ((uint32_t)5000) /* 5 s */ + +/* Private macro -------------------------------------------------------------*/ +#define __MCO1_CLK_ENABLE() __GPIOA_CLK_ENABLE() +#define MCO1_GPIO_PORT GPIOA +#define MCO1_PIN GPIO_PIN_8 +#define MCO2_PIN GPIO_PIN_9 + +/* Private variables ---------------------------------------------------------*/ +extern const uint8_t PLLMulTable[]; +extern const uint8_t APBAHBPrescTable[]; +extern const uint32_t MSIRangeTable[]; + +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup RCC_Private_Functions + * @{ + */ + +/** @defgroup RCC_Group1 Initialization and de-initialization functions + * @brief Initialization and Configuration functions + * +@verbatim + =============================================================================== + ##### Initialization and de-initialization functions ##### + =============================================================================== + [..] + This section provide functions allowing to configure the internal/external + clocks, PLL, CSS and MCO. + [..] Internal/external clock and PLL configuration + (#) HSI (high-speed internal), 16 MHz factory-trimmed RC used directly + or through the PLL as System clock source. + (#) MSI (multi-speed internal), multispeed low power RC + (65.536 KHz to 4.194 MHz) MHz used as System clock source. + (#) LSI (low-speed internal), 37 KHz low consumption RC used as IWDG + and/or RTC clock source. + (#) HSE (high-speed external), 1 to 24 MHz crystal oscillator used + directly or through the PLL as System clock source. Can be used + also as RTC clock source. + (#) LSE (low-speed external), 32 KHz oscillator used as RTC clock source. + (#) PLL (clocked by HSI or HSE), for System clock and USB (48 MHz). + (#) CSS (Clock security system), once enable and if a HSE clock failure + occurs (HSE used directly or through PLL as System clock source), + the System clock is automatically switched to MSI and an interrupt + is generated if enabled. + The interrupt is linked to the Cortex-M3 NMI (Non-Maskable Interrupt) + exception vector. + (#) MCO (microcontroller clock output), used to output SYSCLK, HSI, MSI, + HSE, PLL, LSI or LSE clock (through a configurable prescaler) on + PA8 pin. + [..] System, AHB and APB busses clocks configuration + (#) Several clock sources can be used to drive the System clock (SYSCLK): MSI, HSI, + HSE and PLL. + The AHB clock (HCLK) is derived from System clock through configurable + prescaler and used to clock the CPU, memory and peripherals mapped + on IOPORT, AHB bus (DMA,Flash...). APB1 (PCLK1) and APB2 (PCLK2) clocks are derived + from AHB clock through configurable prescalers and used to clock + the peripherals mapped on these busses. You can use + "HAL_RCC_GetSysClockFreq()" function to retrieve the frequencies of these clocks. + + -@- All the peripheral clocks are derived from the System clock (SYSCLK) except: + (+@) I2S: the I2S clock can be derived from an external clock mapped on the I2S_CKIN pin. + + (+@) RTC: the RTC clock can be derived either from the LSI, LSE or HSE clock + divided by 2 to 16. You have to use __HAL_RCC_RTC_CONFIG() and __HAL_RCC_RTC_ENABLE() + macros to configure this clock. + (+@) USB FS,and RNG require a frequency equal to 48 MHz to work correctly + This clock is derived from the main PLL or HSI48 RC oscillator. + (+@) IWDG clock which is always the LSI clock. + + (#) For the STM32L0xx devices, the maximum + frequency of the SYSCLK ,HCLK, APB1 and APB2 is 32 MHz. + Depending on the device voltage range, the maximum frequency should + be adapted accordingly: + ---------------------------------------------------------------- + | Wait states | HCLK clock frequency (MHz) | + | |------------------------------------------------| + | (Latency) | voltage range | voltage range | + | | 1.65 V - 3.6 V | 2.0 V - 3.6 V | + | |----------------|---------------|---------------| + | | VCORE = 1.2 V | VCORE = 1.5 V | VCORE = 1.8 V | + |-------------- |----------------|---------------|---------------| + |0WS(1CPU cycle)|0 < HCLK <= 2 |0 < HCLK <= 8 |0 < HCLK <= 16 | + |---------------|----------------|---------------|---------------| + |1WS(2CPU cycle)|2 < HCLK <= 4 |8 < HCLK <= 16 |16 < HCLK <= 32| + ---------------------------------------------------------------- +@endverbatim + * @{ + */ + +/** + * @brief Resets the RCC clock configuration to the default reset state. + * @note The default reset state of the clock configuration is given below: + * - MSI ON and used as system clock source (MSI range is not modified + * - by this function, it keep the value configured by user application) + * - HSI, HSE and PLL OFF + * - AHB, APB1 and APB2 prescaler set to 1. + * - CSS and MCO OFF + * - All interrupts disabled + * @note This function doesn't modify the configuration of the + * @note -Peripheral clocks + * @note -HSI48, LSI, LSE and RTC clocks + * @param None + * @retval None + */ +void HAL_RCC_DeInit(void) +{ + /* Set MSION bit */ + SET_BIT(RCC->CR, RCC_CR_MSION); + + /* Reset HSION, HSEON, CSSON, PLLON */ + CLEAR_BIT(RCC->CR, RCC_CR_HSEON | RCC_CR_HSION| RCC_CR_HSIKERON| RCC_CR_CSSHSEON | RCC_CR_PLLON); + + /* Reset CFGR register */ + CLEAR_REG(RCC->CFGR); + + /* Reset HSEBYP bit */ + CLEAR_BIT(RCC->CR, RCC_CR_HSEBYP); + + /* Disable all interrupts */ + CLEAR_REG(RCC->CIER); +} + +/** + * @brief Initializes the RCC Oscillators according to the specified parameters in the + * RCC_OscInitTypeDef. + * @param RCC_OscInitStruct: pointer to an RCC_OscInitTypeDef structure that + * contains the configuration information for the RCC Oscillators. + * @note The PLL is not disabled when used as system clock. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct) +{ + + uint32_t tickstart = 0; + + /* Check the parameters */ + assert_param(IS_RCC_OSCILLATORTYPE(RCC_OscInitStruct->OscillatorType)); + /*------------------------------- HSE Configuration ------------------------*/ + if(((RCC_OscInitStruct->OscillatorType) & RCC_OSCILLATORTYPE_HSE) == RCC_OSCILLATORTYPE_HSE) + { + /* Check the parameters */ + assert_param(IS_RCC_HSE(RCC_OscInitStruct->HSEState)); + /* When the HSE is used as system clock or clock source for PLL in these cases HSE will not disabled */ + if((__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_CFGR_SWS_HSE) || ((__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_CFGR_SWS_PLL) && ((RCC->CFGR & RCC_CFGR_PLLSRC) == RCC_CFGR_PLLSRC_HSE))) + { + if((__HAL_RCC_GET_FLAG(RCC_FLAG_HSERDY) != RESET) && (RCC_OscInitStruct->HSEState != RCC_HSE_ON)) + { + return HAL_ERROR; + } + } + else + { + /* Reset HSEON and HSEBYP bits before configuring the HSE --------------*/ + __HAL_RCC_HSE_CONFIG(RCC_HSE_OFF); + + /* Get timeout */ + tickstart = HAL_GetTick(); + + /* Wait till HSE is disabled */ + while(__HAL_RCC_GET_FLAG(RCC_FLAG_HSERDY) != RESET) + { + if((HAL_GetTick() - tickstart ) > HSE_TIMEOUT_VALUE) + { + return HAL_TIMEOUT; + } + } + + /* Set the new HSE configuration ---------------------------------------*/ + __HAL_RCC_HSE_CONFIG(RCC_OscInitStruct->HSEState); + + /* Check the HSE State */ + if((RCC_OscInitStruct->HSEState) == RCC_HSE_ON) + { + /* Get timeout */ + tickstart = HAL_GetTick(); + + /* Wait till HSE is ready */ + while(__HAL_RCC_GET_FLAG(RCC_FLAG_HSERDY) == RESET) + { + if((HAL_GetTick() - tickstart ) > HSE_TIMEOUT_VALUE) + { + return HAL_TIMEOUT; + } + } + } + else + { + /* Get timeout */ + tickstart = HAL_GetTick(); + + /* Wait till HSE is bypassed or disabled */ + while(__HAL_RCC_GET_FLAG(RCC_FLAG_HSERDY) != RESET) + { + if((HAL_GetTick() - tickstart ) > HSE_TIMEOUT_VALUE) + { + return HAL_TIMEOUT; + } + } + } + } + } + /*----------------------------- HSI Configuration --------------------------*/ + if(((RCC_OscInitStruct->OscillatorType) & RCC_OSCILLATORTYPE_HSI) == RCC_OSCILLATORTYPE_HSI) + { + /* Check the parameters */ + assert_param(IS_RCC_HSI(RCC_OscInitStruct->HSIState)); + assert_param(IS_RCC_CALIBRATION_VALUE(RCC_OscInitStruct->HSICalibrationValue)); + + + /* Adjusts the Internal High Speed oscillator (HSI) calibration value.*/ + __HAL_RCC_HSI_CALIBRATIONVALUE_ADJUST(RCC_OscInitStruct->HSICalibrationValue); + + /* When the HSI is used as system clock it will not disabled */ + if((__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_CFGR_SWS_HSI) || ((__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_CFGR_SWS_PLL) && ((RCC->CFGR & RCC_CFGR_PLLSRC) == RCC_CFGR_PLLSRC_HSI))) + { + if((__HAL_RCC_GET_FLAG(RCC_FLAG_HSIRDY) != RESET) && (RCC_OscInitStruct->HSIState != RCC_HSI_ON)) + { + return HAL_ERROR; + } + } + else + { + /* Check the HSI State */ + if((RCC_OscInitStruct->HSIState)!= RCC_HSI_OFF) + { + /* Enable the Internal High Speed oscillator (HSI or HSIdiv4 */ + __HAL_RCC_HSI_CONFIG(RCC_OscInitStruct->HSIState); + + /* Get timeout */ + tickstart = HAL_GetTick(); + + /* Wait till HSI is ready */ + while(__HAL_RCC_GET_FLAG(RCC_FLAG_HSIRDY) == RESET) + { + if((HAL_GetTick() - tickstart ) > HSI_TIMEOUT_VALUE) + { + return HAL_TIMEOUT; + } + } + } + else + { + /* Disable the Internal High Speed oscillator (HSI). */ + __HAL_RCC_HSI_CONFIG(RCC_OscInitStruct->HSIState); + + /* Get timeout */ + tickstart = HAL_GetTick(); + + /* Wait till HSI is ready */ + while(__HAL_RCC_GET_FLAG(RCC_FLAG_HSIRDY) != RESET) + { + if((HAL_GetTick() - tickstart ) > HSI_TIMEOUT_VALUE) + { + return HAL_TIMEOUT; + } + } + } + } + } + /*----------------------------- MSI Configuration --------------------------*/ + if(((RCC_OscInitStruct->OscillatorType) & RCC_OSCILLATORTYPE_MSI) == RCC_OSCILLATORTYPE_MSI) + { + /* Check the parameters */ + assert_param(IS_RCC_MSI(RCC_OscInitStruct->MSIState)); + assert_param(IS_RCC_CALIBRATION_VALUE(RCC_OscInitStruct->MSICalibrationValue)); + + /* Selects the Internal High Speed oscillator (MSI) clock range .*/ + __HAL_RCC_MSI_RANGE_CONFIG (RCC_OscInitStruct->MSIClockRange); + + /* Adjusts the Internal High Speed oscillator (MSI) calibration value.*/ + __HAL_RCC_MSI_CALIBRATIONVALUE_ADJUST(RCC_OscInitStruct->MSICalibrationValue); + + /* When the MSI is used as system clock it will not disabled */ + if((__HAL_RCC_GET_SYSCLK_SOURCE() == RCC_CFGR_SWS_MSI) ) + { + if((__HAL_RCC_GET_FLAG(RCC_FLAG_MSIRDY) != RESET) && (RCC_OscInitStruct->MSIState != RCC_MSI_ON)) + { + return HAL_ERROR; + } + } + else + { + /* Check the MSI State */ + if((RCC_OscInitStruct->MSIState)!= RCC_MSI_OFF) + { + /* Enable the Internal High Speed oscillator (MSI). */ + __HAL_RCC_MSI_ENABLE(); + + /* Get timeout */ + tickstart = HAL_GetTick(); + + /* Wait till MSI is ready */ + while(__HAL_RCC_GET_FLAG(RCC_FLAG_MSIRDY) == RESET) + { + if((HAL_GetTick() - tickstart ) > MSI_TIMEOUT_VALUE) + { + return HAL_TIMEOUT; + } + } + } + else + { + /* Disable the Internal High Speed oscillator (MSI). */ + __HAL_RCC_MSI_DISABLE(); + + /* Get timeout */ + tickstart = HAL_GetTick(); + + /* Wait till MSI is ready */ + while(__HAL_RCC_GET_FLAG(RCC_FLAG_MSIRDY) != RESET) + { + if((HAL_GetTick() - tickstart ) > MSI_TIMEOUT_VALUE) + { + return HAL_TIMEOUT; + } + } + } + } + } + /*------------------------------ LSI Configuration -------------------------*/ + if(((RCC_OscInitStruct->OscillatorType) & RCC_OSCILLATORTYPE_LSI) == RCC_OSCILLATORTYPE_LSI) + { + /* Check the parameters */ + assert_param(IS_RCC_LSI(RCC_OscInitStruct->LSIState)); + + /* Check the LSI State */ + if((RCC_OscInitStruct->LSIState)!= RCC_LSI_OFF) + { + /* Enable the Internal Low Speed oscillator (LSI). */ + __HAL_RCC_LSI_ENABLE(); + + /* Get timeout */ + tickstart = HAL_GetTick(); + + /* Wait till LSI is ready */ + while(__HAL_RCC_GET_FLAG(RCC_FLAG_LSIRDY) == RESET) + { + if((HAL_GetTick() - tickstart ) > LSI_TIMEOUT_VALUE) + { + return HAL_TIMEOUT; + } + } + } + else + { + /* Disable the Internal Low Speed oscillator (LSI). */ + __HAL_RCC_LSI_DISABLE(); + + /* Get timeout */ + tickstart = HAL_GetTick(); + + /* Wait till LSI is ready */ + while(__HAL_RCC_GET_FLAG(RCC_FLAG_LSIRDY) != RESET) + { + if((HAL_GetTick() - tickstart ) > LSI_TIMEOUT_VALUE) + { + return HAL_TIMEOUT; + } + } + } + } + + + /*------------------------------ HSI48 Configuration -------------------------*/ + if(((RCC_OscInitStruct->OscillatorType) & RCC_OSCILLATORTYPE_HSI48) == RCC_OSCILLATORTYPE_HSI48) + { + /* Check the parameters */ + assert_param(IS_RCC_HSI48(RCC_OscInitStruct->HSI48State)); + + /* Check the HSI48 State */ + if((RCC_OscInitStruct->HSI48State)!= RCC_HSI48_OFF) + { + /* Enable the Internal Low Speed oscillator (HSI48). */ + __HAL_RCC_HSI48_ENABLE(); + + /* Get timeout */ + tickstart = HAL_GetTick(); + + /* Wait till HSI48 is ready */ + while(__HAL_RCC_GET_FLAG(RCC_FLAG_HSI48RDY) == RESET) + { + if((HAL_GetTick() - tickstart ) > HSI48_TIMEOUT_VALUE) + { + return HAL_TIMEOUT; + } + } + } + else + { + /* Disable the Internal Low Speed oscillator (HSI48). */ + __HAL_RCC_HSI48_DISABLE(); + + /* Get timeout */ + tickstart = HAL_GetTick(); + + /* Wait till HSI48 is ready */ + while(__HAL_RCC_GET_FLAG(RCC_FLAG_HSI48RDY) != RESET) + { + if((HAL_GetTick() - tickstart ) > HSI48_TIMEOUT_VALUE) + { + return HAL_TIMEOUT; + } + } + } + } + /*------------------------------ LSE Configuration -------------------------*/ + if(((RCC_OscInitStruct->OscillatorType) & RCC_OSCILLATORTYPE_LSE) == RCC_OSCILLATORTYPE_LSE) + { + /* Check the parameters */ + assert_param(IS_RCC_LSE(RCC_OscInitStruct->LSEState)); + + /* Enable Power Clock*/ + __PWR_CLK_ENABLE(); + + /* Enable write access to Backup domain */ + PWR->CR |= PWR_CR_DBP; + + /* Wait for Backup domain Write protection disable */ + tickstart = HAL_GetTick(); + + while((PWR->CR & PWR_CR_DBP) == RESET) + { + if((HAL_GetTick() - tickstart ) >= DBP_TIMEOUT_VALUE) + { + return HAL_TIMEOUT; + } + } + + /* Reset LSEON and LSEBYP bits before configuring the LSE ----------------*/ + __HAL_RCC_LSE_CONFIG(RCC_LSE_OFF); + + /* Get timeout */ + tickstart = HAL_GetTick(); + + /* Wait till LSE is ready */ + while(__HAL_RCC_GET_FLAG(RCC_FLAG_LSERDY) != RESET) + { + if((HAL_GetTick() - tickstart ) > LSE_TIMEOUT_VALUE) + { + return HAL_TIMEOUT; + } + } + + /* Set the new LSE configuration -----------------------------------------*/ + __HAL_RCC_LSE_CONFIG(RCC_OscInitStruct->LSEState); + /* Check the LSE State */ + if((RCC_OscInitStruct->LSEState) == RCC_LSE_ON) + { + /* Get timeout */ + tickstart = HAL_GetTick(); + + /* Wait till LSE is ready */ + while(__HAL_RCC_GET_FLAG(RCC_FLAG_LSERDY) == RESET) + { + if((HAL_GetTick() - tickstart ) > LSE_TIMEOUT_VALUE) + { + return HAL_TIMEOUT; + } + } + } + else + { + /* Get timeout */ + tickstart = HAL_GetTick(); + + /* Wait till LSE is ready */ + while(__HAL_RCC_GET_FLAG(RCC_FLAG_LSERDY) != RESET) + { + if((HAL_GetTick() - tickstart ) > LSE_TIMEOUT_VALUE) + { + return HAL_TIMEOUT; + } + } + } + } + /*-------------------------------- PLL Configuration -----------------------*/ + /* Check the parameters */ + assert_param(IS_RCC_PLL(RCC_OscInitStruct->PLL.PLLState)); + if ((RCC_OscInitStruct->PLL.PLLState) != RCC_PLL_NONE) + { + /* Check if the PLL is used as system clock or not */ + if(__HAL_RCC_GET_SYSCLK_SOURCE() != RCC_CFGR_SWS_PLL) + { + if((RCC_OscInitStruct->PLL.PLLState) == RCC_PLL_ON) + { + /* Check the parameters */ + assert_param(IS_RCC_PLLSOURCE(RCC_OscInitStruct->PLL.PLLSource)); + assert_param(IS_RCC_PLL_MUL(RCC_OscInitStruct->PLL.PLLMUL)); + assert_param(IS_RCC_PLL_DIV(RCC_OscInitStruct->PLL.PLLDIV)); + + + /* Disable the main PLL. */ + __HAL_RCC_PLL_DISABLE(); + + /* Get timeout */ + tickstart = HAL_GetTick(); + + /* Wait till PLL is ready */ + while(__HAL_RCC_GET_FLAG(RCC_FLAG_PLLRDY) != RESET) + { + if((HAL_GetTick() - tickstart ) > PLL_TIMEOUT_VALUE) + { + return HAL_TIMEOUT; + } + } + + /* Configure the main PLL clock source, multiplication and division factors. */ + __HAL_RCC_PLL_CONFIG(RCC_OscInitStruct->PLL.PLLSource, + RCC_OscInitStruct->PLL.PLLMUL, + RCC_OscInitStruct->PLL.PLLDIV); + /* Enable the main PLL. */ + __HAL_RCC_PLL_ENABLE(); + + /* Get timeout */ + tickstart = HAL_GetTick(); + + /* Wait till PLL is ready */ + while(__HAL_RCC_GET_FLAG(RCC_FLAG_PLLRDY) == RESET) + { + if((HAL_GetTick() - tickstart ) > PLL_TIMEOUT_VALUE) + { + return HAL_TIMEOUT; + } + } + } + else + { + /* Disable the main PLL. */ + __HAL_RCC_PLL_DISABLE(); + /* Get timeout */ + tickstart = HAL_GetTick(); + + /* Wait till PLL is ready */ + while(__HAL_RCC_GET_FLAG(RCC_FLAG_PLLRDY) != RESET) + { + if((HAL_GetTick() - tickstart ) > PLL_TIMEOUT_VALUE) + { + return HAL_TIMEOUT; + } + } + } + } + else + { + return HAL_ERROR; + } + } + return HAL_OK; +} + +/** + * @brief Initializes the CPU, AHB and APB busses clocks according to the specified + * parameters in the RCC_ClkInitStruct. + * @param RCC_ClkInitStruct: pointer to an RCC_OscInitTypeDef structure that + * contains the configuration information for the RCC peripheral. + * @param FLatency: FLASH Latency, this parameter depends on System Clock Frequency + * + * @note The SystemCoreClock CMSIS variable is used to store System Clock Frequency + * and updated by HAL_RCC_GetHCLKFreq() function called within this function + * + * @note The MSI is used (enabled by hardware) as system clock source after + * startup from Reset, wake-up from STOP and STANDBY mode, or in case + * of failure of the HSE used directly or indirectly as system clock + * (if the Clock Security System CSS is enabled). + * + * @note A switch from one clock source to another occurs only if the target + * clock source is ready (clock stable after startup delay or PLL locked). + * If a clock source which is not yet ready is selected, the switch will + * occur when the clock source will be ready. + * @retval None + */ +HAL_StatusTypeDef HAL_RCC_ClockConfig(RCC_ClkInitTypeDef *RCC_ClkInitStruct, uint32_t FLatency) +{ + + uint32_t tickstart = 0; + + /* Check the parameters */ + assert_param(IS_RCC_CLOCKTYPE(RCC_ClkInitStruct->ClockType)); + assert_param(IS_FLASH_LATENCY(FLatency)); + + /* To correctly read data from FLASH memory, the number of wait states (LATENCY) + must be correctly programmed according to the frequency of the CPU clock + (HCLK) and the supply voltage of the device. */ + + /* Increasing the CPU frequency */ + if(FLatency > (FLASH->ACR & FLASH_ACR_LATENCY)) + { + /* Program the new number of wait states to the LATENCY bits in the FLASH_ACR register */ + __HAL_FLASH_SET_LATENCY(FLatency); + + /* Check that the new number of wait states is taken into account to access the Flash + memory by reading the FLASH_ACR register */ + if((FLASH->ACR & FLASH_ACR_LATENCY) != FLatency) + { + return HAL_ERROR; + } + + /*-------------------------- HCLK Configuration --------------------------*/ + if(((RCC_ClkInitStruct->ClockType) & RCC_CLOCKTYPE_HCLK) == RCC_CLOCKTYPE_HCLK) + { + assert_param(IS_RCC_HCLK(RCC_ClkInitStruct->AHBCLKDivider)); + MODIFY_REG(RCC->CFGR, RCC_CFGR_HPRE, RCC_ClkInitStruct->AHBCLKDivider); + } + + /*------------------------- SYSCLK Configuration ---------------------------*/ + if(((RCC_ClkInitStruct->ClockType) & RCC_CLOCKTYPE_SYSCLK) == RCC_CLOCKTYPE_SYSCLK) + { + assert_param(IS_RCC_SYSCLKSOURCE(RCC_ClkInitStruct->SYSCLKSource)); + + /* HSE is selected as System Clock Source */ + if(RCC_ClkInitStruct->SYSCLKSource == RCC_SYSCLKSOURCE_HSE) + { + /* Check the HSE ready flag */ + if(__HAL_RCC_GET_FLAG(RCC_FLAG_HSERDY) == RESET) + { + return HAL_ERROR; + } + } + + /* MSI is selected as System Clock Source */ + else if(RCC_ClkInitStruct->SYSCLKSource == RCC_SYSCLKSOURCE_MSI) + { + /* Check the MSI ready flag */ + if(__HAL_RCC_GET_FLAG(RCC_FLAG_MSIRDY) == RESET) + { + return HAL_ERROR; + } + } + /* PLL is selected as System Clock Source */ + else if(RCC_ClkInitStruct->SYSCLKSource == RCC_SYSCLKSOURCE_PLLCLK) + { + /* Check the PLL ready flag */ + if(__HAL_RCC_GET_FLAG(RCC_FLAG_PLLRDY) == RESET) + { + return HAL_ERROR; + } + } + /* HSI is selected as System Clock Source */ + else + { + /* Check the HSI ready flag */ + if(__HAL_RCC_GET_FLAG(RCC_FLAG_HSIRDY) == RESET) + { + return HAL_ERROR; + } + } + MODIFY_REG(RCC->CFGR, RCC_CFGR_SW, RCC_ClkInitStruct->SYSCLKSource); + + /* Get timeout */ + tickstart = HAL_GetTick(); + + if(RCC_ClkInitStruct->SYSCLKSource == RCC_SYSCLKSOURCE_HSE) + { + while (__HAL_RCC_GET_SYSCLK_SOURCE() != RCC_CFGR_SWS_HSE) + { + if((HAL_GetTick() - tickstart ) > CLOCKSWITCH_TIMEOUT_VALUE) + { + return HAL_TIMEOUT; + } + } + } + else if(RCC_ClkInitStruct->SYSCLKSource == RCC_SYSCLKSOURCE_PLLCLK) + { + while (__HAL_RCC_GET_SYSCLK_SOURCE() != RCC_CFGR_SWS_PLL) + { + if((HAL_GetTick() - tickstart ) > CLOCKSWITCH_TIMEOUT_VALUE) + { + return HAL_TIMEOUT; + } + } + } + else if(RCC_ClkInitStruct->SYSCLKSource == RCC_SYSCLKSOURCE_MSI) + { + while (__HAL_RCC_GET_SYSCLK_SOURCE() != RCC_CFGR_SWS_MSI) + { + if((HAL_GetTick() - tickstart ) > CLOCKSWITCH_TIMEOUT_VALUE) + { + return HAL_TIMEOUT; + } + } + } + else + { + while(__HAL_RCC_GET_SYSCLK_SOURCE() != RCC_CFGR_SWS_HSI) + { + if((HAL_GetTick() - tickstart ) > CLOCKSWITCH_TIMEOUT_VALUE) + { + return HAL_TIMEOUT; + } + } + } + } + } + /* Decreasing the CPU frequency */ + else + { + /*-------------------------- HCLK Configuration --------------------------*/ + if(((RCC_ClkInitStruct->ClockType) & RCC_CLOCKTYPE_HCLK) == RCC_CLOCKTYPE_HCLK) + { + assert_param(IS_RCC_HCLK(RCC_ClkInitStruct->AHBCLKDivider)); + MODIFY_REG(RCC->CFGR, RCC_CFGR_HPRE, RCC_ClkInitStruct->AHBCLKDivider); + } + + /*------------------------- SYSCLK Configuration -------------------------*/ + if(((RCC_ClkInitStruct->ClockType) & RCC_CLOCKTYPE_SYSCLK) == RCC_CLOCKTYPE_SYSCLK) + { + assert_param(IS_RCC_SYSCLKSOURCE(RCC_ClkInitStruct->SYSCLKSource)); + + /* HSE is selected as System Clock Source */ + if(RCC_ClkInitStruct->SYSCLKSource == RCC_SYSCLKSOURCE_HSE) + { + /* Check the HSE ready flag */ + if(__HAL_RCC_GET_FLAG(RCC_FLAG_HSERDY) == RESET) + { + return HAL_ERROR; + } + } + + /* MSI is selected as System Clock Source */ + else if(RCC_ClkInitStruct->SYSCLKSource == RCC_SYSCLKSOURCE_MSI) + { + /* Check the MSI ready flag */ + if(__HAL_RCC_GET_FLAG(RCC_FLAG_MSIRDY) == RESET) + { + return HAL_ERROR; + } + } + /* PLL is selected as System Clock Source */ + else if(RCC_ClkInitStruct->SYSCLKSource == RCC_SYSCLKSOURCE_PLLCLK) + { + /* Check the PLL ready flag */ + if(__HAL_RCC_GET_FLAG(RCC_FLAG_PLLRDY) == RESET) + { + return HAL_ERROR; + } + } + /* HSI is selected as System Clock Source */ + else + { + /* Check the HSI ready flag */ + if(__HAL_RCC_GET_FLAG(RCC_FLAG_HSIRDY) == RESET) + { + return HAL_ERROR; + } + } + MODIFY_REG(RCC->CFGR, RCC_CFGR_SW, RCC_ClkInitStruct->SYSCLKSource); + + /* Get timeout */ + tickstart = HAL_GetTick(); + + if(RCC_ClkInitStruct->SYSCLKSource == RCC_SYSCLKSOURCE_HSE) + { + while (__HAL_RCC_GET_SYSCLK_SOURCE() != RCC_CFGR_SWS_HSE) + { + if((HAL_GetTick() - tickstart ) > CLOCKSWITCH_TIMEOUT_VALUE) + { + return HAL_TIMEOUT; + } + } + } + else if(RCC_ClkInitStruct->SYSCLKSource == RCC_SYSCLKSOURCE_PLLCLK) + { + while (__HAL_RCC_GET_SYSCLK_SOURCE() != RCC_CFGR_SWS_PLL) + { + if((HAL_GetTick() - tickstart ) > CLOCKSWITCH_TIMEOUT_VALUE) + { + return HAL_TIMEOUT; + } + } + } + else if(RCC_ClkInitStruct->SYSCLKSource == RCC_SYSCLKSOURCE_MSI) + { + while (__HAL_RCC_GET_SYSCLK_SOURCE() != RCC_CFGR_SWS_MSI) + { + if((HAL_GetTick() - tickstart ) > CLOCKSWITCH_TIMEOUT_VALUE) + { + return HAL_TIMEOUT; + } + } + } + else + { + while(__HAL_RCC_GET_SYSCLK_SOURCE() != RCC_CFGR_SWS_HSI) + { + if((HAL_GetTick() - tickstart ) > CLOCKSWITCH_TIMEOUT_VALUE) + { + return HAL_TIMEOUT; + } + } + } + } + + /* Program the new number of wait states to the LATENCY bits in the FLASH_ACR register */ + __HAL_FLASH_SET_LATENCY(FLatency); + + /* Check that the new number of wait states is taken into account to access the Flash + memory by reading the FLASH_ACR register */ + if((FLASH->ACR & FLASH_ACR_LATENCY) != FLatency) + { + return HAL_ERROR; + } + } + + /*-------------------------- PCLK1 Configuration ---------------------------*/ + if(((RCC_ClkInitStruct->ClockType) & RCC_CLOCKTYPE_PCLK1) == RCC_CLOCKTYPE_PCLK1) + { + assert_param(IS_RCC_PCLK(RCC_ClkInitStruct->APB1CLKDivider)); + MODIFY_REG(RCC->CFGR, RCC_CFGR_PPRE1, RCC_ClkInitStruct->APB1CLKDivider); + } + + /*-------------------------- PCLK2 Configuration ---------------------------*/ + if(((RCC_ClkInitStruct->ClockType) & RCC_CLOCKTYPE_PCLK2) == RCC_CLOCKTYPE_PCLK2) + { + assert_param(IS_RCC_PCLK(RCC_ClkInitStruct->APB2CLKDivider)); + MODIFY_REG(RCC->CFGR, RCC_CFGR_PPRE2, ((RCC_ClkInitStruct->APB2CLKDivider) << 3)); + } + + /* Configure the source of time base considering new system clocks settings*/ + HAL_InitTick (TICK_INT_PRIORITY); + + return HAL_OK; +} + +/** + * @} + */ + +/** @defgroup HAL_RCC_Group2 Peripheral Control functions + * @brief RCC clocks control functions + * +@verbatim + =============================================================================== + ##### Peripheral Control functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to control the RCC Clocks + frequencies. + +@endverbatim + * @{ + */ + +/** + * @brief Selects the clock source to output on MCO pin. + * @note MCO pin should be configured in alternate function mode. + * @param RCC_MCOx: specifies the output direction for the clock source. + * For STM32L0xx family this parameter can have only one value: + * @arg RCC_MCO1: Clock source to output on MCO pin(PA8). + * @arg RCC_MCO2: Clock source to output on MCO pin(PA9). + * @param RCC_MCOSource: specifies the clock source to output. + * This parameter can be one of the following values: + * @arg RCC_MCO1SOURCE_NOCLOCK: No clock selected + * @arg RCC_MCO1SOURCE_SYSCLK: System clock selected + * @arg RCC_MCO1SOURCE_HSI: HSI oscillator clock selected + * @arg RCC_MCO1SOURCE_MSI: MSI oscillator clock selected + * @arg RCC_MCO1SOURCE_HSE: HSE oscillator clock selected + * @arg RCC_MCO1SOURCE_PLLCLK: PLL clock selected + * @arg RCC_MCO1SOURCE_LSI: LSI clock selected + * @arg RCC_MCO1SOURCE_LSE: LSE clock selected + * @arg RCC_MCO1SOURCE_HSI48: HSI48 clock selected + * @param RCC_MCODIV: specifies the MCO DIV. + * This parameter can be one of the following values: + * @arg RCC_MCODIV_1: no division applied to MCO clock + * @arg RCC_MCODIV_2: division by 2 applied to MCO clock + * @arg RCC_MCODIV_4: division by 4 applied to MCO clock + * @arg RCC_MCODIV_8: division by 8 applied to MCO clock + * @arg RCC_MCODIV_16: division by 16 applied to MCO clock + * @retval None + */ +void HAL_RCC_MCOConfig( uint32_t RCC_MCOx, uint32_t RCC_MCOSource, uint32_t RCC_MCODiv) +{ + GPIO_InitTypeDef GPIO_InitStruct; + /* Check the parameters */ + assert_param(IS_RCC_MCO(RCC_MCOx)); + assert_param(IS_RCC_MCODIV(RCC_MCODiv)); + assert_param(IS_RCC_MCO1SOURCE(RCC_MCOSource)); + + /* MCO Clock Enable */ + __MCO1_CLK_ENABLE(); + + /* Configure the MCO1 pin in alternate function mode */ + if(RCC_MCOx == RCC_MCO1) + { + GPIO_InitStruct.Pin = MCO1_PIN; + } + else + { + GPIO_InitStruct.Pin = MCO2_PIN; + } + GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; + GPIO_InitStruct.Speed = GPIO_SPEED_HIGH; + GPIO_InitStruct.Pull = GPIO_NOPULL; + GPIO_InitStruct.Alternate = GPIO_AF0_MCO; + HAL_GPIO_Init(MCO1_GPIO_PORT, &GPIO_InitStruct); + + /* Mask MCO1 and MCO1PRE[2:0] bits then Select MCO1 clock source and prescaler */ + MODIFY_REG(RCC->CFGR, (RCC_CFGR_MCOSEL | RCC_CFGR_MCO_PRE), ((RCC_MCOSource << 24 | RCC_MCODiv ))); +} + +/** + * @brief Enables the Clock Security System. + * @note If a failure is detected on the HSE oscillator clock, this oscillator + * is automatically disabled and an interrupt is generated to inform the + * software about the failure (Clock Security System Interrupt, CSSI), + * allowing the MCU to perform rescue operations. The CSSI is linked to + * the Cortex-M0+ NMI (Non-Maskable Interrupt) exception vector. + * @param None + * @retval None + */ +void HAL_RCC_EnableCSS(void) +{ + SET_BIT(RCC->CR, RCC_CR_CSSHSEON) ; +} + + +/** + * @brief Returns the SYSCLK frequency + * + * @note The system frequency computed by this function is not the real + * frequency in the chip. It is calculated based on the predefined + * constant and the selected clock source: + * @note If SYSCLK source is MSI, function returns values based on MSI + * Value as defined by the MSI range. + * @note If SYSCLK source is HSI, function returns values based on HSI_VALUE(*) + * @note If SYSCLK source is HSE, function returns values based on HSE_VALUE(**) + * @note If SYSCLK source is PLL, function returns values based on HSE_VALUE(**) + * or HSI_VALUE(*) multiplied/divided by the PLL factors. + * @note (*) HSI_VALUE is a constant defined in stm32l0xx_hal_conf.h file (default value + * 16 MHz) but the real value may vary depending on the variations + * in voltage and temperature. + * @note (**) HSE_VALUE is a constant defined in stm32l0xx_hal_conf.h file (default value + * 8 MHz), user has to ensure that HSE_VALUE is same as the real + * frequency of the crystal used. Otherwise, this function may + * have wrong result. + * + * @note The result of this function could be not correct when using fractional + * value for HSE crystal. + * + * @note This function can be used by the user application to compute the + * baudrate for the communication peripherals or configure other parameters. + * + * @note Each time SYSCLK changes, this function must be called to update the + * right SYSCLK value. Otherwise, any configuration based on this function will be incorrect. + * + * + * @param None + * @retval SYSCLK frequency + */ +uint32_t HAL_RCC_GetSysClockFreq(void) +{ + uint32_t pllmul = 0, plldiv = 0, pllsource = 0, msirange = 0; + uint32_t sysclockfreq = 0; + + /* Get SYSCLK source -------------------------------------------------------*/ + + /*MSI frequency range in HZ*/ + msirange = (RCC->ICSCR & RCC_ICSCR_MSIRANGE) >> 13; + msirange = MSIRangeTable[msirange]; + + switch (RCC->CFGR & RCC_CFGR_SWS) + { + case RCC_CFGR_SWS_MSI: /* MSI used as system clock */ + { + sysclockfreq = msirange; + break; + } + case RCC_CFGR_SWS_HSI: /* HSI used as system clock */ + { + if ((RCC->CR & RCC_CR_HSIDIVF) != 0) + { + sysclockfreq = (HSI_VALUE >> 2); + } + else + { + sysclockfreq = HSI_VALUE; + } + break; + } + case RCC_CFGR_SWS_HSE: /* HSE used as system clock */ + { + sysclockfreq = HSE_VALUE; + break; + } + case RCC_CFGR_SWS_PLL: /* PLL used as system clock */ + { + /* Get PLL clock source and multiplication factor ----------------------*/ + pllmul = RCC->CFGR & RCC_CFGR_PLLMUL; + plldiv = RCC->CFGR & RCC_CFGR_PLLDIV; + pllmul = PLLMulTable[(pllmul >> 18)]; + plldiv = (plldiv >> 22) + 1; + + pllsource = RCC->CFGR & RCC_CFGR_PLLSRC; + + if (pllsource == RCC_CFGR_PLLSRC_HSI) + { + /* HSI oscillator clock selected as PLL clock source */ + sysclockfreq =(((HSI_VALUE) * pllmul) / plldiv); + } + else + { + /* HSE selected as PLL clock source */ + sysclockfreq = (((HSE_VALUE) * pllmul) / plldiv); + } + break; + } + default: /* MSI used as system clock */ + { + sysclockfreq = msirange; + break; + } + } + return sysclockfreq; +} + +/** + * @brief Returns the HCLK frequency + * @note Each time HCLK changes, this function must be called to update the + * right HCLK value. Otherwise, any configuration based on this function will be incorrect. + * + * @note The SystemCoreClock CMSIS variable is used to store System Clock Frequency + * and updated within this function + * @param None + * @retval HCLK frequency + */ +uint32_t HAL_RCC_GetHCLKFreq(void) +{ + SystemCoreClock = HAL_RCC_GetSysClockFreq() >> APBAHBPrescTable[((RCC->CFGR & RCC_CFGR_HPRE) >> 4)]; + + return (SystemCoreClock); + +} + +/** + * @brief Returns the PCLK1 frequency + * @note Each time PCLK1 changes, this function must be called to update the + * right PCLK1 value. Otherwise, any configuration based on this function will be incorrect. + * @param None + * @retval PCLK1 frequency + */ +uint32_t HAL_RCC_GetPCLK1Freq(void) +{ + + return ( HAL_RCC_GetHCLKFreq() >> APBAHBPrescTable[((RCC->CFGR & RCC_CFGR_PPRE1) >> 8)]); + +} + +/** + * @brief Returns the PCLK2 frequency + * @note Each time PCLK2 changes, this function must be called to update the + * right PCLK2 value. Otherwise, any configuration based on this function will be incorrect. + * @param None + * @retval PCLK2 frequency + */ +uint32_t HAL_RCC_GetPCLK2Freq(void) +{ + + return ( HAL_RCC_GetHCLKFreq() >> APBAHBPrescTable[((RCC->CFGR & RCC_CFGR_PPRE2) >> 11)]); + +} + +/** + * @brief Configures the RCC_OscInitStruct according to the internal + * RCC configuration registers. + * @param RCC_OscInitStruct: pointer to an RCC_OscInitTypeDef structure that + * will be configured. + * @retval None + */ +void HAL_RCC_GetOscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct) +{ + /* Set all possible values for the Oscillator type parameter ---------------*/ + RCC_OscInitStruct->OscillatorType = RCC_OSCILLATORTYPE_HSE | RCC_OSCILLATORTYPE_MSI | RCC_OSCILLATORTYPE_HSI | \ + RCC_OSCILLATORTYPE_HSI48 | RCC_OSCILLATORTYPE_LSE | RCC_OSCILLATORTYPE_LSI; + + /* Get the HSE configuration -----------------------------------------------*/ + if((RCC->CR &RCC_CR_HSEBYP) == RCC_CR_HSEBYP) + { + RCC_OscInitStruct->HSEState = RCC_HSE_BYPASS; + } + else if((RCC->CR &RCC_CR_HSEON) == RCC_CR_HSEON) + { + RCC_OscInitStruct->HSEState = RCC_HSE_ON; + } + else + { + RCC_OscInitStruct->HSEState = RCC_HSE_OFF; + } + + /* Get the MSI configuration -----------------------------------------------*/ + if((RCC->CR &RCC_CR_MSION) == RCC_CR_MSION) + { + RCC_OscInitStruct->MSIState = RCC_MSI_ON; + } + else + { + RCC_OscInitStruct->MSIState = RCC_MSI_OFF; + } + + RCC_OscInitStruct->MSICalibrationValue = (uint32_t)((RCC->CR &RCC_ICSCR_MSITRIM) >> 24); + RCC_OscInitStruct->MSIClockRange = (uint32_t)((RCC->ICSCR &RCC_ICSCR_MSIRANGE) >> 13); + + /* Get the HSI48 configuration -----------------------------------------------*/ + if((RCC->CRRCR &RCC_CRRCR_HSI48ON) == RCC_CRRCR_HSI48ON) + { + RCC_OscInitStruct->HSI48State = RCC_HSI48_ON; + } + else + { + RCC_OscInitStruct->HSI48State = RCC_HSI48_OFF; + } + + /* Get the HSI configuration -----------------------------------------------*/ + if((RCC->CR &RCC_CR_HSION) == RCC_CR_HSION) + { + RCC_OscInitStruct->HSIState = RCC_HSI_ON; + } + else + { + RCC_OscInitStruct->HSIState = RCC_HSI_OFF; + } + + RCC_OscInitStruct->HSICalibrationValue = (uint32_t)((RCC->ICSCR &RCC_ICSCR_HSITRIM) >> 8); + + /* Get the LSE configuration -----------------------------------------------*/ + if((RCC->CSR &RCC_CSR_LSEBYP) == RCC_CSR_LSEBYP) + { + RCC_OscInitStruct->LSEState = RCC_LSE_BYPASS; + } + else if((RCC->CSR &RCC_CSR_LSEON) == RCC_CSR_LSEON) + { + RCC_OscInitStruct->LSEState = RCC_LSE_ON; + } + else + { + RCC_OscInitStruct->LSEState = RCC_LSE_OFF; + } + + /* Get the LSI configuration -----------------------------------------------*/ + if((RCC->CSR &RCC_CSR_LSION) == RCC_CSR_LSION) + { + RCC_OscInitStruct->LSIState = RCC_LSI_ON; + } + else + { + RCC_OscInitStruct->LSIState = RCC_LSI_OFF; + } + + /* Get the PLL configuration -----------------------------------------------*/ + if((RCC->CR &RCC_CR_PLLON) == RCC_CR_PLLON) + { + RCC_OscInitStruct->PLL.PLLState = RCC_PLL_ON; + } + else + { + RCC_OscInitStruct->PLL.PLLState = RCC_PLL_OFF; + } + RCC_OscInitStruct->PLL.PLLSource = (uint32_t)(RCC->CFGR & RCC_CFGR_PLLSRC); + RCC_OscInitStruct->PLL.PLLMUL = (uint32_t)(RCC->CFGR & RCC_CFGR_PLLMUL) >> 18; + RCC_OscInitStruct->PLL.PLLDIV = (uint32_t)(RCC->CFGR & RCC_CFGR_PLLDIV) >> 22; + +} + +/** + * @brief Configures the RCC_ClkInitStruct according to the internal + * RCC configuration registers. + * @param RCC_OscInitStruct: pointer to an RCC_ClkInitTypeDef structure that + * will be configured. + * @param pFLatency: Pointer on the Flash Latency. + * @retval None + */ +void HAL_RCC_GetClockConfig(RCC_ClkInitTypeDef *RCC_ClkInitStruct, uint32_t *pFLatency) +{ + /* Set all possible values for the Clock type parameter --------------------*/ + RCC_ClkInitStruct->ClockType = RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2; + + /* Get the SYSCLK configuration --------------------------------------------*/ + RCC_ClkInitStruct->SYSCLKSource = (uint32_t)(RCC->CFGR & RCC_CFGR_SW); + + /* Get the HCLK configuration ----------------------------------------------*/ + RCC_ClkInitStruct->AHBCLKDivider = (uint32_t)(RCC->CFGR & RCC_CFGR_HPRE); + + /* Get the APB1 configuration ----------------------------------------------*/ + RCC_ClkInitStruct->APB1CLKDivider = (uint32_t)(RCC->CFGR & RCC_CFGR_PPRE1); + + /* Get the APB2 configuration ----------------------------------------------*/ + RCC_ClkInitStruct->APB2CLKDivider = (uint32_t)((RCC->CFGR & RCC_CFGR_PPRE2) >> 3); + + /* Get the Flash Wait State (Latency) configuration ------------------------*/ + *pFLatency = (uint32_t)(FLASH->ACR & FLASH_ACR_LATENCY); +} + +/** + * @brief This function handles the RCC CSS interrupt request. + * @note This API should be called under the NMI_Handler(). + * @param None + * @retval None + */ +void HAL_RCC_NMI_IRQHandler(void) +{ + /* Check RCC CSSF flag */ + if(__HAL_RCC_GET_IT(RCC_IT_CSS)) + { + /* RCC Clock Security System interrupt user callback */ + HAL_RCC_CCSCallback(); + + /* Clear RCC CSS pending bit */ + __HAL_RCC_CLEAR_IT(RCC_IT_CSS); + } +} + +/** + * @brief RCC Clock Security System interrupt callback + * @param none + * @retval none + */ +__weak void HAL_RCC_CCSCallback(void) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_RCC_CCSCallback could be implemented in the user file + */ +} + +/** + * @} + */ + +/** + * @} + */ + +#endif /* HAL_RCC_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_rcc.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_rcc.h new file mode 100644 index 0000000000..8950223f60 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_rcc.h @@ -0,0 +1,1151 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_rcc.h + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief Header file of RCC HAL module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32L0xx_HAL_RCC_H +#define __STM32L0xx_HAL_RCC_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal_def.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @addtogroup RCC + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ + +/** + * @brief RCC PLL configuration structure definition + */ +typedef struct +{ + uint32_t PLLState; /*!< The new state of the PLL. + This parameter can be a value of @ref RCC_PLL_Config */ + + uint32_t PLLSource; /*!< RCC_PLLSource: PLL entry clock source. + This parameter must be a value of @ref RCC_PLL_Clock_Source */ + + uint32_t PLLMUL; /*!< PLLMUL: Multiplication factor for PLL VCO output clock + This parameter must of RCC_PLLMultiplication_Factor */ + + uint32_t PLLDIV; /*!< PLLDIV: Division factor for main system clock (SYSCLK) + This parameter must be a value of @ref RCC_PLLDivider_Factor */ + +}RCC_PLLInitTypeDef; + +/** + * @brief RCC Internal/External Oscillator (HSE, HSI, LSE and LSI) configuration structure definition + */ +typedef struct +{ + uint32_t OscillatorType; /*!< The oscillators to be configured. + This parameter can be a value of @ref RCC_Oscillator_Type */ + + uint32_t HSEState; /*!< The new state of the HSE. + This parameter can be a value of @ref RCC_HSE_Config */ + + uint32_t LSEState; /*!< The new state of the LSE. + This parameter can be a value of @ref RCC_LSE_Config */ + + uint32_t HSIState; /*!< The new state of the HSI. + This parameter can be a value of @ref RCC_HSI_Config */ + + uint32_t HSICalibrationValue; /*!< The calibration trimming value. + This parameter must be a number between Min_Data = 0x00 and Max_Data = 0x1F */ + + uint32_t LSIState; /*!< The new state of the LSI. + This parameter can be a value of @ref RCC_LSI_Config */ + + uint32_t HSI48State; /*!< The new state of the HSI48. + This parameter can be a value of @ref RCC_HSI48_Config */ + + uint32_t MSIState; /*!< The new state of the MSI. + This parameter can be a value of @ref RCC_MSI_Config */ + + uint32_t MSICalibrationValue; /*!< The calibration trimming value. + This parameter must be a number between Min_Data = 0x00 and Max_Data = 0xFF */ + + uint32_t MSIClockRange; /*!< The MSI frequency range. + This parameter can be a value of @ref RCC_MSI_Clock_Range */ + + RCC_PLLInitTypeDef PLL; /*!< PLL structure parameters */ + +}RCC_OscInitTypeDef; + +/** + * @brief RCC System, AHB and APB busses clock configuration structure definition + */ +typedef struct +{ + uint32_t ClockType; /*!< The clock to be configured. + This parameter can be a value of @ref RCC_System_Clock_Type */ + + uint32_t SYSCLKSource; /*!< The clock source (SYSCLKS) used as system clock. + This parameter can be a value of @ref RCC_System_Clock_Source */ + + uint32_t AHBCLKDivider; /*!< The AHB clock (HCLK) divider. This clock is derived from the system clock (SYSCLK). + This parameter can be a value of @ref RCC_AHB_Clock_Source */ + + uint32_t APB1CLKDivider; /*!< The APB1 clock (PCLK1) divider. This clock is derived from the AHB clock (HCLK). + This parameter can be a value of @ref RCC_APB1_APB2_Clock_Source */ + + uint32_t APB2CLKDivider; /*!< The APB2 clock (PCLK2) divider. This clock is derived from the AHB clock (HCLK). + This parameter can be a value of @ref RCC_APB1_APB2_Clock_Source */ + +}RCC_ClkInitTypeDef; + +/* Exported constants --------------------------------------------------------*/ +/** @defgroup RCC_Exported_Constants + * @{ + */ + +/** @defgroup RCC_BitAddress_AliasRegion + * @brief RCC registers bit address in the alias region + * @{ + */ +#define RCC_OFFSET (RCC_BASE - PERIPH_BASE) +/* --- CR Register ---*/ +/* Alias word address of HSION bit */ +#define RCC_CR_OFFSET (RCC_OFFSET + 0x00) +/* --- CFGR Register ---*/ +/* Alias word address of I2SSRC bit */ +#define RCC_CFGR_OFFSET (RCC_OFFSET + 0x08) +/* --- CSR Register ---*/ +#define RCC_CSR_OFFSET (RCC_OFFSET + 0x74) + +/* CR register byte 3 (Bits[23:16]) base address */ +#define CR_BYTE2_ADDRESS ((uint32_t)0x40023802) + +/* CIER register byte 0 (Bits[0:8]) base address */ +#define CIER_BYTE0_ADDRESS ((uint32_t)(RCC_BASE + 0x10 + 0x00)) + +#define LSE_TIMEOUT_VALUE LSE_STARTUP_TIMEOUT +#define DBP_TIMEOUT_VALUE ((uint32_t)100) /* 100 ms */ + +/** + * @} + */ + +/** @defgroup RCC_Oscillator_Type + * @{ + */ +#define RCC_OSCILLATORTYPE_NONE ((uint32_t)0x00000000) +#define RCC_OSCILLATORTYPE_HSE ((uint32_t)0x00000001) +#define RCC_OSCILLATORTYPE_HSI ((uint32_t)0x00000002) +#define RCC_OSCILLATORTYPE_LSE ((uint32_t)0x00000004) +#define RCC_OSCILLATORTYPE_LSI ((uint32_t)0x00000008) +#define RCC_OSCILLATORTYPE_MSI ((uint32_t)0x00000010) +#define RCC_OSCILLATORTYPE_HSI48 ((uint32_t)0x00000020) + +#define IS_RCC_OSCILLATORTYPE(OSCILLATOR) (((OSCILLATOR) == RCC_OSCILLATORTYPE_NONE) || \ + ((OSCILLATOR) == RCC_OSCILLATORTYPE_HSE) || \ + ((OSCILLATOR) == RCC_OSCILLATORTYPE_HSI) || \ + ((OSCILLATOR) == RCC_OSCILLATORTYPE_LSE) || \ + ((OSCILLATOR) == RCC_OSCILLATORTYPE_LSI) || \ + ((OSCILLATOR) == RCC_OSCILLATORTYPE_MSI) || \ + ((OSCILLATOR) == RCC_OSCILLATORTYPE_HSI48)) +/** + * @} + */ + +/** @defgroup RCC_HSE_Config + * @{ + */ +#define RCC_HSE_OFF ((uint32_t)0x00000000) +#define RCC_HSE_ON RCC_CR_HSEON +#define RCC_HSE_BYPASS ((uint32_t)(RCC_CR_HSEBYP | RCC_CR_HSEON)) + +#define IS_RCC_HSE(HSE) (((HSE) == RCC_HSE_OFF) || ((HSE) == RCC_HSE_ON) || \ + ((HSE) == RCC_HSE_BYPASS)) +/** + * @} + */ + +/** @defgroup RCC_LSE_Config + * @{ + */ +#define RCC_LSE_OFF ((uint32_t)0x00000000) +#define RCC_LSE_ON RCC_CSR_LSEON +#define RCC_LSE_BYPASS ((uint32_t)(RCC_CSR_LSEBYP | RCC_CSR_LSEON)) + +#define IS_RCC_LSE(LSE) (((LSE) == RCC_LSE_OFF) || ((LSE) == RCC_LSE_ON) || \ + ((LSE) == RCC_LSE_BYPASS)) +/** + * @} + */ + +/** @defgroup RCC_HSI_Config + * @{ + */ +#define RCC_HSI_OFF ((uint8_t)0x00) +#define RCC_HSI_ON ((uint8_t)0x01) +#define RCC_HSI_DIV4 ((uint8_t)0x09) +#define IS_RCC_HSI(HSI) (((HSI) == RCC_HSI_OFF) || ((HSI) == RCC_HSI_ON) || \ + ((HSI) == RCC_HSI_DIV4)) + +/** + * @} + */ + +/** @defgroup RCC_MSI_Clock_Range + * @{ + */ + +#define RCC_MSIRANGE_0 RCC_ICSCR_MSIRANGE_0 /*!< MSI = 65.536 KHz */ +#define RCC_MSIRANGE_1 RCC_ICSCR_MSIRANGE_1 /*!< MSI = 131.072 KHz */ +#define RCC_MSIRANGE_2 RCC_ICSCR_MSIRANGE_2 /*!< MSI = 262.144 KHz */ +#define RCC_MSIRANGE_3 RCC_ICSCR_MSIRANGE_3 /*!< MSI = 524.288 KHz */ +#define RCC_MSIRANGE_4 RCC_ICSCR_MSIRANGE_4 /*!< MSI = 1.048 MHz */ +#define RCC_MSIRANGE_5 RCC_ICSCR_MSIRANGE_5 /*!< MSI = 2.097 MHz */ +#define RCC_MSIRANGE_6 RCC_ICSCR_MSIRANGE_6 /*!< MSI = 4.194 MHz */ + +#define IS_RCC_MSI_CLOCK_RANGE(RANGE) (((RANGE) == RCC_MSIRANGE_0) || \ + ((RANGE) == RCC_MSIRANGE_1) || \ + ((RANGE) == RCC_MSIRANGE_2) || \ + ((RANGE) == RCC_MSIRANGE_3) || \ + ((RANGE) == RCC_MSIRANGE_4) || \ + ((RANGE) == RCC_MSIRANGE_5) || \ + ((RANGE) == RCC_MSIRANGE_6)) + +/** + * @} + */ + +/** @defgroup RCC_LSI_Config + * @{ + */ +#define RCC_LSI_OFF ((uint8_t)0x00) +#define RCC_LSI_ON ((uint8_t)0x01) + +#define IS_RCC_LSI(LSI) (((LSI) == RCC_LSI_OFF) || ((LSI) == RCC_LSI_ON)) +/** + * @} + */ + + +/** @defgroup RCC_MSI_Config + * @{ + */ +#define RCC_MSI_OFF ((uint8_t)0x00) +#define RCC_MSI_ON ((uint8_t)0x01) + +#define IS_RCC_MSI(MSI) (((MSI) == RCC_MSI_OFF) || ((MSI) == RCC_MSI_ON)) +/** + * @} + */ + +/** @defgroup RCC_HSI48_Config + * @{ + */ +#define RCC_HSI48_OFF ((uint8_t)0x00) +#define RCC_HSI48_ON ((uint8_t)0x01) + +#define IS_RCC_HSI48(HSI48) (((HSI48) == RCC_HSI48_OFF) || ((HSI48) == RCC_HSI48_ON)) +/** + * @} + */ + +/** @defgroup RCC_PLL_Config + * @{ + */ +#define RCC_PLL_NONE ((uint8_t)0x00) +#define RCC_PLL_OFF ((uint8_t)0x01) +#define RCC_PLL_ON ((uint8_t)0x02) + +#define IS_RCC_PLL(PLL) (((PLL) == RCC_PLL_NONE) ||((PLL) == RCC_PLL_OFF) || ((PLL) == RCC_PLL_ON)) +/** + * @} + */ + +/** @defgroup RCC_PLL_Clock_Source + * @{ + */ +#define RCC_PLLSOURCE_HSI RCC_CFGR_PLLSRC_HSI +#define RCC_PLLSOURCE_HSE RCC_CFGR_PLLSRC_HSE + +#define IS_RCC_PLLSOURCE(SOURCE) (((SOURCE) == RCC_PLLSOURCE_HSI) || \ + ((SOURCE) == RCC_PLLSOURCE_HSE)) + +/** + * @} + */ + +/** @defgroup RCC_PLLMultiplication_Factor + * @{ + */ + +#define RCC_PLLMUL_3 RCC_CFGR_PLLMUL3 +#define RCC_PLLMUL_4 RCC_CFGR_PLLMUL4 +#define RCC_PLLMUL_6 RCC_CFGR_PLLMUL6 +#define RCC_PLLMUL_8 RCC_CFGR_PLLMUL8 +#define RCC_PLLMUL_12 RCC_CFGR_PLLMUL12 +#define RCC_PLLMUL_16 RCC_CFGR_PLLMUL16 +#define RCC_PLLMUL_24 RCC_CFGR_PLLMUL24 +#define RCC_PLLMUL_32 RCC_CFGR_PLLMUL32 +#define RCC_PLLMUL_48 RCC_CFGR_PLLMUL48 +#define IS_RCC_PLL_MUL(MUL) (((MUL) == RCC_PLLMUL_3) || ((MUL) == RCC_PLLMUL_4) || \ + ((MUL) == RCC_PLLMUL_6) || ((MUL) == RCC_PLLMUL_8) || \ + ((MUL) == RCC_PLLMUL_12) || ((MUL) == RCC_PLLMUL_16) || \ + ((MUL) == RCC_PLLMUL_24) || ((MUL) == RCC_PLLMUL_32) || \ + ((MUL) == RCC_PLLMUL_48)) +/** + * @} + */ + +/** @defgroup RCC_PLLDivider_Factor + * @{ + */ + +#define RCC_PLLDIV_2 RCC_CFGR_PLLDIV2 +#define RCC_PLLDIV_3 RCC_CFGR_PLLDIV3 +#define RCC_PLLDIV_4 RCC_CFGR_PLLDIV4 +#define IS_RCC_PLL_DIV(DIV) (((DIV) == RCC_PLLDIV_2) || ((DIV) == RCC_PLLDIV_3) || \ + ((DIV) == RCC_PLLDIV_4)) +/** + * @} + */ + +/** @defgroup RCC_System_Clock_Type + * @{ + */ +#define RCC_CLOCKTYPE_SYSCLK ((uint32_t)0x00000001) +#define RCC_CLOCKTYPE_HCLK ((uint32_t)0x00000002) +#define RCC_CLOCKTYPE_PCLK1 ((uint32_t)0x00000004) +#define RCC_CLOCKTYPE_PCLK2 ((uint32_t)0x00000008) + +#define IS_RCC_CLOCKTYPE(CLK) ((1 <= (CLK)) && ((CLK) <= 15)) +/** + * @} + */ + +/** @defgroup RCC_System_Clock_Source + * @{ + */ +#define RCC_SYSCLKSOURCE_MSI RCC_CFGR_SW_MSI +#define RCC_SYSCLKSOURCE_HSI RCC_CFGR_SW_HSI +#define RCC_SYSCLKSOURCE_HSE RCC_CFGR_SW_HSE +#define RCC_SYSCLKSOURCE_PLLCLK RCC_CFGR_SW_PLL + +#define IS_RCC_SYSCLKSOURCE(SOURCE) (((SOURCE) == RCC_SYSCLKSOURCE_HSI) || \ + ((SOURCE) == RCC_SYSCLKSOURCE_HSE) || \ + ((SOURCE) == RCC_SYSCLKSOURCE_MSI) || \ + ((SOURCE) == RCC_SYSCLKSOURCE_PLLCLK)) +/** + * @} + */ + +/** @defgroup RCC_AHB_Clock_Source + * @{ + */ +#define RCC_SYSCLK_DIV1 RCC_CFGR_HPRE_DIV1 +#define RCC_SYSCLK_DIV2 RCC_CFGR_HPRE_DIV2 +#define RCC_SYSCLK_DIV4 RCC_CFGR_HPRE_DIV4 +#define RCC_SYSCLK_DIV8 RCC_CFGR_HPRE_DIV8 +#define RCC_SYSCLK_DIV16 RCC_CFGR_HPRE_DIV16 +#define RCC_SYSCLK_DIV64 RCC_CFGR_HPRE_DIV64 +#define RCC_SYSCLK_DIV128 RCC_CFGR_HPRE_DIV128 +#define RCC_SYSCLK_DIV256 RCC_CFGR_HPRE_DIV256 +#define RCC_SYSCLK_DIV512 RCC_CFGR_HPRE_DIV512 + +#define IS_RCC_HCLK(HCLK) (((HCLK) == RCC_SYSCLK_DIV1) || ((HCLK) == RCC_SYSCLK_DIV2) || \ + ((HCLK) == RCC_SYSCLK_DIV4) || ((HCLK) == RCC_SYSCLK_DIV8) || \ + ((HCLK) == RCC_SYSCLK_DIV16) || ((HCLK) == RCC_SYSCLK_DIV64) || \ + ((HCLK) == RCC_SYSCLK_DIV128) || ((HCLK) == RCC_SYSCLK_DIV256) || \ + ((HCLK) == RCC_SYSCLK_DIV512)) +/** + * @} + */ + +/** @defgroup RCC_APB1_APB2_Clock_Source + * @{ + */ +#define RCC_HCLK_DIV1 RCC_CFGR_PPRE1_DIV1 +#define RCC_HCLK_DIV2 RCC_CFGR_PPRE1_DIV2 +#define RCC_HCLK_DIV4 RCC_CFGR_PPRE1_DIV4 +#define RCC_HCLK_DIV8 RCC_CFGR_PPRE1_DIV8 +#define RCC_HCLK_DIV16 RCC_CFGR_PPRE1_DIV16 + +#define IS_RCC_PCLK(PCLK) (((PCLK) == RCC_HCLK_DIV1) || ((PCLK) == RCC_HCLK_DIV2) || \ + ((PCLK) == RCC_HCLK_DIV4) || ((PCLK) == RCC_HCLK_DIV8) || \ + ((PCLK) == RCC_HCLK_DIV16)) +/** + * @} + */ + +/** @defgroup RCC_RTC_Clock_Source + * @{ + */ +#define RCC_RTCCLKSOURCE_LSE RCC_CSR_RTCSEL_LSE +#define RCC_RTCCLKSOURCE_LSI RCC_CSR_RTCSEL_LSI +#define RCC_RTCCLKSOURCE_HSE_DIV2 RCC_CSR_RTCSEL_HSE +#define RCC_RTCCLKSOURCE_HSE_DIV4 ((uint32_t)RCC_CSR_RTCSEL_HSE | RCC_CR_RTCPRE_0) +#define RCC_RTCCLKSOURCE_HSE_DIV8 ((uint32_t)RCC_CSR_RTCSEL_HSE | RCC_CR_RTCPRE_1) +#define RCC_RTCCLKSOURCE_HSE_DIV16 ((uint32_t)RCC_CSR_RTCSEL_HSE | RCC_CR_RTCPRE) +#define IS_RCC_RTCCLK_SOURCE(SOURCE) (((SOURCE) == RCC_RTCCLKSOURCE_LSE) || \ + ((SOURCE) == RCC_RTCCLKSOURCE_LSI) || \ + ((SOURCE) == RCC_RTCCLKSOURCE_HSE_DIV2) || \ + ((SOURCE) == RCC_RTCCLKSOURCE_HSE_DIV4) || \ + ((SOURCE) == RCC_RTCCLKSOURCE_HSE_DIV8) || \ + ((SOURCE) == RCC_RTCCLKSOURCE_HSE_DIV16)) +/** + * @} + */ + +/** @defgroup RCC_MCO_Clock_Source + * @{ + */ +#define RCC_MCO1SOURCE_NOCLOCK ((uint8_t)0x00) +#define RCC_MCO1SOURCE_SYSCLK ((uint8_t)0x01) +#define RCC_MCO1SOURCE_HSI ((uint8_t)0x02) +#define RCC_MCO1SOURCE_MSI ((uint8_t)0x03) +#define RCC_MCO1SOURCE_HSE ((uint8_t)0x04) +#define RCC_MCO1SOURCE_PLLCLK ((uint8_t)0x05) +#define RCC_MCO1SOURCE_LSI ((uint8_t)0x06) +#define RCC_MCO1SOURCE_LSE ((uint8_t)0x07) +#define RCC_MCO1SOURCE_HSI48 ((uint8_t)0x08) + +#define IS_RCC_MCO1SOURCE(SOURCE) (((SOURCE) == RCC_MCO1SOURCE_NOCLOCK) || ((SOURCE) == RCC_MCO1SOURCE_SYSCLK) || \ + ((SOURCE) == RCC_MCO1SOURCE_HSI) || ((SOURCE) == RCC_MCO1SOURCE_MSI) || \ + ((SOURCE) == RCC_MCO1SOURCE_HSE) || ((SOURCE) == RCC_MCO1SOURCE_PLLCLK) || \ + ((SOURCE) == RCC_MCO1SOURCE_LSI) || ((SOURCE) == RCC_MCO1SOURCE_LSE) || \ + ((SOURCE) == RCC_MCO1SOURCE_HSI48)) +/** + * @} + */ + +/** @defgroup RCC_MCOPrescaler + * @{ + */ + +#define RCC_MCODIV_1 RCC_CFGR_MCO_PRE_1 +#define RCC_MCODIV_2 RCC_CFGR_MCO_PRE_2 +#define RCC_MCODIV_4 RCC_CFGR_MCO_PRE_4 +#define RCC_MCODIV_8 RCC_CFGR_MCO_PRE_8 +#define RCC_MCODIV_16 RCC_CFGR_MCO_PRE_16 + +#define IS_RCC_MCODIV(DIV) (((DIV) == RCC_MCODIV_1) || \ + ((DIV) == RCC_MCODIV_2) || \ + ((DIV) == RCC_MCODIV_4) || \ + ((DIV) == RCC_MCODIV_8) || \ + ((DIV) == RCC_MCODIV_16)) +/** + * @} + */ + +/** @defgroup RCC_MCO_Index + * @{ + */ +#define RCC_MCO1 ((uint32_t)0x00000000) +#define RCC_MCO2 ((uint32_t)0x00000001) + +#define IS_RCC_MCO(MCOx) (((MCOx) == RCC_MCO1) || ((MCOx) == RCC_MCO2)) +/** + * @} + */ + +/** @defgroup RCC_Interrupt + * @{ + */ +#define RCC_IT_LSIRDY RCC_CIFR_LSIRDYF +#define RCC_IT_LSERDY RCC_CIFR_LSERDYF +#define RCC_IT_HSIRDY RCC_CIFR_HSIRDYF +#define RCC_IT_HSERDY RCC_CIFR_HSERDYF +#define RCC_IT_PLLRDY RCC_CIFR_PLLRDYF +#define RCC_IT_MSIRDY RCC_CIFR_MSIRDYF +#define RCC_IT_HSI48RDY RCC_CIFR_HSI48RDYF +#define RCC_IT_LSECSS RCC_CIFR_LSECSSF +#define RCC_IT_CSS RCC_CIFR_CSSF + +#define IS_RCC_IT(IT) (((IT) == RCC_IT_LSIRDY) || ((IT) == RCC_IT_LSERDY) || \ + ((IT) == RCC_IT_HSIRDY) || ((IT) == RCC_IT_HSERDY) || \ + ((IT) == RCC_IT_PLLRDY) || ((IT) == RCC_IT_MSIRDY) || \ + ((IT) == RCC_IT_HSI48RDY) || ((IT) == RCC_IT_LSECSS)) + +#define IS_RCC_GET_IT(IT) (((IT) == RCC_IT_LSIRDY) || ((IT) == RCC_IT_LSERDY) || \ + ((IT) == RCC_IT_HSIRDY) || ((IT) == RCC_IT_HSERDY) || \ + ((IT) == RCC_IT_PLLRDY) || ((IT) == RCC_IT_MSIRDY) || \ + ((IT) == RCC_IT_CSS) || ((IT) == RCC_IT_HSI48RDY) || \ + ((IT) == RCC_IT_LSECSS)) + +#define IS_RCC_CLEAR_IT(IT) (((IT) == RCC_IT_LSIRDY) || ((IT) == RCC_IT_LSERDY) || \ + ((IT) == RCC_IT_HSIRDY) || ((IT) == RCC_IT_HSERDY) || \ + ((IT) == RCC_IT_PLLRDY) || ((IT) == RCC_IT_MSIRDY) || \ + ((IT) == RCC_IT_CSS) || ((IT) == RCC_IT_HSI48RDY) || \ + ((IT) == RCC_IT_LSECSS)) + +/** + * @} + */ + +/** @defgroup RCC_Flag + * Elements values convention: 0XXYYYYYb + * - YYYYY : Flag position in the register + * - 0XX : Register index + * - 01: CR register + * - 10: CSR register + * - 11: CRRCR register + * @{ + */ +/* Flags in the CR register */ +#define RCC_FLAG_HSIRDY ((uint8_t)0x22) +#define RCC_FLAG_HSIDIV ((uint8_t)0x24) +#define RCC_FLAG_MSIRDY ((uint8_t)0x29) +#define RCC_FLAG_HSERDY ((uint8_t)0x31) +#define RCC_FLAG_PLLRDY ((uint8_t)0x39) + +/* Flags in the CSR register */ +#define RCC_FLAG_LSERDY ((uint8_t)0x49) +#define RCC_FLAG_LSECSS ((uint8_t)0x4E) +#define RCC_FLAG_LSIRDY ((uint8_t)0x41) +#define RCC_FLAG_FIREWALLRST ((uint8_t)0x58) +#define RCC_FLAG_OBLRST ((uint8_t)0x59) +#define RCC_FLAG_PINRST ((uint8_t)0x5A) +#define RCC_FLAG_PORRST ((uint8_t)0x5B) +#define RCC_FLAG_SFTRST ((uint8_t)0x5C) +#define RCC_FLAG_IWDGRST ((uint8_t)0x5D) +#define RCC_FLAG_WWDGRST ((uint8_t)0x5E) +#define RCC_FLAG_LPWRRST ((uint8_t)0x5F) + +/* Flags in the CRRCR register */ +#define RCC_FLAG_HSI48RDY ((uint8_t)0x61) + + + +#define IS_RCC_CALIBRATION_VALUE(VALUE) ((VALUE) <= 0x1F) +/** + * @} + */ + +/** + * @} + */ +/* Exported macro ------------------------------------------------------------*/ +/** @defgroup RCC_Exported macro + * @{ + */ + +/** @brief Enable or disable the AHB peripheral clock. + * @note After reset, the peripheral clock (used for registers read/write access) + * is disabled and the application software has to enable this clock before + * using it. + */ +#define __DMA1_CLK_ENABLE() (RCC->AHBENR |= (RCC_AHBENR_DMA1EN)) +#define __MIF_CLK_ENABLE() (RCC->AHBENR |= (RCC_AHBENR_MIFEN)) +#define __CRC_CLK_ENABLE() (RCC->AHBENR |= (RCC_AHBENR_CRCEN)) + + +#define __DMA1_CLK_DISABLE() (RCC->AHBENR &= ~ (RCC_AHBENR_DMA1EN)) +#define __MIF_CLK_DISABLE() (RCC->AHBENR &= ~ (RCC_AHBENR_MIFEN)) +#define __CRC_CLK_DISABLE() (RCC->AHBENR &= ~ (RCC_AHBENR_CRCEN)) + + +/** @brief Enable or disable the IOPORT peripheral clock. + * @note After reset, the peripheral clock (used for registers read/write access) + * is disabled and the application software has to enable this clock before + * using it. + */ +#define __GPIOA_CLK_ENABLE() (RCC->IOPENR |= (RCC_IOPENR_GPIOAEN)) +#define __GPIOB_CLK_ENABLE() (RCC->IOPENR |= (RCC_IOPENR_GPIOBEN)) +#define __GPIOC_CLK_ENABLE() (RCC->IOPENR |= (RCC_IOPENR_GPIOCEN)) +#define __GPIOD_CLK_ENABLE() (RCC->IOPENR |= (RCC_IOPENR_GPIODEN)) +#define __GPIOH_CLK_ENABLE() (RCC->IOPENR |= (RCC_IOPENR_GPIOHEN)) + +#define __GPIOA_CLK_DISABLE() (RCC->IOPENR &= ~(RCC_IOPENR_GPIOAEN)) +#define __GPIOB_CLK_DISABLE() (RCC->IOPENR &= ~(RCC_IOPENR_GPIOBEN)) +#define __GPIOC_CLK_DISABLE() (RCC->IOPENR &= ~(RCC_IOPENR_GPIOCEN)) +#define __GPIOD_CLK_DISABLE() (RCC->IOPENR &= ~(RCC_IOPENR_GPIODEN)) +#define __GPIOH_CLK_DISABLE() (RCC->IOPENR &= ~(RCC_IOPENR_GPIOHEN)) + + +/** @brief Enable or disable the Low Speed APB (APB1) peripheral clock. + * @note After reset, the peripheral clock (used for registers read/write access) + * is disabled and the application software has to enable this clock before + * using it. + */ +#define __WWDG_CLK_ENABLE() (RCC->APB1ENR |= (RCC_APB1ENR_WWDGEN)) +#define __PWR_CLK_ENABLE() (RCC->APB1ENR |= (RCC_APB1ENR_PWREN)) + +#define __WWDG_CLK_DISABLE() (RCC->APB1ENR &= ~ (RCC_APB1ENR_WWDGEN)) +#define __PWR_CLK_DISABLE() (RCC->APB1ENR &= ~ (RCC_APB1ENR_PWREN)) + +/** @brief Enable or disable the High Speed APB (APB2) peripheral clock. + * @note After reset, the peripheral clock (used for registers read/write access) + * is disabled and the application software has to enable this clock before + * using it. + */ +#define __SYSCFG_CLK_ENABLE() (RCC->APB2ENR |= (RCC_APB2ENR_SYSCFGEN)) +#define __DBGMCU_CLK_ENABLE() (RCC->APB2ENR |= (RCC_APB2ENR_DBGMCUEN)) + +#define __SYSCFG_CLK_DISABLE() (RCC->APB2ENR &= ~ (RCC_APB2ENR_SYSCFGEN)) +#define __DBGMCU_CLK_DISABLE() (RCC->APB2ENR &= ~ (RCC_APB2ENR_DBGMCUEN)) + +/** @brief Force or release AHB peripheral reset. + */ +#define __AHB_FORCE_RESET() (RCC->AHBRSTR = 0xFFFFFFFF) +#define __DMA1_FORCE_RESET() (RCC->AHBRSTR |= (RCC_AHBRSTR_DMA1RST)) +#define __MIF_FORCE_RESET() (RCC->AHBRSTR |= (RCC_AHBRSTR_MIFRST)) +#define __CRC_FORCE_RESET() (RCC->AHBRSTR |= (RCC_AHBRSTR_CRCRST)) + +#define __AHB_RELEASE_RESET() (RCC->AHBRSTR = 0x00) +#define __CRC_RELEASE_RESET() (RCC->AHBRSTR &= ~ (RCC_AHBRSTR_CRCRST)) +#define __DMA1_RELEASE_RESET() (RCC->AHBRSTR &= ~ (RCC_AHBRSTR_DMA1RST)) +#define __MIF_RELEASE_RESET() (RCC->AHBRSTR &= ~ (RCC_AHBRSTR_MIFRST)) + + +/** @brief Force or release IOPORT peripheral reset. + */ +#define __IOP_FORCE_RESET() (RCC->IOPRSTR = 0xFFFFFFFF) +#define __GPIOA_FORCE_RESET() (RCC->IOPRSTR |= (RCC_IOPRSTR_GPIOARST)) +#define __GPIOB_FORCE_RESET() (RCC->IOPRSTR |= (RCC_IOPRSTR_GPIOBRST)) +#define __GPIOC_FORCE_RESET() (RCC->IOPRSTR |= (RCC_IOPRSTR_GPIOCRST)) +#define __GPIOD_FORCE_RESET() (RCC->IOPRSTR |= (RCC_IOPRSTR_GPIODRST)) +#define __GPIOH_FORCE_RESET() (RCC->IOPRSTR |= (RCC_IOPRSTR_GPIOHRST)) + +#define __IOP_RELEASE_RESET() (RCC->IOPRSTR = 0x00) +#define __GPIOA_RELEASE_RESET() (RCC->IOPRSTR &= ~(RCC_IOPRSTR_GPIOARST)) +#define __GPIOB_RELEASE_RESET() (RCC->IOPRSTR &= ~(RCC_IOPRSTR_GPIOBRST)) +#define __GPIOC_RELEASE_RESET() (RCC->IOPRSTR &= ~(RCC_IOPRSTR_GPIOCRST)) +#define __GPIOD_RELEASE_RESET() (RCC->IOPRSTR &= ~(RCC_IOPRSTR_GPIODRST)) +#define __GPIOH_RELEASE_RESET() (RCC->IOPRSTR &= ~(RCC_IOPRSTR_GPIOHRST)) + +/** @brief Force or release APB1 peripheral reset. + */ +#define __APB1_FORCE_RESET() (RCC->APB1RSTR = 0xFFFFFFFF) +#define __WWDG_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_WWDGRST)) +#define __PWR_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_PWRRST)) + +#define __APB1_RELEASE_RESET() (RCC->APB1RSTR = 0x00) +#define __WWDG_RELEASE_RESET() (RCC->APB1RSTR &= ~ (RCC_APB1RSTR_WWDGRST)) +#define __PWR_RELEASE_RESET() (RCC->APB1RSTR &= ~ (RCC_APB1RSTR_PWRRST)) + +/** @brief Force or release APB2 peripheral reset. + */ +#define __APB2_FORCE_RESET() (RCC->APB2RSTR = 0xFFFFFFFF) +#define __DBGMCU_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_DBGMCURST)) +#define __SYSCFG_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_SYSCFGRST)) + +#define __APB2_RELEASE_RESET() (RCC->APB2RSTR = 0x00) +#define __DBGMCU_RELEASE_RESET() (RCC->APB2RSTR &= ~ (RCC_APB2RSTR_DBGMCURST)) +#define __SYSCFG_RELEASE_RESET() (RCC->APB2RSTR &= ~ (RCC_APB2RSTR_SYSCFGRST)) + +/** @brief Enable or disable the AHB peripheral clock during Low Power (Sleep) mode. + * @note Peripheral clock gating in SLEEP mode can be used to further reduce + * power consumption. + * @note After wakeup from SLEEP mode, the peripheral clock is enabled again. + * @note By default, all peripheral clocks are enabled during SLEEP mode. + */ +#define __CRC_CLK_SLEEP_ENABLE() (RCC->AHBSMENR |= (RCC_AHBSMENR_CRCSMEN)) +#define __MIF_CLK_SLEEP_ENABLE() (RCC->AHBSMENR |= (RCC_AHBSMENR_MIFSMEN)) +#define __SRAM_CLK_SLEEP_ENABLE() (RCC->AHBSMENR |= (RCC_AHBSMENR_SRAMSMEN)) +#define __DMA1_CLK_SLEEP_ENABLE() (RCC->AHBSMENR |= (RCC_AHBSMENR_DMA1SMEN)) + +#define __CRC_CLK_SLEEP_DISABLE() (RCC->AHBSMENR &= ~ (RCC_AHBSMENR_CRCSMEN)) +#define __MIF_CLK_SLEEP_DISABLE() (RCC->AHBSMENR &= ~ (RCC_AHBSMENR_MIFSMEN)) +#define __SRAM_CLK_SLEEP_DISABLE() (RCC->AHBSMENR &= ~ (RCC_AHBSMENR_SRAMSMEN)) +#define __DMA1_CLK_SLEEP_DISABLE() (RCC->AHBSMENR &= ~ (RCC_AHBSMENR_DMA1SMEN)) + +/** @brief Enable or disable the IOPORT peripheral clock during Low Power (Sleep) mode. + * @note Peripheral clock gating in SLEEP mode can be used to further reduce + * power consumption. + * @note After wakeup from SLEEP mode, the peripheral clock is enabled again. + * @note By default, all peripheral clocks are enabled during SLEEP mode. + */ + +#define __GPIOA_CLK_SLEEP_ENABLE() (RCC->IOPSMENR |= (RCC_IOPSMENR_GPIOASMEN)) +#define __GPIOB_CLK_SLEEP_ENABLE() (RCC->IOPSMENR |= (RCC_IOPSMENR_GPIOBSMEN)) +#define __GPIOC_CLK_SLEEP_ENABLE() (RCC->IOPSMENR |= (RCC_IOPSMENR_GPIOCSMEN)) +#define __GPIOD_CLK_SLEEP_ENABLE() (RCC->IOPSMENR |= (RCC_IOPSMENR_GPIODSMEN)) +#define __GPIOH_CLK_SLEEP_ENABLE() (RCC->IOPSMENR |= (RCC_IOPSMENR_GPIOHSMEN)) + +#define __GPIOA_CLK_SLEEP_DISABLE() (RCC->IOPSMENR &= ~(RCC_IOPSMENR_GPIOASMEN)) +#define __GPIOB_CLK_SLEEP_DISABLE() (RCC->IOPSMENR &= ~(RCC_IOPSMENR_GPIOBSMEN)) +#define __GPIOC_CLK_SLEEP_DISABLE() (RCC->IOPSMENR &= ~(RCC_IOPSMENR_GPIOCSMEN)) +#define __GPIOD_CLK_SLEEP_DISABLE() (RCC->IOPSMENR &= ~(RCC_IOPSMENR_GPIODSMEN)) +#define __GPIOH_CLK_SLEEP_DISABLE() (RCC->IOPSMENR &= ~(RCC_IOPSMENR_GPIOHSMEN)) + +/** @brief Enable or disable the APB1 peripheral clock during Low Power (Sleep) mode. + * @note Peripheral clock gating in SLEEP mode can be used to further reduce + * power consumption. + * @note After wakeup from SLEEP mode, the peripheral clock is enabled again. + * @note By default, all peripheral clocks are enabled during SLEEP mode. + */ +#define __WWDG_CLK_SLEEP_ENABLE() (RCC->APB1SMENR |= (RCC_APB1SMENR_WWDGSMEN)) +#define __PWR_CLK_SLEEP_ENABLE() (RCC->APB1SMENR |= (RCC_APB1SMENR_PWRSMEN)) + +#define __WWDG_CLK_SLEEP_DISABLE() (RCC->APB1SMENR &= ~ (RCC_APB1SMENR_WWDGSMEN)) +#define __PWR_CLK_SLEEP_DISABLE() (RCC->APB1SMENR &= ~ (RCC_APB1SMENR_PWRSMEN)) + +/** @brief Enable or disable the APB2 peripheral clock during Low Power (Sleep) mode. + * @note Peripheral clock gating in SLEEP mode can be used to further reduce + * power consumption. + * @note After wakeup from SLEEP mode, the peripheral clock is enabled again. + * @note By default, all peripheral clocks are enabled during SLEEP mode. + */ +#define __SYSCFG_CLK_SLEEP_ENABLE() (RCC->APB2SMENR |= (RCC_APB2SMENR_SYSCFGSMEN)) +#define __DBGMCU_CLK_SLEEP_ENABLE() (RCC->APB2SMENR |= (RCC_APB2SMENR_DBGMCUSMEN)) + +#define __SYSCFG_CLK_SLEEP_DISABLE() (RCC->APB2SMENR &= ~ (RCC_APB2SMENR_SYSCFGSMEN)) +#define __DBGMCU_CLK_SLEEP_DISABLE() (RCC->APB2SMENR &= ~ (RCC_APB2SMENR_DBGMCUSMEN)) + +/** @brief Macro to enable or disable the Internal High Speed oscillator (HSI). + * @note After enabling the HSI, the application software should wait on + * HSIRDY flag to be set indicating that HSI clock is stable and can + * be used to clock the PLL and/or system clock. + * @note HSI can not be stopped if it is used directly or through the PLL + * as system clock. In this case, you have to select another source + * of the system clock then stop the HSI. + * @note The HSI is stopped by hardware when entering STOP and STANDBY modes. + * @param __STATE__: specifies the new state of the HSI. + * This parameter can be one of the following values: + * @arg RCC_HSI_OFF: turn OFF the HSI oscillator + * @arg RCC_HSI_ON: turn ON the HSI oscillator + * @arg RCC_HSI_DIV4: turn ON the HSI oscillator and divide it by 4 + * @note When the HSI is stopped, HSIRDY flag goes low after 6 HSI oscillator + * clock cycles. + */ +#define __HAL_RCC_HSI_CONFIG(__STATE__) \ + MODIFY_REG(RCC->CR, RCC_CR_HSION|RCC_CR_HSIDIVEN, (uint32_t)(__STATE__)) + +/** @brief Macros to enable or disable the Internal High Speed oscillator (HSI). + * @note The HSI is stopped by hardware when entering STOP and STANDBY modes. + * It is used (enabled by hardware) as system clock source after startup + * from Reset, wakeup from STOP and STANDBY mode, or in case of failure + * of the HSE used directly or indirectly as system clock (if the Clock + * Security System CSS is enabled). + * @note HSI can not be stopped if it is used as system clock source. In this case, + * you have to select another source of the system clock then stop the HSI. + * @note After enabling the HSI, the application software should wait on HSIRDY + * flag to be set indicating that HSI clock is stable and can be used as + * system clock source. + * @note When the HSI is stopped, HSIRDY flag goes low after 6 HSI oscillator + * clock cycles. + */ +#define __HAL_RCC_HSI_ENABLE() SET_BIT(RCC->CR, RCC_CR_HSION) +#define __HAL_RCC_HSI_DISABLE() CLEAR_BIT(RCC->CR, RCC_CR_HSION) + +/** + * @brief Macros to enable or disable the Internal Multi Speed oscillator (MSI). + * @note The MSI is stopped by hardware when entering STOP and STANDBY modes. + * It is used (enabled by hardware) as system clock source after + * startup from Reset, wakeup from STOP and STANDBY mode, or in case + * of failure of the HSE used directly or indirectly as system clock + * (if the Clock Security System CSS is enabled). + * @note MSI can not be stopped if it is used as system clock source. + * In this case, you have to select another source of the system + * clock then stop the MSI. + * @note After enabling the MSI, the application software should wait on + * MSIRDY flag to be set indicating that MSI clock is stable and can + * be used as system clock source. + * @note When the MSI is stopped, MSIRDY flag goes low after 6 MSI oscillator + * clock cycles. + */ +#define __HAL_RCC_MSI_ENABLE() SET_BIT(RCC->CR, RCC_CR_MSION) +#define __HAL_RCC_MSI_DISABLE() CLEAR_BIT(RCC->CR, RCC_CR_MSION) + +/** + * @brief Macro to enable or disable the Internal High Speed oscillator for USB (HSI48). + * @note After enabling the HSI48, the application software should wait on + * HSI48RDY flag to be set indicating that HSI48 clock is stable and can + * be used to clock the USB. + * @note The HSI48 is stopped by hardware when entering STOP and STANDBY modes. + */ +#define __HAL_RCC_HSI48_ENABLE() do { SET_BIT(RCC->CRRCR, RCC_CRRCR_HSI48ON); \ + RCC->APB2ENR |= RCC_APB2ENR_SYSCFGEN; \ + SYSCFG->CFGR3 |= (SYSCFG_CFGR3_ENREF_HSI48 | SYSCFG_CFGR3_EN_VREFINT); \ + } while (0) +#define __HAL_RCC_HSI48_DISABLE() do { CLEAR_BIT(RCC->CRRCR, RCC_CRRCR_HSI48ON); \ + SYSCFG->CFGR3 &= (uint32_t)~((uint32_t)(SYSCFG_CFGR3_ENREF_HSI48 | SYSCFG_CFGR3_EN_VREFINT)); \ + } while (0) + +/** @brief Macro to adjust the Internal High Speed oscillator (HSI) calibration value. + * @note The calibration is used to compensate for the variations in voltage + * and temperature that influence the frequency of the internal HSI RC. + * @param __HSICalibrationValue__: specifies the calibration trimming value. + * This parameter must be a number between 0 and 0x1F. + */ +#define __HAL_RCC_HSI_CALIBRATIONVALUE_ADJUST(__HSICalibrationValue__) (MODIFY_REG(RCC->ICSCR,\ + RCC_ICSCR_HSITRIM, (uint32_t)(__HSICalibrationValue__) << 8)) + +/** @brief Macro Adjusts the Internal Multi Speed oscillator (MSI) calibration value. + * @note The calibration is used to compensate for the variations in voltage + * and temperature that influence the frequency of the internal MSI RC. + * Refer to the Application Note AN3300 for more details on how to + * calibrate the MSI. + * @param __MSICalibrationValue__: specifies the calibration trimming value. + * This parameter must be a number between 0 and 0xFF. + */ +#define __HAL_RCC_MSI_CALIBRATIONVALUE_ADJUST(__MSICalibrationValue__) (MODIFY_REG(RCC->ICSCR,\ + RCC_ICSCR_MSITRIM, (uint32_t)(__MSICalibrationValue__) << 24)) + +/** + * @brief Macro to configures the Internal Multi Speed oscillator (MSI) clock range. + * @note After restart from Reset or wakeup from STANDBY, the MSI clock is + * around 2.097 MHz. The MSI clock does not change after wake-up from + * STOP mode. + * @note The MSI clock range can be modified on the fly. + * @param RCC_MSIRange: specifies the MSI Clock range. + * This parameter must be one of the following values: + * @arg RCC_MSIRANGE_0: MSI clock is around 65.536 KHz + * @arg RCC_MSIRANGE_1: MSI clock is around 131.072 KHz + * @arg RCC_MSIRANGE_2: MSI clock is around 262.144 KHz + * @arg RCC_MSIRANGE_3: MSI clock is around 524.288 KHz + * @arg RCC_MSIRANGE_4: MSI clock is around 1.048 MHz + * @arg RCC_MSIRANGE_5: MSI clock is around 2.097 MHz (default after Reset or wake-up from STANDBY) + * @arg RCC_MSIRANGE_6: MSI clock is around 4.194 MHz + */ +#define __HAL_RCC_MSI_RANGE_CONFIG(__RCC_MSIRange__) (MODIFY_REG(RCC->ICSCR,\ + RCC_ICSCR_MSIRANGE, (uint32_t)(__RCC_MSIRange__) )) + +/** @brief Macros to enable or disable the Internal Low Speed oscillator (LSI). + * @note After enabling the LSI, the application software should wait on + * LSIRDY flag to be set indicating that LSI clock is stable and can + * be used to clock the IWDG and/or the RTC. + * @note LSI can not be disabled if the IWDG is running. + * @note When the LSI is stopped, LSIRDY flag goes low after 6 LSI oscillator + * clock cycles. + */ +#define __HAL_RCC_LSI_ENABLE() SET_BIT(RCC->CSR, RCC_CSR_LSION) +#define __HAL_RCC_LSI_DISABLE() CLEAR_BIT(RCC->CSR, RCC_CSR_LSION) + +/** + * @brief Macro to configure the External High Speed oscillator (HSE). + * @note After enabling the HSE (RCC_HSE_ON or RCC_HSE_Bypass), the application + * software should wait on HSERDY flag to be set indicating that HSE clock + * is stable and can be used to clock the PLL and/or system clock. + * @note HSE state can not be changed if it is used directly or through the + * PLL as system clock. In this case, you have to select another source + * of the system clock then change the HSE state (ex. disable it). + * @note The HSE is stopped by hardware when entering STOP and STANDBY modes. + * @note This function reset the CSSON bit, so if the clock security system(CSS) + * was previously enabled you have to enable it again after calling this + * function. + * @param __STATE__: specifies the new state of the HSE. + * This parameter can be one of the following values: + * @arg RCC_HSE_OFF: turn OFF the HSE oscillator, HSERDY flag goes low after + * 6 HSE oscillator clock cycles. + * @arg RCC_HSE_ON: turn ON the HSE oscillator. + * @arg RCC_HSE_BYPASS: HSE oscillator bypassed with external clock. + */ +#define __HAL_RCC_HSE_CONFIG(__STATE__) \ + MODIFY_REG(RCC->CR, RCC_CR_HSEON|RCC_CR_HSEBYP, (uint32_t)(__STATE__)) + +/** + * @brief Macro to configure the External Low Speed oscillator (LSE). + * @note As the LSE is in the Backup domain and write access is denied to + * this domain after reset, you have to enable write access using + * HAL_PWR_EnableBkUpAccess() function before to configure the LSE + * (to be done once after reset). + * @note After enabling the LSE (RCC_LSE_ON or RCC_LSE_BYPASS), the application + * software should wait on LSERDY flag to be set indicating that LSE clock + * is stable and can be used to clock the RTC. + * @param __STATE__: specifies the new state of the LSE. + * This parameter can be one of the following values: + * @arg RCC_LSE_OFF: turn OFF the LSE oscillator, LSERDY flag goes low after + * 6 LSE oscillator clock cycles. + * @arg RCC_LSE_ON: turn ON the LSE oscillator. + * @arg RCC_LSE_BYPASS: LSE oscillator bypassed with external clock. + */ +#define __HAL_RCC_LSE_CONFIG(__STATE__) \ + MODIFY_REG(RCC->CSR, RCC_CSR_LSEON|RCC_CSR_LSEBYP, (uint32_t)(__STATE__)) + +/** @brief Macros to enable or disable the the RTC clock. + * @note These macros must be used only after the RTC clock source was selected. + */ +#define __HAL_RCC_RTC_ENABLE() SET_BIT(RCC->CSR, RCC_CSR_RTCEN) +#define __HAL_RCC_RTC_DISABLE() CLEAR_BIT(RCC->CSR, RCC_CSR_RTCEN) + +/** + * @brief Configures or Get the RTC and LCD clock (RTCCLK / LCDCLK). + * @note As the RTC clock configuration bits are in the RTC domain and write + * access is denied to this domain after reset, you have to enable write + * access using PWR_RTCAccessCmd(ENABLE) function before to configure + * the RTC clock source (to be done once after reset). + * @note Once the RTC clock is configured it can't be changed unless the RTC + * is reset using RCC_RTCResetCmd function, or by a Power On Reset (POR) + * @note The RTC clock (RTCCLK) is used also to clock the LCD (LCDCLK). + * + * @param RCC_RTCCLKSource: specifies the RTC clock source. + * This parameter can be one of the following values: + * @arg RCC_RTCCLKSOURCE_LSE: LSE selected as RTC clock + * @arg RCC_RTCCLKSOURCE_LSI: LSI selected as RTC clock + * @arg RCC_RTCCLKSOURCE_HSE_DIV2: HSE divided by 2 selected as RTC clock + * @arg RCC_RTCCLKSOURCE_HSE_DIV4: HSE divided by 4 selected as RTC clock + * @arg RCC_RTCCLKSOURCE_HSE_DIV8: HSE divided by 8 selected as RTC clock + * @arg RCC_RTCCLKSOURCE_HSE_DIV16: HSE divided by 16 selected as RTC clock + * + * @note If the LSE or LSI is used as RTC clock source, the RTC continues to + * work in STOP and STANDBY modes, and can be used as wakeup source. + * However, when the HSE clock is used as RTC clock source, the RTC + * cannot be used in STOP and STANDBY modes. + * @note The maximum input clock frequency for RTC is 1MHz (when using HSE as + * RTC clock source). + */ +#define __HAL_RCC_RTC_CLKPRESCALER(__RTCCLKSource__) (((__RTCCLKSource__) & RCC_CSR_RTCSEL) == RCC_CSR_RTCSEL) ? \ + MODIFY_REG(RCC->CR, RCC_CR_RTCPRE, ((__RTCCLKSource__) & 0xFFFCFFFF)) : CLEAR_BIT(RCC->CR, RCC_CR_RTCPRE) + +#define __HAL_RCC_RTC_CONFIG(__RTCCLKSource__) do { __HAL_RCC_RTC_CLKPRESCALER(__RTCCLKSource__); \ + MODIFY_REG( RCC->CSR, RCC_CSR_RTCSEL, (uint32_t)(__RTCCLKSource__)); \ + } while (0) + +#define __HAL_RCC_GET_RTC_SOURCE() ((uint32_t)(READ_BIT(RCC->CCIPR, RCC_CSR_RTCSEL))) + +/** @brief Macros to force or release the Backup domain reset. + * @note This function resets the RTC peripheral (including the backup registers) + * and the RTC clock source selection in RCC_CSR register. + * @note The BKPSRAM is not affected by this reset. + */ +#define __HAL_RCC_BACKUPRESET_FORCE() SET_BIT(RCC->CSR, RCC_CSR_RTCRST) +#define __HAL_RCC_BACKUPRESET_RELEASE() CLEAR_BIT(RCC->CSR, RCC_CSR_RTCRST) + +/** @brief Macros to enable or disable the main PLL. + * @note After enabling the main PLL, the application software should wait on + * PLLRDY flag to be set indicating that PLL clock is stable and can + * be used as system clock source. + * @note The main PLL can not be disabled if it is used as system clock source + * @note The main PLL is disabled by hardware when entering STOP and STANDBY modes. + */ +#define __HAL_RCC_PLL_ENABLE() SET_BIT(RCC->CR, RCC_CR_PLLON) +#define __HAL_RCC_PLL_DISABLE() CLEAR_BIT(RCC->CR, RCC_CR_PLLON) + +/** @brief Macro to configure the main PLL clock source, multiplication and division factors. + * @note This function must be used only when the main PLL is disabled. + * @param __RCC_PLLSource__: specifies the PLL entry clock source. + * This parameter can be one of the following values: + * @arg RCC_PLLSOURCE_HSI: HSI oscillator clock selected as PLL clock entry + * @arg RCC_PLLSOURCE_HSE: HSE oscillator clock selected as PLL clock entry + * @param __PLLMUL__: specifies the multiplication factor to generate the PLL VCO clock + * This parameter must be one of the following values: + * @arg RCC_CFGR_PLLMUL3: PLLVCO = PLL clock entry x 3 + * @arg RCC_CFGR_PLLMUL4: PLLVCO = PLL clock entry x 4 + * @arg RCC_CFGR_PLLMUL6: PLLVCO = PLL clock entry x 6 + * @arg RCC_CFGR_PLLMUL8: PLLVCO = PLL clock entry x 8 + * @arg RCC_CFGR_PLLMUL12: PLLVCO = PLL clock entry x 12 + * @arg RCC_CFGR_PLLMUL16: PLLVCO = PLL clock entry x 16 + * @arg RCC_CFGR_PLLMUL24: PLLVCO = PLL clock entry x 24 + * @arg RCC_CFGR_PLLMUL32: PLLVCO = PLL clock entry x 32 + * @arg RCC_CFGR_PLLMUL48: PLLVCO = PLL clock entry x 48 + * @note The PLL VCO clock frequency must not exceed 96 MHz when the product is in + * Range 1, 48 MHz when the product is in Range 2 and 24 MHz when the product is + * in Range 3. + * @param __PLLDIV__: specifies the PLL output clock division from PLL VCO clock + * This parameter must be one of the following values: + * @arg RCC_PLLDIV_2: PLL clock output = PLLVCO / 2 + * @arg RCC_PLLDIV_3: PLL clock output = PLLVCO / 3 + * @arg RCC_PLLDIV_4: PLL clock output = PLLVCO / 4 + */ + +#define __HAL_RCC_PLL_CONFIG(__RCC_PLLSource__ , __PLLMUL__ ,__PLLDIV__ ) \ + MODIFY_REG(RCC->CFGR, RCC_CFGR_PLLMUL | RCC_CFGR_PLLDIV | RCC_CFGR_PLLSRC, (uint32_t)((__PLLMUL__)| (__PLLDIV__)| (__RCC_PLLSource__))) + +/** @brief Macro to get the clock source used as system clock. + * @retval The clock source used as system clock. The returned value can be one + * of the following: + * - RCC_CFGR_SWS_HSI: HSI used as system clock. + * - RCC_CFGR_SWS_HSE: HSE used as system clock. + * - RCC_CFGR_SWS_PLL: PLL used as system clock. + */ +#define __HAL_RCC_GET_SYSCLK_SOURCE() ((uint32_t)(RCC->CFGR & RCC_CFGR_SWS)) + +/** @brief Macro to get the oscillator used as PLL clock source. + * @retval The oscillator used as PLL clock source. The returned value can be one + * of the following: + * - RCC_PLLSOURCE_HSI: HSI oscillator is used as PLL clock source. + * - RCC_PLLSOURCE_HSE: HSE oscillator is used as PLL clock source. + */ +#define __HAL_RCC_GET_PLL_OSCSOURCE() ((uint32_t)(RCC->CFGR & RCC_CFGR_PLLSRC)) + +/** @defgroup RCC_Flags_Interrupts_Management + * @brief macros to manage the specified RCC Flags and interrupts. + * @{ + */ + +/** @brief Enable RCC interrupt (Perform Byte access to RCC_CIER[0:7] bits to enable + * the selected interrupts). + * @note The CSS interrupt doesn't have an enable bit; once the CSS is enabled + * and if the HSE clock fails, the CSS interrupt occurs and an NMI is + * automatically generated. The NMI will be executed indefinitely, and + * since NMI has higher priority than any other IRQ (and main program) + * the application will be stacked in the NMI ISR unless the CSS interrupt + * pending bit is cleared. + * @param __INTERRUPT__: specifies the RCC interrupt sources to be enabled. + * This parameter can be any combination of the following values: + * @arg RCC_IT_LSIRDY: LSI ready interrupt + * @arg RCC_IT_LSERDY: LSE ready interrupt + * @arg RCC_IT_HSIRDY: HSI ready interrupt + * @arg RCC_IT_HSERDY: HSE ready interrupt + * @arg RCC_IT_PLLRDY: PLL ready interrupt + * @arg RCC_IT_MSIRDY: MSI ready interrupt + * @arg RCC_IT_LSECSS: LSE CSS interrupt + */ +#define __HAL_RCC_ENABLE_IT(__INTERRUPT__) (*(__IO uint8_t *) CIER_BYTE0_ADDRESS |= (__INTERRUPT__)) + +/** @brief Disable RCC interrupt (Perform Byte access to RCC_CIER[0:7] bits to disable + * the selected interrupts). + * @note The CSS interrupt doesn't have an enable bit; once the CSS is enabled + * and if the HSE clock fails, the CSS interrupt occurs and an NMI is + * automatically generated. The NMI will be executed indefinitely, and + * since NMI has higher priority than any other IRQ (and main program) + * the application will be stacked in the NMI ISR unless the CSS interrupt + * pending bit is cleared. + * @param __INTERRUPT__: specifies the RCC interrupt sources to be disabled. + * This parameter can be any combination of the following values: + * @arg RCC_IT_LSIRDY: LSI ready interrupt + * @arg RCC_IT_LSERDY: LSE ready interrupt + * @arg RCC_IT_HSIRDY: HSI ready interrupt + * @arg RCC_IT_HSERDY: HSE ready interrupt + * @arg RCC_IT_PLLRDY: PLL ready interrupt + * @arg RCC_IT_MSIRDY: MSI ready interrupt + * @arg RCC_IT_LSECSS: LSE CSS interrupt + */ +#define __HAL_RCC_DISABLE_IT(__INTERRUPT__) (*(__IO uint8_t *) CIER_BYTE0_ADDRESS &= ~(__INTERRUPT__)) + +/** @brief Clear the RCC's interrupt pending bits (Perform Byte access to RCC_CIR[23:16] + * bits to clear the selected interrupt pending bits. + * @param __INTERRUPT__: specifies the interrupt pending bit to clear. + * This parameter can be any combination of the following values: + * @arg RCC_IT_LSIRDY: LSI ready interrupt + * @arg RCC_IT_LSERDY: LSE ready interrupt + * @arg RCC_IT_HSIRDY: HSI ready interrupt + * @arg RCC_IT_HSERDY: HSE ready interrupt + * @arg RCC_IT_PLLRDY: PLL ready interrupt + * @arg RCC_IT_MSIRDY: MSI ready interrupt + * @arg RCC_IT_LSECSS: LSE CSS interrupt + * @arg RCC_IT_CSS: Clock Security System interrupt + */ + #define __HAL_RCC_CLEAR_IT(__INTERRUPT__) SET_BIT(RCC->CICR, (__INTERRUPT__)) + +/** @brief Check the RCC's interrupt has occurred or not. + * @param __INTERRUPT__: specifies the RCC interrupt source to check. + * This parameter can be one of the following values: + * @arg RCC_IT_LSIRDY: LSI ready interrupt + * @arg RCC_IT_LSERDY: LSE ready interrupt + * @arg RCC_IT_HSIRDY: HSI ready interrupt + * @arg RCC_IT_HSERDY: HSE ready interrupt + * @arg RCC_IT_PLLRDY: PLL ready interrupt + * @arg RCC_IT_MSIRDY: MSI ready interrupt + * @arg RCC_IT_LSECSS: LSE CSS interrupt + * @arg RCC_IT_CSS: Clock Security System interrupt + * @retval The new state of __INTERRUPT__ (TRUE or FALSE). + */ +#define __HAL_RCC_GET_IT(__INTERRUPT__) ((RCC->CIFR & (__INTERRUPT__)) == (__INTERRUPT__)) + +/** @brief Set RMVF bit to clear the reset flags. + * The reset flags are: RCC_FLAG_OBLRST, RCC_FLAG_PINRST, RCC_FLAG_PORRST, + * RCC_FLAG_SFTRST, RCC_FLAG_IWDGRST, RCC_FLAG_WWDGRST, RCC_FLAG_LPWRRST. + */ +#define __HAL_RCC_CLEAR_RESET_FLAGS() (RCC->CSR |= RCC_CSR_RMVF) + +/** @brief Check RCC flag is set or not. + * @param __FLAG__: specifies the flag to check. + * This parameter can be one of the following values: + * @arg RCC_FLAG_HSIRDY: HSI oscillator clock ready + * @arg RCC_FLAG_MSIRDY: MSI oscillator clock ready + * @arg RCC_FLAG_HSERDY: HSE oscillator clock ready + * @arg RCC_FLAG_PLLRDY: PLL clock ready + * @arg RCC_FLAG_LSECSS: LSE oscillator clock CSS detected + * @arg RCC_FLAG_LSERDY: LSE oscillator clock ready + * @arg RCC_FLAG_LSIRDY: LSI oscillator clock ready + * @arg RCC_FLAG_OBLRST: Option Byte Loader (OBL) reset + * @arg RCC_FLAG_PINRST: Pin reset + * @arg RCC_FLAG_PORRST: POR/PDR reset + * @arg RCC_FLAG_SFTRST: Software reset + * @arg RCC_FLAG_IWDGRST: Independent Watchdog reset + * @arg RCC_FLAG_WWDGRST: Window Watchdog reset + * @arg RCC_FLAG_LPWRRST: Low Power reset + * @retval The new state of __FLAG__ (TRUE or FALSE). + */ +#define RCC_FLAG_MASK ((uint8_t)0x1F) +#define __HAL_RCC_GET_FLAG(__FLAG__) (((((((__FLAG__) >> 5) == 1)? RCC->CR :((((__FLAG__) >> 5) == 2) ? RCC->CSR :((((__FLAG__) >> 5) == 3)? \ + RCC->CRRCR :RCC->CIFR))) & ((uint32_t)1 << ((__FLAG__) & RCC_FLAG_MASK))) != 0 ) ? 1 : 0 ) + +/** + * @} + */ + +#define __RCC_PLLSRC() ((RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC) >> POSITION_VAL(RCC_PLLCFGR_PLLSRC)) +/** + * @} + */ + +/* Include RCC HAL Extension module */ +#include "stm32l0xx_hal_rcc_ex.h" + +/* Exported functions --------------------------------------------------------*/ +/* Initialization and de-initialization methods ******************************/ +void HAL_RCC_DeInit(void); +HAL_StatusTypeDef HAL_RCC_OscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct); +HAL_StatusTypeDef HAL_RCC_ClockConfig(RCC_ClkInitTypeDef *RCC_ClkInitStruct, uint32_t FLatency); + +/* Peripheral Control methods ************************************************/ +void HAL_RCC_MCOConfig(uint32_t RCC_MCOx, uint32_t RCC_MCOSource, uint32_t RCC_MCODiv); +void HAL_RCC_EnableCSS(void); +uint32_t HAL_RCC_GetSysClockFreq(void); +uint32_t HAL_RCC_GetHCLKFreq(void); +uint32_t HAL_RCC_GetPCLK1Freq(void); +uint32_t HAL_RCC_GetPCLK2Freq(void); +void HAL_RCC_GetOscConfig(RCC_OscInitTypeDef *RCC_OscInitStruct); +void HAL_RCC_GetClockConfig(RCC_ClkInitTypeDef *RCC_ClkInitStruct, uint32_t *pFLatency); + +/* CSS NMI IRQ handler */ +void HAL_RCC_NMI_IRQHandler(void); + +/* User Callbacks in non blocking mode (IT mode) */ +void HAL_RCC_CCSCallback(void); + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __STM32L0xx_HAL_RCC_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_rcc_ex.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_rcc_ex.c new file mode 100644 index 0000000000..7d8be7676a --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_rcc_ex.c @@ -0,0 +1,535 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_rcc_ex.c + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief Extended RCC HAL module driver. + * + * This file provides firmware functions to manage the following + * functionalities RCC extension peripheral: + * + Extended Peripheral Control functions + * + @verbatim + ============================================================================== + ##### RCC specific features ##### + ============================================================================== + For CRS, RCC Extension HAL driver can be used as follows: + + (#) In System clock configuration, HSI48 need to be enabled + + (#] Enable CRS clock in IP MSP init which will use CRS functions + + (#) Call CRS functions like this + (##) Prepare synchronization configuration necessary for HSI48 calibration + (+++) Default values can be set for frequency Error Measurement (reload and error limit) + and also HSI48 oscillator smooth trimming. + (+++) Macro __HAL_RCC_CRS_CALCULATE_RELOADVALUE can be also used to calculate + directly reload value with target and synchronization frequencies values + (##) Call function HAL_RCCEx_CRSConfig which + (+++) Reset CRS registers to their default values. + (+++) Configure CRS registers with synchronization configuration + (+++) Enable automatic calibration and frequency error counter feature + + (##) A polling function is provided to wait for complete Synchronization + (+++) Call function 'HAL_RCCEx_CRSWaitSynchronization()' + (+++) According to CRS status, user can decide to adjust again the calibration or continue + application if synchronization is OK + + (#) User can retrieve information related to synchronization in calling function + HAL_RCCEx_CRSGetSynchronizationInfo() + + (#) Regarding synchronization status and synchronization information, user can try a new calibration + in changing synchronization configuration and call again HAL_RCCEx_CRSConfig. + Note: When the SYNC event is detected during the downcounting phase (before reaching the zero value), + it means that the actual frequency is lower than the target (and so, that the TRIM value should be + incremented), while when it is detected during the upcounting phase it means that the actual frequency + is higher (and that the TRIM value should be decremented). + + (#) To use IT mode, user needs to handle it in calling different macros available to do it + (__HAL_RCC_CRS_XXX_IT). Interruptions will go through RCC Handler (RCC_IRQn/RCC_CRS_IRQHandler) + (+++) Call function HAL_RCCEx_CRSConfig() + (+++) Enable RCC_IRQn (thnaks to NVIC functions) + (+++) Enable CRS IT (__HAL_RCC_CRS_ENABLE_IT) + [+++) Implement CRS status management in RCC_CRS_IRQHandler + + (#) To force a SYNC EVENT, user can use function 'HAL_RCCEx_CRSSoftwareSynchronizationGenerate()'. Function can be + called before calling HAL_RCCEx_CRSConfig (for instance in Systick handler) + + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @defgroup RCCEx + * @brief RCC Extension HAL module driver + * @{ + */ + +#ifdef HAL_RCC_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Bit position in register */ +#define CRS_CFGR_FELIM_BITNUMBER 16 +#define CRS_CR_TRIM_BITNUMBER 8 +#define CRS_ISR_FECAP_BITNUMBER 16 + +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup RCCEx_Private_Functions + * @{ + */ + +/** @defgroup RCCEx_Group1 Extended Peripheral Control functions + * @brief Extended Peripheral Control functions + * +@verbatim + =============================================================================== + ##### Extended Peripheral Control functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to control the RCC Clocks + frequencies. + +@endverbatim + * @{ + */ + +/** + * @brief Initializes the RCC extended peripherals clocks according to the specified parameters in the + * RCC_PeriphCLKInitTypeDef. + * @param PeriphClkInit: pointer to an RCC_PeriphCLKInitTypeDef structure that + * contains the configuration information for the Extended Peripherals clocks(USART1,USART2, LPUART1, + * I2C1, RTC, USB/RNG and LPTIM1 clocks). + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClkInit) +{ + uint32_t tickstart = 0; + uint32_t tmpreg = 0; + + /* Check the parameters */ + assert_param(IS_RCC_PERIPHCLK(PeriphClkInit->PeriphClockSelection)); + + /*------------------------------- USART1 Configuration ------------------------*/ + if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_USART1) == RCC_PERIPHCLK_USART1) + { + /* Check the parameters */ + assert_param(IS_RCC_USART1CLKSOURCE(PeriphClkInit->Usart1ClockSelection)); + + /* Configure the USART1 clock source */ + __HAL_RCC_USART1_CONFIG(PeriphClkInit->Usart1ClockSelection); + } + + /*----------------------------- USART2 Configuration --------------------------*/ + if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_USART2) == RCC_PERIPHCLK_USART2) + { + /* Check the parameters */ + assert_param(IS_RCC_USART2CLKSOURCE(PeriphClkInit->Usart2ClockSelection)); + + /* Configure the USART2 clock source */ + __HAL_RCC_USART2_CONFIG(PeriphClkInit->Usart2ClockSelection); + } + + /*------------------------------ LPUART1 Configuration ------------------------*/ + if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_LPUART1) == RCC_PERIPHCLK_LPUART1) + { + /* Check the parameters */ + assert_param(IS_RCC_LPUART1CLKSOURCE(PeriphClkInit->Lpuart1ClockSelection)); + + /* Configure the LPUAR1 clock source */ + __HAL_RCC_LPUART1_CONFIG(PeriphClkInit->Lpuart1ClockSelection); + } + + /*------------------------------ I2C1 Configuration ------------------------*/ + if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_I2C1) == RCC_PERIPHCLK_I2C1) + { + /* Check the parameters */ + assert_param(IS_RCC_I2C1CLKSOURCE(PeriphClkInit->I2c1ClockSelection)); + + /* Configure the I2C1 clock source */ + __HAL_RCC_I2C1_CONFIG(PeriphClkInit->I2c1ClockSelection); + } + + + /*---------------------------- RTC configuration -------------------------------*/ + if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_RTC) == (RCC_PERIPHCLK_RTC)) + { + /* Enable Power Clock*/ + __PWR_CLK_ENABLE(); + + /* Enable write access to Backup domain */ + PWR->CR |= PWR_CR_DBP; + + /* Wait for Backup domain Write protection disable */ + tickstart = HAL_GetTick(); + + while((PWR->CR & PWR_CR_DBP) == RESET) + { + if((HAL_GetTick() - tickstart ) > DBP_TIMEOUT_VALUE) + { + return HAL_TIMEOUT; + } + } + + /* Reset the Backup domain only if the RTC Clock source selection is modified */ + if((RCC->CSR & RCC_CSR_RTCSEL) != (PeriphClkInit->RTCClockSelection & RCC_CSR_RTCSEL)) + { + /* Store the content of CSR register before the reset of Backup Domain */ + tmpreg = (RCC->CSR & ~(RCC_CSR_RTCSEL)); + /* RTC Clock selection can be changed only if the Backup Domain is reset */ + __HAL_RCC_BACKUPRESET_FORCE(); + __HAL_RCC_BACKUPRESET_RELEASE(); + /* Restore the Content of CSR register */ + RCC->CSR = tmpreg; + } + + /* If LSE is selected as RTC clock source, wait for LSE reactivation */ + if(PeriphClkInit->RTCClockSelection == RCC_RTCCLKSOURCE_LSE) + { + /* Get timeout */ + tickstart = HAL_GetTick(); + + /* Wait till LSE is ready */ + while(__HAL_RCC_GET_FLAG(RCC_FLAG_LSERDY) == RESET) + { + if((HAL_GetTick() - tickstart ) > LSE_TIMEOUT_VALUE) + { + return HAL_TIMEOUT; + } + } + } + __HAL_RCC_RTC_CONFIG(PeriphClkInit->RTCClockSelection); + } +#if !defined(STM32L051xx) && !defined(STM32L061xx) + /*---------------------------- USB and RNG configuration --------------------*/ + if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_USB) == (RCC_PERIPHCLK_USB)) + { + assert_param(IS_RCC_USBCLKSOURCE(PeriphClkInit->UsbClockSelection)); + __HAL_RCC_USB_CONFIG(PeriphClkInit->UsbClockSelection); + } +#endif /* !(STM32L051xx) && !(STM32L061xx) */ + + /*---------------------------- LPTIM1 configuration ------------------------*/ + if(((PeriphClkInit->PeriphClockSelection) & RCC_PERIPHCLK_LPTIM1) == (RCC_PERIPHCLK_LPTIM1)) + { + assert_param(IS_RCC_LPTIMCLK(PeriphClkInit->LptimClockSelection)); + __HAL_RCC_LPTIM1_CONFIG(PeriphClkInit->LptimClockSelection); + } + return HAL_OK; +} + +/** + * @brief Get the RCC_ClkInitStruct according to the internal + * RCC configuration registers. + * @param PeriphClkInit: pointer to an RCC_PeriphCLKInitTypeDef structure that + * returns the configuration information for the Extended Peripherals clocks(USART1,USART2, LPUART1, + * I2C1, RTC, USB/RNG and LPTIM1 clocks). + * @retval None + */ +void HAL_RCCEx_GetPeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClkInit) +{ + /* Set all possible values for the extended clock type parameter -----------*/ + /* Common part first */ + #if !defined(STM32L051xx) && !defined(STM32L061xx) + PeriphClkInit->PeriphClockSelection = RCC_PERIPHCLK_USART1 | RCC_PERIPHCLK_USART2 | RCC_PERIPHCLK_LPUART1 | \ + RCC_PERIPHCLK_I2C1 | RCC_PERIPHCLK_I2C2 | RCC_PERIPHCLK_RTC | \ + RCC_PERIPHCLK_USB | RCC_PERIPHCLK_LPTIM1; + + #else + PeriphClkInit->PeriphClockSelection = RCC_PERIPHCLK_USART1 | RCC_PERIPHCLK_USART2 | RCC_PERIPHCLK_LPUART1 | \ + RCC_PERIPHCLK_I2C1 | RCC_PERIPHCLK_I2C2 | RCC_PERIPHCLK_RTC | \ + RCC_PERIPHCLK_LPTIM1; + #endif /* !(STM32L051xx) && !(STM32L061xx) */ + + /* Get the USART1 configuration --------------------------------------------*/ + PeriphClkInit->Usart1ClockSelection = __HAL_RCC_GET_USART1_SOURCE(); + /* Get the USART2 clock source ---------------------------------------------*/ + PeriphClkInit->Usart2ClockSelection = __HAL_RCC_GET_USART2_SOURCE(); + /* Get the LPUART1 clock source ---------------------------------------------*/ + PeriphClkInit->Lpuart1ClockSelection = __HAL_RCC_GET_LPUART1_SOURCE(); + /* Get the I2C1 clock source -----------------------------------------------*/ + PeriphClkInit->I2c1ClockSelection = __HAL_RCC_GET_I2C1_SOURCE(); + /* Get the LPTIM1 clock source -----------------------------------------------*/ + PeriphClkInit->LptimClockSelection = __HAL_RCC_GET_LPTIM1_SOURCE(); + /* Get the RTC clock source -----------------------------------------------*/ + PeriphClkInit->RTCClockSelection = __HAL_RCC_GET_RTC_SOURCE(); + +#if !defined(STM32L051xx) && !defined(STM32L061xx) + /* Get the USB/RNG clock source -----------------------------------------------*/ + PeriphClkInit->UsbClockSelection = __HAL_RCC_GET_USB_SOURCE(); +#endif /* !(STM32L051xx) && !(STM32L061xx) */ +} + +/** + * @brief Enables the LSE Clock Security System. + * @param None + * @retval None + */ +void HAL_RCCEx_EnableLSECSS(void) +{ + SET_BIT(RCC->CSR, RCC_CSR_LSECSSON) ; +} + +/** + * @brief Disables the LSE Clock Security System. + * @param None + * @retval None + */ +void HAL_RCCEx_DisableLSECSS(void) +{ + CLEAR_BIT(RCC->CSR, RCC_CSR_LSECSSON) ; +} + +#if !defined(STM32L051xx) && !defined(STM32L061xx) + +/** + * @brief Start automatic synchronization using polling mode + * @param pInit Pointer on RCC_CRSInitTypeDef structure + * @retval None + */ +void HAL_RCCEx_CRSConfig(RCC_CRSInitTypeDef *pInit) +{ + /* Check the parameters */ + assert_param(IS_RCC_CRS_SYNC_DIV(pInit->Prescaler)); + assert_param(IS_RCC_CRS_SYNC_SOURCE(pInit->Source)); + assert_param(IS_RCC_CRS_SYNC_POLARITY(pInit->Polarity)); + assert_param(IS_RCC_CRS_RELOADVALUE(pInit->ReloadValue)); + assert_param(IS_RCC_CRS_ERRORLIMIT(pInit->ErrorLimitValue)); + assert_param(IS_RCC_CRS_HSI48CALIBRATION(pInit->HSI48CalibrationValue)); + + + /* CONFIGURATION */ + + /* Before configuration, reset CRS registers to their default values*/ + __CRS_FORCE_RESET(); + __CRS_RELEASE_RESET(); + + /* Configure Synchronization input */ + /* Clear SYNCDIV[2:0], SYNCSRC[1:0] & SYNCSPOL bits */ + CRS->CFGR &= ~(CRS_CFGR_SYNCDIV | CRS_CFGR_SYNCSRC | CRS_CFGR_SYNCPOL); + + /* Set the CRS_CFGR_SYNCDIV[2:0] bits according to Prescaler value */ + CRS->CFGR |= pInit->Prescaler; + + /* Set the SYNCSRC[1:0] bits according to Source value */ + CRS->CFGR |= pInit->Source; + + /* Set the SYNCSPOL bits according to Polarity value */ + CRS->CFGR |= pInit->Polarity; + + /* Configure Frequency Error Measurement */ + /* Clear RELOAD[15:0] & FELIM[7:0] bits*/ + CRS->CFGR &= ~(CRS_CFGR_RELOAD | CRS_CFGR_FELIM); + + /* Set the RELOAD[15:0] bits according to ReloadValue value */ + CRS->CFGR |= pInit->ReloadValue; + + /* Set the FELIM[7:0] bits according to ErrorLimitValue value */ + CRS->CFGR |= (pInit->ErrorLimitValue << CRS_CFGR_FELIM_BITNUMBER); + + /* Adjust HSI48 oscillator smooth trimming */ + /* Clear TRIM[5:0] bits */ + CRS->CR &= ~CRS_CR_TRIM; + + /* Set the TRIM[5:0] bits according to RCC_CRS_HSI48CalibrationValue value */ + CRS->CR |= (pInit->HSI48CalibrationValue << CRS_CR_TRIM_BITNUMBER); + + + /* START AUTOMATIC SYNCHRONIZATION*/ + + /* Enable Automatic trimming */ + __HAL_RCC_CRS_ENABLE_AUTOMATIC_CALIB(); + + /* Enable Frequency error counter */ + __HAL_RCC_CRS_ENABLE_FREQ_ERROR_COUNTER(); + +} + +/** + * @brief Generate the software synchronization event + * @param None + * @retval None + */ +void HAL_RCCEx_CRSSoftwareSynchronizationGenerate(void) +{ + CRS->CR |= CRS_CR_SWSYNC; +} + + +/** + * @brief Function to return synchronization info + * @param pSynchroInfo Pointer on RCC_CRSSynchroInfoTypeDef structure + * @retval None + */ +void HAL_RCCEx_CRSGetSynchronizationInfo(RCC_CRSSynchroInfoTypeDef *pSynchroInfo) +{ + /* Check the parameter */ + assert_param(pSynchroInfo != NULL); + + /* Get the reload value */ + pSynchroInfo->ReloadValue = (uint32_t)(CRS->CFGR & CRS_CFGR_RELOAD); + + /* Get HSI48 oscillator smooth trimming */ + pSynchroInfo->HSI48CalibrationValue = (uint32_t)((CRS->CR & CRS_CR_TRIM) >> CRS_CR_TRIM_BITNUMBER); + + /* Get Frequency error capture */ + pSynchroInfo->FreqErrorCapture = (uint32_t)((CRS->ISR & CRS_ISR_FECAP) >> CRS_ISR_FECAP_BITNUMBER); + + /* Get Frequency error direction */ + pSynchroInfo->FreqErrorDirection = (uint32_t)(CRS->ISR & CRS_ISR_FEDIR); + + +} + +/** +* @brief This function handles CRS Synchronization Timeout. +* @param Timeout: Duration of the timeout +* @note Timeout is based on the maximum time to receive a SYNC event based on synchronization +* frequency. +* @note If Timeout set to HAL_MAX_DELAY, HAL_TIMEOUT will be never returned. +* @retval Combination of Synchronization status +* This parameter can be a combination of the following values: +* @arg RCC_CRS_TIMEOUT +* @arg RCC_CRS_SYNCOK +* @arg RCC_CRS_SYNCWARM +* @arg RCC_CRS_SYNCERR +* @arg RCC_CRS_SYNCMISS +* @arg RCC_CRS_TRIMOV +*/ +RCC_CRSStatusTypeDef HAL_RCCEx_CRSWaitSynchronization(uint32_t Timeout) +{ + RCC_CRSStatusTypeDef crsstatus = RCC_CRS_NONE; + uint32_t tickstart = 0; + + /* Get timeout */ + tickstart = HAL_GetTick(); + + /* Check that if one of CRS flags have been set */ + while(RCC_CRS_NONE == crsstatus) + { + if(Timeout != HAL_MAX_DELAY) + { + if((HAL_GetTick() - tickstart ) > Timeout) + { + crsstatus = RCC_CRS_TIMEOUT; + } + } + /* Check CRS SYNCOK flag */ + if(__HAL_RCC_CRS_GET_FLAG(RCC_CRS_FLAG_SYNCOK)) + { + /* CRS SYNC event OK */ + crsstatus |= RCC_CRS_SYNCOK; + + /* Clear CRS SYNC event OK bit */ + __HAL_RCC_CRS_CLEAR_FLAG(RCC_CRS_FLAG_SYNCOK); + } + + /* Check CRS SYNCWARN flag */ + if(__HAL_RCC_CRS_GET_FLAG(RCC_CRS_FLAG_SYNCWARN)) + { + /* CRS SYNC warning */ + crsstatus |= RCC_CRS_SYNCWARM; + + /* Clear CRS SYNCWARN bit */ + __HAL_RCC_CRS_CLEAR_FLAG(RCC_CRS_FLAG_SYNCWARN); + } + + /* Check CRS TRIM overflow flag */ + if(__HAL_RCC_CRS_GET_FLAG(RCC_CRS_FLAG_TRIMOVF)) + { + /* CRS SYNC Error */ + crsstatus |= RCC_CRS_TRIMOV; + + /* Clear CRS Error bit */ + __HAL_RCC_CRS_CLEAR_FLAG(RCC_CRS_FLAG_TRIMOVF); + } + + /* Check CRS Error flag */ + if(__HAL_RCC_CRS_GET_FLAG(RCC_CRS_FLAG_SYNCERR)) + { + /* CRS SYNC Error */ + crsstatus |= RCC_CRS_SYNCERR; + + /* Clear CRS Error bit */ + __HAL_RCC_CRS_CLEAR_FLAG(RCC_CRS_FLAG_SYNCERR); + } + + /* Check CRS SYNC Missed flag */ + if(__HAL_RCC_CRS_GET_FLAG(RCC_CRS_FLAG_SYNCMISS)) + { + /* CRS SYNC Missed */ + crsstatus |= RCC_CRS_SYNCMISS; + + /* Clear CRS SYNC Missed bit */ + __HAL_RCC_CRS_CLEAR_FLAG(RCC_CRS_FLAG_SYNCMISS); + } + + /* Check CRS Expected SYNC flag */ + if(__HAL_RCC_CRS_GET_FLAG(RCC_CRS_FLAG_ESYNC)) + { + /* frequency error counter reached a zero value */ + __HAL_RCC_CRS_CLEAR_FLAG(RCC_CRS_FLAG_ESYNC); + } + } + + return crsstatus; +} + +#endif /* !(STM32L051xx) && !(STM32L061xx) */ + +/** + * @} + */ + +/** + * @} + */ + +#endif /* HAL_RCC_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_rcc_ex.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_rcc_ex.h new file mode 100644 index 0000000000..49217f18d1 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_rcc_ex.h @@ -0,0 +1,1121 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_rcc_ex.h + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief Header file of RCC HAL Extension module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32L0xx_HAL_RCC_EX_H +#define __STM32L0xx_HAL_RCC_EX_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal_def.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @addtogroup RCCEx + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/** + * @brief RCC extended clocks structure definition + */ +#if !defined(STM32L051xx) && !defined(STM32L061xx) +typedef struct +{ + uint32_t PeriphClockSelection; /*!< The Extended Clock to be configured. + This parameter can be a value of @ref RCCEx_Periph_Clock_Selection */ + uint32_t Usart1ClockSelection; /*!< USART1 clock source + This parameter can be a value of @ref RCCEx_USART1_Clock_Source */ + + uint32_t Usart2ClockSelection; /*!< USART2 clock source + This parameter can be a value of @ref RCCEx_USART2_Clock_Source */ + + uint32_t Lpuart1ClockSelection; /*!< LPUART1 clock source + This parameter can be a value of @ref RCCEx_LPUART1_Clock_Source */ + + uint32_t I2c1ClockSelection; /*!< I2C1 clock source + This parameter can be a value of @ref RCCEx_I2C1_Clock_Source */ + + uint32_t RTCClockSelection; /*!< Specifies RTC Clock Prescalers Selection + This parameter can be a value of @ref RCCEx_RTC_Clock_Source */ + + uint32_t UsbClockSelection; /*!< Specifies USB and RNG Clock Selection + This parameter can be a value of @ref RCCEx_USB_Clock_Source */ + + uint32_t LptimClockSelection; /*!< LPTIM1 clock source + This parameter can be a value of @ref RCCEx_LPTIM1_Clock_Source */ + +}RCC_PeriphCLKInitTypeDef; +#endif /* !(STM32L051xx) && !(STM32L061xx) */ + +#if defined(STM32L051xx) || defined(STM32L061xx) +typedef struct +{ + uint32_t PeriphClockSelection; /*!< The Extended Clock to be configured. + This parameter can be a value of @ref RCCEx_Periph_Clock_Selection */ + uint32_t Usart1ClockSelection; /*!< USART1 clock source + This parameter can be a value of @ref RCCEx_USART1_Clock_Source */ + + uint32_t Usart2ClockSelection; /*!< USART2 clock source + This parameter can be a value of @ref RCCEx_USART2_Clock_Source */ + + uint32_t Lpuart1ClockSelection; /*!< LPUART1 clock source + This parameter can be a value of @ref RCCEx_LPUART1_Clock_Source */ + + uint32_t I2c1ClockSelection; /*!< I2C1 clock source + This parameter can be a value of @ref RCCEx_I2C1_Clock_Source */ + + uint32_t RTCClockSelection; /*!< Specifies RTC Clock Prescalers Selection + This parameter can be a value of @ref RCCEx_RTC_Clock_Source */ + + uint32_t LptimClockSelection; /*!< LPTIM1 clock source + This parameter can be a value of @ref RCCEx_LPTIM1_Clock_Source */ + +}RCC_PeriphCLKInitTypeDef; +#endif /* STM32L051xx || STM32L061xx */ + +#if !defined(STM32L051xx) && !defined(STM32L061xx) +/** + * @brief RCC CRS Status structures definition + */ +typedef enum +{ + RCC_CRS_NONE = 0x00, + RCC_CRS_TIMEOUT = 0x01, + RCC_CRS_SYNCOK = 0x02, + RCC_CRS_SYNCWARM = 0x04, + RCC_CRS_SYNCERR = 0x08, + RCC_CRS_SYNCMISS = 0x10, + RCC_CRS_TRIMOV = 0x20 +} RCC_CRSStatusTypeDef; + +/** + * @brief RCC_CRS Init structure definition + */ +typedef struct +{ + uint32_t Prescaler; /*!< Specifies the division factor of the SYNC signal. + This parameter can be a value of @ref RCCEx_CRS_SynchroDivider */ + + uint32_t Source; /*!< Specifies the SYNC signal source. + This parameter can be a value of @ref RCCEx_CRS_SynchroSource */ + + uint32_t Polarity; /*!< Specifies the input polarity for the SYNC signal source. + This parameter can be a value of @ref RCCEx_CRS_SynchroPolarity */ + + uint32_t ReloadValue; /*!< Specifies the value to be loaded in the frequency error counter with each SYNC event. + It can be calculated in using macro __HAL_RCC_CRS_CALCULATE_RELOADVALUE(_FTARGET_, _FSYNC_) + This parameter must be a number between 0 and 0xFFFF or a value of @ref RCCEx_CRS_ReloadValueDefault .*/ + + uint32_t ErrorLimitValue; /*!< Specifies the value to be used to evaluate the captured frequency error value. + This parameter must be a number between 0 and 0xFF or a value of @ref RCCEx_CRS_ErrorLimitDefault */ + + uint32_t HSI48CalibrationValue; /*!< Specifies a user-programmable trimming value to the HSI48 oscillator. + This parameter must be a number between 0 and 0x3F or a value of @ref RCCEx_CRS_HSI48CalibrationDefault */ + +}RCC_CRSInitTypeDef; + +/** + * @brief RCC_CRS Synchronization structure definition + */ +typedef struct +{ + uint32_t ReloadValue; /*!< Specifies the value loaded in the Counter reload value. + This parameter must be a number between 0 and 0xFFFF*/ + + uint32_t HSI48CalibrationValue; /*!< Specifies value loaded in HSI48 oscillator smooth trimming. + This parameter must be a number between 0 and 0x3F */ + + uint32_t FreqErrorCapture; /*!< Specifies the value loaded in the .FECAP, the frequency error counter + value latched in the time of the last SYNC event. + This parameter must be a number between 0 and 0xFFFF */ + + uint32_t FreqErrorDirection; /*!< Specifies the value loaded in the .FEDIR, the counting direction of the + frequency error counter latched in the time of the last SYNC event. + It shows whether the actual frequency is below or above the target. + This parameter must be a value of @ref RCCEx_CRS_FreqErrorDirection*/ + +}RCC_CRSSynchroInfoTypeDef; +#endif /* !(STM32L051xx ) && !(STM32L061xx ) */ + +/* Exported constants --------------------------------------------------------*/ +/** @defgroup RCCEx_Exported_Constants + * @{ + */ + +/** @defgroup RCCEx_Periph_Clock_Selection + * @{ + */ +#if !defined(STM32L051xx) && !defined(STM32L061xx) +#define RCC_PERIPHCLK_USART1 ((uint32_t)0x00000001) +#define RCC_PERIPHCLK_USART2 ((uint32_t)0x00000002) +#define RCC_PERIPHCLK_LPUART1 ((uint32_t)0x00000004) +#define RCC_PERIPHCLK_I2C1 ((uint32_t)0x00000008) +#define RCC_PERIPHCLK_I2C2 ((uint32_t)0x00000010) +#define RCC_PERIPHCLK_RTC ((uint32_t)0x00000020) +#define RCC_PERIPHCLK_USB ((uint32_t)0x00000040) +#define RCC_PERIPHCLK_LPTIM1 ((uint32_t)0x00000080) + + +#define IS_RCC_PERIPHCLK(CLK) ((CLK) <= (RCC_PERIPHCLK_USART1 | RCC_PERIPHCLK_USART2 | RCC_PERIPHCLK_LPUART1 | \ + RCC_PERIPHCLK_I2C1 | RCC_PERIPHCLK_I2C2 | RCC_PERIPHCLK_RTC | \ + RCC_PERIPHCLK_USB | RCC_PERIPHCLK_LPTIM1)) +#endif /* !(STM32L051xx) && !(STM32L061xx) */ + +#if defined(STM32L051xx) || defined(STM32L061xx) +#define RCC_PERIPHCLK_USART1 ((uint32_t)0x00000001) +#define RCC_PERIPHCLK_USART2 ((uint32_t)0x00000002) +#define RCC_PERIPHCLK_LPUART1 ((uint32_t)0x00000004) +#define RCC_PERIPHCLK_I2C1 ((uint32_t)0x00000008) +#define RCC_PERIPHCLK_I2C2 ((uint32_t)0x00000010) +#define RCC_PERIPHCLK_RTC ((uint32_t)0x00000020) +#define RCC_PERIPHCLK_LPTIM1 ((uint32_t)0x00000080) + + +#define IS_RCC_PERIPHCLK(CLK) ((CLK) <= (RCC_PERIPHCLK_USART1 | RCC_PERIPHCLK_USART2 | RCC_PERIPHCLK_LPUART1 | \ + RCC_PERIPHCLK_I2C1 | RCC_PERIPHCLK_I2C2 | RCC_PERIPHCLK_RTC | \ + RCC_PERIPHCLK_LPTIM1)) +#endif /* !(STM32L051xx) && !(STM32L061xx) */ +/** + * @} + */ + +/** @defgroup RCCEx_USART1_Clock_Source + * @{ + */ +#define RCC_USART1CLKSOURCE_PCLK2 ((uint32_t)0x00000000) +#define RCC_USART1CLKSOURCE_SYSCLK RCC_CCIPR_USART1SEL_0 +#define RCC_USART1CLKSOURCE_HSI RCC_CCIPR_USART1SEL_1 +#define RCC_USART1CLKSOURCE_LSE (RCC_CCIPR_USART1SEL_0 | RCC_CCIPR_USART1SEL_1) +#define IS_RCC_USART1CLKSOURCE(SOURCE) (((SOURCE) == RCC_USART1CLKSOURCE_PCLK2) || \ + ((SOURCE) == RCC_USART1CLKSOURCE_SYSCLK) || \ + ((SOURCE) == RCC_USART1CLKSOURCE_LSE) || \ + ((SOURCE) == RCC_USART1CLKSOURCE_HSI)) +/** + * @} + */ + +/** @defgroup RCCEx_USART2_Clock_Source + * @{ + */ +#define RCC_USART2CLKSOURCE_PCLK1 ((uint32_t)0x00000000) +#define RCC_USART2CLKSOURCE_SYSCLK RCC_CCIPR_USART2SEL_0 +#define RCC_USART2CLKSOURCE_HSI RCC_CCIPR_USART2SEL_1 +#define RCC_USART2CLKSOURCE_LSE (RCC_CCIPR_USART2SEL_0 | RCC_CCIPR_USART2SEL_1) +#define IS_RCC_USART2CLKSOURCE(SOURCE) (((SOURCE) == RCC_USART2CLKSOURCE_PCLK1) || \ + ((SOURCE) == RCC_USART2CLKSOURCE_SYSCLK) || \ + ((SOURCE) == RCC_USART2CLKSOURCE_LSE) || \ + ((SOURCE) == RCC_USART2CLKSOURCE_HSI)) +/** + * @} + */ + +/** @defgroup RCCEx_LPUART_Clock_Source + * @{ + */ +#define RCC_LPUART1CLKSOURCE_PCLK1 ((uint32_t)0x00000000) +#define RCC_LPUART1CLKSOURCE_SYSCLK RCC_CCIPR_LPUART1SEL_0 +#define RCC_LPUART1CLKSOURCE_HSI RCC_CCIPR_LPUART1SEL_1 +#define RCC_LPUART1CLKSOURCE_LSE (RCC_CCIPR_LPUART1SEL_0 | RCC_CCIPR_LPUART1SEL_1) +#define IS_RCC_LPUART1CLKSOURCE(SOURCE) (((SOURCE) == RCC_LPUART1CLKSOURCE_PCLK1) || \ + ((SOURCE) == RCC_LPUART1CLKSOURCE_SYSCLK) || \ + ((SOURCE) == RCC_LPUART1CLKSOURCE_LSE) || \ + ((SOURCE) == RCC_LPUART1CLKSOURCE_HSI)) +/** + * @} + */ + +/** @defgroup RCCEx_I2C1_Clock_Source + * @{ + */ +#define RCC_I2C1CLKSOURCE_PCLK1 ((uint32_t)0x00000000) +#define RCC_I2C1CLKSOURCE_SYSCLK RCC_CCIPR_I2C1SEL_0 +#define RCC_I2C1CLKSOURCE_HSI RCC_CCIPR_I2C1SEL_1 +#define IS_RCC_I2C1CLKSOURCE(SOURCE) (((SOURCE) == RCC_I2C1CLKSOURCE_PCLK1) || \ + ((SOURCE) == RCC_I2C1CLKSOURCE_SYSCLK)|| \ + ((SOURCE) == RCC_I2C1CLKSOURCE_HSI)) +/** + * @} + */ + +/** @defgroup RCCEx_TIM_PRescaler_Selection + * @{ + */ +#define RCC_TIMPRES_DESACTIVATED ((uint8_t)0x00) +#define RCC_TIMPRES_ACTIVATED ((uint8_t)0x01) +/** + * @} + */ + +#if !defined(STM32L051xx) && !defined(STM32L061xx) +/** @defgroup RCCEx_USB_Clock_Source + * @{ + */ +#define RCC_USBCLKSOURCE_HSI48 RCC_CCIPR_HSI48SEL +#define RCC_USBCLKSOURCE_PLLCLK ((uint32_t)0x00000000) + +#define IS_RCC_USBCLKSOURCE(SOURCE) (((SOURCE) == RCC_USBCLKSOURCE_HSI48) || \ + ((SOURCE) == RCC_USBCLKSOURCE_PLLCLK)) +/** + * @} + */ + +/** @defgroup RCCEx_RNG_Clock_Source + * @{ + */ +#define RCC_RNGCLKSOURCE_HSI48 RCC_CCIPR_HSI48SEL +#define RCC_RNGCLKSOURCE_PLLCLK ((uint32_t)0x00000000) + +#define IS_RCC_RNGCLKSOURCE(SOURCE) (((SOURCE) == RCC_RNGCLKSOURCE_HSI48) || \ + ((SOURCE) == RCC_RNGCLKSOURCE_PLLCLK)) +/** + * @} + */ + +/** @defgroup RCCEx_HSI48M_Clock_Source + * @{ + */ + +#define RCC_HSI48M_PLL ((uint32_t)0x00000000) +#define RCC_HSI48M_RC48 RCC_CCIPR_HSI48SEL + +#define IS_RCC_HSI48MCLKSOURCE(HSI48MCLK) (((HSI48MCLK) == RCC_HSI48M_PLL) || ((HSI48MCLK) == RCC_HSI48M_RC48)) + +/** + * @} + */ +#endif /* !(STM32L051xx ) && !(STM32L061xx ) */ + +/** @defgroup RCCEx_LPTIM1_Clock_Source + * @{ + */ +#define RCC_LPTIM1CLKSOURCE_PCLK ((uint32_t)0x00000000) +#define RCC_LPTIM1CLKSOURCE_LSI RCC_CCIPR_LPTIM1SEL_0 +#define RCC_LPTIM1CLKSOURCE_HSI RCC_CCIPR_LPTIM1SEL_1 +#define RCC_LPTIM1CLKSOURCE_LSE RCC_CCIPR_LPTIM1SEL + +#define IS_RCC_LPTIMCLK(LPTIMCLK) (((LPTIMCLK) == RCC_LPTIM1CLKSOURCE_PCLK) || \ + ((LPTIMCLK) == RCC_LPTIM1CLKSOURCE_LSI) || \ + ((LPTIMCLK) == RCC_LPTIM1CLKSOURCE_HSI) || \ + ((LPTIMCLK) == RCC_LPTIM1CLKSOURCE_LSE)) +/** + * @} + */ + +/** @defgroup RCCEx_StopWakeUp_Clock + * @{ + */ + +#define RCC_StopWakeUpClock_MSI ((uint32_t)0x00) +#define RCC_StopWakeUpClock_HSI RCC_CFGR_STOPWUCK + +#define IS_RCC_STOPWAKEUP_CLOCK(SOURCE) (((SOURCE) == RCC_StopWakeUpClock_MSI) || \ + ((SOURCE) == RCC_StopWakeUpClock_HSI)) +/** + * @} + */ + +/** @defgroup RCCEx_LSEDrive_Configuration + * @{ + */ + +#define RCC_LSEDRIVE_LOW ((uint32_t)0x00000000) +#define RCC_LSEDRIVE_MEDIUMLOW RCC_CSR_LSEDRV_0 +#define RCC_LSEDRIVE_MEDIUMHIGH RCC_CSR_LSEDRV_1 +#define RCC_LSEDRIVE_HIGH RCC_CSR_LSEDRV +#define IS_RCC_LSE_DRIVE(DRIVE) (((DRIVE) == RCC_LSEDRIVE_LOW) || ((DRIVE) == RCC_LSEDRIVE_MEDIUMLOW) || \ + ((DRIVE) == RCC_LSEDRIVE_MEDIUMHIGH) || ((DRIVE) == RCC_LSEDRIVE_HIGH)) +/** + * @} + */ + +#if !defined(STM32L051xx) && !defined(STM32L061xx) +/** @defgroup RCCEx_CRS_SynchroSource + * @{ + */ +#define RCC_CRS_SYNC_SOURCE_GPIO ((uint32_t)0x00) /*!< Synchro Signal source GPIO */ +#define RCC_CRS_SYNC_SOURCE_LSE CRS_CFGR_SYNCSRC_0 /*!< Synchro Signal source LSE */ +#define RCC_CRS_SYNC_SOURCE_USB CRS_CFGR_SYNCSRC_1 /*!< Synchro Signal source USB SOF (default)*/ + +#define IS_RCC_CRS_SYNC_SOURCE(_SOURCE_) (((_SOURCE_) == RCC_CRS_SYNC_SOURCE_GPIO) || \ + ((_SOURCE_) == RCC_CRS_SYNC_SOURCE_LSE) ||\ + ((_SOURCE_) == RCC_CRS_SYNC_SOURCE_USB)) +/** + * @} + */ + +/** @defgroup RCCEx_CRS_SynchroDivider + * @{ + */ +#define RCC_CRS_SYNC_DIV1 ((uint32_t)0x00) /*!< Synchro Signal not divided (default) */ +#define RCC_CRS_SYNC_DIV2 CRS_CFGR_SYNCDIV_0 /*!< Synchro Signal divided by 2 */ +#define RCC_CRS_SYNC_DIV4 CRS_CFGR_SYNCDIV_1 /*!< Synchro Signal divided by 4 */ +#define RCC_CRS_SYNC_DIV8 (CRS_CFGR_SYNCDIV_1 | CRS_CFGR_SYNCDIV_0) /*!< Synchro Signal divided by 8 */ +#define RCC_CRS_SYNC_DIV16 CRS_CFGR_SYNCDIV_2 /*!< Synchro Signal divided by 16 */ +#define RCC_CRS_SYNC_DIV32 (CRS_CFGR_SYNCDIV_2 | CRS_CFGR_SYNCDIV_0) /*!< Synchro Signal divided by 32 */ +#define RCC_CRS_SYNC_DIV64 (CRS_CFGR_SYNCDIV_2 | CRS_CFGR_SYNCDIV_1) /*!< Synchro Signal divided by 64 */ +#define RCC_CRS_SYNC_DIV128 CRS_CFGR_SYNCDIV /*!< Synchro Signal divided by 128 */ + +#define IS_RCC_CRS_SYNC_DIV(_DIV_) (((_DIV_) == RCC_CRS_SYNC_DIV1) || ((_DIV_) == RCC_CRS_SYNC_DIV2) ||\ + ((_DIV_) == RCC_CRS_SYNC_DIV4) || ((_DIV_) == RCC_CRS_SYNC_DIV8) || \ + ((_DIV_) == RCC_CRS_SYNC_DIV16) || ((_DIV_) == RCC_CRS_SYNC_DIV32) || \ + ((_DIV_) == RCC_CRS_SYNC_DIV64) || ((_DIV_) == RCC_CRS_SYNC_DIV128)) +/** + * @} + */ + +/** @defgroup RCCEx_CRS_SynchroPolarity + * @{ + */ +#define RCC_CRS_SYNC_POLARITY_RISING ((uint32_t)0x00) /*!< Synchro Active on rising edge (default) */ +#define RCC_CRS_SYNC_POLARITY_FALLING CRS_CFGR_SYNCPOL /*!< Synchro Active on falling edge */ + +#define IS_RCC_CRS_SYNC_POLARITY(_POLARITY_) (((_POLARITY_) == RCC_CRS_SYNC_POLARITY_RISING) || \ + ((_POLARITY_) == RCC_CRS_SYNC_POLARITY_FALLING)) +/** + * @} + */ + +/** @defgroup RCCEx_CRS_ReloadValueDefault + * @{ + */ +#define RCC_CRS_RELOADVALUE_DEFAULT ((uint32_t)0xBB7F) /*!< The reset value of the RELOAD field corresponds + to a target frequency of 48 MHz and a synchronization signal frequency of 1 kHz (SOF signal from USB). */ + +#define IS_RCC_CRS_RELOADVALUE(_VALUE_) (((_VALUE_) <= 0xFFFF)) +/** + * @} + */ + +/** @defgroup RCCEx_CRS_ErrorLimitDefault + * @{ + */ +#define RCC_CRS_ERRORLIMIT_DEFAULT ((uint32_t)0x22) /*!< Default Frequency error limit */ + +#define IS_RCC_CRS_ERRORLIMIT(_VALUE_) (((_VALUE_) <= 0xFF)) +/** + * @} + */ + +/** @defgroup RCCEx_CRS_HSI48CalibrationDefault + * @{ + */ +#define RCC_CRS_HSI48CALIBRATION_DEFAULT ((uint32_t)0x20) /*!< The default value is 32, which corresponds to the middle of the trimming interval. + The trimming step is around 67 kHz between two consecutive TRIM steps. A higher TRIM value + corresponds to a higher output frequency */ + +#define IS_RCC_CRS_HSI48CALIBRATION(_VALUE_) (((_VALUE_) <= 0x3F)) +/** + * @} + */ + +/** @defgroup RCCEx_CRS_FreqErrorDirection + * @{ + */ +#define RCC_CRS_FREQERRORDIR_UP ((uint32_t)0x00) /*!< Upcounting direction, the actual frequency is above the target */ +#define RCC_CRS_FREQERRORDIR_DOWN ((uint32_t)CRS_ISR_FEDIR) /*!< Downcounting direction, the actual frequency is below the target */ + +#define IS_RCC_CRS_FREQERRORDIR(_DIR_) (((_DIR_) == RCC_CRS_FREQERRORDIR_UP) || \ + ((_DIR_) == RCC_CRS_FREQERRORDIR_DOWN)) +/** + * @} + */ + +/** @defgroup RCCEx_CRS_Interrupt_Sources + * @{ + */ +#define RCC_CRS_IT_SYNCOK CRS_ISR_SYNCOKF /*!< SYNC event OK */ +#define RCC_CRS_IT_SYNCWARN CRS_ISR_SYNCWARNF /*!< SYNC warning */ +#define RCC_CRS_IT_ERR CRS_ISR_ERRF /*!< error */ +#define RCC_CRS_IT_ESYNC CRS_ISR_ESYNCF /*!< Expected SYNC */ +#define RCC_CRS_IT_TRIMOVF CRS_ISR_TRIMOVF /*!< Trimming overflow or underflow */ +#define RCC_CRS_IT_SYNCERR CRS_ISR_SYNCERR /*!< SYNC error */ +#define RCC_CRS_IT_SYNCMISS CRS_ISR_SYNCMISS /*!< SYNC missed*/ + +/** + * @} + */ + +/** @defgroup RCCEx_CRS_Flags + * @{ + */ +#define RCC_CRS_FLAG_SYNCOK CRS_ISR_SYNCOKF /* SYNC event OK flag */ +#define RCC_CRS_FLAG_SYNCWARN CRS_ISR_SYNCWARNF /* SYNC warning flag */ +#define RCC_CRS_FLAG_ERR CRS_ISR_ERRF /* Error flag */ +#define RCC_CRS_FLAG_ESYNC CRS_ISR_ESYNCF /* Expected SYNC flag */ +#define RCC_CRS_FLAG_TRIMOVF CRS_ISR_TRIMOVF /*!< Trimming overflow or underflow */ +#define RCC_CRS_FLAG_SYNCERR CRS_ISR_SYNCERR /*!< SYNC error */ +#define RCC_CRS_FLAG_SYNCMISS CRS_ISR_SYNCMISS /*!< SYNC missed*/ + +/** + * @} + */ + +#endif /* !(STM32L051xx ) && !(STM32L061xx ) */ +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ +/** @defgroup RCCEx_Exported_Macros + * @{ + */ + +/** @brief Enable or disable the AHB peripheral clock. + * @note After reset, the peripheral clock (used for registers read/write access) + * is disabled and the application software has to enable this clock before + * using it. + */ + +#if defined(STM32L062xx) || defined(STM32L063xx) +#define __CRYP_CLK_ENABLE() (RCC->AHBENR |= (RCC_AHBENR_CRYPEN)) +#define __CRYP_CLK_DISABLE() (RCC->AHBENR &= ~ (RCC_AHBENR_CRYPEN)) +#endif /* STM32L062xx || STM32L063xx */ + +#if !defined(STM32L051xx) && !defined(STM32L061xx) +#define __TSC_CLK_ENABLE() (RCC->AHBENR |= (RCC_AHBENR_TSCEN)) +#define __TSC_CLK_DISABLE() (RCC->AHBENR &= ~ (RCC_AHBENR_TSCEN)) + +#define __RNG_CLK_ENABLE() (RCC->AHBENR |= (RCC_AHBENR_RNGEN)) +#define __RNG_CLK_DISABLE() (RCC->AHBENR &= ~ (RCC_AHBENR_RNGEN)) +#endif /* !(STM32L051xx ) && !(STM32L061xx ) */ + +/** @brief Enable or disable the APB1 peripheral clock. + * @note After reset, the peripheral clock (used for registers read/write access) + * is disabled and the application software has to enable this clock before + * using it. + */ + +#if !defined(STM32L051xx) && !defined(STM32L061xx) +#define __USB_CLK_ENABLE() (RCC->APB1ENR |= (RCC_APB1ENR_USBEN)) +#define __USB_CLK_DISABLE() (RCC->APB1ENR &= ~ (RCC_APB1ENR_USBEN)) +#endif /* !(STM32L051xx ) && !(STM32L061xx ) */ + +#if !defined(STM32L051xx) && !defined(STM32L061xx) +#define __CRS_CLK_ENABLE() (RCC->APB1ENR |= (RCC_APB1ENR_CRSEN)) +#define __CRS_CLK_DISABLE() (RCC->APB1ENR &= ~(RCC_APB1ENR_CRSEN)) +#endif /* !(STM32L051xx ) && !(STM32L061xx ) */ + + +#if defined(STM32L053xx) || defined(STM32L063xx) +#define __LCD_CLK_ENABLE() (RCC->APB1ENR |= (RCC_APB1ENR_LCDEN)) +#define __LCD_CLK_DISABLE() (RCC->APB1ENR &= ~ (RCC_APB1ENR_LCDEN)) +#endif /* STM32L053xx || STM32L063xx */ + +#if defined(STM32L053xx) || defined(STM32L063xx) || \ + defined(STM32L052xx) || defined(STM32L062xx) || \ + defined(STM32L051xx) || defined(STM32L061xx) +#define __TIM2_CLK_ENABLE() (RCC->APB1ENR |= (RCC_APB1ENR_TIM2EN)) +#define __TIM6_CLK_ENABLE() (RCC->APB1ENR |= (RCC_APB1ENR_TIM6EN)) +#define __SPI2_CLK_ENABLE() (RCC->APB1ENR |= (RCC_APB1ENR_SPI2EN)) +#define __USART2_CLK_ENABLE() (RCC->APB1ENR |= (RCC_APB1ENR_USART2EN)) +#define __LPUART1_CLK_ENABLE() (RCC->APB1ENR |= (RCC_APB1ENR_LPUART1EN)) +#define __I2C1_CLK_ENABLE() (RCC->APB1ENR |= (RCC_APB1ENR_I2C1EN)) +#define __I2C2_CLK_ENABLE() (RCC->APB1ENR |= (RCC_APB1ENR_I2C2EN)) +#define __DAC_CLK_ENABLE() (RCC->APB1ENR |= (RCC_APB1ENR_DACEN)) +#define __LPTIM1_CLK_ENABLE() (RCC->APB1ENR |= (RCC_APB1ENR_LPTIM1EN)) + +#define __TIM2_CLK_DISABLE() (RCC->APB1ENR &= ~ (RCC_APB1ENR_TIM2EN)) +#define __TIM6_CLK_DISABLE() (RCC->APB1ENR &= ~ (RCC_APB1ENR_TIM6EN)) +#define __SPI2_CLK_DISABLE() (RCC->APB1ENR &= ~ (RCC_APB1ENR_SPI2EN)) +#define __USART2_CLK_DISABLE() (RCC->APB1ENR &= ~ (RCC_APB1ENR_USART2EN)) +#define __LPUART1_CLK_DISABLE() (RCC->APB1ENR &= ~ (RCC_APB1ENR_LPUART1EN)) +#define __I2C1_CLK_DISABLE() (RCC->APB1ENR &= ~ (RCC_APB1ENR_I2C1EN)) +#define __I2C2_CLK_DISABLE() (RCC->APB1ENR &= ~ (RCC_APB1ENR_I2C2EN)) +#define __DAC_CLK_DISABLE() (RCC->APB1ENR &= ~ (RCC_APB1ENR_DACEN)) +#define __LPTIM1_CLK_DISABLE() (RCC->APB1ENR &= ~ (RCC_APB1ENR_LPTIM1EN)) +#endif /* STM32L051xx || STM32L061xx || */ + /* STM32L052xx || STM32L062xx || */ + /* STM32L053xx || STM32L063xx || */ + +/** @brief Enable or disable the APB2 peripheral clock. + * @note After reset, the peripheral clock (used for registers read/write access) + * is disabled and the application software has to enable this clock before + * using it. + */ + +#if defined(STM32L053xx) || defined(STM32L063xx) || \ + defined(STM32L052xx) || defined(STM32L062xx) || \ + defined(STM32L051xx) || defined(STM32L061xx) +#define __TIM21_CLK_ENABLE() (RCC->APB2ENR |= (RCC_APB2ENR_TIM21EN)) +#define __TIM22_CLK_ENABLE() (RCC->APB2ENR |= (RCC_APB2ENR_TIM22EN)) +#define __FIREWALL_CLK_ENABLE() (RCC->APB2ENR |= (RCC_APB2ENR_MIFIEN)) +#define __ADC1_CLK_ENABLE() (RCC->APB2ENR |= (RCC_APB2ENR_ADC1EN)) +#define __SPI1_CLK_ENABLE() (RCC->APB2ENR |= (RCC_APB2ENR_SPI1EN)) +#define __USART1_CLK_ENABLE() (RCC->APB2ENR |= (RCC_APB2ENR_USART1EN)) + +#define __TIM21_CLK_DISABLE() (RCC->APB2ENR &= ~ (RCC_APB2ENR_TIM21EN)) +#define __TIM22_CLK_DISABLE() (RCC->APB2ENR &= ~ (RCC_APB2ENR_TIM22EN)) +#define __FIREWALL_CLK_DISABLE() (RCC->APB2ENR &= ~ (RCC_APB2ENR_MIFIEN)) +#define __ADC1_CLK_DISABLE() (RCC->APB2ENR &= ~ (RCC_APB2ENR_ADC1EN)) +#define __SPI1_CLK_DISABLE() (RCC->APB2ENR &= ~ (RCC_APB2ENR_SPI1EN)) +#define __USART1_CLK_DISABLE() (RCC->APB2ENR &= ~ (RCC_APB2ENR_USART1EN)) +#endif /* STM32L051xx || STM32L061xx || */ + /* STM32L052xx || STM32L062xx || */ + /* STM32L053xx || STM32L063xx || */ + +/** @brief Force or release AHB peripheral reset. + */ +#if defined(STM32L062xx) || defined(STM32L063xx) +#define __CRYP_FORCE_RESET() (RCC->AHBRSTR |= (RCC_AHBRSTR_CRYPRST)) +#define __CRYP_RELEASE_RESET() (RCC->AHBRSTR &= ~ (RCC_AHBRSTR_CRYPRST)) +#endif /* STM32L062xx || STM32L063xx */ + +#if !defined(STM32L051xx) && !defined(STM32L061xx) +#define __TSC_FORCE_RESET() (RCC->AHBRSTR |= (RCC_AHBRSTR_TSCRST)) +#define __TSC_RELEASE_RESET() (RCC->AHBRSTR &= ~ (RCC_AHBRSTR_TSCRST)) +#define __RNG_FORCE_RESET() (RCC->AHBRSTR |= (RCC_AHBRSTR_RNGRST)) +#define __RNG_RELEASE_RESET() (RCC->AHBRSTR &= ~ (RCC_AHBRSTR_RNGRST)) +#endif /* !(STM32L051xx ) && !(STM32L061xx ) */ + +/** @brief Force or release APB1 peripheral reset. + */ +#if defined(STM32L053xx) || defined(STM32L063xx) || \ + defined(STM32L052xx) || defined(STM32L062xx) || \ + defined(STM32L051xx) || defined(STM32L061xx) +#define __TIM2_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM2RST)) +#define __TIM6_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_TIM6RST)) +#define __LPTIM1_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_LPTIM1RST)) +#define __I2C1_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_I2C1RST)) +#define __I2C2_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_I2C2RST)) +#define __USART2_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_USART2RST)) +#define __LPUART1_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_LPUART1RST)) +#define __SPI2_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_SPI2RST)) +#define __DAC_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_DACRST)) + +#define __TIM2_RELEASE_RESET() (RCC->APB1RSTR &= ~ (RCC_APB1RSTR_TIM2RST)) +#define __TIM6_RELEASE_RESET() (RCC->APB1RSTR &= ~ (RCC_APB1RSTR_TIM6RST)) +#define __LPTIM1_RELEASE_RESET() (RCC->APB1RSTR &= ~ (RCC_APB1RSTR_LPTIM1RST)) +#define __I2C1_RELEASE_RESET() (RCC->APB1RSTR &= ~ (RCC_APB1RSTR_I2C1RST)) +#define __I2C2_RELEASE_RESET() (RCC->APB1RSTR &= ~ (RCC_APB1RSTR_I2C2RST)) +#define __USART2_RELEASE_RESET() (RCC->APB1RSTR &= ~ (RCC_APB1RSTR_USART2RST)) +#define __LPUART1_RELEASE_RESET() (RCC->APB1RSTR &= ~ (RCC_APB1RSTR_LPUART1RST)) +#define __SPI2_RELEASE_RESET() (RCC->APB1RSTR &= ~ (RCC_APB1RSTR_SPI2RST)) +#define __DAC_RELEASE_RESET() (RCC->APB1RSTR &= ~ (RCC_APB1RSTR_DACRST)) +#endif /* STM32L051xx || STM32L061xx || */ + /* STM32L052xx || STM32L062xx || */ + /* STM32L053xx || STM32L063xx || */ + +#if !defined(STM32L051xx) && !defined(STM32L061xx) +#define __USB_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_USBRST)) +#define __USB_RELEASE_RESET() (RCC->APB1RSTR &= ~ (RCC_APB1RSTR_USBRST)) +#endif /* !(STM32L051xx ) && !(STM32L061xx ) */ + +#if !defined(STM32L051xx) && !defined(STM32L061xx) +#define __CRS_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_CRSRST)) +#define __CRS_RELEASE_RESET() (RCC->APB1RSTR &= ~(RCC_APB1RSTR_CRSRST)) +#endif /* !(STM32L051xx ) && !(STM32L061xx ) */ + +#if defined(STM32L053xx) || defined(STM32L063xx) +#define __LCD_FORCE_RESET() (RCC->APB1RSTR |= (RCC_APB1RSTR_LCDRST)) +#define __LCD_RELEASE_RESET() (RCC->APB1RSTR &= ~ (RCC_APB1RSTR_LCDRST)) +#endif /* STM32L053xx || STM32L063xx */ + +/** @brief Force or release APB2 peripheral reset. + */ +#if defined(STM32L053xx) || defined(STM32L063xx) || \ + defined(STM32L052xx) || defined(STM32L062xx) || \ + defined(STM32L051xx) || defined(STM32L061xx) +#define __USART1_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_USART1RST)) +#define __ADC1_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_ADC1RST)) +#define __SPI1_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_SPI1RST)) +#define __TIM21_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_TIM21RST)) +#define __TIM22_FORCE_RESET() (RCC->APB2RSTR |= (RCC_APB2RSTR_TIM22RST)) + +#define __USART1_RELEASE_RESET() (RCC->APB2RSTR &= ~ (RCC_APB2RSTR_USART1RST)) +#define __ADC1_RELEASE_RESET() (RCC->APB2RSTR &= ~ (RCC_APB2RSTR_ADC1RST)) +#define __SPI1_RELEASE_RESET() (RCC->APB2RSTR &= ~ (RCC_APB2RSTR_SPI1RST)) +#define __TIM21_RELEASE_RESET() (RCC->APB2RSTR &= ~ (RCC_APB2RSTR_TIM21RST)) +#define __TIM22_RELEASE_RESET() (RCC->APB2RSTR &= ~ (RCC_APB2RSTR_TIM22RST)) +#endif /* STM32L051xx || STM32L061xx || */ + /* STM32L052xx || STM32L062xx || */ + /* STM32L053xx || STM32L063xx || */ + +/** @brief Enable or disable the AHB peripheral clock during Low Power (Sleep) mode. + * @note Peripheral clock gating in SLEEP mode can be used to further reduce + * power consumption. + * @note After wakeup from SLEEP mode, the peripheral clock is enabled again. + * @note By default, all peripheral clocks are enabled during SLEEP mode. + */ + +#if !defined(STM32L051xx) && !defined(STM32L061xx) +#define __TSC_CLK_SLEEP_ENABLE() (RCC->AHBSMENR |= (RCC_AHBSMENR_TSCSMEN)) +#define __RNG_CLK_SLEEP_ENABLE() (RCC->AHBSMENR |= (RCC_AHBSMENR_RNGSMEN)) +#define __TSC_CLK_SLEEP_DISABLE() (RCC->AHBSMENR &= ~ (RCC_AHBSMENR_TSCSMEN)) +#define __RNG_CLK_SLEEP_DISABLE() (RCC->AHBSMENR &= ~ (RCC_AHBSMENR_RNGSMEN)) +#endif /* !(STM32L051xx ) && !(STM32L061xx ) */ + +#if defined(STM32L062xx) || defined(STM32L063xx) +#define __CRYP_CLK_SLEEP_ENABLE() (RCC->AHBLPENR |= (RCC_AHBSMENR_CRYPSMEN)) +#define __CRYP_CLK_SLEEP_DISABLE() (RCC->AHBLPENR &= ~ (RCC_AHBSMENR_CRYPSMEN)) +#endif /* STM32L062xx || STM32L063xx */ + + +/** @brief Enable or disable the APB1 peripheral clock during Low Power (Sleep) mode. + * @note Peripheral clock gating in SLEEP mode can be used to further reduce + * power consumption. + * @note After wakeup from SLEEP mode, the peripheral clock is enabled again. + * @note By default, all peripheral clocks are enabled during SLEEP mode. + */ + +#if defined(STM32L053xx) || defined(STM32L063xx) || \ + defined(STM32L052xx) || defined(STM32L062xx) || \ + defined(STM32L051xx) || defined(STM32L061xx) +#define __TIM2_CLK_SLEEP_ENABLE() (RCC->APB1SMENR |= (RCC_APB1SMENR_TIM2SMEN)) +#define __TIM6_CLK_SLEEP_ENABLE() (RCC->APB1SMENR |= (RCC_APB1SMENR_TIM6SMEN)) +#define __SPI2_CLK_SLEEP_ENABLE() (RCC->APB1SMENR |= (RCC_APB1SMENR_SPI2SMEN)) +#define __USART2_CLK_SLEEP_ENABLE() (RCC->APB1SMENR |= (RCC_APB1SMENR_USART2SMEN)) +#define __LPUART1_CLK_SLEEP_ENABLE() (RCC->APB1SMENR |= (RCC_APB1SMENR_LPUART1SMEN)) +#define __I2C1_CLK_SLEEP_ENABLE() (RCC->APB1SMENR |= (RCC_APB1SMENR_I2C1SMEN)) +#define __I2C2_CLK_SLEEP_ENABLE() (RCC->APB1SMENR |= (RCC_APB1SMENR_I2C2SMEN)) +#define __DAC_CLK_SLEEP_ENABLE() (RCC->APB1SMENR |= (RCC_APB1SMENR_DACSMEN)) +#define __LPTIM1_CLK_SLEEP_ENABLE() (RCC->APB1SMENR |= (RCC_APB1SMENR_LPTIM1SMEN)) + +#define __TIM2_CLK_SLEEP_DISABLE() (RCC->APB1SMENR &= ~ (RCC_APB1SMENR_TIM2SMEN)) +#define __TIM6_CLK_SLEEP_DISABLE() (RCC->APB1SMENR &= ~ (RCC_APB1SMENR_TIM6SMEN)) +#define __SPI2_CLK_SLEEP_DISABLE() (RCC->APB1SMENR &= ~ (RCC_APB1SMENR_SPI2SMEN)) +#define __USART2_CLK_SLEEP_DISABLE() (RCC->APB1SMENR &= ~ (RCC_APB1SMENR_USART2SMEN)) +#define __LPUART1_CLK_SLEEP_DISABLE() (RCC->APB1SMENR &= ~ (RCC_APB1SMENR_LPUART1SMEN)) +#define __I2C1_CLK_SLEEP_DISABLE() (RCC->APB1SMENR &= ~ (RCC_APB1SMENR_I2C1SMEN)) +#define __I2C2_CLK_SLEEP_DISABLE() (RCC->APB1SMENR &= ~ (RCC_APB1SMENR_I2C2SMEN)) +#define __DAC_CLK_SLEEP_DISABLE() (RCC->APB1SMENR &= ~ (RCC_APB1SMENR_DACSMEN)) +#define __LPTIM1_CLK_SLEEP_DISABLE() (RCC->APB1SMENR &= ~ (RCC_APB1SMENR_LPTIM1SMEN)) +#endif /* STM32L051xx || STM32L061xx || */ + /* STM32L052xx || STM32L062xx || */ + /* STM32L053xx || STM32L063xx || */ + +#if !defined(STM32L051xx) && !defined(STM32L061xx) +#define __USB_CLK_SLEEP_ENABLE() (RCC->APB1SMENR |= (RCC_APB1SMENR_USBSMEN)) +#define __USB_CLK_SLEEP_DISABLE() (RCC->APB1SMENR &= ~ (RCC_APB1SMENR_USBSMEN)) + +#define __CRS_CLK_SLEEP_ENABLE() (RCC->APB1SMENR |= (RCC_APB1SMENR_CRSSMEN)) +#define __CRS_CLK_SLEEP_DISABLE() (RCC->APB1SMENR &= ~ (RCC_APB1SMENR_CRSSMEN)) +#endif /* !(STM32L051xx ) && !(STM32L061xx ) */ + +#if defined(STM32L053xx) || defined(STM32L063xx) +#define __LCD_CLK_SLEEP_ENABLE() (RCC->APB1SMENR |= (RCC_APB1SMENR_LCDSMEN)) +#define __LCD_CLK_SLEEP_DISABLE() (RCC->APB1SMENR &= ~ (RCC_APB1SMENR_LCDSMEN)) +#endif /* STM32L053xx || STM32L063xx */ + +/** @brief Enable or disable the APB2 peripheral clock during Low Power (Sleep) mode. + * @note Peripheral clock gating in SLEEP mode can be used to further reduce + * power consumption. + * @note After wakeup from SLEEP mode, the peripheral clock is enabled again. + * @note By default, all peripheral clocks are enabled during SLEEP mode. + */ +#if defined(STM32L053xx) || defined(STM32L063xx) || \ + defined(STM32L052xx) || defined(STM32L062xx) || \ + defined(STM32L051xx) || defined(STM32L061xx) +#define __TIM21_CLK_SLEEP_ENABLE() (RCC->APB2SMENR |= (RCC_APB2SMENR_TIM21SMEN)) +#define __TIM22_CLK_SLEEP_ENABLE() (RCC->APB2SMENR |= (RCC_APB2SMENR_TIM22SMEN)) +#define __ADC1_CLK_SLEEP_ENABLE() (RCC->APB2SMENR |= (RCC_APB2SMENR_ADC1SMEN)) +#define __SPI1_CLK_SLEEP_ENABLE() (RCC->APB2SMENR |= (RCC_APB2SMENR_SPI1SMEN)) +#define __USART1_CLK_SLEEP_ENABLE() (RCC->APB2SMENR |= (RCC_APB2SMENR_USART1SMEN)) + +#define __TIM21_CLK_SLEEP_DISABLE() (RCC->APB2SMENR &= ~ (RCC_APB2SMENR_TIM21SMEN)) +#define __TIM22_CLK_SLEEP_DISABLE() (RCC->APB2SMENR &= ~ (RCC_APB2SMENR_TIM22SMEN)) +#define __ADC1_CLK_SLEEP_DISABLE() (RCC->APB2SMENR &= ~ (RCC_APB2SMENR_ADC1SMEN)) +#define __SPI1_CLK_SLEEP_DISABLE() (RCC->APB2SMENR &= ~ (RCC_APB2SMENR_SPI1SMEN)) +#define __USART1_CLK_SLEEP_DISABLE() (RCC->APB2SMENR &= ~ (RCC_APB2SMENR_USART1SMEN)) +#endif /* STM32L051xx || STM32L061xx || */ + /* STM32L052xx || STM32L062xx || */ + /* STM32L053xx || STM32L063xx || */ + +/** @brief macro to configure the I2C1 clock (I2C1CLK). + * + * @param __I2C1CLKSource__: specifies the I2C1 clock source. + * This parameter can be one of the following values: + * @arg RCC_I2C1CLKSOURCE_PCLK1: PCLK1 selected as I2C1 clock + * @arg RCC_I2C1CLKSOURCE_HSI: HSI selected as I2C1 clock + * @arg RCC_I2C1CLKSOURCE_SYSCLK: System Clock selected as I2C1 clock + */ +#define __HAL_RCC_I2C1_CONFIG(__I2C1CLKSource__) \ + MODIFY_REG(RCC->CCIPR, RCC_CCIPR_I2C1SEL, (uint32_t)(__I2C1CLKSource__)) + +/** @brief macro to get the I2C1 clock source. + * @retval The clock source can be one of the following values: + * @arg RCC_I2C1CLKSOURCE_PCLK1: PCLK1 selected as I2C1 clock + * @arg RCC_I2C1CLKSOURCE_HSI: HSI selected as I2C1 clock + * @arg RCC_I2C1CLKSOURCE_SYSCLK: System Clock selected as I2C1 clock + */ +#define __HAL_RCC_GET_I2C1_SOURCE() ((uint32_t)(READ_BIT(RCC->CCIPR, RCC_CCIPR_I2C1SEL))) + +/** @brief macro to configure the USART1 clock (USART1CLK). + * + * @param __USART1CLKSource__: specifies the USART1 clock source. + * This parameter can be one of the following values: + * @arg RCC_USART1CLKSOURCE_PCLK2: PCLK2 selected as USART1 clock + * @arg RCC_USART1CLKSOURCE_HSI: HSI selected as USART1 clock + * @arg RCC_USART1CLKSOURCE_SYSCLK: System Clock selected as USART1 clock + * @arg RCC_USART1CLKSOURCE_LSE: LSE selected as USART1 clock + */ +#define __HAL_RCC_USART1_CONFIG(__USART1CLKSource__) \ + MODIFY_REG(RCC->CCIPR, RCC_CCIPR_USART1SEL, (uint32_t)(__USART1CLKSource__)) + +/** @brief macro to get the USART1 clock source. + * @retval The clock source can be one of the following values: + * @arg RCC_USART1CLKSOURCE_PCLK2: PCLK2 selected as USART1 clock + * @arg RCC_USART1CLKSOURCE_HSI: HSI selected as USART1 clock + * @arg RCC_USART1CLKSOURCE_SYSCLK: System Clock selected as USART1 clock + * @arg RCC_USART1CLKSOURCE_LSE: LSE selected as USART1 clock + */ +#define __HAL_RCC_GET_USART1_SOURCE() ((uint32_t)(READ_BIT(RCC->CCIPR, RCC_CCIPR_USART1SEL))) + +/** @brief macro to configure the USART2 clock (USART2CLK). + * + * @param __USART2CLKSource__: specifies the USART2 clock source. + * This parameter can be one of the following values: + * @arg RCC_USART2CLKSOURCE_PCLK1: PCLK1 selected as USART2 clock + * @arg RCC_USART2CLKSOURCE_HSI: HSI selected as USART2 clock + * @arg RCC_USART2CLKSOURCE_SYSCLK: System Clock selected as USART2 clock + * @arg RCC_USART2CLKSOURCE_LSE: LSE selected as USART2 clock + */ +#define __HAL_RCC_USART2_CONFIG(__USART2CLKSource__) \ + MODIFY_REG(RCC->CCIPR, RCC_CCIPR_USART2SEL, (uint32_t)(__USART2CLKSource__)) + +/** @brief macro to get the USART2 clock source. + * @retval The clock source can be one of the following values: + * @arg RCC_USART2CLKSOURCE_PCLK1: PCLK1 selected as USART2 clock + * @arg RCC_USART2CLKSOURCE_HSI: HSI selected as USART2 clock + * @arg RCC_USART2CLKSOURCE_SYSCLK: System Clock selected as USART2 clock + * @arg RCC_USART2CLKSOURCE_LSE: LSE selected as USART2 clock + */ +#define __HAL_RCC_GET_USART2_SOURCE() ((uint32_t)(READ_BIT(RCC->CCIPR, RCC_CCIPR_USART2SEL))) + +/** @brief macro to configure the LPUART1 clock (LPUART1CLK). + * + * @param __LPUART1CLKSource__: specifies the LPUART1 clock source. + * This parameter can be one of the following values: + * @arg RCC_LPUART1CLKSOURCE_PCLK1: PCLK1 selected as LPUART1 clock + * @arg RCC_LPUART1CLKSOURCE_HSI: HSI selected as LPUART1 clock + * @arg RCC_LPUART1CLKSOURCE_SYSCLK: System Clock selected as LPUART1 clock + * @arg RCC_LPUART1CLKSOURCE_LSE: LSE selected as LPUART1 clock + */ +#define __HAL_RCC_LPUART1_CONFIG(__LPUART1CLKSource__) \ + MODIFY_REG(RCC->CCIPR, RCC_CCIPR_LPUART1SEL, (uint32_t)(__LPUART1CLKSource__)) + +/** @brief macro to get the LPUART1 clock source. + * @retval The clock source can be one of the following values: + * @arg RCC_LPUART1CLKSOURCE_PCLK1: PCLK1 selected as LPUART1 clock + * @arg RCC_LPUART1CLKSOURCE_HSI: HSI selected as LPUART1 clock + * @arg RCC_LPUART1CLKSOURCE_SYSCLK: System Clock selected as LPUART1 clock + * @arg RCC_LPUART1CLKSOURCE_LSE: LSE selected as LPUART1 clock + */ +#define __HAL_RCC_GET_LPUART1_SOURCE() ((uint32_t)(READ_BIT(RCC->CCIPR, RCC_CCIPR_LPUART1SEL))) + +/** @brief macro to configure the LPTIM1 clock (LPTIM1CLK). + * + * @param __LPTIM1CLKSource__: specifies the LPTIM1 clock source. + * This parameter can be one of the following values: + * @arg RCC_LPTIM1CLKSOURCE_PCLK: PCLK selected as LPTIM1 clock + * @arg RCC_LPTIM1CLKSOURCE_LSI : HSI selected as LPTIM1 clock + * @arg RCC_LPTIM1CLKSOURCE_HSI : LSI selected as LPTIM1 clock + * @arg RCC_LPTIM1CLKSOURCE_LSE : LSE selected as LPTIM1 clock + */ +#define __HAL_RCC_LPTIM1_CONFIG(__LPTIM1CLKSource__) \ + MODIFY_REG(RCC->CCIPR, RCC_CCIPR_LPTIM1SEL, (uint32_t)(__LPTIM1CLKSource__)) + +/** @brief macro to get the LPTIM1 clock source. + * @retval The clock source can be one of the following values: + * @arg RCC_LPTIM1CLKSOURCE_PCLK: PCLK selected as LPUART1 clock + * @arg RCC_LPTIM1CLKSOURCE_LSI : HSI selected as LPUART1 clock + * @arg RCC_LPTIM1CLKSOURCE_HSI : System Clock selected as LPUART1 clock + * @arg RCC_LPTIM1CLKSOURCE_LSE : LSE selected as LPUART1 clock + */ +#define __HAL_RCC_GET_LPTIM1_SOURCE() ((uint32_t)(READ_BIT(RCC->CCIPR, RCC_CCIPR_LPTIM1SEL))) + +#if !defined(STM32L051xx) && !defined(STM32L061xx) +/** @brief Macro to configure the USB clock (USBCLK). + * @param __USBCLKSource__: specifies the USB clock source. + * This parameter can be one of the following values: + * @arg RCC_USBCLKSOURCE_HSI48: HSI48 selected as USB clock + * @arg RCC_USBCLKSOURCE_PLLCLK: PLL Clock selected as USB clock + */ +#define __HAL_RCC_USB_CONFIG(__USBCLKSource__) \ + MODIFY_REG(RCC->CCIPR, RCC_CCIPR_HSI48SEL, (uint32_t)(__USBCLKSource__)) + +/** @brief Macro to get the USB clock source. + * @retval The clock source can be one of the following values: + * @arg RCC_USBCLKSOURCE_HSI48: HSI48 selected as USB clock + * @arg RCC_USBCLKSOURCE_PLLCLK: PLL Clock selected as USB clock + */ +#define __HAL_RCC_GET_USB_SOURCE() ((uint32_t)(READ_BIT(RCC->CCIPR, RCC_CCIPR_HSI48SEL))) + +/** @brief Macro to configure the RNG clock (RNGCLK). + * @param __RNGCLKSource__: specifies the USB clock source. + * This parameter can be one of the following values: + * @arg RCC_RNGCLKSOURCE_HSI48: HSI48 selected as RNG clock + * @arg RCC_RNGCLKSOURCE_PLLCLK: PLL Clock selected as RNG clock + */ +#define __HAL_RCC_RNG_CONFIG(__RNGCLKSource__) \ + MODIFY_REG(RCC->CCIPR, RCC_CCIPR_HSI48SEL, (uint32_t)(__RNGCLKSource__)) + +/** @brief Macro to get the RNG clock source. + * @retval The clock source can be one of the following values: + * @arg RCC_RNGCLKSOURCE_HSI48: HSI48 selected as RNG clock + * @arg RCC_RNGCLKSOURCE_PLLCLK: PLL Clock selected as RNG clock + */ +#define __HAL_RCC_GET_RNG_SOURCE() ((uint32_t)(READ_BIT(RCC->CCIPR, RCC_CCIPR_HSI48SEL))) + +/** @brief macro to select the HSI48M clock source + * @note This macro can be replaced by either __HAL_RCC_RNG_CONFIG or + * __HAL_RCC_USB_CONFIG to configure respectively RNG or UBS clock sources. + * + * @param __HSI48MCLKSource__: specifies the HSI48M clock source dedicated for + * USB an RNG peripherals. + * This parameter can be one of the following values: + * @arg RCC_HSI48M_PLL: A dedicated 48MHZ PLL output. + * @arg RCC_HSI48M_RC48: 48MHZ issued from internal HSI48 oscillator. + */ +#define __HAL_RCC_HSI48M_CONFIG(__HSI48MCLKSource__) \ + MODIFY_REG(RCC->CCIPR, RCC_CCIPR_HSI48SEL, (uint32_t)(__HSI48MCLKSource__)) + +/** @brief macro to get the HSI48M clock source. + * @note This macro can be replaced by either __HAL_RCC_GET_RNG_SOURCE or + * __HAL_RCC_GET_USB_SOURCE to get respectively RNG or UBS clock sources. + * @retval The clock source can be one of the following values: + * @arg RCC_HSI48M_PLL: A dedicated 48MHZ PLL output. + * @arg RCC_HSI48M_RC48: 48MHZ issued from internal HSI48 oscillator. + */ +#define __HAL_RCC_GET_HSI48M_SOURCE() ((uint32_t)(READ_BIT(RCC->CCIPR, RCC_CCIPR_HSI48SEL))) +#endif /* !(STM32L051xx ) && !(STM32L061xx ) */ + +/** + * @brief Macros to enable or disable the force of the Internal High Speed oscillator (HSI) + * in STOP mode to be quickly available as kernel clock for USART and I2C. + * @note The Enable of this function has not effect on the HSION bit. + * This parameter can be: ENABLE or DISABLE. + * @retval None + */ +#define __HAL_RCC_HSISTOP_ENABLE() SET_BIT(RCC->CR, RCC_CR_HSIKERON) +#define __HAL_RCC_HSISTOP_DISABLE() CLEAR_BIT(RCC->CR, RCC_CR_HSIKERON) + +/** + * @brief Macro to configures the External Low Speed oscillator (LSE) drive capability. + * @param RCC_LSEDrive: specifies the new state of the LSE drive capability. + * This parameter can be one of the following values: + * @arg RCC_LSEDRIVE_LOW: LSE oscillator low drive capability. + * @arg RCC_LSEDRIVE_MEDIUMLOW: LSE oscillator medium low drive capability. + * @arg RCC_LSEDRIVE_MEDIUMHIGH: LSE oscillator medium high drive capability. + * @arg RCC_LSEDRIVE_HIGH: LSE oscillator high drive capability. + * @retval None + */ +#define __HAL_RCC_LSEDRIVE_CONFIG(__RCC_LSEDrive__) (MODIFY_REG(RCC->CSR,\ + RCC_CSR_LSEDRV, (uint32_t)(__RCC_LSEDrive__) )) + +/** + * @brief Macro to configures the wake up from stop clock. + * @param RCC_STOPWUCLK: specifies the clock source used after wake up from stop + * This parameter can be one of the following values: + * @arg RCC_StopWakeUpClock_MSI: MSI selected as system clock source + * @arg RCC_StopWakeUpClock_HSI: HSI selected as system clock source + * @retval None + */ +#define __HAL_RCC_WAKEUPSTOP_CLK_CONFIG(__RCC_STOPWUCLK__) (MODIFY_REG(RCC->CFGR,\ + RCC_CFGR_STOPWUCK, (uint32_t)(__RCC_STOPWUCLK__) )) + +#if !defined(STM32L051xx) && !defined(STM32L061xx) +/** + * @brief Enables the specified CRS interrupts. + * @param __INTERRUPT__: specifies the CRS interrupt sources to be enabled. + * This parameter can be any combination of the following values: + * @arg RCC_CRS_IT_SYNCOK + * @arg RCC_CRS_IT_SYNCWARN + * @arg RCC_CRS_IT_ERR + * @arg RCC_CRS_IT_ESYNC + * @retval None + */ +#define __HAL_RCC_CRS_ENABLE_IT(__INTERRUPT__) (CRS->CR |= (__INTERRUPT__)) + +/** + * @brief Disables the specified CRS interrupts. + * @param __INTERRUPT__: specifies the CRS interrupt sources to be disabled. + * This parameter can be any combination of the following values: + * @arg RCC_CRS_IT_SYNCOK + * @arg RCC_CRS_IT_SYNCWARN + * @arg RCC_CRS_IT_ERR + * @arg RCC_CRS_IT_ESYNC + * @retval None + */ +#define __HAL_RCC_CRS_DISABLE_IT(__INTERRUPT__) (CRS->CR &= ~(__INTERRUPT__)) + +/** @brief Check the CRS's interrupt has occurred or not. + * @param __INTERRUPT__: specifies the CRS interrupt source to check. + * This parameter can be one of the following values: + * @arg RCC_CRS_IT_SYNCOK + * @arg RCC_CRS_IT_SYNCWARN + * @arg RCC_CRS_IT_ERR + * @arg RCC_CRS_IT_ESYNC + * @retval The new state of __INTERRUPT__ (SET or RESET). + */ +#define __HAL_RCC_CRS_GET_IT_SOURCE(__INTERRUPT__) ((CRS->CR & (__INTERRUPT__))? SET : RESET) + +/** @brief Clear the CRS's interrupt pending bits + * bits to clear the selected interrupt pending bits. + * @param __INTERRUPT__: specifies the interrupt pending bit to clear. + * This parameter can be any combination of the following values: + * @arg RCC_CRS_IT_SYNCOK + * @arg RCC_CRS_IT_SYNCWARN + * @arg RCC_CRS_IT_ERR + * @arg RCC_CRS_IT_ESYNC + * @arg RCC_CRS_IT_TRIMOVF + * @arg RCC_CRS_IT_SYNCERR + * @arg RCC_CRS_IT_SYNCMISS + */ +/* CRS IT Error Mask */ +#define RCC_CRS_IT_ERROR_MASK ((uint32_t)(RCC_CRS_IT_TRIMOVF | RCC_CRS_IT_SYNCERR | RCC_CRS_IT_SYNCMISS)) + +#define __HAL_RCC_CRS_CLEAR_IT(__INTERRUPT__) ((((__INTERRUPT__) & RCC_CRS_IT_ERROR_MASK)!= 0) ? (CRS->ICR |= CRS_ICR_ERRC) : \ + (CRS->ICR |= (__INTERRUPT__))) + +/** + * @brief Checks whether the specified CRS flag is set or not. + * @param _FLAG_: specifies the flag to check. + * This parameter can be one of the following values: + * @arg RCC_CRS_FLAG_SYNCOK + * @arg RCC_CRS_FLAG_SYNCWARN + * @arg RCC_CRS_FLAG_ERR + * @arg RCC_CRS_FLAG_ESYNC + * @arg RCC_CRS_FLAG_TRIMOVF + * @arg RCC_CRS_FLAG_SYNCERR + * @arg RCC_CRS_FLAG_SYNCMISS + * @retval The new state of _FLAG_ (TRUE or FALSE). + */ +#define __HAL_RCC_CRS_GET_FLAG(_FLAG_) ((CRS->ISR & (_FLAG_)) == (_FLAG_)) + +/** + * @brief Clears the CRS specified FLAG. + * @param _FLAG_: specifies the flag to clear. + * This parameter can be one of the following values: + * @arg RCC_CRS_FLAG_SYNCOK + * @arg RCC_CRS_FLAG_SYNCWARN + * @arg RCC_CRS_FLAG_ERR + * @arg RCC_CRS_FLAG_ESYNC + * @arg RCC_CRS_FLAG_TRIMOVF + * @arg RCC_CRS_FLAG_SYNCERR + * @arg RCC_CRS_FLAG_SYNCMISS + * @retval None + */ + +/* CRS Flag Error Mask */ +#define RCC_CRS_FLAG_ERROR_MASK ((uint32_t)(RCC_CRS_FLAG_TRIMOVF | RCC_CRS_FLAG_SYNCERR | RCC_CRS_FLAG_SYNCMISS)) + +#define __HAL_RCC_CRS_CLEAR_FLAG(__FLAG__) ((((__FLAG__) & RCC_CRS_FLAG_ERROR_MASK)!= 0) ? (CRS->ICR |= CRS_ICR_ERRC) : \ + (CRS->ICR |= (__FLAG__))) + + +/** + * @brief Enables the oscillator clock for frequency error counter. + * @note when the CEN bit is set the CRS_CFGR register becomes write-protected. + * @param None + * @retval None + */ +#define __HAL_RCC_CRS_ENABLE_FREQ_ERROR_COUNTER() (CRS->CR |= CRS_CR_CEN) + +/** + * @brief Disables the oscillator clock for frequency error counter. + * @param None + * @retval None + */ +#define __HAL_RCC_CRS_DISABLE_FREQ_ERROR_COUNTER() (CRS->CR &= ~CRS_CR_CEN) + +/** + * @brief Enables the automatic hardware adjustment of TRIM bits. + * @note When the AUTOTRIMEN bit is set the CRS_CFGR register becomes write-protected. + * @param None + * @retval None + */ +#define __HAL_RCC_CRS_ENABLE_AUTOMATIC_CALIB() (CRS->CR |= CRS_CR_AUTOTRIMEN) + +/** + * @brief Enables or disables the automatic hardware adjustment of TRIM bits. + * @param None + * @retval None + */ +#define __HAL_RCC_CRS_DISABLE_AUTOMATIC_CALIB() (CRS->CR &= ~CRS_CR_AUTOTRIMEN) + +/** + * @brief Macro to calculate reload value to be set in CRS register according to target and sync frequencies + * @note The RELOAD value should be selected according to the ratio between the target frequency and the frequency + * of the synchronization source after prescaling. It is then decreased by one in order to + * reach the expected synchronization on the zero value. The formula is the following: + * RELOAD = (fTARGET / fSYNC) -1 + * @param _FTARGET_ Target frequency (value in Hz) + * @param _FSYNC_ Synchronization signal frequency (value in Hz) + * @retval None + */ +#define __HAL_RCC_CRS_CALCULATE_RELOADVALUE(_FTARGET_, _FSYNC_) (((_FTARGET_) / (_FSYNC_)) - 1) + +#endif /* !(STM32L051xx) && !(STM32L061xx) */ + +/** + * @} + */ + + +/* Exported functions --------------------------------------------------------*/ +HAL_StatusTypeDef HAL_RCCEx_PeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClkInit); +void HAL_RCCEx_GetPeriphCLKConfig(RCC_PeriphCLKInitTypeDef *PeriphClkInit); +void HAL_RCCEx_EnableLSECSS(void); +void HAL_RCCEx_DisableLSECSS(void); +#if !defined(STM32L051xx) && !defined(STM32L061xx) +void HAL_RCCEx_CRSConfig(RCC_CRSInitTypeDef *pInit); +void HAL_RCCEx_CRSSoftwareSynchronizationGenerate(void); +void HAL_RCCEx_CRSGetSynchronizationInfo(RCC_CRSSynchroInfoTypeDef *pSynchroInfo); +RCC_CRSStatusTypeDef HAL_RCCEx_CRSWaitSynchronization(uint32_t Timeout); +#endif /* !(STM32L051xx) && !(STM32L061xx) */ + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __STM32L0xx_HAL_RCC_EX_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_rng.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_rng.c new file mode 100644 index 0000000000..90a82ba17f --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_rng.c @@ -0,0 +1,429 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_rng.c + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief RNG HAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the Random Number Generator (RNG) peripheral: + * + Initialization/de-initialization functions + * + Peripheral Control functions + * + Peripheral State functions + * + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + The RNG HAL driver can be used as follows: + + (#) Enable the RNG controller clock using __RNG_CLK_ENABLE() macro. + (#) Activate the RNG peripheral using __HAL_RNG_ENABLE() macro. + (#) Wait until the 32 bit Random Number Generator contains a valid + random data using (polling/interrupt) mode. + (#) Get the 32 bit random number using HAL_RNG_GetRandomNumber() function. + + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @defgroup RNG + * @brief RNG HAL module driver. + * @{ + */ + +#ifdef HAL_RNG_MODULE_ENABLED +#if !defined (STM32L051xx) && !defined (STM32L061xx) + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +#define RNG_TIMEOUT_VALUE 1000 +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup RNG_Private_Functions + * @{ + */ + +/** @defgroup RNG_Group1 Initialization and de-initialization functions + * @brief Initialization and Configuration functions. + * +@verbatim + =============================================================================== + ##### Initialization and de-initialization functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Initialize the RNG according to the specified parameters + in the RNG_InitTypeDef and create the associated handle + (+) DeInitialize the RNG peripheral + (+) Initialize the RNG MSP + (+) DeInitialize RNG MSP + +@endverbatim + * @{ + */ + +/** + * @brief Initializes the RNG according to the specified + * parameters in the RNG_InitTypeDef and creates the associated handle. + * @param hrng: pointer to a RNG_HandleTypeDef structure that contains + * the configuration information for RNG. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RNG_Init(RNG_HandleTypeDef *hrng) +{ + /* Check the RNG handle allocation */ + if(hrng == NULL) + { + return HAL_ERROR; + } + + if(hrng->State == HAL_RNG_STATE_RESET) + { + /* Init the low level hardware */ + HAL_RNG_MspInit(hrng); + } + + /* Change RNG peripheral state */ + hrng->State = HAL_RNG_STATE_BUSY; + + /* Enable the RNG Peripheral */ + __HAL_RNG_ENABLE(hrng); + + /* Initialize the RNG state */ + hrng->State = HAL_RNG_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief DeInitializes the RNG peripheral. + * @param hrng: pointer to a RNG_HandleTypeDef structure that contains + * the configuration information for RNG. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RNG_DeInit(RNG_HandleTypeDef *hrng) +{ + /* Check the RNG peripheral state */ + if(hrng->State == HAL_RNG_STATE_BUSY) + { + return HAL_BUSY; + } + + /* Update the RNG state */ + hrng->State = HAL_RNG_STATE_BUSY; + + /* Disable the RNG Peripheral */ + __HAL_RNG_DISABLE(hrng); + + /* Set the RNG registers to their reset values */ + hrng->Instance->CR &= 0xFFFFFFF3; + hrng->Instance->SR &= 0xFFFFFF98; + hrng->Instance->DR &= 0x0; + + /* DeInit the low level hardware */ + HAL_RNG_MspDeInit(hrng); + + /* Update the RNG state */ + hrng->State = HAL_RNG_STATE_RESET; + + /* Release Lock */ + __HAL_UNLOCK(hrng); + + /* Return the function status */ + return HAL_OK; +} + +/** + * @brief Initializes the RNG MSP. + * @param hrng: pointer to a RNG_HandleTypeDef structure that contains + * the configuration information for RNG. + * @retval None + */ +__weak void HAL_RNG_MspInit(RNG_HandleTypeDef *hrng) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_RNG_MspInit could be implemented in the user file + */ +} + +/** + * @brief DeInitializes the RNG MSP. + * @param hrng: pointer to a RNG_HandleTypeDef structure that contains + * the configuration information for RNG. + * @retval None + */ +__weak void HAL_RNG_MspDeInit(RNG_HandleTypeDef *hrng) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_RNG_MspDeInit could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup RNG_Group2 Peripheral Control functions + * @brief management functions. + * +@verbatim + =============================================================================== + ##### Peripheral Control functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Get the 32 bit Random number + (+) Get the 32 bit Random number with interrupt enabled + (+) Handle RNG interrupt request + + +@endverbatim + * @{ + */ + +/** + * @brief Returns a 32-bit random number. + * @note Each time the random number data is read the RNG_FLAG_DRDY flag + * is automatically cleared. + * @param hrng: pointer to a RNG_HandleTypeDef structure that contains + * the configuration information for RNG. + * @retval 32-bit random number + */ +uint32_t HAL_RNG_GetRandomNumber(RNG_HandleTypeDef *hrng) +{ + uint32_t random32bit = 0; + uint32_t tickstart = 0; + + /* Process Locked */ + __HAL_LOCK(hrng); + + /* Get timeout */ + tickstart = HAL_GetTick(); + + /* Check if data register contains valid random data */ + while(__HAL_RNG_GET_FLAG(hrng, RNG_FLAG_DRDY) == RESET) + { + if((HAL_GetTick() - tickstart ) > RNG_TIMEOUT_VALUE) + { + return HAL_TIMEOUT; + } + } + + /* Get a 32bit Random number */ + random32bit = hrng->Instance->DR; + + /* Process Unlocked */ + __HAL_UNLOCK(hrng); + + /* Return the 32 bit random number */ + return random32bit; +} + +/** + * @brief Returns a 32-bit random number with interrupt enabled. + * @param hrng: pointer to a RNG_HandleTypeDef structure that contains + * the configuration information for RNG. + * @retval 32-bit random number + */ +uint32_t HAL_RNG_GetRandomNumber_IT(RNG_HandleTypeDef *hrng) +{ + uint32_t random32bit = 0; + + /* Process Locked */ + __HAL_LOCK(hrng); + + /* Change RNG peripheral state */ + hrng->State = HAL_RNG_STATE_BUSY; + + /* Get a 32bit Random number */ + random32bit = hrng->Instance->DR; + + /* Enable the RNG Interrupts: Data Ready, Clock error, Seed error */ + __HAL_RNG_ENABLE_IT(hrng); + + /* Return the 32 bit random number */ + return random32bit; +} + +/** + * @brief Handles RNG interrupt request. + * @note In the case of a clock error, the RNG is no more able to generate + * random numbers because the PLL48CLK clock is not correct. User has + * to check that the clock controller is correctly configured to provide + * the RNG clock and clear the CEIS bit using __HAL_RNG_CLEAR_FLAG(). + * The clock error has no impact on the previously generated + * random numbers, and the RNG_DR register contents can be used. + * @note In the case of a seed error, the generation of random numbers is + * interrupted as long as the SECS bit is '1'. If a number is + * available in the RNG_DR register, it must not be used because it may + * not have enough entropy. In this case, it is recommended to clear the + * SEIS bit using __HAL_RNG_CLEAR_FLAG(), then disable and enable + * the RNG peripheral to reinitialize and restart the RNG. + * @param hrng: pointer to a RNG_HandleTypeDef structure that contains + * the configuration information for RNG. + * @retval None + + */ +void HAL_RNG_IRQHandler(RNG_HandleTypeDef *hrng) +{ + /* RNG clock error interrupt occurred */ + if(__HAL_RNG_GET_FLAG(hrng, RNG_IT_CEI) != RESET) + { + HAL_RNG_ErrorCallback(hrng); + + /* Clear the clock error flag */ + __HAL_RNG_CLEAR_FLAG(hrng, RNG_IT_CEI); + + /* Change RNG peripheral state */ + hrng->State = HAL_RNG_STATE_ERROR; + + /* Process Unlocked */ + __HAL_UNLOCK(hrng); + } + + /* RNG seed error interrupt occurred */ + if(__HAL_RNG_GET_FLAG(hrng, RNG_IT_SEI) != RESET) + { + HAL_RNG_ErrorCallback(hrng); + + /* Clear the seed error flag */ + __HAL_RNG_CLEAR_FLAG(hrng, RNG_IT_SEI); + + /* Change RNG peripheral state */ + hrng->State = HAL_RNG_STATE_ERROR; + + /* Process Unlocked */ + __HAL_UNLOCK(hrng); + } + + /* Check RNG data ready flag */ + if(__HAL_RNG_GET_FLAG(hrng, RNG_FLAG_DRDY) != RESET) + { + /* Data Ready callback */ + HAL_RNG_ReadyCallback(hrng); + + /* Change RNG peripheral state */ + hrng->State = HAL_RNG_STATE_READY; + + /* Clear the RNG Data Ready flag */ + __HAL_RNG_CLEAR_FLAG(hrng, RNG_FLAG_DRDY); + + /* Process Unlocked */ + __HAL_UNLOCK(hrng); + } +} + +/** + * @brief Data Ready callback in non-blocking mode. + * @param hrng: pointer to a RNG_HandleTypeDef structure that contains + * the configuration information for RNG. + * @retval None + */ + +__weak void HAL_RNG_ReadyCallback(RNG_HandleTypeDef* hrng) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_RNG_ReadyCallback could be implemented in the user file + */ +} + +/** + * @brief RNG error callbacks. + * @param hrng: pointer to a RNG_HandleTypeDef structure that contains + * the configuration information for RNG. + * @retval None + */ +__weak void HAL_RNG_ErrorCallback(RNG_HandleTypeDef *hrng) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_RNG_ErrorCallback could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup RNG_Group3 Peripheral State functions + * @brief Peripheral State functions. + * +@verbatim + =============================================================================== + ##### Peripheral State functions ##### + =============================================================================== + [..] + This subsection permits to get in run-time the status of the peripheral + and the data flow. + +@endverbatim + * @{ + */ + +/** + * @brief Returns the RNG state. + * @param hrng: pointer to a RNG_HandleTypeDef structure that contains + * the configuration information for RNG. + * @retval HAL state + */ +HAL_RNG_StateTypeDef HAL_RNG_GetState(RNG_HandleTypeDef *hrng) +{ + return hrng->State; +} + +/** + * @} + */ + +/** + * @} + */ +#endif /* STM32L051xx && STM32L061xx*/ +#endif /* HAL_RNG_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ + diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_rng.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_rng.h new file mode 100644 index 0000000000..96dcba3e8c --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_rng.h @@ -0,0 +1,225 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_rng.h + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief Header file of RNG HAL module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32L0xx_HAL_RNG_H +#define __STM32L0xx_HAL_RNG_H + +#ifdef __cplusplus + extern "C" { +#endif + +#if !defined (STM32L051xx) && !defined (STM32L061xx) +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal_def.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @addtogroup RNG + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ + +/** + * @brief RNG HAL State Structure definition + */ +typedef enum +{ + HAL_RNG_STATE_RESET = 0x00, /*!< RNG not yet initialized or disabled */ + HAL_RNG_STATE_READY = 0x01, /*!< RNG initialized and ready for use */ + HAL_RNG_STATE_BUSY = 0x02, /*!< RNG internal process is ongoing */ + HAL_RNG_STATE_TIMEOUT = 0x03, /*!< RNG timeout state */ + HAL_RNG_STATE_ERROR = 0x04 /*!< RNG error state */ + +}HAL_RNG_StateTypeDef; + +/** + * @brief RNG Handle Structure definition + */ +typedef struct +{ + RNG_TypeDef *Instance; /*!< Register base address */ + + HAL_LockTypeDef Lock; /*!< RNG locking object */ + + __IO HAL_RNG_StateTypeDef State; /*!< RNG communication state */ + +}RNG_HandleTypeDef; + +/* Exported constants --------------------------------------------------------*/ + +/** @defgroup RNG_Exported_Constants + * @{ + */ + +/** @defgroup RNG_Interrupt_definition + * @{ + */ +#define RNG_IT_CEI ((uint32_t)0x20) /*!< Clock error interrupt */ +#define RNG_IT_SEI ((uint32_t)0x40) /*!< Seed error interrupt */ + +#define IS_RNG_IT(IT) (((IT) == RNG_IT_CEI) || \ + ((IT) == RNG_IT_SEI)) +/** + * @} + */ + + +/** @defgroup RNG_Flag_definition + * @{ + */ +#define RNG_FLAG_DRDY ((uint32_t)0x0001) /*!< Data ready */ +#define RNG_FLAG_CECS ((uint32_t)0x0002) /*!< Clock error current status */ +#define RNG_FLAG_SECS ((uint32_t)0x0004) /*!< Seed error current status */ + +#define IS_RNG_FLAG(FLAG) (((FLAG) == RNG_FLAG_DRDY) || \ + ((FLAG) == RNG_FLAG_CECS) || \ + ((FLAG) == RNG_FLAG_SECS)) +/** + * @} + */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ + +/** @brief Reset RNG handle state + * @param __HANDLE__: RNG Handle + * @retval None + */ +#define __HAL_RNG_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_RNG_STATE_RESET) + +/** + * @brief Enables the RNG peripheral. + * @param __HANDLE__: RNG Handle + * @retval None + */ +#define __HAL_RNG_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= RNG_CR_RNGEN) + +/** + * @brief Disables the RNG peripheral. + * @param __HANDLE__: RNG Handle + * @retval None + */ +#define __HAL_RNG_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~RNG_CR_RNGEN) + +/** + * @brief Gets the selected RNG's flag status. + * @param __HANDLE__: RNG Handle + * @param __FLAG__: RNG flag + * @retval The new state of RNG_FLAG (SET or RESET). + */ +#define __HAL_RNG_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->SR & (__FLAG__)) == (__FLAG__)) + +/** + * @brief Clears the RNG's pending flags. + * @param __HANDLE__: RNG Handle + * @param __FLAG__: RNG flag + * @retval None + */ +#define __HAL_RNG_CLEAR_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->SR) &= ~(__FLAG__)) + +/** + * @brief Enables the RNG interrupts. + * @param __HANDLE__: RNG Handle + * @retval None + */ +#define __HAL_RNG_ENABLE_IT(__HANDLE__) ((__HANDLE__)->Instance->CR |= RNG_CR_IE) + +/** + * @brief Disables the RNG interrupts. + * @param __HANDLE__: RNG Handle + * @param __INTERRUPT__: specifies the RNG interrupt source to check. + * This parameter can be one of the following values: + * @arg RNG_FLAG_DRDY: Data ready interrupt + * @arg RNG_FLAG_CECS: Clock error interrupt + * @arg RNG_FLAG_SECS: Seed error interrupt + * @retval None + */ +#define __HAL_RNG_DISABLE_IT(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~RNG_CR_IE) + +/** + * @brief Checks whether the specified RNG interrupt has occurred or not. + * @param __HANDLE__: RNG Handle + * @param __INTERRUPT__: specifies the RNG interrupt source to check. + * This parameter can be one of the following values: + * @arg RNG_FLAG_DRDY: Data ready interrupt + * @arg RNG_FLAG_CECS: Clock error interrupt + * @arg RNG_FLAG_SECS: Seed error interrupt + * @retval The new state of RNG_FLAG (SET or RESET). + */ +#define __HAL_RNG_GET_IT(__HANDLE__, __INTERRUPT__) (((__HANDLE__)->Instance->SR & (__INTERRUPT__)) == (__INTERRUPT__)) + +/* Exported functions --------------------------------------------------------*/ + +/* Initialization/de-initialization functions **********************************/ +HAL_StatusTypeDef HAL_RNG_Init(RNG_HandleTypeDef *hrng); +HAL_StatusTypeDef HAL_RNG_DeInit (RNG_HandleTypeDef *hrng); +void HAL_RNG_MspInit(RNG_HandleTypeDef *hrng); +void HAL_RNG_MspDeInit(RNG_HandleTypeDef *hrng); + +/* Peripheral Control functions ************************************************/ +uint32_t HAL_RNG_GetRandomNumber(RNG_HandleTypeDef *hrng); +uint32_t HAL_RNG_GetRandomNumber_IT(RNG_HandleTypeDef *hrng); +void HAL_RNG_IRQHandler(RNG_HandleTypeDef *hrng); +void HAL_RNG_ReadyCallback(RNG_HandleTypeDef* hrng); +void HAL_RNG_ErrorCallback(RNG_HandleTypeDef *hrng); + +/* Peripheral State functions **************************************************/ +HAL_RNG_StateTypeDef HAL_RNG_GetState(RNG_HandleTypeDef *hrng); + +#endif /* STM32L051xx && STM32L061xx*/ +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __STM32L0xx_HAL_RNG_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_rtc.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_rtc.c new file mode 100644 index 0000000000..a29abfc4b1 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_rtc.c @@ -0,0 +1,1567 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_rtc.c + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief RTC HAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the Real Time Clock (RTC) peripheral: + * + Initialization/de-initialization functions + * + I/O operation functions + * + Peripheral Control functions + * + Peripheral State functions + * + @verbatim + ============================================================================== + ##### Backup Domain Operating Condition ##### + ============================================================================== + [..] As long as the supply voltage remains in the operating range, + the RTC never stops, regardless of the device status (Run mode, + low power modes or under reset). + + ##### Backup Domain Reset ##### + ================================================================== + [..] The backup domain reset sets all RTC registers and the RCC_CSR register + to their reset values. + [..] A backup domain reset is generated when one of the following events occurs: + (+) Software reset, triggered by setting the RTCRST bit in the + RCC Control Status register (RCC_CSR). + (+) Power reset (BOR/POR/PDR). + + ##### Backup Domain Access ##### + ================================================================== + [..] After reset, the backup domain (RTC registers and RTC backup data registers) + is protected against possible unwanted write accesses. + [..] To enable access to the RTC Domain and RTC registers, proceed as follows: + (+) Enable the Power Controller (PWR) APB1 interface clock using the + __PWR_CLK_ENABLE() function. + (+) Enable access to RTC domain using the HAL_PWR_EnableBkUpAccess() function. + (+) Select the RTC clock source using the __HAL_RCC_RTC_CONFIG() function. + (+) Enable RTC Clock using the __HAL_RCC_RTC_ENABLE() function. + + + ##### How to use this driver ##### + ================================================================== + [..] + (+) Enable the RTC domain access (see description in the section above). + (+) Configure the RTC Prescaler (Asynchronous and Synchronous) and RTC hour + format using the HAL_RTC_Init() function. + + *** Time and Date configuration *** + =================================== + [..] + (+) To configure the RTC Calendar (Time and Date) use the HAL_RTC_SetTime() + and HAL_RTC_SetDate() functions. + (+) To read the RTC Calendar, use the HAL_RTC_GetTime() and HAL_RTC_GetDate() functions. + + *** Alarm configuration *** + =========================== + [..] + (+) To configure the RTC Alarm use the HAL_RTC_SetAlarm() function. + You can also configure the RTC Alarm with interrupt mode using the HAL_RTC_SetAlarm_IT() function. + (+) To read the RTC Alarm, use the HAL_RTC_GetAlarm() function. + + *** RTC Wakeup configuration *** + ================================ + [..] + (+) To configure the RTC Wakeup Clock source and Counter use the HAL_RTC_SetWakeUpTimer() + function. You can also configure the RTC Wakeup timer with interrupt mode + using the HAL_RTC_SetWakeUpTimer_IT() function. + (+) To read the RTC WakeUp Counter register, use the HAL_RTC_GetWakeUpTimer() + function. + + *** Outputs configuration *** + ============================= + [..] The RTC has 2 different outputs: + (+) RTC_ALARM: this output is used to manage the RTC Alarm A, Alarm B + and WaKeUp signals. + To output the selected RTC signal, use the HAL_RTC_Init() function. + (+) RTC_CALIB: this output is 512Hz signal or 1Hz. + To enable the RTC_CALIB, use the HAL_RTCEx_SetCalibrationOutPut() function. + (+) Two pins can be used as RTC_ALARM or RTC_CALIB (PC13, PB14) managed on + the RTC_OR register. + (+) When the RTC_CALIB or RTC_ALARM output is selected, the RTC_OUT pin is + automatically configured in output alternate function. + + *** Smooth digital Calibration configuration *** + ================================================ + [..] + (+) Configure the RTC Original Digital Calibration Value and the corresponding + calibration cycle period (32s,16s and 8s) using the HAL_RTCEx_SetSmoothCalib() + function. + + *** TimeStamp configuration *** + =============================== + [..] + (+) Enables the RTC TimeStamp using the HAL_RTC_SetTimeStamp() function. + You can also configure the RTC TimeStamp with interrupt mode using the + HAL_RTC_SetTimeStamp_IT() function. + (+) To read the RTC TimeStamp Time and Date register, use the HAL_RTC_GetTimeStamp() + function. + + *** Tamper configuration *** + ============================ + [..] + (+) Enable the RTC Tamper and Configure the Tamper filter count, trigger Edge + or Level according to the Tamper filter (if equal to 0 Edge else Level) + value, sampling frequency, NoErase, MaskFlag, precharge or discharge and + Pull-UP using the HAL_RTC_SetTamper() function. You can configure RTC Tamper + with interrupt mode using HAL_RTC_SetTamper_IT() function. + (+) The default configuration of the Tamper erases the backup registers. To avoid + erase, enable the NoErase field on the RTC_TAMPCR register. + + *** Backup Data Registers configuration *** + =========================================== + [..] + (+) To write to the RTC Backup Data registers, use the HAL_RTC_BKUPWrite() + function. + (+) To read the RTC Backup Data registers, use the HAL_RTC_BKUPRead() + function. + (+) The backup registers are reset when a tamper detection event occurs + + + ##### RTC and low power modes ##### + ================================================================== + [..] The MCU can be woken up from a low power mode by an RTC alternate + function. + [..] The RTC alternate functions are the RTC alarms (Alarm A and Alarm B), + RTC wakeup, RTC tamper event detection and RTC time stamp event detection. + These RTC alternate functions can wake up the system from the Stop and + Standby low power modes. + [..] The system can also wake up from low power modes without depending + on an external interrupt (Auto-wakeup mode), by using the RTC alarm + or the RTC wakeup events. + [..] The RTC provides a programmable time base for waking up from the + Stop or Standby mode at regular intervals. + Wakeup from STOP and Standby modes is possible only when the RTC clock source + is LSE or LSI. + + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @defgroup RTC + * @brief RTC HAL module driver + * @{ + */ + +#ifdef HAL_RTC_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Masks Definition */ +#define RTC_TR_RESERVED_MASK ((uint32_t)0x007F7F7F) +#define RTC_DR_RESERVED_MASK ((uint32_t)0x00FFFF3F) +#define RTC_INIT_MASK ((uint32_t)0xFFFFFFFF) +#define RTC_RSF_MASK ((uint32_t)0xFFFFFF5F) +#define RTC_FLAGS_MASK ((uint32_t)(RTC_FLAG_TSOVF | RTC_FLAG_TSF | RTC_FLAG_WUTF | \ + RTC_FLAG_ALRBF | RTC_FLAG_INITF | RTC_FLAG_RSF | \ + RTC_FLAG_INITS | RTC_FLAG_WUTWF | RTC_FLAG_ALRBWF | \ + RTC_FLAG_TAMP1F | RTC_FLAG_TAMP2F | \ + RTC_FLAG_RECALPF | RTC_FLAG_SHPF)) + +#define RTC_TIMEOUT_VALUE 1000 +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ + +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup RTC_Private_Functions + * @{ + */ + +/** @defgroup RTC_Group1 Initialization and de-initialization functions + * @brief Initialization and Configuration functions + * +@verbatim + =============================================================================== + ##### Initialization and de-initialization functions ##### + =============================================================================== + [..] This section provides functions allowing to initialize and configure the + RTC Prescaler (Synchronous and Asynchronous), RTC Hour format, disable + RTC registers Write protection, enter and exit the RTC initialization mode, + RTC registers synchronization check and reference clock detection enable. + (#) The RTC Prescaler is programmed to generate the RTC 1Hz time base. + It is split into 2 programmable prescalers to minimize power consumption. + (++) A 7-bit asynchronous prescaler and a 13-bit synchronous prescaler. + (++) When both prescalers are used, it is recommended to configure the + asynchronous prescaler to a high value to minimize power consumption. + (#) All RTC registers are Write protected. Writing to the RTC registers + is enabled by writing a key into the Write Protection register, RTC_WPR. + (#) To configure the RTC Calendar, user application should enter + initialization mode. In this mode, the calendar counter is stopped + and its value can be updated. When the initialization sequence is + complete, the calendar restarts counting after 4 RTCCLK cycles. + (#) To read the calendar through the shadow registers after Calendar + initialization, calendar update or after wakeup from low power modes + the software must first clear the RSF flag. The software must then + wait until it is set again before reading the calendar, which means + that the calendar registers have been correctly copied into the + RTC_TR and RTC_DR shadow registers.The HAL_RTC_WaitForSynchro() function + implements the above software sequence (RSF clear and RSF check). + +@endverbatim + * @{ + */ + +/** + * @brief Initializes the RTC peripheral + * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTC_Init(RTC_HandleTypeDef *hrtc) +{ + /* Check the RTC peripheral state */ + if(hrtc == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_RTC_HOUR_FORMAT(hrtc->Init.HourFormat)); + assert_param(IS_RTC_ASYNCH_PREDIV(hrtc->Init.AsynchPrediv)); + assert_param(IS_RTC_SYNCH_PREDIV(hrtc->Init.SynchPrediv)); + assert_param(IS_RTC_OUTPUT(hrtc->Init.OutPut)); + assert_param(IS_RTC_OUTPUT_REMAP(hrtc->Init.OutPutRemap)); + assert_param(IS_RTC_OUTPUT_POL(hrtc->Init.OutPutPolarity)); + assert_param(IS_RTC_OUTPUT_TYPE(hrtc->Init.OutPutType)); + + if(hrtc->State == HAL_RTC_STATE_RESET) + { + /* Initialize RTC MSP */ + HAL_RTC_MspInit(hrtc); + } + + /* Set RTC state */ + hrtc->State = HAL_RTC_STATE_BUSY; + + /* Disable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + /* Set Initialization mode */ + if(RTC_EnterInitMode(hrtc) != HAL_OK) + { + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + /* Set RTC state */ + hrtc->State = HAL_RTC_STATE_ERROR; + + return HAL_ERROR; + } + else + { + /* Clear RTC_CR FMT, OSEL and POL Bits */ + hrtc->Instance->CR &= ((uint32_t)~(RTC_CR_FMT | RTC_CR_OSEL | RTC_CR_POL)); + /* Set RTC_CR register */ + hrtc->Instance->CR |= (uint32_t)(hrtc->Init.HourFormat | hrtc->Init.OutPut | hrtc->Init.OutPutPolarity); + + /* Configure the RTC PRER */ + hrtc->Instance->PRER = (uint32_t)(hrtc->Init.SynchPrediv); + hrtc->Instance->PRER |= (uint32_t)(hrtc->Init.AsynchPrediv << 16); + + /* Exit Initialization mode */ + hrtc->Instance->ISR &= (uint32_t)~RTC_ISR_INIT; + + hrtc->Instance->OR &= (uint32_t)~(RTC_OR_ALARMOUTTYPE | RTC_OR_RTC_OUT_RMP); + hrtc->Instance->OR |= (uint32_t)(hrtc->Init.OutPutType | hrtc->Init.OutPutRemap); + + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + /* Set RTC state */ + hrtc->State = HAL_RTC_STATE_READY; + + return HAL_OK; + } +} + +/** + * @brief DeInitializes the RTC peripheral + * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @note This function doesn't reset the RTC Backup Data registers. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTC_DeInit(RTC_HandleTypeDef *hrtc) +{ + uint32_t tickstart; + + /* Set RTC state */ + hrtc->State = HAL_RTC_STATE_BUSY; + + /* Disable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + /* Set Initialization mode */ + if(RTC_EnterInitMode(hrtc) != HAL_OK) + { + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + /* Set RTC state */ + hrtc->State = HAL_RTC_STATE_ERROR; + + return HAL_ERROR; + } + else + { + /* Reset TR, DR and CR registers */ + hrtc->Instance->TR = (uint32_t)0x00000000; + hrtc->Instance->DR = (uint32_t)0x00002101; + /* Reset All CR bits except CR[2:0] */ + hrtc->Instance->CR &= (uint32_t)0x00000007; + + tickstart = HAL_GetTick(); + + /* Wait till WUTWF flag is set and if Time out is reached exit */ + while(((hrtc->Instance->ISR) & RTC_ISR_WUTWF) == (uint32_t)RESET) + { + if((HAL_GetTick() - tickstart ) > RTC_TIMEOUT_VALUE) + { + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + /* Set RTC state */ + hrtc->State = HAL_RTC_STATE_TIMEOUT; + + return HAL_TIMEOUT; + } + } + + /* Reset all RTC CR register bits */ + hrtc->Instance->CR &= (uint32_t)0x00000000; + hrtc->Instance->WUTR = (uint32_t)0x0000FFFF; + hrtc->Instance->PRER = (uint32_t)0x007F00FF; + hrtc->Instance->ALRMAR = (uint32_t)0x00000000; + hrtc->Instance->ALRMBR = (uint32_t)0x00000000; + hrtc->Instance->SHIFTR = (uint32_t)0x00000000; + hrtc->Instance->CALR = (uint32_t)0x00000000; + hrtc->Instance->ALRMASSR = (uint32_t)0x00000000; + hrtc->Instance->ALRMBSSR = (uint32_t)0x00000000; + + /* Reset ISR register and exit initialization mode */ + hrtc->Instance->ISR = (uint32_t)0x00000000; + + /* Reset Tamper configuration register */ + hrtc->Instance->TAMPCR = 0x00000000; + + /* Reset Option register */ + hrtc->Instance->OR = 0x00000000; + + /* If RTC_CR_BYPSHAD bit = 0, wait for synchro else this check is not needed */ + if((hrtc->Instance->CR & RTC_CR_BYPSHAD) == RESET) + { + if(HAL_RTC_WaitForSynchro(hrtc) != HAL_OK) + { + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + hrtc->State = HAL_RTC_STATE_ERROR; + + return HAL_ERROR; + } + } + } + + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + /* De-Initialize RTC MSP */ + HAL_RTC_MspDeInit(hrtc); + + hrtc->State = HAL_RTC_STATE_RESET; + + /* Release Lock */ + __HAL_UNLOCK(hrtc); + + return HAL_OK; +} + +/** + * @brief Initializes the RTC MSP. + * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @retval None + */ +__weak void HAL_RTC_MspInit(RTC_HandleTypeDef* hrtc) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_RTC_MspInit could be implenetd in the user file + */ +} + +/** + * @brief DeInitializes the RTC MSP. + * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @retval None + */ +__weak void HAL_RTC_MspDeInit(RTC_HandleTypeDef* hrtc) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_RTC_MspDeInit could be implenetd in the user file + */ +} + +/** + * @} + */ + +/** @defgroup RTC_Group2 RTC Time and Date functions + * @brief RTC Time and Date functions + * +@verbatim + =============================================================================== + ##### RTC Time and Date functions ##### + =============================================================================== + + [..] This section provide functions allowing to control RTC features + (Time, Date, Alarm, Timestamp, Tamper, RefClock ...). + +@endverbatim + * @{ + */ + +/** + * @brief Sets RTC current time. + * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @param sTime: Pointer to Time structure + * @param Format: Specifies the format of the entered parameters. + * This parameter can be one of the following values: + * @arg FORMAT_BIN: Binary data format + * @arg FORMAT_BCD: BCD data format + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTC_SetTime(RTC_HandleTypeDef *hrtc, RTC_TimeTypeDef *sTime, uint32_t Format) +{ + uint32_t tmpreg = 0; + + /* Check the parameters */ + assert_param(IS_RTC_FORMAT(Format)); + assert_param(IS_RTC_DAYLIGHT_SAVING(sTime->DayLightSaving)); + assert_param(IS_RTC_STORE_OPERATION(sTime->StoreOperation)); + + /* Process Locked */ + __HAL_LOCK(hrtc); + + hrtc->State = HAL_RTC_STATE_BUSY; + + if(Format == FORMAT_BIN) + { + if((hrtc->Instance->CR & RTC_CR_FMT) != (uint32_t)RESET) + { + assert_param(IS_RTC_HOUR12(sTime->Hours)); + assert_param(IS_RTC_HOURFORMAT12(sTime->TimeFormat)); + } + else + { + sTime->TimeFormat = 0x00; + assert_param(IS_RTC_HOUR24(sTime->Hours)); + } + assert_param(IS_RTC_MINUTES(sTime->Minutes)); + assert_param(IS_RTC_SECONDS(sTime->Seconds)); + + tmpreg = (uint32_t)(((uint32_t)RTC_ByteToBcd2(sTime->Hours) << 16) | \ + ((uint32_t)RTC_ByteToBcd2(sTime->Minutes) << 8) | \ + ((uint32_t)RTC_ByteToBcd2(sTime->Seconds)) | \ + (((uint32_t)sTime->TimeFormat) << 16)); + } + else + { + if((hrtc->Instance->CR & RTC_CR_FMT) != (uint32_t)RESET) + { + tmpreg = RTC_Bcd2ToByte(sTime->Hours); + assert_param(IS_RTC_HOUR12(tmpreg)); + assert_param(IS_RTC_HOURFORMAT12(sTime->TimeFormat)); + } + else + { + sTime->TimeFormat = 0x00; + assert_param(IS_RTC_HOUR24(RTC_Bcd2ToByte(sTime->Hours))); + } + assert_param(IS_RTC_MINUTES(RTC_Bcd2ToByte(sTime->Minutes))); + assert_param(IS_RTC_SECONDS(RTC_Bcd2ToByte(sTime->Seconds))); + tmpreg = (((uint32_t)(sTime->Hours) << 16) | \ + ((uint32_t)(sTime->Minutes) << 8) | \ + ((uint32_t)sTime->Seconds) | \ + ((uint32_t)(sTime->TimeFormat) << 16)); + } + + /* Disable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + /* Set Initialization mode */ + if(RTC_EnterInitMode(hrtc) != HAL_OK) + { + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + /* Set RTC state */ + hrtc->State = HAL_RTC_STATE_ERROR; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_ERROR; + } + else + { + /* Set the RTC_TR register */ + hrtc->Instance->TR = (uint32_t)(tmpreg & RTC_TR_RESERVED_MASK); + + /* Clear the bits to be configured */ + hrtc->Instance->CR &= (uint32_t)~RTC_CR_BCK; + + /* Configure the RTC_CR register */ + hrtc->Instance->CR |= (uint32_t)(sTime->DayLightSaving | sTime->StoreOperation); + + /* Exit Initialization mode */ + hrtc->Instance->ISR &= (uint32_t)~RTC_ISR_INIT; + + /* If CR_BYPSHAD bit = 0, wait for synchro else this check is not needed */ + if((hrtc->Instance->CR & RTC_CR_BYPSHAD) == RESET) + { + if(HAL_RTC_WaitForSynchro(hrtc) != HAL_OK) + { + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + hrtc->State = HAL_RTC_STATE_ERROR; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_ERROR; + } + } + + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + hrtc->State = HAL_RTC_STATE_READY; + + __HAL_UNLOCK(hrtc); + + return HAL_OK; + } +} + +/** + * @brief Gets RTC current time. + * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @param sTime: Pointer to Time structure + * @param Format: Specifies the format of the entered parameters. + * This parameter can be one of the following values: + * @arg FORMAT_BIN: Binary data format + * @arg FORMAT_BCD: BCD data format + * @note Call HAL_RTC_GetDate() after HAL_RTC_GetTime() to unlock the values + * in the higher-order calendar shadow registers. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTC_GetTime(RTC_HandleTypeDef *hrtc, RTC_TimeTypeDef *sTime, uint32_t Format) +{ + uint32_t tmpreg = 0; + + /* Check the parameters */ + assert_param(IS_RTC_FORMAT(Format)); + + /* Get subseconds values from the correspondent registers*/ + sTime->SubSeconds = (uint32_t)(hrtc->Instance->SSR); + + /* Get the TR register */ + tmpreg = (uint32_t)(hrtc->Instance->TR & RTC_TR_RESERVED_MASK); + + /* Fill the structure fields with the read parameters */ + sTime->Hours = (uint8_t)((tmpreg & (RTC_TR_HT | RTC_TR_HU)) >> 16); + sTime->Minutes = (uint8_t)((tmpreg & (RTC_TR_MNT | RTC_TR_MNU)) >>8); + sTime->Seconds = (uint8_t)(tmpreg & (RTC_TR_ST | RTC_TR_SU)); + sTime->TimeFormat = (uint8_t)((tmpreg & (RTC_TR_PM)) >> 16); + + /* Check the input parameters format */ + if(Format == FORMAT_BIN) + { + /* Convert the time structure parameters to Binary format */ + sTime->Hours = (uint8_t)RTC_Bcd2ToByte(sTime->Hours); + sTime->Minutes = (uint8_t)RTC_Bcd2ToByte(sTime->Minutes); + sTime->Seconds = (uint8_t)RTC_Bcd2ToByte(sTime->Seconds); + } + + return HAL_OK; +} + +/** + * @brief Sets RTC current date. + * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @param sDate: Pointer to date structure + * @param Format: specifies the format of the entered parameters. + * This parameter can be one of the following values: + * @arg FORMAT_BIN: Binary data format + * @arg FORMAT_BCD: BCD data format + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTC_SetDate(RTC_HandleTypeDef *hrtc, RTC_DateTypeDef *sDate, uint32_t Format) +{ + uint32_t datetmpreg = 0; + + /* Check the parameters */ + assert_param(IS_RTC_FORMAT(Format)); + + /* Process Locked */ + __HAL_LOCK(hrtc); + + hrtc->State = HAL_RTC_STATE_BUSY; + + if((Format == FORMAT_BIN) && ((sDate->Month & 0x10) == 0x10)) + { + sDate->Month = (sDate->Month & (uint32_t)~(0x10)) + 0x0A; + } + + assert_param(IS_RTC_WEEKDAY(sDate->WeekDay)); + + if(Format == FORMAT_BIN) + { + assert_param(IS_RTC_YEAR(sDate->Year)); + assert_param(IS_RTC_MONTH(sDate->Month)); + assert_param(IS_RTC_DATE(sDate->Date)); + + datetmpreg = (((uint32_t)RTC_ByteToBcd2(sDate->Year) << 16) | \ + ((uint32_t)RTC_ByteToBcd2(sDate->Month) << 8) | \ + ((uint32_t)RTC_ByteToBcd2(sDate->Date)) | \ + ((uint32_t)sDate->WeekDay << 13)); + } + else + { + assert_param(IS_RTC_YEAR(RTC_Bcd2ToByte(sDate->Year))); + datetmpreg = RTC_Bcd2ToByte(sDate->Month); + assert_param(IS_RTC_MONTH(datetmpreg)); + datetmpreg = RTC_Bcd2ToByte(sDate->Date); + assert_param(IS_RTC_DATE(datetmpreg)); + + datetmpreg = ((((uint32_t)sDate->Year) << 16) | \ + (((uint32_t)sDate->Month) << 8) | \ + ((uint32_t)sDate->Date) | \ + (((uint32_t)sDate->WeekDay) << 13)); + } + + /* Disable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + /* Set Initialization mode */ + if(RTC_EnterInitMode(hrtc) != HAL_OK) + { + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + /* Set RTC state*/ + hrtc->State = HAL_RTC_STATE_ERROR; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_ERROR; + } + else + { + /* Set the RTC_DR register */ + hrtc->Instance->DR = (uint32_t)(datetmpreg & RTC_DR_RESERVED_MASK); + + /* Exit Initialization mode */ + hrtc->Instance->ISR &= (uint32_t)~RTC_ISR_INIT; + + /* If CR_BYPSHAD bit = 0, wait for synchro else this check is not needed */ + if((hrtc->Instance->CR & RTC_CR_BYPSHAD) == RESET) + { + if(HAL_RTC_WaitForSynchro(hrtc) != HAL_OK) + { + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + hrtc->State = HAL_RTC_STATE_ERROR; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_ERROR; + } + } + + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + hrtc->State = HAL_RTC_STATE_READY ; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_OK; + } +} + +/** + * @brief Gets RTC current date. + * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @param sDate: Pointer to Date structure + * @param Format: Specifies the format of the entered parameters. + * This parameter can be one of the following values: + * @arg FORMAT_BIN: Binary data format + * @arg FORMAT_BCD: BCD data format + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTC_GetDate(RTC_HandleTypeDef *hrtc, RTC_DateTypeDef *sDate, uint32_t Format) +{ + uint32_t datetmpreg = 0; + + /* Check the parameters */ + assert_param(IS_RTC_FORMAT(Format)); + + /* Get the DR register */ + datetmpreg = (uint32_t)(hrtc->Instance->DR & RTC_DR_RESERVED_MASK); + + /* Fill the structure fields with the read parameters */ + sDate->Year = (uint8_t)((datetmpreg & (RTC_DR_YT | RTC_DR_YU)) >> 16); + sDate->Month = (uint8_t)((datetmpreg & (RTC_DR_MT | RTC_DR_MU)) >> 8); + sDate->Date = (uint8_t)(datetmpreg & (RTC_DR_DT | RTC_DR_DU)); + sDate->WeekDay = (uint8_t)((datetmpreg & (RTC_DR_WDU)) >> 13); + + /* Check the input parameters format */ + if(Format == FORMAT_BIN) + { + /* Convert the date structure parameters to Binary format */ + sDate->Year = (uint8_t)RTC_Bcd2ToByte(sDate->Year); + sDate->Month = (uint8_t)RTC_Bcd2ToByte(sDate->Month); + sDate->Date = (uint8_t)RTC_Bcd2ToByte(sDate->Date); + } + return HAL_OK; +} + +/** + * @} + */ + +/** @defgroup RTC_Group3 RTC Alarm functions + * @brief RTC Alarm functions + * +@verbatim + =============================================================================== + ##### RTC Alarm functions ##### + =============================================================================== + + [..] This section provides functions allowing to configure Alarm feature + +@endverbatim + * @{ + */ +/** + * @brief Sets the specified RTC Alarm. + * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @param sAlarm: Pointer to Alarm structure + * @param Format: Specifies the format of the entered parameters. + * This parameter can be one of the following values: + * @arg FORMAT_BIN: Binary data format + * @arg FORMAT_BCD: BCD data format + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTC_SetAlarm(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef *sAlarm, uint32_t Format) +{ + uint32_t tickstart; + uint32_t tmpreg = 0, subsecondtmpreg = 0; + + /* Check the parameters */ + assert_param(IS_RTC_FORMAT(Format)); + assert_param(IS_ALARM(sAlarm->Alarm)); + assert_param(IS_ALARM_MASK(sAlarm->AlarmMask)); + assert_param(IS_RTC_ALARM_DATE_WEEKDAY_SEL(sAlarm->AlarmDateWeekDaySel)); + assert_param(IS_RTC_ALARM_SUB_SECOND_VALUE(sAlarm->AlarmTime.SubSeconds)); + assert_param(IS_RTC_ALARM_SUB_SECOND_MASK(sAlarm->AlarmSubSecondMask)); + + /* Process Locked */ + __HAL_LOCK(hrtc); + + hrtc->State = HAL_RTC_STATE_BUSY; + + if(Format == FORMAT_BIN) + { + if((hrtc->Instance->CR & RTC_CR_FMT) != (uint32_t)RESET) + { + assert_param(IS_RTC_HOUR12(sAlarm->AlarmTime.Hours)); + assert_param(IS_RTC_HOURFORMAT12(sAlarm->AlarmTime.TimeFormat)); + } + else + { + sAlarm->AlarmTime.TimeFormat = 0x00; + assert_param(IS_RTC_HOUR24(sAlarm->AlarmTime.Hours)); + } + assert_param(IS_RTC_MINUTES(sAlarm->AlarmTime.Minutes)); + assert_param(IS_RTC_SECONDS(sAlarm->AlarmTime.Seconds)); + + if(sAlarm->AlarmDateWeekDaySel == RTC_ALARMDATEWEEKDAYSEL_DATE) + { + assert_param(IS_RTC_ALARM_DATE_WEEKDAY_DATE(sAlarm->AlarmDateWeekDay)); + } + else + { + assert_param(IS_RTC_ALARM_DATE_WEEKDAY_WEEKDAY(sAlarm->AlarmDateWeekDay)); + } + + tmpreg = (((uint32_t)RTC_ByteToBcd2(sAlarm->AlarmTime.Hours) << 16) | \ + ((uint32_t)RTC_ByteToBcd2(sAlarm->AlarmTime.Minutes) << 8) | \ + ((uint32_t)RTC_ByteToBcd2(sAlarm->AlarmTime.Seconds)) | \ + ((uint32_t)(sAlarm->AlarmTime.TimeFormat) << 16) | \ + ((uint32_t)RTC_ByteToBcd2(sAlarm->AlarmDateWeekDay) << 24) | \ + ((uint32_t)sAlarm->AlarmDateWeekDaySel) | \ + ((uint32_t)sAlarm->AlarmMask)); + } + else + { + if((hrtc->Instance->CR & RTC_CR_FMT) != (uint32_t)RESET) + { + tmpreg = RTC_Bcd2ToByte(sAlarm->AlarmTime.Hours); + assert_param(IS_RTC_HOUR12(tmpreg)); + assert_param(IS_RTC_HOURFORMAT12(sAlarm->AlarmTime.TimeFormat)); + } + else + { + sAlarm->AlarmTime.TimeFormat = 0x00; + assert_param(IS_RTC_HOUR24(RTC_Bcd2ToByte(sAlarm->AlarmTime.Hours))); + } + + assert_param(IS_RTC_MINUTES(RTC_Bcd2ToByte(sAlarm->AlarmTime.Minutes))); + assert_param(IS_RTC_SECONDS(RTC_Bcd2ToByte(sAlarm->AlarmTime.Seconds))); + + if(sAlarm->AlarmDateWeekDaySel == RTC_ALARMDATEWEEKDAYSEL_DATE) + { + tmpreg = RTC_Bcd2ToByte(sAlarm->AlarmDateWeekDay); + assert_param(IS_RTC_ALARM_DATE_WEEKDAY_DATE(tmpreg)); + } + else + { + tmpreg = RTC_Bcd2ToByte(sAlarm->AlarmDateWeekDay); + assert_param(IS_RTC_ALARM_DATE_WEEKDAY_WEEKDAY(tmpreg)); + } + + tmpreg = (((uint32_t)(sAlarm->AlarmTime.Hours) << 16) | \ + ((uint32_t)(sAlarm->AlarmTime.Minutes) << 8) | \ + ((uint32_t) sAlarm->AlarmTime.Seconds) | \ + ((uint32_t)(sAlarm->AlarmTime.TimeFormat) << 16) | \ + ((uint32_t)(sAlarm->AlarmDateWeekDay) << 24) | \ + ((uint32_t)sAlarm->AlarmDateWeekDaySel) | \ + ((uint32_t)sAlarm->AlarmMask)); + } + + /* Configure the Alarm A or Alarm B Sub Second registers */ + subsecondtmpreg = (uint32_t)((uint32_t)(sAlarm->AlarmTime.SubSeconds) | (uint32_t)(sAlarm->AlarmSubSecondMask)); + + /* Disable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + /* Configure the Alarm register */ + if(sAlarm->Alarm == RTC_ALARM_A) + { + /* Disable the Alarm A interrupt */ + __HAL_RTC_ALARMA_DISABLE(hrtc); + + /* In case of interrupt mode is used, the interrupt source must disabled */ + __HAL_RTC_ALARM_DISABLE_IT(hrtc, RTC_IT_ALRA); + + tickstart = HAL_GetTick(); + /* Wait till RTC ALRAWF flag is set and if Time out is reached exit */ + while(__HAL_RTC_ALARM_GET_FLAG(hrtc, RTC_FLAG_ALRAWF) == RESET) + { + if((HAL_GetTick() - tickstart ) > RTC_TIMEOUT_VALUE) + { + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + hrtc->State = HAL_RTC_STATE_TIMEOUT; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_TIMEOUT; + } + } + + hrtc->Instance->ALRMAR = (uint32_t)tmpreg; + /* Configure the Alarm A Sub Second register */ + hrtc->Instance->ALRMASSR = subsecondtmpreg; + /* Configure the Alarm state: Enable Alarm */ + __HAL_RTC_ALARMA_ENABLE(hrtc); + } + else + { + /* Disable the Alarm B interrupt */ + __HAL_RTC_ALARMB_DISABLE(hrtc); + + /* In case of interrupt mode is used, the interrupt source must disabled */ + __HAL_RTC_ALARM_DISABLE_IT(hrtc, RTC_IT_ALRB); + + tickstart = HAL_GetTick(); + /* Wait till RTC ALRBWF flag is set and if Time out is reached exit */ + while(__HAL_RTC_ALARM_GET_FLAG(hrtc, RTC_FLAG_ALRBWF) == RESET) + { + if((HAL_GetTick() - tickstart ) > RTC_TIMEOUT_VALUE) + { + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + hrtc->State = HAL_RTC_STATE_TIMEOUT; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_TIMEOUT; + } + } + + hrtc->Instance->ALRMBR = (uint32_t)tmpreg; + /* Configure the Alarm B Sub Second register */ + hrtc->Instance->ALRMBSSR = subsecondtmpreg; + /* Configure the Alarm state: Enable Alarm */ + __HAL_RTC_ALARMB_ENABLE(hrtc); + } + + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_OK; +} + +/** + * @brief Sets the specified RTC Alarm with Interrupt + * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @param sAlarm: Pointer to Alarm structure + * @param Format: Specifies the format of the entered parameters. + * This parameter can be one of the following values: + * @arg FORMAT_BIN: Binary data format + * @arg FORMAT_BCD: BCD data format + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTC_SetAlarm_IT(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef *sAlarm, uint32_t Format) +{ + uint32_t tickstart; + uint32_t tmpreg = 0, subsecondtmpreg = 0; + + /* Check the parameters */ + assert_param(IS_RTC_FORMAT(Format)); + assert_param(IS_ALARM(sAlarm->Alarm)); + assert_param(IS_ALARM_MASK(sAlarm->AlarmMask)); + assert_param(IS_RTC_ALARM_DATE_WEEKDAY_SEL(sAlarm->AlarmDateWeekDaySel)); + assert_param(IS_RTC_ALARM_SUB_SECOND_VALUE(sAlarm->AlarmTime.SubSeconds)); + assert_param(IS_RTC_ALARM_SUB_SECOND_MASK(sAlarm->AlarmSubSecondMask)); + + /* Process Locked */ + __HAL_LOCK(hrtc); + + hrtc->State = HAL_RTC_STATE_BUSY; + + if(Format == FORMAT_BIN) + { + if((hrtc->Instance->CR & RTC_CR_FMT) != (uint32_t)RESET) + { + assert_param(IS_RTC_HOUR12(sAlarm->AlarmTime.Hours)); + assert_param(IS_RTC_HOURFORMAT12(sAlarm->AlarmTime.TimeFormat)); + } + else + { + sAlarm->AlarmTime.TimeFormat = 0x00; + assert_param(IS_RTC_HOUR24(sAlarm->AlarmTime.Hours)); + } + assert_param(IS_RTC_MINUTES(sAlarm->AlarmTime.Minutes)); + assert_param(IS_RTC_SECONDS(sAlarm->AlarmTime.Seconds)); + + if(sAlarm->AlarmDateWeekDaySel == RTC_ALARMDATEWEEKDAYSEL_DATE) + { + assert_param(IS_RTC_ALARM_DATE_WEEKDAY_DATE(sAlarm->AlarmDateWeekDay)); + } + else + { + assert_param(IS_RTC_ALARM_DATE_WEEKDAY_WEEKDAY(sAlarm->AlarmDateWeekDay)); + } + tmpreg = (((uint32_t)RTC_ByteToBcd2(sAlarm->AlarmTime.Hours) << 16) | \ + ((uint32_t)RTC_ByteToBcd2(sAlarm->AlarmTime.Minutes) << 8) | \ + ((uint32_t)RTC_ByteToBcd2(sAlarm->AlarmTime.Seconds)) | \ + ((uint32_t)(sAlarm->AlarmTime.TimeFormat) << 16) | \ + ((uint32_t)RTC_ByteToBcd2(sAlarm->AlarmDateWeekDay) << 24) | \ + ((uint32_t)sAlarm->AlarmDateWeekDaySel) | \ + ((uint32_t)sAlarm->AlarmMask)); + } + else + { + if((hrtc->Instance->CR & RTC_CR_FMT) != (uint32_t)RESET) + { + tmpreg = RTC_Bcd2ToByte(sAlarm->AlarmTime.Hours); + assert_param(IS_RTC_HOUR12(tmpreg)); + assert_param(IS_RTC_HOURFORMAT12(sAlarm->AlarmTime.TimeFormat)); + } + else + { + sAlarm->AlarmTime.TimeFormat = 0x00; + assert_param(IS_RTC_HOUR24(RTC_Bcd2ToByte(sAlarm->AlarmTime.Hours))); + } + + assert_param(IS_RTC_MINUTES(RTC_Bcd2ToByte(sAlarm->AlarmTime.Minutes))); + assert_param(IS_RTC_SECONDS(RTC_Bcd2ToByte(sAlarm->AlarmTime.Seconds))); + + if(sAlarm->AlarmDateWeekDaySel == RTC_ALARMDATEWEEKDAYSEL_DATE) + { + tmpreg = RTC_Bcd2ToByte(sAlarm->AlarmDateWeekDay); + assert_param(IS_RTC_ALARM_DATE_WEEKDAY_DATE(tmpreg)); + } + else + { + tmpreg = RTC_Bcd2ToByte(sAlarm->AlarmDateWeekDay); + assert_param(IS_RTC_ALARM_DATE_WEEKDAY_WEEKDAY(tmpreg)); + } + tmpreg = (((uint32_t)(sAlarm->AlarmTime.Hours) << 16) | \ + ((uint32_t)(sAlarm->AlarmTime.Minutes) << 8) | \ + ((uint32_t) sAlarm->AlarmTime.Seconds) | \ + ((uint32_t)(sAlarm->AlarmTime.TimeFormat) << 16) | \ + ((uint32_t)(sAlarm->AlarmDateWeekDay) << 24) | \ + ((uint32_t)sAlarm->AlarmDateWeekDaySel) | \ + ((uint32_t)sAlarm->AlarmMask)); + } + /* Configure the Alarm A or Alarm B Sub Second registers */ + subsecondtmpreg = (uint32_t)((uint32_t)(sAlarm->AlarmTime.SubSeconds) | (uint32_t)(sAlarm->AlarmSubSecondMask)); + + /* Disable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + /* Configure the Alarm register */ + if(sAlarm->Alarm == RTC_ALARM_A) + { + /* Disable the Alarm A interrupt */ + __HAL_RTC_ALARMA_DISABLE(hrtc); + + /* Clear flag alarm A */ + __HAL_RTC_ALARM_CLEAR_FLAG(hrtc, RTC_FLAG_ALRAF); + + tickstart = HAL_GetTick(); + /* Wait till RTC ALRAWF flag is set and if Time out is reached exit */ + while(__HAL_RTC_ALARM_GET_FLAG(hrtc, RTC_FLAG_ALRAWF) == RESET) + { + if((HAL_GetTick() - tickstart ) > RTC_TIMEOUT_VALUE) + { + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + hrtc->State = HAL_RTC_STATE_TIMEOUT; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_TIMEOUT; + } + } + + hrtc->Instance->ALRMAR = (uint32_t)tmpreg; + /* Configure the Alarm A Sub Second register */ + hrtc->Instance->ALRMASSR = subsecondtmpreg; + /* Configure the Alarm state: Enable Alarm */ + __HAL_RTC_ALARMA_ENABLE(hrtc); + /* Configure the Alarm interrupt */ + __HAL_RTC_ALARM_ENABLE_IT(hrtc,RTC_IT_ALRA); + } + else + { + /* Disable the Alarm B interrupt */ + __HAL_RTC_ALARMB_DISABLE(hrtc); + + /* Clear flag alarm B */ + __HAL_RTC_ALARM_CLEAR_FLAG(hrtc, RTC_FLAG_ALRBF); + + tickstart = HAL_GetTick(); + /* Wait till RTC ALRBWF flag is set and if Time out is reached exit */ + while(__HAL_RTC_ALARM_GET_FLAG(hrtc, RTC_FLAG_ALRBWF) == RESET) + { + if((HAL_GetTick() - tickstart ) > RTC_TIMEOUT_VALUE) + { + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + hrtc->State = HAL_RTC_STATE_TIMEOUT; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_TIMEOUT; + } + } + + hrtc->Instance->ALRMBR = (uint32_t)tmpreg; + /* Configure the Alarm B Sub Second register */ + hrtc->Instance->ALRMBSSR = subsecondtmpreg; + /* Configure the Alarm state: Enable Alarm */ + __HAL_RTC_ALARMB_ENABLE(hrtc); + /* Configure the Alarm interrupt */ + __HAL_RTC_ALARM_ENABLE_IT(hrtc, RTC_IT_ALRB); + } + + /* RTC Alarm Interrupt Configuration: EXTI configuration */ + __HAL_RTC_EXTI_ENABLE_IT(RTC_EXTI_LINE_ALARM_EVENT); + + EXTI->RTSR |= RTC_EXTI_LINE_ALARM_EVENT; + + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + hrtc->State = HAL_RTC_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_OK; +} + +/** + * @brief Deactive the specified RTC Alarm + * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @param Alarm: Specifies the Alarm. + * This parameter can be one of the following values: + * @arg ALARM_A : AlarmA + * @arg ALARM_B : AlarmB + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTC_DeactivateAlarm(RTC_HandleTypeDef *hrtc, uint32_t Alarm) +{ + uint32_t tickstart; + + /* Check the parameters */ + assert_param(IS_ALARM(Alarm)); + + /* Process Locked */ + __HAL_LOCK(hrtc); + + hrtc->State = HAL_RTC_STATE_BUSY; + + /* Disable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + if(Alarm == RTC_ALARM_A) + { + /* AlarmA */ + __HAL_RTC_ALARMA_DISABLE(hrtc); + + /* In case of interrupt mode is used, the interrupt source must disabled */ + __HAL_RTC_ALARM_DISABLE_IT(hrtc, RTC_IT_ALRA); + + tickstart = HAL_GetTick(); + + /* Wait till RTC ALRxWF flag is set and if Time out is reached exit */ + while(__HAL_RTC_ALARM_GET_FLAG(hrtc, RTC_FLAG_ALRAWF) == RESET) + { + if((int32_t) (HAL_GetTick() - tickstart ) >= RTC_TIMEOUT_VALUE) + { + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + hrtc->State = HAL_RTC_STATE_TIMEOUT; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_TIMEOUT; + } + } + } + else + { + /* AlarmB */ + __HAL_RTC_ALARMB_DISABLE(hrtc); + + /* In case of interrupt mode is used, the interrupt source must disabled */ + __HAL_RTC_ALARM_DISABLE_IT(hrtc,RTC_IT_ALRB); + + tickstart = HAL_GetTick(); + + /* Wait till RTC ALRxWF flag is set and if Time out is reached exit */ + while(__HAL_RTC_ALARM_GET_FLAG(hrtc, RTC_FLAG_ALRBWF) == RESET) + { + if((HAL_GetTick() - tickstart ) > RTC_TIMEOUT_VALUE) + { + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + hrtc->State = HAL_RTC_STATE_TIMEOUT; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_TIMEOUT; + } + } + } + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + hrtc->State = HAL_RTC_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_OK; +} + +/** + * @brief Gets the RTC Alarm value and masks. + * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @param sAlarm: Pointer to Date structure + * @param Alarm: Specifies the Alarm. + * This parameter can be one of the following values: + * @arg ALARM_A: AlarmA + * @arg ALARM_B: AlarmB + * @param Format: Specifies the format of the entered parameters. + * This parameter can be one of the following values: + * @arg FORMAT_BIN: Binary data format + * @arg FORMAT_BCD: BCD data format + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTC_GetAlarm(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef *sAlarm, uint32_t Alarm, uint32_t Format) +{ + uint32_t tmpreg = 0, subsecondtmpreg = 0; + + /* Check the parameters */ + assert_param(IS_RTC_FORMAT(Format)); + assert_param(IS_ALARM(Alarm)); + + if(Alarm == RTC_ALARM_A) + { + /* AlarmA */ + sAlarm->Alarm = RTC_ALARM_A; + + tmpreg = (uint32_t)(hrtc->Instance->ALRMAR); + subsecondtmpreg = (uint32_t)((hrtc->Instance->ALRMASSR ) & RTC_ALRMASSR_SS); + } + else + { + sAlarm->Alarm = RTC_ALARM_B; + + tmpreg = (uint32_t)(hrtc->Instance->ALRMBR); + subsecondtmpreg = (uint32_t)((hrtc->Instance->ALRMBSSR) & RTC_ALRMBSSR_SS); + } + + /* Fill the structure with the read parameters */ + sAlarm->AlarmTime.Hours = (uint32_t)((tmpreg & (RTC_ALRMBR_HT | RTC_ALRMBR_HU)) >> 16); + sAlarm->AlarmTime.Minutes = (uint32_t)((tmpreg & (RTC_ALRMBR_MNT | RTC_ALRMBR_MNU)) >> 8); + sAlarm->AlarmTime.Seconds = (uint32_t)(tmpreg & (RTC_ALRMBR_ST | RTC_ALRMBR_SU)); + sAlarm->AlarmTime.TimeFormat = (uint32_t)((tmpreg & RTC_ALRMBR_PM) >> 16); + sAlarm->AlarmTime.SubSeconds = (uint32_t) subsecondtmpreg; + sAlarm->AlarmDateWeekDay = (uint32_t)((tmpreg & (RTC_ALRMBR_DT | RTC_ALRMBR_DU)) >> 24); + sAlarm->AlarmDateWeekDaySel = (uint32_t)(tmpreg & RTC_ALRMBR_WDSEL); + sAlarm->AlarmMask = (uint32_t)(tmpreg & RTC_ALARMMASK_ALL); + + if(Format == FORMAT_BIN) + { + sAlarm->AlarmTime.Hours = RTC_Bcd2ToByte(sAlarm->AlarmTime.Hours); + sAlarm->AlarmTime.Minutes = RTC_Bcd2ToByte(sAlarm->AlarmTime.Minutes); + sAlarm->AlarmTime.Seconds = RTC_Bcd2ToByte(sAlarm->AlarmTime.Seconds); + sAlarm->AlarmDateWeekDay = RTC_Bcd2ToByte(sAlarm->AlarmDateWeekDay); + } + + return HAL_OK; +} + +/** + * @brief This function handles Alarm interrupt request. + * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @retval None + */ +void HAL_RTC_AlarmIRQHandler(RTC_HandleTypeDef* hrtc) +{ + if(__HAL_RTC_ALARM_GET_IT(hrtc, RTC_IT_ALRA)) + { + /* Get the status of the Interrupt */ + if((uint32_t)(hrtc->Instance->CR & RTC_IT_ALRA) != (uint32_t)RESET) + { + /* AlarmA callback */ + HAL_RTC_AlarmAEventCallback(hrtc); + + /* Clear the Alarm interrupt pending bit */ + __HAL_RTC_ALARM_CLEAR_FLAG(hrtc,RTC_FLAG_ALRAF); + } + } + + if(__HAL_RTC_ALARM_GET_IT(hrtc, RTC_IT_ALRB)) + { + /* Get the status of the Interrupt */ + if((uint32_t)(hrtc->Instance->CR & RTC_IT_ALRB) != (uint32_t)RESET) + { + /* AlarmB callback */ + HAL_RTCEx_AlarmBEventCallback(hrtc); + + /* Clear the Alarm interrupt pending bit */ + __HAL_RTC_ALARM_CLEAR_FLAG(hrtc,RTC_FLAG_ALRBF); + } + } + + /* Clear the EXTI's line Flag for RTC Alarm */ + __HAL_RTC_EXTI_CLEAR_FLAG(RTC_EXTI_LINE_ALARM_EVENT); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_READY; +} + +/** + * @brief Alarm A callback. + * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @retval None + */ +__weak void HAL_RTC_AlarmAEventCallback(RTC_HandleTypeDef *hrtc) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_RTC_AlarmAEventCallback could be implemented in the user file + */ +} + +/** + * @brief This function handles AlarmA Polling request. + * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @param Timeout: Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTC_PollForAlarmAEvent(RTC_HandleTypeDef *hrtc, uint32_t Timeout) +{ + + uint32_t tickstart; + + /* Get Timeout value */ + tickstart = HAL_GetTick(); + + while(__HAL_RTC_ALARM_GET_FLAG(hrtc, RTC_FLAG_ALRAF) == RESET) + { + if(Timeout != HAL_MAX_DELAY) + { + if((HAL_GetTick() - tickstart ) > RTC_TIMEOUT_VALUE) + { + hrtc->State = HAL_RTC_STATE_TIMEOUT; + return HAL_TIMEOUT; + } + } + } + + /* Clear the Alarm interrupt pending bit */ + __HAL_RTC_ALARM_CLEAR_FLAG(hrtc, RTC_FLAG_ALRAF); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_READY; + + return HAL_OK; +} + +/** + * @} + */ + +/** @defgroup RTC_Group4 Peripheral Control functions + * @brief Peripheral Control functions + * +@verbatim + =============================================================================== + ##### Peripheral Control functions ##### + =============================================================================== + [..] + This subsection provides functions allowing to + (+) get the RTC state + (+) poll for alarm, timestamp, tamper or wakeup timer events + (+) handle alarm, timestamp, tamper or wakeup timer interrupt request. + +@endverbatim + * @{ + */ + +/** + * @brief Waits until the RTC Time and Date registers (RTC_TR and RTC_DR) are + * synchronized with RTC APB clock. + * @note The RTC Resynchronization mode is write protected, use the + * __HAL_RTC_WRITEPROTECTION_DISABLE() before calling this function. + * @note To read the calendar through the shadow registers after Calendar + * initialization, calendar update or after wakeup from low power modes + * the software must first clear the RSF flag. + * The software must then wait until it is set again before reading + * the calendar, which means that the calendar registers have been + * correctly copied into the RTC_TR and RTC_DR shadow registers. + * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTC_WaitForSynchro(RTC_HandleTypeDef* hrtc) +{ + uint32_t tickstart; + + /* Clear RSF flag */ + hrtc->Instance->ISR &= (uint32_t)RTC_RSF_MASK; + + tickstart = HAL_GetTick(); + + /* Wait the registers to be synchronised */ + while((hrtc->Instance->ISR & RTC_ISR_RSF) == (uint32_t)RESET) + { + if((HAL_GetTick() - tickstart ) > RTC_TIMEOUT_VALUE) + { + return HAL_TIMEOUT; + } + } + + return HAL_OK; +} + +/** @defgroup RTC_Group5 Peripheral State functions + * @brief Peripheral State functions + * +@verbatim + =============================================================================== + ##### Peripheral State functions ##### + =============================================================================== + [..] + This subsection provides functions allowing to + (+) Get RTC state + +@endverbatim + * @{ + */ +/** + * @brief Returns the RTC state. + * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @retval HAL state + */ +HAL_RTCStateTypeDef HAL_RTC_GetState(RTC_HandleTypeDef* hrtc) +{ + return hrtc->State; +} + +/** + * @} + */ + +/** + * @brief Enters the RTC Initialization mode. + * @note The RTC Initialization mode is write protected, use the + * __HAL_RTC_WRITEPROTECTION_DISABLE() before calling this function. + * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @retval HAL status + */ +HAL_StatusTypeDef RTC_EnterInitMode(RTC_HandleTypeDef* hrtc) +{ + uint32_t tickstart; + + /* Check if the Initialization mode is set */ + if((hrtc->Instance->ISR & RTC_ISR_INITF) == (uint32_t)RESET) + { + /* Set the Initialization mode */ + hrtc->Instance->ISR = (uint32_t)RTC_INIT_MASK; + + tickstart = HAL_GetTick(); + /* Wait till RTC is in INIT state and if Time out is reached exit */ + while((hrtc->Instance->ISR & RTC_ISR_INITF) == (uint32_t)RESET) + { + if((int32_t) (HAL_GetTick() - tickstart ) >= RTC_TIMEOUT_VALUE) + { + return HAL_TIMEOUT; + } + } + } + + return HAL_OK; +} + + +/** + * @brief Converts a 2 digit decimal to BCD format. + * @param Value: Byte to be converted + * @retval Converted byte + */ +uint8_t RTC_ByteToBcd2(uint8_t Value) +{ + uint32_t bcdhigh = 0; + + while(Value >= 10) + { + bcdhigh++; + Value -= 10; + } + + return ((uint8_t)(bcdhigh << 4) | Value); +} + +/** + * @brief Converts from 2 digit BCD to Binary. + * @param Value: BCD value to be converted + * @retval Converted word + */ +uint8_t RTC_Bcd2ToByte(uint8_t Value) +{ + uint32_t tmp = 0; + tmp = ((uint8_t)(Value & (uint8_t)0xF0) >> (uint8_t)0x4) * 10; + return (tmp + (Value & (uint8_t)0x0F)); +} + +/** + * @} + */ + +#endif /* HAL_RTC_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_rtc.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_rtc.h new file mode 100644 index 0000000000..f61fa65cea --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_rtc.h @@ -0,0 +1,765 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_rtc.h + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief Header file of RTC HAL module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32L0xx_HAL_RTC_H +#define __STM32L0xx_HAL_RTC_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal_def.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @addtogroup RTC + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/** + * @brief HAL State structures definition + */ +typedef enum +{ + HAL_RTC_STATE_RESET = 0x00, /*!< RTC not yet initialized or disabled */ + HAL_RTC_STATE_READY = 0x01, /*!< RTC initialized and ready for use */ + HAL_RTC_STATE_BUSY = 0x02, /*!< RTC process is ongoing */ + HAL_RTC_STATE_TIMEOUT = 0x03, /*!< RTC timeout state */ + HAL_RTC_STATE_ERROR = 0x04 /*!< RTC error state */ + +}HAL_RTCStateTypeDef; + +/** + * @brief RTC Configuration Structure definition + */ +typedef struct +{ + uint32_t HourFormat; /*!< Specifies the RTC Hour Format. + This parameter can be a value of @ref RTC_Hour_Formats */ + + uint32_t AsynchPrediv; /*!< Specifies the RTC Asynchronous Predivider value. + This parameter must be a number between Min_Data = 0x00 and Max_Data = 0x7F */ + + uint32_t SynchPrediv; /*!< Specifies the RTC Synchronous Predivider value. + This parameter must be a number between Min_Data = 0x00 and Max_Data = 0x7FFF */ + + uint32_t OutPut; /*!< Specifies which signal will be routed to the RTC output. + This parameter can be a value of @ref RTC_Output_selection_Definitions */ + + uint32_t OutPutRemap; /*!< Specifies the remap for RTC output. + This parameter can be a value of @ref RTC_Output_ALARM_OUT_Remap */ + + uint32_t OutPutPolarity; /*!< Specifies the polarity of the output signal. + This parameter can be a value of @ref RTC_Output_Polarity_Definitions */ + + uint32_t OutPutType; /*!< Specifies the RTC Output Pin mode. + This parameter can be a value of @ref RTC_Output_Type_ALARM_OUT */ +}RTC_InitTypeDef; + +/** + * @brief RTC Time structure definition + */ +typedef struct +{ + uint8_t Hours; /*!< Specifies the RTC Time Hour. + This parameter must be a number between Min_Data = 0 and Max_Data = 12 if the RTC_HourFormat_12 is selected. + This parameter must be a number between Min_Data = 0 and Max_Data = 23 if the RTC_HourFormat_24 is selected */ + + uint8_t Minutes; /*!< Specifies the RTC Time Minutes. + This parameter must be a number between Min_Data = 0 and Max_Data = 59 */ + + uint8_t Seconds; /*!< Specifies the RTC Time Seconds. + This parameter must be a number between Min_Data = 0 and Max_Data = 59 */ + + uint32_t SubSeconds; /*!< Specifies the RTC Time SubSeconds. + This parameter must be a number between Min_Data = 0 and Max_Data = 59 */ + + uint8_t TimeFormat; /*!< Specifies the RTC AM/PM Time. + This parameter can be a value of @ref RTC_AM_PM_Definitions */ + + uint32_t DayLightSaving; /*!< Specifies DayLight Save Operation. + This parameter can be a value of @ref RTC_DayLightSaving_Definitions */ + + uint32_t StoreOperation; /*!< Specifies RTC_StoreOperation value to be written in the BCK bit + in CR register to store the operation. + This parameter can be a value of @ref RTC_StoreOperation_Definitions */ +}RTC_TimeTypeDef; + +/** + * @brief RTC Date structure definition + */ +typedef struct +{ + uint8_t WeekDay; /*!< Specifies the RTC Date WeekDay. + This parameter can be a value of @ref RTC_WeekDay_Definitions */ + + uint8_t Month; /*!< Specifies the RTC Date Month (in BCD format). + This parameter can be a value of @ref RTC_Month_Date_Definitions */ + + uint8_t Date; /*!< Specifies the RTC Date. + This parameter must be a number between Min_Data = 1 and Max_Data = 31 */ + + uint8_t Year; /*!< Specifies the RTC Date Year. + This parameter must be a number between Min_Data = 0 and Max_Data = 99 */ + +}RTC_DateTypeDef; + +/** + * @brief RTC Alarm structure definition + */ +typedef struct +{ + RTC_TimeTypeDef AlarmTime; /*!< Specifies the RTC Alarm Time members */ + + uint32_t AlarmMask; /*!< Specifies the RTC Alarm Masks. + This parameter can be a value of @ref RTC_AlarmMask_Definitions */ + + uint32_t AlarmSubSecondMask; /*!< Specifies the RTC Alarm SubSeconds Masks. + This parameter can be a value of @ref RTC_Alarm_Sub_Seconds_Masks_Definitions */ + + uint32_t AlarmDateWeekDaySel; /*!< Specifies the RTC Alarm is on Date or WeekDay. + This parameter can be a value of @ref RTC_AlarmDateWeekDay_Definitions */ + + uint8_t AlarmDateWeekDay; /*!< Specifies the RTC Alarm Date/WeekDay. + If the Alarm Date is selected, this parameter must be set to a value in the 1-31 range. + If the Alarm WeekDay is selected, this parameter can be a value of @ref RTC_WeekDay_Definitions */ + + uint32_t Alarm; /*!< Specifies the alarm . + This parameter can be a value of @ref RTC_Alarms_Definitions */ +}RTC_AlarmTypeDef; + +/** + * @brief Time Handle Structure definition + */ +typedef struct +{ + RTC_TypeDef *Instance; /*!< Register base address */ + + RTC_InitTypeDef Init; /*!< RTC required parameters */ + + HAL_LockTypeDef Lock; /*!< RTC locking object */ + + __IO HAL_RTCStateTypeDef State; /*!< Time communication state */ + +}RTC_HandleTypeDef; + +/* Exported constants --------------------------------------------------------*/ +/** @defgroup RTC_Exported_Constants + * @{ + */ + +/** @defgroup RTC_Hour_Formats + * @{ + */ +#define RTC_HOURFORMAT_24 ((uint32_t)0x00000000) +#define RTC_HOURFORMAT_12 ((uint32_t)0x00000040) + +#define IS_RTC_HOUR_FORMAT(FORMAT) (((FORMAT) == RTC_HOURFORMAT_12) || \ + ((FORMAT) == RTC_HOURFORMAT_24)) +/** + * @} + */ + +/** @defgroup RTC_Output_selection_Definitions + * @{ + */ +#define RTC_OUTPUT_DISABLE ((uint32_t)0x00000000) +#define RTC_OUTPUT_ALARMA ((uint32_t)RTC_CR_OSEL_0) +#define RTC_OUTPUT_ALARMB ((uint32_t)RTC_CR_OSEL_1) +#define RTC_OUTPUT_WAKEUP ((uint32_t)RTC_CR_OSEL) + +#define IS_RTC_OUTPUT(OUTPUT) (((OUTPUT) == RTC_OUTPUT_DISABLE) || \ + ((OUTPUT) == RTC_OUTPUT_ALARMA) || \ + ((OUTPUT) == RTC_OUTPUT_ALARMB) || \ + ((OUTPUT) == RTC_OUTPUT_WAKEUP)) +/** + * @} + */ + +/** @defgroup RTC_Output_Polarity_Definitions + * @{ + */ +#define RTC_OUTPUT_POLARITY_HIGH ((uint32_t)0x00000000) +#define RTC_OUTPUT_POLARITY_LOW ((uint32_t)0x00100000) + +#define IS_RTC_OUTPUT_POL(POL) (((POL) == RTC_OUTPUT_POLARITY_HIGH) || \ + ((POL) == RTC_OUTPUT_POLARITY_LOW)) +/** + * @} + */ + +/** @defgroup RTC_Output_Type_ALARM_OUT + * @{ + */ +#define RTC_OUTPUT_TYPE_OPENDRAIN ((uint32_t)0x00000000) +#define RTC_OUTPUT_TYPE_PUSHPULL ((uint32_t)RTC_OR_ALARMOUTTYPE) + +#define IS_RTC_OUTPUT_TYPE(TYPE) (((TYPE) == RTC_OUTPUT_TYPE_OPENDRAIN) || \ + ((TYPE) == RTC_OUTPUT_TYPE_PUSHPULL)) + +/** + * @} + */ + +/** @defgroup RTC_Output_ALARM_OUT_Remap + * @{ + */ +#define RTC_OUTPUT_REMAP_PC13 ((uint32_t)0x00000000) +#define RTC_OUTPUT_REMAP_PB14 ((uint32_t)RTC_OR_RTC_OUT_RMP) +#define IS_RTC_OUTPUT_REMAP(REMAP) (((REMAP) == RTC_OUTPUT_REMAP_PC13) || \ + ((REMAP) == RTC_OUTPUT_REMAP_PB14)) + +/** + * @} + */ + +/** @defgroup RTC_Asynchronous_Predivider + * @{ + */ +#define IS_RTC_ASYNCH_PREDIV(PREDIV) ((PREDIV) <= (uint32_t)0x7F) +/** + * @} + */ + + +/** @defgroup RTC_Synchronous_Predivider + * @{ + */ +#define IS_RTC_SYNCH_PREDIV(PREDIV) ((PREDIV) <= (uint32_t)0x7FFF) +/** + * @} + */ + +/** @defgroup RTC_Time_Definitions + * @{ + */ +#define IS_RTC_HOUR12(HOUR) (((HOUR) > (uint32_t)0) && ((HOUR) <= (uint32_t)12)) +#define IS_RTC_HOUR24(HOUR) ((HOUR) <= (uint32_t)23) +#define IS_RTC_MINUTES(MINUTES) ((MINUTES) <= (uint32_t)59) +#define IS_RTC_SECONDS(SECONDS) ((SECONDS) <= (uint32_t)59) +/** + * @} + */ + +/** @defgroup RTC_AM_PM_Definitions + * @{ + */ +#define RTC_HOURFORMAT12_AM ((uint8_t)0x00) +#define RTC_HOURFORMAT12_PM ((uint8_t)0x40) + +#define IS_RTC_HOURFORMAT12(PM) (((PM) == RTC_HOURFORMAT12_AM) || ((PM) == RTC_HOURFORMAT12_PM)) +/** + * @} + */ + +/** @defgroup RTC_DayLightSaving_Definitions + * @{ + */ +#define RTC_DAYLIGHTSAVING_SUB1H ((uint32_t)0x00020000) +#define RTC_DAYLIGHTSAVING_ADD1H ((uint32_t)0x00010000) +#define RTC_DAYLIGHTSAVING_NONE ((uint32_t)0x00000000) + +#define IS_RTC_DAYLIGHT_SAVING(SAVE) (((SAVE) == RTC_DAYLIGHTSAVING_SUB1H) || \ + ((SAVE) == RTC_DAYLIGHTSAVING_ADD1H) || \ + ((SAVE) == RTC_DAYLIGHTSAVING_NONE)) +/** + * @} + */ + +/** @defgroup RTC_StoreOperation_Definitions + * @{ + */ +#define RTC_STOREOPERATION_RESET ((uint32_t)0x00000000) +#define RTC_STOREOPERATION_SET ((uint32_t)0x00040000) + +#define IS_RTC_STORE_OPERATION(OPERATION) (((OPERATION) == RTC_STOREOPERATION_RESET) || \ + ((OPERATION) == RTC_STOREOPERATION_SET)) +/** + * @} + */ + +/** @defgroup RTC_Input_parameter_format_definitions + * @{ + */ +#define FORMAT_BIN ((uint32_t)0x000000000) +#define FORMAT_BCD ((uint32_t)0x000000001) + +#define IS_RTC_FORMAT(FORMAT) (((FORMAT) == FORMAT_BIN) || ((FORMAT) == FORMAT_BCD)) +/** + * @} + */ + +/** @defgroup RTC_Year_Date_Definitions + * @{ + */ +#define IS_RTC_YEAR(YEAR) ((YEAR) <= (uint32_t)99) +/** + * @} + */ + +/** @defgroup RTC_Month_Date_Definitions + * @{ + */ + +/* Coded in BCD format */ +#define RTC_MONTH_JANUARY ((uint8_t)0x01) +#define RTC_MONTH_FEBRUARY ((uint8_t)0x02) +#define RTC_MONTH_MARCH ((uint8_t)0x03) +#define RTC_MONTH_APRIL ((uint8_t)0x04) +#define RTC_MONTH_MAY ((uint8_t)0x05) +#define RTC_MONTH_JUNE ((uint8_t)0x06) +#define RTC_MONTH_JULY ((uint8_t)0x07) +#define RTC_MONTH_AUGUST ((uint8_t)0x08) +#define RTC_MONTH_SEPTEMBER ((uint8_t)0x09) +#define RTC_MONTH_OCTOBER ((uint8_t)0x10) +#define RTC_MONTH_NOVEMBER ((uint8_t)0x11) +#define RTC_MONTH_DECEMBER ((uint8_t)0x12) + +#define IS_RTC_MONTH(MONTH) (((MONTH) >= (uint32_t)1) && ((MONTH) <= (uint32_t)12)) +#define IS_RTC_DATE(DATE) (((DATE) >= (uint32_t)1) && ((DATE) <= (uint32_t)31)) +/** + * @} + */ + +/** @defgroup RTC_WeekDay_Definitions + * @{ + */ +#define RTC_WEEKDAY_MONDAY ((uint8_t)0x01) +#define RTC_WEEKDAY_TUESDAY ((uint8_t)0x02) +#define RTC_WEEKDAY_WEDNESDAY ((uint8_t)0x03) +#define RTC_WEEKDAY_THURSDAY ((uint8_t)0x04) +#define RTC_WEEKDAY_FRIDAY ((uint8_t)0x05) +#define RTC_WEEKDAY_SATURDAY ((uint8_t)0x06) +#define RTC_WEEKDAY_SUNDAY ((uint8_t)0x07) + +#define IS_RTC_WEEKDAY(WEEKDAY) (((WEEKDAY) == RTC_WEEKDAY_MONDAY) || \ + ((WEEKDAY) == RTC_WEEKDAY_TUESDAY) || \ + ((WEEKDAY) == RTC_WEEKDAY_WEDNESDAY) || \ + ((WEEKDAY) == RTC_WEEKDAY_THURSDAY) || \ + ((WEEKDAY) == RTC_WEEKDAY_FRIDAY) || \ + ((WEEKDAY) == RTC_WEEKDAY_SATURDAY) || \ + ((WEEKDAY) == RTC_WEEKDAY_SUNDAY)) +/** + * @} + */ + +/** @defgroup RTC_Alarm_Definitions + * @{ + */ +#define IS_RTC_ALARM_DATE_WEEKDAY_DATE(DATE) (((DATE) >(uint32_t) 0) && ((DATE) <= (uint32_t)31)) +#define IS_RTC_ALARM_DATE_WEEKDAY_WEEKDAY(WEEKDAY) (((WEEKDAY) == RTC_WEEKDAY_MONDAY) || \ + ((WEEKDAY) == RTC_WEEKDAY_TUESDAY) || \ + ((WEEKDAY) == RTC_WEEKDAY_WEDNESDAY) || \ + ((WEEKDAY) == RTC_WEEKDAY_THURSDAY) || \ + ((WEEKDAY) == RTC_WEEKDAY_FRIDAY) || \ + ((WEEKDAY) == RTC_WEEKDAY_SATURDAY) || \ + ((WEEKDAY) == RTC_WEEKDAY_SUNDAY)) +/** + * @} + */ + + +/** @defgroup RTC_AlarmDateWeekDay_Definitions + * @{ + */ +#define RTC_ALARMDATEWEEKDAYSEL_DATE ((uint32_t)0x00000000) +#define RTC_ALARMDATEWEEKDAYSEL_WEEKDAY ((uint32_t)0x40000000) + +#define IS_RTC_ALARM_DATE_WEEKDAY_SEL(SEL) (((SEL) == RTC_ALARMDATEWEEKDAYSEL_DATE) || \ + ((SEL) == RTC_ALARMDATEWEEKDAYSEL_WEEKDAY)) +/** + * @} + */ + + +/** @defgroup RTC_AlarmMask_Definitions + * @{ + */ +#define RTC_ALARMMASK_NONE ((uint32_t)0x00000000) +#define RTC_ALARMMASK_DATEWEEKDAY RTC_ALRMAR_MSK4 +#define RTC_ALARMMASK_HOURS RTC_ALRMAR_MSK3 +#define RTC_ALARMMASK_MINUTES RTC_ALRMAR_MSK2 +#define RTC_ALARMMASK_SECONDS RTC_ALRMAR_MSK1 +#define RTC_ALARMMASK_ALL ((uint32_t)0x80808080) + +#define IS_ALARM_MASK(MASK) (((MASK) & 0x7F7F7F7F) == (uint32_t)RESET) +/** + * @} + */ + +/** @defgroup RTC_Alarms_Definitions + * @{ + */ +#define RTC_ALARM_A RTC_CR_ALRAE +#define RTC_ALARM_B RTC_CR_ALRBE + +#define IS_ALARM(ALARM) (((ALARM) == RTC_ALARM_A) || ((ALARM) == RTC_ALARM_B)) +/** + * @} + */ + +/** @defgroup RTC_Alarm_Sub_Seconds_Value + * @{ + */ +#define IS_RTC_ALARM_SUB_SECOND_VALUE(VALUE) ((VALUE) <= (uint32_t)0x00007FFF) +/** + * @} + */ + + /** @defgroup RTC_Alarm_Sub_Seconds_Masks_Definitions + * @{ + */ +#define RTC_ALARMSUBSECONDMASK_ALL ((uint32_t)0x00000000) /*!< All Alarm SS fields are masked. + There is no comparison on sub seconds + for Alarm */ +#define RTC_ALARMSUBSECONDMASK_SS14_1 ((uint32_t)0x01000000) /*!< SS[14:1] are don't care in Alarm + comparison. Only SS[0] is compared. */ +#define RTC_ALARMSUBSECONDMASK_SS14_2 ((uint32_t)0x02000000) /*!< SS[14:2] are don't care in Alarm + comparison. Only SS[1:0] are compared */ +#define RTC_ALARMSUBSECONDMASK_SS14_3 ((uint32_t)0x03000000) /*!< SS[14:3] are don't care in Alarm + comparison. Only SS[2:0] are compared */ +#define RTC_ALARMSUBSECONDMASK_SS14_4 ((uint32_t)0x04000000) /*!< SS[14:4] are don't care in Alarm + comparison. Only SS[3:0] are compared */ +#define RTC_ALARMSUBSECONDMASK_SS14_5 ((uint32_t)0x05000000) /*!< SS[14:5] are don't care in Alarm + comparison. Only SS[4:0] are compared */ +#define RTC_ALARMSUBSECONDMASK_SS14_6 ((uint32_t)0x06000000) /*!< SS[14:6] are don't care in Alarm + comparison. Only SS[5:0] are compared */ +#define RTC_ALARMSUBSECONDMASK_SS14_7 ((uint32_t)0x07000000) /*!< SS[14:7] are don't care in Alarm + comparison. Only SS[6:0] are compared */ +#define RTC_ALARMSUBSECONDMASK_SS14_8 ((uint32_t)0x08000000) /*!< SS[14:8] are don't care in Alarm + comparison. Only SS[7:0] are compared */ +#define RTC_ALARMSUBSECONDMASK_SS14_9 ((uint32_t)0x09000000) /*!< SS[14:9] are don't care in Alarm + comparison. Only SS[8:0] are compared */ +#define RTC_ALARMSUBSECONDMASK_SS14_10 ((uint32_t)0x0A000000) /*!< SS[14:10] are don't care in Alarm + comparison. Only SS[9:0] are compared */ +#define RTC_ALARMSUBSECONDMASK_SS14_11 ((uint32_t)0x0B000000) /*!< SS[14:11] are don't care in Alarm + comparison. Only SS[10:0] are compared */ +#define RTC_ALARMSUBSECONDMASK_SS14_12 ((uint32_t)0x0C000000) /*!< SS[14:12] are don't care in Alarm + comparison.Only SS[11:0] are compared */ +#define RTC_ALARMSUBSECONDMASK_SS14_13 ((uint32_t)0x0D000000) /*!< SS[14:13] are don't care in Alarm + comparison. Only SS[12:0] are compared */ +#define RTC_ALARMSUBSECONDMASK_SS14 ((uint32_t)0x0E000000) /*!< SS[14] is don't care in Alarm + comparison.Only SS[13:0] are compared */ +#define RTC_ALARMSUBSECONDMASK_None ((uint32_t)0x0F000000) /*!< SS[14:0] are compared and must match + to activate alarm. */ + +#define IS_RTC_ALARM_SUB_SECOND_MASK(MASK) (((MASK) == RTC_ALARMSUBSECONDMASK_ALL) || \ + ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_1) || \ + ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_2) || \ + ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_3) || \ + ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_4) || \ + ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_5) || \ + ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_6) || \ + ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_7) || \ + ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_8) || \ + ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_9) || \ + ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_10) || \ + ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_11) || \ + ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_12) || \ + ((MASK) == RTC_ALARMSUBSECONDMASK_SS14_13) || \ + ((MASK) == RTC_ALARMSUBSECONDMASK_SS14) || \ + ((MASK) == RTC_ALARMSUBSECONDMASK_None)) +/** + * @} + */ + +/** @defgroup RTC_Interrupts_Definitions + * @{ + */ +#define RTC_IT_TS ((uint32_t)RTC_CR_TSIE) +#define RTC_IT_WUT ((uint32_t)RTC_CR_WUTIE) +#define RTC_IT_ALRA ((uint32_t)RTC_CR_ALRAIE) +#define RTC_IT_ALRB ((uint32_t)RTC_CR_ALRBIE) +#define RTC_IT_TAMP ((uint32_t)RTC_TAMPCR_TAMPIE) /* Used only to Enable the Tamper Interrupt */ +#define RTC_IT_TAMP1 ((uint32_t)RTC_TAMPCR_TAMP1IE) +#define RTC_IT_TAMP2 ((uint32_t)RTC_TAMPCR_TAMP2IE) +/** + * @} + */ + +/** @defgroup RTC_Flags_Definitions + * @{ + */ +#define RTC_FLAG_RECALPF ((uint32_t)RTC_ISR_RECALPF) +#define RTC_FLAG_TAMP2F ((uint32_t)RTC_ISR_TAMP2F) +#define RTC_FLAG_TAMP1F ((uint32_t)RTC_ISR_TAMP1F) +#define RTC_FLAG_TSOVF ((uint32_t)RTC_ISR_TSOVF) +#define RTC_FLAG_TSF ((uint32_t)RTC_ISR_TSF) +#define RTC_FLAG_WUTF ((uint32_t)RTC_ISR_WUTF) +#define RTC_FLAG_ALRBF ((uint32_t)RTC_ISR_ALRBF) +#define RTC_FLAG_ALRAF ((uint32_t)RTC_ISR_ALRAF) +#define RTC_FLAG_INITF ((uint32_t)RTC_ISR_INITF) +#define RTC_FLAG_RSF ((uint32_t)RTC_ISR_RSF) +#define RTC_FLAG_INITS ((uint32_t)RTC_ISR_INITS) +#define RTC_FLAG_SHPF ((uint32_t)RTC_ISR_SHPF) +#define RTC_FLAG_WUTWF ((uint32_t)RTC_ISR_WUTWF) +#define RTC_FLAG_ALRBWF ((uint32_t)RTC_ISR_ALRBWF) +#define RTC_FLAG_ALRAWF ((uint32_t)RTC_ISR_ALRAWF) +/** + * @} + */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ + +/** @brief Reset RTC handle state + * @param __HANDLE__: specifies the RTC handle. + * @retval None + */ +#define __HAL_RTC_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_RTC_STATE_RESET) + +/** + * @brief Disable the write protection for RTC registers. + * @param __HANDLE__: specifies the RTC handle. + * @retval None + */ +#define __HAL_RTC_WRITEPROTECTION_DISABLE(__HANDLE__) \ + do{ \ + (__HANDLE__)->Instance->WPR = 0xCA; \ + (__HANDLE__)->Instance->WPR = 0x53; \ + } while(0) + +/** + * @brief Enable the write protection for RTC registers. + * @param __HANDLE__: specifies the RTC handle. + * @retval None + */ +#define __HAL_RTC_WRITEPROTECTION_ENABLE(__HANDLE__) \ + do{ \ + (__HANDLE__)->Instance->WPR = 0xFF; \ + } while(0) + +/** + * @brief Enable the RTC ALARMA peripheral. + * @param __HANDLE__: specifies the RTC handle. + * @retval None + */ +#define __HAL_RTC_ALARMA_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= (RTC_CR_ALRAE)) + +/** + * @brief Disable the RTC ALARMA peripheral. + * @param __HANDLE__: specifies the RTC handle. + * @retval None + */ +#define __HAL_RTC_ALARMA_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~(RTC_CR_ALRAE)) + +/** + * @brief Enable the RTC ALARMB peripheral. + * @param __HANDLE__: specifies the RTC handle. + * @retval None + */ +#define __HAL_RTC_ALARMB_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= (RTC_CR_ALRBE)) + +/** + * @brief Disable the RTC ALARMB peripheral. + * @param __HANDLE__: specifies the RTC handle. + * @retval None + */ +#define __HAL_RTC_ALARMB_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~(RTC_CR_ALRBE)) + +/** + * @brief Enable the RTC Alarm interrupt. + * @param __HANDLE__: specifies the RTC handle. + * @param __INTERRUPT__: specifies the RTC Alarm interrupt sources to be enabled or disabled. + * This parameter can be any combination of the following values: + * @arg RTC_IT_ALRA: Alarm A interrupt + * @arg RTC_IT_ALRB: Alarm B interrupt + * @retval None + */ +#define __HAL_RTC_ALARM_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR |= (__INTERRUPT__)) + +/** + * @brief Disable the RTC Alarm interrupt. + * @param __HANDLE__: specifies the RTC handle. + * @param __INTERRUPT__: specifies the RTC Alarm interrupt sources to be enabled or disabled. + * This parameter can be any combination of the following values: + * @arg RTC_IT_ALRA: Alarm A interrupt + * @arg RTC_IT_ALRB: Alarm B interrupt + * @retval None + */ +#define __HAL_RTC_ALARM_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR &= ~(__INTERRUPT__)) + +/** + * @brief Check whether the specified RTC Alarm interrupt has occurred or not. + * @param __HANDLE__: specifies the RTC handle. + * @param __FLAG__: specifies the RTC Alarm interrupt sources to be enabled or disabled. + * This parameter can be: + * @arg RTC_IT_ALRA: Alarm A interrupt + * @arg RTC_IT_ALRB: Alarm B interrupt + * @retval None + */ +#define __HAL_RTC_ALARM_GET_IT(__HANDLE__, __FLAG__) ((((((__HANDLE__)->Instance->ISR)& ((__FLAG__)>> 4)) & 0x0000FFFF) != RESET)? SET : RESET) + +/** + * @brief Get the selected RTC Alarm's flag status. + * @param __HANDLE__: specifies the RTC handle. + * @param __FLAG__: specifies the RTC Alarm Flag sources to be enabled or disabled. + * This parameter can be: + * @arg RTC_FLAG_ALRAF + * @arg RTC_FLAG_ALRBF + * @arg RTC_FLAG_ALRAWF + * @arg RTC_FLAG_ALRBWF + * @retval None + */ +#define __HAL_RTC_ALARM_GET_FLAG(__HANDLE__, __FLAG__) (((((__HANDLE__)->Instance->ISR) & (__FLAG__)) != RESET)? SET : RESET) + +/** + * @brief Clear the RTC Alarm's pending flags. + * @param __HANDLE__: specifies the RTC handle. + * @param __FLAG__: specifies the RTC Alarm Flag sources to be enabled or disabled. + * This parameter can be: + * @arg RTC_FLAG_ALRAF + * @arg RTC_FLAG_ALRBF + * @retval None + */ +#define __HAL_RTC_ALARM_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->ISR) = (~(((__FLAG__) | RTC_ISR_INIT)& 0x0000FFFF)|((__HANDLE__)->Instance->ISR & RTC_ISR_INIT)) + + +#define RTC_EXTI_LINE_ALARM_EVENT ((uint32_t)0x00020000) /*!< External interrupt line 17 Connected to the RTC Alarm event */ +#define RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT ((uint32_t)0x00080000) /*!< External interrupt line 19 Connected to the RTC Tamper and Time Stamp events */ +#define RTC_EXTI_LINE_WAKEUPTIMER_EVENT ((uint32_t)0x00100000) /*!< External interrupt line 20 Connected to the RTC Wakeup event */ + +/** + * @brief Enable the RTC Exti line. + * @param __EXTILINE__: specifies the RTC Exti sources to be enabled or disabled. + * This parameter can be: + * @arg RTC_EXTI_LINE_ALARM_EVENT + * @arg RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT + * @arg RTC_EXTI_LINE_WAKEUPTIMER_EVENT + * @retval None + */ +#define __HAL_RTC_EXTI_ENABLE_IT(__EXTILINE__) (EXTI->IMR |= (__EXTILINE__)) + +/* alias define maintained for legacy */ +#define __HAL_RTC_ENABLE_IT __HAL_RTC_EXTI_ENABLE_IT + +/** + * @brief Disable the RTC Exti line. + * @param __EXTILINE__: specifies the RTC Exti sources to be enabled or disabled. + * This parameter can be: + * @arg RTC_EXTI_LINE_ALARM_EVENT + * @arg RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT + * @arg RTC_EXTI_LINE_WAKEUPTIMER_EVENT + * @retval None + */ +#define __HAL_RTC_EXTI_DISABLE_IT(__EXTILINE__) (EXTI->IMR &= ~(__EXTILINE__)) + +/* alias define maintained for legacy */ +#define __HAL_RTC_DISABLE_IT __HAL_RTC_EXTI_DISABLE_IT + +/** + * @brief Generates a Software interrupt on selected EXTI line. + * @param __EXTILINE__: specifies the RTC Exti sources to be enabled or disabled. + * This parameter can be: + * @arg RTC_EXTI_LINE_ALARM_EVENT + * @arg RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT + * @arg RTC_EXTI_LINE_WAKEUPTIMER_EVENT + * @retval None + */ +#define __HAL_RTC_EXTI_GENERATE_SWIT(__EXTI_LINE__) (EXTI->SWIER |= (__EXTI_LINE__)) + +/** + * @brief Clear the RTC Exti flags. + * @param __FLAG__: specifies the RTC Exti sources to be enabled or disabled. + * This parameter can be: + * @arg RTC_EXTI_LINE_ALARM_EVENT + * @arg RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT + * @arg RTC_EXTI_LINE_WAKEUPTIMER_EVENT + * @retval None + */ +#define __HAL_RTC_EXTI_CLEAR_FLAG(__FLAG__) (EXTI->PR = (__FLAG__)) + +/* alias define maintained for legacy */ +#define __HAL_RTC_CLEAR_FLAG __HAL_RTC_EXTI_CLEAR_FLAG + +/* Include RTC HAL Extension module */ +#include "stm32l0xx_hal_rtc_ex.h" + +/* Exported functions --------------------------------------------------------*/ + +/* Initialization and de-initialization functions ****************************/ +HAL_StatusTypeDef HAL_RTC_Init(RTC_HandleTypeDef *hrtc); +HAL_StatusTypeDef HAL_RTC_DeInit(RTC_HandleTypeDef *hrtc); +void HAL_RTC_MspInit(RTC_HandleTypeDef *hrtc); +void HAL_RTC_MspDeInit(RTC_HandleTypeDef *hrtc); + +/* RTC Time and Date functions ************************************************/ +HAL_StatusTypeDef HAL_RTC_SetTime(RTC_HandleTypeDef *hrtc, RTC_TimeTypeDef *sTime, uint32_t Format); +HAL_StatusTypeDef HAL_RTC_GetTime(RTC_HandleTypeDef *hrtc, RTC_TimeTypeDef *sTime, uint32_t Format); +HAL_StatusTypeDef HAL_RTC_SetDate(RTC_HandleTypeDef *hrtc, RTC_DateTypeDef *sDate, uint32_t Format); +HAL_StatusTypeDef HAL_RTC_GetDate(RTC_HandleTypeDef *hrtc, RTC_DateTypeDef *sDate, uint32_t Format); + +HAL_StatusTypeDef HAL_RTC_SetAlarm(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef *sAlarm, uint32_t Format); +HAL_StatusTypeDef HAL_RTC_SetAlarm_IT(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef *sAlarm, uint32_t Format); +HAL_StatusTypeDef HAL_RTC_DeactivateAlarm(RTC_HandleTypeDef *hrtc, uint32_t Alarm); +HAL_StatusTypeDef HAL_RTC_GetAlarm(RTC_HandleTypeDef *hrtc, RTC_AlarmTypeDef *sAlarm, uint32_t Alarm, uint32_t Format); + +/* Peripheral State functions ***************************************************/ +HAL_StatusTypeDef HAL_RTC_WaitForSynchro(RTC_HandleTypeDef* hrtc); +HAL_RTCStateTypeDef HAL_RTC_GetState(RTC_HandleTypeDef *hrtc); +void HAL_RTC_AlarmIRQHandler(RTC_HandleTypeDef *hrtc); +HAL_StatusTypeDef HAL_RTC_PollForAlarmAEvent(RTC_HandleTypeDef *hrtc, uint32_t Timeout); +void HAL_RTC_AlarmAEventCallback(RTC_HandleTypeDef *hrtc); + +/* Peripheral State functions *************************************************/ +HAL_StatusTypeDef RTC_EnterInitMode(RTC_HandleTypeDef* hrtc); +uint8_t RTC_ByteToBcd2(uint8_t Value); +uint8_t RTC_Bcd2ToByte(uint8_t Value); + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __STM32L0xx_HAL_RTC_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_rtc_ex.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_rtc_ex.c new file mode 100644 index 0000000000..0f61dceaa6 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_rtc_ex.c @@ -0,0 +1,1638 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_rtc_ex.c + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief Extended RTC HAL module driver. + * + * This file provides firmware functions to manage the following + * functionalities of the Real Time Clock (RTC) Extension peripheral: + * + RTC Time Stamp functions + * + RTC Tamper functions + * + RTC Wake-up functions + * + Extension Control functions + * + Extension RTC features functions + * + @verbatim + ============================================================================== + ##### Backup Domain Operating Condition ##### + ============================================================================== + [..] As long as the supply voltage remains in the operating range, + the RTC never stops, regardless of the device status (Run mode, + low power modes or under reset). + + ##### Backup Domain Reset ##### + ================================================================== + [..] The backup domain reset sets all RTC registers and the RCC_CSR register + to their reset values. + [..] A backup domain reset is generated when one of the following events occurs: + (+) Software reset, triggered by setting the RTCRST bit in the + RCC Control Status register (RCC_CSR). + (+) Power reset (BOR/POR/PDR). + + ##### Backup Domain Access ##### + ================================================================== + [..] After reset, the backup domain (RTC registers and RTC backup data registers) + is protected against possible unwanted write accesses. + [..] To enable access to the RTC Domain and RTC registers, proceed as follows: + (+) Enable the Power Controller (PWR) APB1 interface clock using the + __PWR_CLK_ENABLE() function. + (+) Enable access to RTC domain using the HAL_PWR_EnableBkUpAccess() function. + (+) Select the RTC clock source using the __HAL_RCC_RTC_CONFIG() function. + (+) Enable RTC Clock using the __HAL_RCC_RTC_ENABLE() function. + + + ##### How to use this driver ##### + ============================================================================== + [..] + (+) Enable the RTC domain access. + (+) Configure the RTC Prescaler (Asynchronous and Synchronous) and RTC hour + format using the HAL_RTC_Init() function. + + *** Time and Date configuration *** + =================================== + [..] + (+) To configure the RTC Calendar (Time and Date) use the HAL_RTC_SetTime() + and HAL_RTC_SetDate() functions. + (+) To read the RTC Calendar, use the HAL_RTC_GetTime() and HAL_RTC_GetDate() functions. + + *** Alarm configuration *** + =========================== + [..] + (+) To configure the RTC Alarm use the HAL_RTC_SetAlarm() function. + You can also configure the RTC Alarm with interrupt mode using the HAL_RTC_SetAlarm_IT() function. + (+) To read the RTC Alarm, use the HAL_RTC_GetAlarm() function. + + *** RTC Wakeup configuration *** + ================================ + [..] + (+) To configure the RTC Wakeup Clock source and Counter use the HAL_RTC_SetWakeUpTimer() + function. You can also configure the RTC Wakeup timer in interrupt mode + using the HAL_RTC_SetWakeUpTimer_IT() function. + (+) To read the RTC WakeUp Counter register, use the HAL_RTC_GetWakeUpTimer() + function. + + *** Outputs configuration *** + ============================= + [..] The RTC has 2 different outputs: + (+) RTC_ALARM: this output is used to manage the RTC Alarm A, Alarm B + and WaKeUp signals. + To output the selected RTC signal, use the HAL_RTC_Init() function. + (+) RTC_CALIB: this output is 512Hz signal or 1Hz. + To enable the RTC_CALIB, use the HAL_RTCEx_SetCalibrationOutPut() function. + (+) Two pins can be used as RTC_ALARM or RTC_CALIB (PC13, PB14) managed on + the RTC_OR register. + (+) When the RTC_CALIB or RTC_ALARM output is selected, the RTC_OUT pin is + automatically configured in output alternate function. + + *** Smooth digital Calibration configuration *** + ================================================ + [..] + (+) Configure the RTC Original Digital Calibration Value and the corresponding + calibration cycle period (32s,16s and 8s) using the HAL_RTCEx_SetSmoothCalib() + function. + + *** TimeStamp configuration *** + =============================== + [..] + (+) Enables the RTC TimeStamp using the HAL_RTC_SetTimeStamp() function. + You can also configure the RTC TimeStamp with interrupt mode using the + HAL_RTC_SetTimeStamp_IT() function. + (+) To read the RTC TimeStamp Time and Date register, use the HAL_RTC_GetTimeStamp() + function. + + *** Tamper configuration *** + ============================ + [..] + (+) Enable the RTC Tamper and Configure the Tamper filter count, trigger Edge + or Level according to the Tamper filter (if equal to 0 Edge else Level) + value, sampling frequency, NoErase, MaskFlag, precharge or discharge and + Pull-UP using the HAL_RTC_SetTamper() function. You can configure RTC Tamper + with interrupt mode using HAL_RTC_SetTamper_IT() function. + (+) The default configuration of the Tamper erases the backup registers. To avoid + erase, enable the NoErase field on the RTC_TAMPCR register. + + *** Backup Data Registers configuration *** + =========================================== + [..] + (+) To write to the RTC Backup Data registers, use the HAL_RTC_BKUPWrite() + function. + (+) To read the RTC Backup Data registers, use the HAL_RTC_BKUPRead() + function. + (+) The backup registers are reset when a tamper detection event occurs + + + ##### RTC and low power modes ##### + ================================================================== + [..] The MCU can be woken up from a low power mode by an RTC alternate + function. + [..] The RTC alternate functions are the RTC alarms (Alarm A and Alarm B), + RTC wakeup, RTC tamper event detection and RTC time stamp event detection. + These RTC alternate functions can wake up the system from the Stop and + Standby low power modes. + [..] The system can also wake up from low power modes without depending + on an external interrupt (Auto-wakeup mode), by using the RTC alarm + or the RTC wakeup events. + [..] The RTC provides a programmable time base for waking up from the + Stop or Standby mode at regular intervals. + Wakeup from STOP and Standby modes is possible only when the RTC clock source + is LSE or LSI. + + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @defgroup RTCEx + * @brief RTC HAL module driver + * @{ + */ + +#ifdef HAL_RTC_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Masks Definition */ +#define RTC_TR_RESERVED_MASK ((uint32_t)0x007F7F7F) +#define RTC_DR_RESERVED_MASK ((uint32_t)0x00FFFF3F) +#define RTC_INIT_MASK ((uint32_t)0xFFFFFFFF) +#define RTC_RSF_MASK ((uint32_t)0xFFFFFF5F) +#define RTC_FLAGS_MASK ((uint32_t)(RTC_FLAG_TSOVF | RTC_FLAG_TSF | RTC_FLAG_WUTF | \ + RTC_FLAG_ALRBF | RTC_FLAG_INITF | RTC_FLAG_RSF | \ + RTC_FLAG_INITS | RTC_FLAG_WUTWF | RTC_FLAG_ALRBWF | \ + RTC_FLAG_TAMP1F | RTC_FLAG_TAMP2F | \ + RTC_FLAG_RECALPF | RTC_FLAG_SHPF)) + +#define RTC_TIMEOUT_VALUE 1000 +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup RTCEx_Private_Functions + * @{ + */ + +/** @defgroup RTCEx_Group1 RTC TimeStamp and Tamper functions + * @brief RTC TimeStamp and Tamper functions + * +@verbatim + =============================================================================== + ##### RTC TimeStamp and Tamper functions ##### + =============================================================================== +@endverbatim + * @{ + */ + +/** + * @brief Sets TimeStamp. + * @note This API must be called before enabling the TimeStamp feature. + * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @param TimeStampEdge: Specifies the pin edge on which the TimeStamp is + * activated. + * This parameter can be one of the following values: + * @arg RTC_TIMESTAMPEDGE_RISING: the Time stamp event occurs on the + * rising edge of the related pin. + * @arg RTC_TIMESTAMPEDGE_FALLING: the Time stamp event occurs on the + * falling edge of the related pin. + * @param RTC_TimeStampPin: specifies the RTC TimeStamp Pin. + * This parameter can be one of the following values: + * @arg RTC_TIMESTAMPPIN_PC13: PC13 is selected as RTC TimeStamp Pin. + * The RTC TimeStamp Pin is per default PC13, but for reasons of + * compatibility, this parameter is used. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_SetTimeStamp(RTC_HandleTypeDef *hrtc, uint32_t TimeStampEdge, uint32_t RTC_TimeStampPin) +{ + uint32_t tmpreg = 0; + + /* Check the parameters */ + assert_param(IS_TIMESTAMP_EDGE(TimeStampEdge)); + assert_param(IS_RTC_TIMESTAMP_PIN(RTC_TimeStampPin)); + + /* Process Locked */ + __HAL_LOCK(hrtc); + + hrtc->State = HAL_RTC_STATE_BUSY; + + /* Get the RTC_CR register and clear the bits to be configured */ + tmpreg = (uint32_t)(hrtc->Instance->CR & (uint32_t)~(RTC_CR_TSEDGE | RTC_CR_TSE)); + + tmpreg|= TimeStampEdge; + + /* Disable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + /* Configure the Time Stamp TSEDGE and Enable bits */ + hrtc->Instance->CR = (uint32_t)tmpreg; + + __HAL_RTC_TIMESTAMP_ENABLE(hrtc); + + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_OK; +} + +/** + * @brief Sets TimeStamp with Interrupt. + * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @note This API must be called before enabling the TimeStamp feature. + * @param TimeStampEdge: Specifies the pin edge on which the TimeStamp is + * activated. + * This parameter can be one of the following values: + * @arg RTC_TIMESTAMPEDGE_RISING: the Time stamp event occurs on the + * rising edge of the related pin. + * @arg RTC_TIMESTAMPEDGE_FALLING: the Time stamp event occurs on the + * falling edge of the related pin. + * @param RTC_TimeStampPin: Specifies the RTC TimeStamp Pin. + * This parameter can be one of the following values: + * @arg RTC_TIMESTAMPPIN_PC13: PC13 is selected as RTC TimeStamp Pin. + * The RTC TimeStamp Pin is per default PC13, but for reasons of + * compatibility, this parameter is used. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_SetTimeStamp_IT(RTC_HandleTypeDef *hrtc, uint32_t TimeStampEdge, uint32_t RTC_TimeStampPin) +{ + uint32_t tmpreg = 0; + + /* Check the parameters */ + assert_param(IS_TIMESTAMP_EDGE(TimeStampEdge)); + assert_param(IS_RTC_TIMESTAMP_PIN(RTC_TimeStampPin)); + + /* Process Locked */ + __HAL_LOCK(hrtc); + + hrtc->State = HAL_RTC_STATE_BUSY; + + /* Get the RTC_CR register and clear the bits to be configured */ + tmpreg = (uint32_t)(hrtc->Instance->CR & (uint32_t)~(RTC_CR_TSEDGE | RTC_CR_TSE)); + + tmpreg |= TimeStampEdge; + + /* Disable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + /* Configure the Time Stamp TSEDGE and Enable bits */ + hrtc->Instance->CR = (uint32_t)tmpreg; + + __HAL_RTC_TIMESTAMP_ENABLE(hrtc); + + /* Enable IT timestamp */ + __HAL_RTC_TIMESTAMP_ENABLE_IT(hrtc,RTC_IT_TS); + + /* RTC timestamp Interrupt Configuration: EXTI configuration */ + __HAL_RTC_EXTI_ENABLE_IT(RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT); + + EXTI->RTSR |= RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT; + + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + hrtc->State = HAL_RTC_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_OK; +} + +/** + * @brief Deactivates TimeStamp. + * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_DeactivateTimeStamp(RTC_HandleTypeDef *hrtc) +{ + uint32_t tmpreg = 0; + + /* Process Locked */ + __HAL_LOCK(hrtc); + + hrtc->State = HAL_RTC_STATE_BUSY; + + /* Disable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + /* In case of interrupt mode is used, the interrupt source must disabled */ + __HAL_RTC_TIMESTAMP_DISABLE_IT(hrtc, RTC_IT_TS); + + /* Get the RTC_CR register and clear the bits to be configured */ + tmpreg = (uint32_t)(hrtc->Instance->CR & (uint32_t)~(RTC_CR_TSEDGE | RTC_CR_TSE)); + + /* Configure the Time Stamp TSEDGE and Enable bits */ + hrtc->Instance->CR = (uint32_t)tmpreg; + + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + hrtc->State = HAL_RTC_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_OK; +} + +/** + * @brief Gets the RTC TimeStamp value. + * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @param sTimeStamp: Pointer to Time structure + * @param sTimeStampDate: Pointer to Date structure + * @param Format: specifies the format of the entered parameters. + * This parameter can be one of the following values: + * FORMAT_BIN: Binary data format + * FORMAT_BCD: BCD data format + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_GetTimeStamp(RTC_HandleTypeDef *hrtc, RTC_TimeTypeDef* sTimeStamp, RTC_DateTypeDef* sTimeStampDate, uint32_t Format) +{ + uint32_t tmptime = 0, tmpdate = 0; + + /* Check the parameters */ + assert_param(IS_RTC_FORMAT(Format)); + + /* Get the TimeStamp time and date registers values */ + tmptime = (uint32_t)(hrtc->Instance->TSTR & RTC_TR_RESERVED_MASK); + tmpdate = (uint32_t)(hrtc->Instance->TSDR & RTC_DR_RESERVED_MASK); + + /* Fill the Time structure fields with the read parameters */ + sTimeStamp->Hours = (uint8_t)((tmptime & (RTC_TR_HT | RTC_TR_HU)) >> 16); + sTimeStamp->Minutes = (uint8_t)((tmptime & (RTC_TR_MNT | RTC_TR_MNU)) >> 8); + sTimeStamp->Seconds = (uint8_t)(tmptime & (RTC_TR_ST | RTC_TR_SU)); + sTimeStamp->TimeFormat = (uint8_t)((tmptime & (RTC_TR_PM)) >> 16); + sTimeStamp->SubSeconds = (uint32_t) hrtc->Instance->TSSSR; + + /* Fill the Date structure fields with the read parameters */ + sTimeStampDate->Year = 0; + sTimeStampDate->Month = (uint8_t)((tmpdate & (RTC_DR_MT | RTC_DR_MU)) >> 8); + sTimeStampDate->Date = (uint8_t)(tmpdate & (RTC_DR_DT | RTC_DR_DU)); + sTimeStampDate->WeekDay = (uint8_t)((tmpdate & (RTC_DR_WDU)) >> 13); + + /* Check the input parameters format */ + if(Format == FORMAT_BIN) + { + /* Convert the TimeStamp structure parameters to Binary format */ + sTimeStamp->Hours = (uint8_t)RTC_Bcd2ToByte(sTimeStamp->Hours); + sTimeStamp->Minutes = (uint8_t)RTC_Bcd2ToByte(sTimeStamp->Minutes); + sTimeStamp->Seconds = (uint8_t)RTC_Bcd2ToByte(sTimeStamp->Seconds); + + /* Convert the DateTimeStamp structure parameters to Binary format */ + sTimeStampDate->Month = (uint8_t)RTC_Bcd2ToByte(sTimeStampDate->Month); + sTimeStampDate->Date = (uint8_t)RTC_Bcd2ToByte(sTimeStampDate->Date); + sTimeStampDate->WeekDay = (uint8_t)RTC_Bcd2ToByte(sTimeStampDate->WeekDay); + } + + /* Clear the TIMESTAMP Flag */ + __HAL_RTC_TIMESTAMP_CLEAR_FLAG(hrtc, RTC_FLAG_TSF); + + return HAL_OK; +} + +/** + * @brief Sets Tamper + * @note By calling this API we disable the tamper interrupt for all tampers. + * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @param sTamper: Pointer to Tamper Structure. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_SetTamper(RTC_HandleTypeDef *hrtc, RTC_TamperTypeDef* sTamper) +{ + uint32_t tmpreg = 0; + + /* Check the parameters */ + assert_param(IS_TAMPER(sTamper->Tamper)); + assert_param(IS_TAMPER_TRIGGER(sTamper->Trigger)); + assert_param(IS_TAMPER_ERASE_MODE(sTamper->NoErase)); + assert_param(IS_TAMPER_MASKFLAG_STATE(sTamper->MaskFlag)); + assert_param(IS_TAMPER_FILTER(sTamper->Filter)); + assert_param(IS_TAMPER_SAMPLING_FREQ(sTamper->SamplingFrequency)); + assert_param(IS_TAMPER_PRECHARGE_DURATION(sTamper->PrechargeDuration)); + assert_param(IS_TAMPER_PULLUP_STATE(sTamper->TamperPullUp)); + assert_param(IS_TAMPER_TIMESTAMPONTAMPER_DETECTION(sTamper->TimeStampOnTamperDetection)); + + /* Process Locked */ + __HAL_LOCK(hrtc); + + hrtc->State = HAL_RTC_STATE_BUSY; + + /* Configure the tamper trigger */ + if(sTamper->Trigger != RTC_TAMPERTRIGGER_RISINGEDGE) + { + sTamper->Trigger = (uint32_t)(sTamper->Tamper << 1); + } + + if(sTamper->NoErase == RTC_TAMPERERASEBACKUP_ENABLED) + { + /* Configure the RTC_TAMPCR register */ + sTamper->NoErase = RTC_TAMPERERASEBACKUP_ENABLED; + } + else + { + sTamper->NoErase = (uint32_t)(sTamper->Tamper << 17); + } + + if(sTamper->MaskFlag == RTC_MASKTAMPERFLAG_DISABLED) + { + /* Configure the RTC_TAMPCR register */ + sTamper->MaskFlag = RTC_MASKTAMPERFLAG_DISABLED; + } + else + { + sTamper->MaskFlag = (uint32_t)(sTamper->Tamper << 18); + } + + tmpreg = ((uint32_t)sTamper->Tamper | (uint32_t)sTamper->Trigger | (uint32_t)sTamper->NoErase |\ + (uint32_t)sTamper->MaskFlag | (uint32_t)sTamper->Filter | (uint32_t)sTamper->SamplingFrequency |\ + (uint32_t)sTamper->PrechargeDuration | (uint32_t)sTamper->TamperPullUp | sTamper->TimeStampOnTamperDetection); + + hrtc->Instance->TAMPCR &= (uint32_t)~((uint32_t)sTamper->Tamper | (uint32_t)(sTamper->Tamper << 1) | (uint32_t)RTC_TAMPCR_TAMPTS |\ + (uint32_t)RTC_TAMPCR_TAMPFREQ | (uint32_t)RTC_TAMPCR_TAMPFLT | (uint32_t)RTC_TAMPCR_TAMPPRCH |\ + (uint32_t)RTC_TAMPCR_TAMPPUDIS | (uint32_t)RTC_TAMPCR_TAMPIE | (uint32_t)RTC_TAMPCR_TAMP1IE |\ + (uint32_t)RTC_TAMPCR_TAMP2IE); + + hrtc->Instance->TAMPCR |= tmpreg; + + hrtc->State = HAL_RTC_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_OK; +} + +/** + * @brief Sets Tamper with interrupt. + * @note By calling this API we force the tamper interrupt for all tampers. + * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @param sTamper: Pointer to RTC Tamper. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_SetTamper_IT(RTC_HandleTypeDef *hrtc, RTC_TamperTypeDef* sTamper) +{ + uint32_t tmpreg = 0; + + /* Check the parameters */ + assert_param(IS_TAMPER(sTamper->Tamper)); + assert_param(IS_TAMPER_INTERRUPT(sTamper->Interrupt)); + assert_param(IS_TAMPER_TRIGGER(sTamper->Trigger)); + assert_param(IS_TAMPER_ERASE_MODE(sTamper->NoErase)); + assert_param(IS_TAMPER_MASKFLAG_STATE(sTamper->MaskFlag)); + assert_param(IS_TAMPER_FILTER(sTamper->Filter)); + assert_param(IS_TAMPER_SAMPLING_FREQ(sTamper->SamplingFrequency)); + assert_param(IS_TAMPER_PRECHARGE_DURATION(sTamper->PrechargeDuration)); + assert_param(IS_TAMPER_PULLUP_STATE(sTamper->TamperPullUp)); + assert_param(IS_TAMPER_TIMESTAMPONTAMPER_DETECTION(sTamper->TimeStampOnTamperDetection)); + + /* Process Locked */ + __HAL_LOCK(hrtc); + + hrtc->State = HAL_RTC_STATE_BUSY; + + /* Configure the tamper trigger */ + if(sTamper->Trigger != RTC_TAMPERTRIGGER_RISINGEDGE) + { + sTamper->Trigger = (uint32_t)(sTamper->Tamper << 1); + } + + if(sTamper->NoErase == RTC_TAMPERERASEBACKUP_ENABLED) + { + /* Configure the RTC_TAMPCR register */ + sTamper->NoErase = RTC_TAMPERERASEBACKUP_ENABLED; + } + else + { + sTamper->NoErase = (uint32_t)(sTamper->Tamper << 17); + } + + if(sTamper->MaskFlag == RTC_MASKTAMPERFLAG_DISABLED) + { + /* Configure the RTC_TAMPCR register */ + sTamper->MaskFlag = RTC_MASKTAMPERFLAG_DISABLED; + } + else + { + sTamper->MaskFlag = (uint32_t)(sTamper->Tamper << 18); + } + + tmpreg = ((uint32_t)sTamper->Tamper | (uint32_t)sTamper->Interrupt | (uint32_t)sTamper->Trigger | (uint32_t)sTamper->NoErase |\ + (uint32_t)sTamper->MaskFlag | (uint32_t)sTamper->Filter | (uint32_t)sTamper->SamplingFrequency |\ + (uint32_t)sTamper->PrechargeDuration | (uint32_t)sTamper->TamperPullUp | sTamper->TimeStampOnTamperDetection); + + hrtc->Instance->TAMPCR &= (uint32_t)~((uint32_t)sTamper->Tamper | (uint32_t)(sTamper->Tamper << 1) | (uint32_t)RTC_TAMPCR_TAMPTS |\ + (uint32_t)RTC_TAMPCR_TAMPFREQ | (uint32_t)RTC_TAMPCR_TAMPFLT | (uint32_t)RTC_TAMPCR_TAMPPRCH |\ + (uint32_t)RTC_TAMPCR_TAMPPUDIS | (uint32_t)RTC_TAMPCR_TAMPIE | (uint32_t)RTC_TAMPCR_TAMP1IE |\ + (uint32_t)RTC_TAMPCR_TAMP2IE); + + hrtc->Instance->TAMPCR |= tmpreg; + + /* RTC Tamper Interrupt Configuration: EXTI configuration */ + __HAL_RTC_EXTI_ENABLE_IT(RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT); + + EXTI->RTSR |= RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT; + + hrtc->State = HAL_RTC_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_OK; +} + +/** + * @brief Deactivates Tamper. + * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @param Tamper: Selected tamper pin. + * This parameter can be RTC_Tamper_1 and/or RTC_TAMPER_2. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_DeactivateTamper(RTC_HandleTypeDef *hrtc, uint32_t Tamper) +{ + assert_param(IS_TAMPER(Tamper)); + + /* Process Locked */ + __HAL_LOCK(hrtc); + + hrtc->State = HAL_RTC_STATE_BUSY; + + /* Disable the selected Tamper pin */ + hrtc->Instance->TAMPCR &= (uint32_t)~Tamper; + + if (Tamper == RTC_TAMPER_1) + { + /* Disable the Tamper1 interrupt */ + hrtc->Instance->TAMPCR &= (uint32_t)~(RTC_IT_TAMP | RTC_IT_TAMP1); + } + else + { + /* Disable the Tamper2 interrupt */ + hrtc->Instance->TAMPCR &= (uint32_t)~(RTC_IT_TAMP | RTC_IT_TAMP2); + } + + hrtc->State = HAL_RTC_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_OK; +} + +/** + * @brief Sets wake up timer. + * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @param WakeUpCounter: Wake up counter + * @param WakeUpClock: Wake up clock + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_SetWakeUpTimer(RTC_HandleTypeDef *hrtc, uint32_t WakeUpCounter, uint32_t WakeUpClock) +{ + uint32_t tickstart; + + /* Check the parameters */ + assert_param(IS_WAKEUP_CLOCK(WakeUpClock)); + assert_param(IS_WAKEUP_COUNTER(WakeUpCounter)); + + /* Process Locked */ + __HAL_LOCK(hrtc); + + hrtc->State = HAL_RTC_STATE_BUSY; + + /* Disable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + __HAL_RTC_WAKEUPTIMER_DISABLE(hrtc); + + tickstart = HAL_GetTick(); + + /* Wait till RTC WUTWF flag is set and if Time out is reached exit */ + while(__HAL_RTC_WAKEUPTIMER_GET_FLAG(hrtc, RTC_FLAG_WUTWF) == RESET) + { + if((HAL_GetTick() - tickstart ) > RTC_TIMEOUT_VALUE) + { + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + hrtc->State = HAL_RTC_STATE_TIMEOUT; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_TIMEOUT; + } + } + + /* Clear the Wakeup Timer clock source bits in CR register */ + hrtc->Instance->CR &= (uint32_t)~RTC_CR_WUCKSEL; + + /* Configure the clock source */ + hrtc->Instance->CR |= (uint32_t)WakeUpClock; + + /* Configure the Wakeup Timer counter */ + hrtc->Instance->WUTR = (uint32_t)WakeUpCounter; + + /* Enable the Wakeup Timer */ + __HAL_RTC_WAKEUPTIMER_ENABLE(hrtc); + + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + hrtc->State = HAL_RTC_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_OK; +} + +/** + * @brief Sets wake up timer with interrupt + * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @param WakeUpCounter: Wake up counter + * @param WakeUpClock: Wake up clock + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_SetWakeUpTimer_IT(RTC_HandleTypeDef *hrtc, uint32_t WakeUpCounter, uint32_t WakeUpClock) +{ + uint32_t tickstart; + + /* Check the parameters */ + assert_param(IS_WAKEUP_CLOCK(WakeUpClock)); + assert_param(IS_WAKEUP_COUNTER(WakeUpCounter)); + + /* Process Locked */ + __HAL_LOCK(hrtc); + + hrtc->State = HAL_RTC_STATE_BUSY; + + /* Disable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + __HAL_RTC_WAKEUPTIMER_DISABLE(hrtc); + + tickstart = HAL_GetTick(); + + /* Wait till RTC WUTWF flag is set and if Time out is reached exit */ + while(__HAL_RTC_WAKEUPTIMER_GET_FLAG(hrtc, RTC_FLAG_WUTWF) == RESET) + { + if((HAL_GetTick() - tickstart ) > RTC_TIMEOUT_VALUE) + { + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + hrtc->State = HAL_RTC_STATE_TIMEOUT; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_TIMEOUT; + } + } + + /* Configure the Wakeup Timer counter */ + hrtc->Instance->WUTR = (uint32_t)WakeUpCounter; + + /* Clear the Wakeup Timer clock source bits in CR register */ + hrtc->Instance->CR &= (uint32_t)~RTC_CR_WUCKSEL; + + /* Configure the clock source */ + hrtc->Instance->CR |= (uint32_t)WakeUpClock; + + /* RTC WakeUpTimer Interrupt Configuration: EXTI configuration */ + __HAL_RTC_EXTI_ENABLE_IT(RTC_EXTI_LINE_WAKEUPTIMER_EVENT); + + EXTI->RTSR |= RTC_EXTI_LINE_WAKEUPTIMER_EVENT; + + /* Configure the Interrupt in the RTC_CR register */ + __HAL_RTC_WAKEUPTIMER_ENABLE_IT(hrtc,RTC_IT_WUT); + + /* Enable the Wakeup Timer */ + __HAL_RTC_WAKEUPTIMER_ENABLE(hrtc); + + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + hrtc->State = HAL_RTC_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_OK; +} + +/** + * @brief Deactivates wake up timer counter. + * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @retval HAL status + */ +uint32_t HAL_RTCEx_DeactivateWakeUpTimer(RTC_HandleTypeDef *hrtc) +{ + uint32_t tickstart; + + /* Process Locked */ + __HAL_LOCK(hrtc); + + hrtc->State = HAL_RTC_STATE_BUSY; + + /* Disable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + /* Disable the Wakeup Timer */ + __HAL_RTC_WAKEUPTIMER_DISABLE(hrtc); + + /* In case of interrupt mode is used, the interrupt source must disabled */ + __HAL_RTC_WAKEUPTIMER_DISABLE_IT(hrtc,RTC_IT_WUT); + + tickstart = HAL_GetTick(); + /* Wait till RTC WUTWF flag is set and if Time out is reached exit */ + while(__HAL_RTC_WAKEUPTIMER_GET_FLAG(hrtc, RTC_FLAG_WUTWF) == RESET) + { + if((HAL_GetTick() - tickstart ) > RTC_TIMEOUT_VALUE) + { + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + hrtc->State = HAL_RTC_STATE_TIMEOUT; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_TIMEOUT; + } + } + + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + hrtc->State = HAL_RTC_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_OK; +} + +/** + * @brief Gets wake up timer counter. + * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @retval Counter value + */ +uint32_t HAL_RTCEx_GetWakeUpTimer(RTC_HandleTypeDef *hrtc) +{ + /* Get the counter value */ + return ((uint32_t)(hrtc->Instance->WUTR & RTC_WUTR_WUT)); +} + +/** + * @brief Writes a data in a specified RTC Backup data register. + * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @param BackupRegister: RTC Backup data Register number. + * This parameter can be: RTC_BKP_DRx where x can be from 0 to 19 to + * specify the register. + * @param Data: Data to be written in the specified RTC Backup data register. + * @retval None + */ +void HAL_RTCEx_BKUPWrite(RTC_HandleTypeDef *hrtc, uint32_t BackupRegister, uint32_t Data) +{ + uint32_t tmp = 0; + + /* Check the parameters */ + assert_param(IS_RTC_BKP(BackupRegister)); + + tmp = (uint32_t)&(hrtc->Instance->BKP0R); + tmp += (BackupRegister * 4); + + /* Write the specified register */ + *(__IO uint32_t *)tmp = (uint32_t)Data; +} + +/** + * @brief Reads data from the specified RTC Backup data Register. + * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @param BackupRegister: RTC Backup data Register number. + * This parameter can be: RTC_BKP_DRx where x can be from 0 to 19 to + * specify the register. + * @retval Read value + */ +uint32_t HAL_RTCEx_BKUPRead(RTC_HandleTypeDef *hrtc, uint32_t BackupRegister) +{ + uint32_t tmp = 0; + + /* Check the parameters */ + assert_param(IS_RTC_BKP(BackupRegister)); + + tmp = (uint32_t)&(hrtc->Instance->BKP0R); + tmp += (BackupRegister * 4); + + /* Read the specified register */ + return (*(__IO uint32_t *)tmp); +} + +/** + * @brief Sets the Smooth calibration parameters. + * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @param SmoothCalibPeriod: Select the Smooth Calibration Period. + * This parameter can be can be one of the following values : + * @arg RTC_SMOOTHCALIB_PERIOD_32SEC: The smooth calibration periode is 32s. + * @arg RTC_SMOOTHCALIB_PERIOD_16SEC: The smooth calibration periode is 16s. + * @arg RTC_SMOOTHCALIB_PERIOD_8SEC: The smooth calibartion periode is 8s. + * @param SmoothCalibPlusPulses: Select to Set or reset the CALP bit. + * This parameter can be one of the following values: + * @arg RTC_SMOOTHCALIB_PLUSPULSES_SET: Add one RTCCLK puls every 2*11 pulses. + * @arg RTC_SMOOTHCALIB_PLUSPULSES_RESET: No RTCCLK pulses are added. + * @param SmouthCalibMinusPulsesValue: Select the value of CALM[8:0] bits. + * This parameter can be one any value from 0 to 0x000001FF. + * @note To deactivate the smooth calibration, the field SmoothCalibPlusPulses + * must be equal to SMOOTHCALIB_PLUSPULSES_RESET and the field + * SmouthCalibMinusPulsesValue mut be equal to 0. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_SetSmoothCalib(RTC_HandleTypeDef* hrtc, uint32_t SmoothCalibPeriod, uint32_t SmoothCalibPlusPulses, uint32_t SmouthCalibMinusPulsesValue) +{ + uint32_t tickstart; + + /* Check the parameters */ + assert_param(IS_RTC_SMOOTH_CALIB_PERIOD(SmoothCalibPeriod)); + assert_param(IS_RTC_SMOOTH_CALIB_PLUS(SmoothCalibPlusPulses)); + assert_param(IS_RTC_SMOOTH_CALIB_MINUS(SmouthCalibMinusPulsesValue)); + + /* Process Locked */ + __HAL_LOCK(hrtc); + + hrtc->State = HAL_RTC_STATE_BUSY; + + /* Disable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + /* check if a calibration is pending*/ + if((hrtc->Instance->ISR & RTC_ISR_RECALPF) != RESET) + { + tickstart = HAL_GetTick(); + + /* check if a calibration is pending*/ + while((hrtc->Instance->ISR & RTC_ISR_RECALPF) != RESET) + { + if((HAL_GetTick() - tickstart ) > RTC_TIMEOUT_VALUE) + { + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_TIMEOUT; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_TIMEOUT; + } + } + } + + /* Configure the Smooth calibration settings */ + hrtc->Instance->CALR = (uint32_t)((uint32_t)SmoothCalibPeriod | (uint32_t)SmoothCalibPlusPulses | (uint32_t)SmouthCalibMinusPulsesValue); + + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_OK; +} + +/** + * @brief Configures the Synchronization Shift Control Settings. + * @note When REFCKON is set, firmware must not write to Shift control register. + * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @param ShiftAdd1S: Select to add or not 1 second to the time calendar. + * This parameter can be one of the following values : + * @arg RTC_SHIFTADD1S_SET: Add one second to the clock calendar. + * @arg RTC_SHIFTADD1S_RESET: No effect. + * @param ShiftSubFS: Select the number of Second Fractions to substitute. + * This parameter can be one any value from 0 to 0x7FFF. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_SetSynchroShift(RTC_HandleTypeDef* hrtc, uint32_t ShiftAdd1S, uint32_t ShiftSubFS) +{ + uint32_t tickstart; + + /* Check the parameters */ + assert_param(IS_RTC_SHIFT_ADD1S(ShiftAdd1S)); + assert_param(IS_RTC_SHIFT_SUBFS(ShiftSubFS)); + + /* Process Locked */ + __HAL_LOCK(hrtc); + + hrtc->State = HAL_RTC_STATE_BUSY; + + /* Disable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + tickstart = HAL_GetTick(); + + /* Wait until the shift is completed*/ + while((hrtc->Instance->ISR & RTC_ISR_SHPF) != RESET) + { + if((HAL_GetTick() - tickstart ) > RTC_TIMEOUT_VALUE) + { + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + hrtc->State = HAL_RTC_STATE_TIMEOUT; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_TIMEOUT; + } + } + + /* Check if the reference clock detection is disabled */ + if((hrtc->Instance->CR & RTC_CR_REFCKON) == RESET) + { + /* Configure the Shift settings */ + hrtc->Instance->SHIFTR = (uint32_t)(uint32_t)(ShiftSubFS) | (uint32_t)(ShiftAdd1S); + + /* If RTC_CR_BYPSHAD bit = 0, wait for synchro else this check is not needed */ + if((hrtc->Instance->CR & RTC_CR_BYPSHAD) == RESET) + { + if(HAL_RTC_WaitForSynchro(hrtc) != HAL_OK) + { + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + hrtc->State = HAL_RTC_STATE_ERROR; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_ERROR; + } + } + } + else + { + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_ERROR; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_ERROR; + } + + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_OK; +} + +/** + * @brief Configures the Calibration Pinout (RTC_CALIB) Selection (1Hz or 512Hz). + * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @param CalibOutput : Select the Calibration output Selection . + * This parameter can be one of the following values: + * @arg RTC_CALIBOUTPUT_512HZ: A signal has a regular waveform at 512Hz. + * @arg RTC_CALIBOUTPUT_1HZ: A signal has a regular waveform at 1Hz. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_SetCalibrationOutPut(RTC_HandleTypeDef* hrtc, uint32_t CalibOutput) +{ + /* Check the parameters */ + assert_param(IS_RTC_CALIB_OUTPUT(CalibOutput)); + + /* Process Locked */ + __HAL_LOCK(hrtc); + + hrtc->State = HAL_RTC_STATE_BUSY; + + /* Disable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + /* Clear flags before config */ + hrtc->Instance->CR &= (uint32_t)~RTC_CR_COSEL; + + /* Configure the RTC_CR register */ + hrtc->Instance->CR |= (uint32_t)CalibOutput; + + __HAL_RTC_CALIBRATION_OUTPUT_ENABLE(hrtc); + + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_OK; +} + +/** + * @brief Deactivates the Calibration Pinout (RTC_CALIB) Selection (1Hz or 512Hz). + * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_DeactivateCalibrationOutPut(RTC_HandleTypeDef* hrtc) +{ + /* Process Locked */ + __HAL_LOCK(hrtc); + + hrtc->State = HAL_RTC_STATE_BUSY; + + /* Disable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + __HAL_RTC_CALIBRATION_OUTPUT_DISABLE(hrtc); + + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_OK; +} + +/** + * @brief Enables the RTC reference clock detection. + * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_SetRefClock(RTC_HandleTypeDef* hrtc) +{ + /* Process Locked */ + __HAL_LOCK(hrtc); + + hrtc->State = HAL_RTC_STATE_BUSY; + + /* Disable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + /* Set Initialization mode */ + if(RTC_EnterInitMode(hrtc) != HAL_OK) + { + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + /* Set RTC state*/ + hrtc->State = HAL_RTC_STATE_ERROR; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_ERROR; + } + else + { + __HAL_RTC_CLOCKREF_DETECTION_ENABLE(hrtc); + + /* Exit Initialization mode */ + hrtc->Instance->ISR &= (uint32_t)~RTC_ISR_INIT; + } + + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_OK; +} + +/** + * @brief Disable the RTC reference clock detection. + * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_DeactivateRefClock(RTC_HandleTypeDef* hrtc) +{ + /* Process Locked */ + __HAL_LOCK(hrtc); + + hrtc->State = HAL_RTC_STATE_BUSY; + + /* Disable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + /* Set Initialization mode */ + if(RTC_EnterInitMode(hrtc) != HAL_OK) + { + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + /* Set RTC state*/ + hrtc->State = HAL_RTC_STATE_ERROR; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_ERROR; + } + else + { + __HAL_RTC_CLOCKREF_DETECTION_DISABLE(hrtc); + + /* Exit Initialization mode */ + hrtc->Instance->ISR &= (uint32_t)~RTC_ISR_INIT; + } + + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_OK; +} + +/** + * @brief Enables the Bypass Shadow feature. + * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @note When the Bypass Shadow is enabled the calendar value are taken + * directly from the Calendar counter. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_EnableBypassShadow(RTC_HandleTypeDef* hrtc) +{ + /* Process Locked */ + __HAL_LOCK(hrtc); + + hrtc->State = HAL_RTC_STATE_BUSY; + + /* Disable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + /* Set the BYPSHAD bit */ + hrtc->Instance->CR |= (uint8_t)RTC_CR_BYPSHAD; + + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_OK; +} + +/** + * @brief Disables the Bypass Shadow feature. + * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @note When the Bypass Shadow is enabled the calendar value are taken + * directly from the Calendar counter. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_DisableBypassShadow(RTC_HandleTypeDef* hrtc) +{ + /* Process Locked */ + __HAL_LOCK(hrtc); + + hrtc->State = HAL_RTC_STATE_BUSY; + + /* Disable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_DISABLE(hrtc); + + /* Reset the BYPSHAD bit */ + hrtc->Instance->CR &= (uint8_t)~RTC_CR_BYPSHAD; + + /* Enable the write protection for RTC registers */ + __HAL_RTC_WRITEPROTECTION_ENABLE(hrtc); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hrtc); + + return HAL_OK; +} + +/** + * @brief This function handles TimeStamp interrupt request. + * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @retval None + */ +void HAL_RTCEx_TamperTimeStampIRQHandler(RTC_HandleTypeDef *hrtc) +{ + if(__HAL_RTC_TIMESTAMP_GET_IT(hrtc, RTC_IT_TS)) + { + /* Get the status of the Interrupt */ + if((uint32_t)(hrtc->Instance->CR & RTC_IT_TS) != (uint32_t)RESET) + { + /* TIMESTAMP callback */ + HAL_RTCEx_TimeStampEventCallback(hrtc); + + /* Clear the TIMESTAMP interrupt pending bit */ + __HAL_RTC_TIMESTAMP_CLEAR_FLAG(hrtc,RTC_FLAG_TSF); + } + } + + /* Get the status of the Interrupt */ + if(__HAL_RTC_TAMPER_GET_IT(hrtc,RTC_IT_TAMP1)) + { + /* Get the TAMPER Interrupt enable bit and pending bit */ + if(((hrtc->Instance->TAMPCR & (RTC_TAMPCR_TAMPIE))) != (uint32_t)RESET) + { + /* Tamper callback */ + HAL_RTCEx_Tamper1EventCallback(hrtc); + + /* Clear the Tamper interrupt pending bit */ + __HAL_RTC_TAMPER_CLEAR_FLAG(hrtc,RTC_FLAG_TAMP1F); + } + } + + /* Get the status of the Interrupt */ + if(__HAL_RTC_TAMPER_GET_IT(hrtc, RTC_IT_TAMP2)) + { + /* Get the TAMPER Interrupt enable bit and pending bit */ + if(((hrtc->Instance->TAMPCR & RTC_TAMPCR_TAMPIE)) != (uint32_t)RESET) + { + /* Tamper callback */ + HAL_RTCEx_Tamper2EventCallback(hrtc); + + /* Clear the Tamper interrupt pending bit */ + __HAL_RTC_TAMPER_CLEAR_FLAG(hrtc, RTC_FLAG_TAMP2F); + } + } + /* Clear the EXTI's Flag for RTC TimeStamp and Tamper */ + __HAL_RTC_EXTI_CLEAR_FLAG(RTC_EXTI_LINE_TAMPER_TIMESTAMP_EVENT); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_READY; +} + +/** + * @brief This function handles Wake Up Timer interrupt request. + * @param hrtc: RTC handle + * @retval None + */ +void HAL_RTCEx_WakeUpTimerIRQHandler(RTC_HandleTypeDef *hrtc) +{ + if(__HAL_RTC_WAKEUPTIMER_GET_IT(hrtc, RTC_IT_WUT)) + { + /* Get the status of the Interrupt */ + if((uint32_t)(hrtc->Instance->CR & RTC_IT_WUT) != (uint32_t)RESET) + { + /* WAKEUPTIMER callback */ + HAL_RTCEx_WakeUpTimerEventCallback(hrtc); + + /* Clear the WAKEUPTIMER interrupt pending bit */ + __HAL_RTC_WAKEUPTIMER_CLEAR_FLAG(hrtc, RTC_FLAG_WUTF); + } + } + + /* Clear the EXTI's line Flag for RTC WakeUpTimer */ + __HAL_RTC_EXTI_CLEAR_FLAG(RTC_EXTI_LINE_WAKEUPTIMER_EVENT); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_READY; +} + +/** + * @brief Alarm B callback. + * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @retval None + */ +__weak void HAL_RTCEx_AlarmBEventCallback(RTC_HandleTypeDef *hrtc) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_RTC_AlarmBEventCallback could be implemented in the user file + */ +} + +/** + * @brief TimeStamp callback. + * @param hrtc: RTC handle + * @retval None + */ +__weak void HAL_RTCEx_TimeStampEventCallback(RTC_HandleTypeDef *hrtc) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_RTC_TimeStampEventCallback could be implemented in the user file + */ +} + +/** + * @brief Tamper 1 callback. + * @param hrtc: RTC handle + * @retval None + */ +__weak void HAL_RTCEx_Tamper1EventCallback(RTC_HandleTypeDef *hrtc) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_RTC_Tamper1EventCallback could be implemented in the user file + */ +} + +/** + * @brief Tamper 2 callback. + * @param hrtc: RTC handle + * @retval None + */ +__weak void HAL_RTCEx_Tamper2EventCallback(RTC_HandleTypeDef *hrtc) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_RTC_Tamper2EventCallback could be implemented in the user file + */ +} + +/** + * @brief Wake Up Timer callback. + * @param hrtc: RTC handle + * @retval None + */ +__weak void HAL_RTCEx_WakeUpTimerEventCallback(RTC_HandleTypeDef *hrtc) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_RTC_WakeUpTimerEventCallback could be implemented in the user file + */ +} + +/** + * @brief This function handles AlarmB Polling request. + * @param hrtc: pointer to a RTC_HandleTypeDef structure that contains + * the configuration information for RTC. + * @param Timeout: Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_PollForAlarmBEvent(RTC_HandleTypeDef *hrtc, uint32_t Timeout) +{ + uint32_t tickstart; + + /* Get Timeout value */ + tickstart = HAL_GetTick(); + + while(__HAL_RTC_ALARM_GET_FLAG(hrtc, RTC_FLAG_ALRBF) == RESET) + { + if(Timeout != HAL_MAX_DELAY) + { + if((int32_t) (HAL_GetTick() - tickstart ) >= Timeout) + { + hrtc->State = HAL_RTC_STATE_TIMEOUT; + return HAL_TIMEOUT; + } + } + } + + /* Clear the Alarm Flag */ + __HAL_RTC_ALARM_CLEAR_FLAG(hrtc, RTC_FLAG_ALRBF); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_READY; + + return HAL_OK; +} + +/** + * @brief This function handles TimeStamp polling request. + * @param hrtc: RTC handle + * @param Timeout: Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_PollForTimeStampEvent(RTC_HandleTypeDef *hrtc, uint32_t Timeout) +{ + uint32_t tickstart; + + /* Get Timeout value */ + tickstart = HAL_GetTick(); + + while(__HAL_RTC_TIMESTAMP_GET_FLAG(hrtc, RTC_FLAG_TSF) == RESET) + { + if(__HAL_RTC_TIMESTAMP_GET_FLAG(hrtc, RTC_FLAG_TSOVF) != RESET) + { + /* Clear the TIMESTAMP OverRun Flag */ + __HAL_RTC_TIMESTAMP_CLEAR_FLAG(hrtc, RTC_FLAG_TSOVF); + + /* Change TIMESTAMP state */ + hrtc->State = HAL_RTC_STATE_ERROR; + + return HAL_ERROR; + } + + if(Timeout != HAL_MAX_DELAY) + { + if((HAL_GetTick() - tickstart ) > Timeout) + { + hrtc->State = HAL_RTC_STATE_TIMEOUT; + return HAL_TIMEOUT; + } + } + } + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_READY; + + return HAL_OK; +} + +/** + * @brief This function handles Tamper1 Polling. + * @param hrtc: RTC handle + * @param Timeout: Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_PollForTamper1Event(RTC_HandleTypeDef *hrtc, uint32_t Timeout) +{ + uint32_t tickstart; + + /* Get Timeout value */ + tickstart = HAL_GetTick(); + + /* Get the status of the Interrupt */ + while(__HAL_RTC_TAMPER_GET_FLAG(hrtc, RTC_FLAG_TAMP1F)== RESET) + { + if(Timeout != HAL_MAX_DELAY) + { + if((HAL_GetTick() - tickstart ) > Timeout) + { + hrtc->State = HAL_RTC_STATE_TIMEOUT; + return HAL_TIMEOUT; + } + } + } + + /* Clear the Tamper Flag */ + __HAL_RTC_TAMPER_CLEAR_FLAG(hrtc,RTC_FLAG_TAMP1F); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_READY; + + return HAL_OK; +} + +/** + * @brief This function handles Tamper2 Polling. + * @param hrtc: RTC handle + * @param Timeout: Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_PollForTamper2Event(RTC_HandleTypeDef *hrtc, uint32_t Timeout) +{ + uint32_t tickstart; + + /* Get Timeout value */ + tickstart = HAL_GetTick(); + + /* Get the status of the Interrupt */ + while(__HAL_RTC_TAMPER_GET_FLAG(hrtc, RTC_FLAG_TAMP2F) == RESET) + { + if(Timeout != HAL_MAX_DELAY) + { + if((HAL_GetTick() - tickstart ) > Timeout) + { + hrtc->State = HAL_RTC_STATE_TIMEOUT; + return HAL_TIMEOUT; + } + } + } + + /* Clear the Tamper Flag */ + __HAL_RTC_TAMPER_CLEAR_FLAG(hrtc,RTC_FLAG_TAMP2F); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_READY; + + return HAL_OK; +} + + +/** + * @brief This function handles Wake Up Timer Polling. + * @param hrtc: RTC handle + * @param Timeout: Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RTCEx_PollForWakeUpTimerEvent(RTC_HandleTypeDef *hrtc, uint32_t Timeout) +{ + uint32_t tickstart; + + /* Get Timeout value */ + tickstart = HAL_GetTick(); + + while(__HAL_RTC_WAKEUPTIMER_GET_FLAG(hrtc, RTC_FLAG_WUTF) == RESET) + { + if(Timeout != HAL_MAX_DELAY) + { + if((HAL_GetTick() - tickstart ) > Timeout) + { + hrtc->State = HAL_RTC_STATE_TIMEOUT; + + return HAL_TIMEOUT; + } + } + } + + /* Clear the WAKEUPTIMER Flag */ + __HAL_RTC_WAKEUPTIMER_CLEAR_FLAG(hrtc, RTC_FLAG_WUTF); + + /* Change RTC state */ + hrtc->State = HAL_RTC_STATE_READY; + + return HAL_OK; +} + +/** + * @} + */ + +/** + * @} + */ + +#endif /* HAL_RTC_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_rtc_ex.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_rtc_ex.h new file mode 100644 index 0000000000..bd2135ad1a --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_rtc_ex.h @@ -0,0 +1,681 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_rtc_ex.h + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief Header file of PWR HAL Extension module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32L0xx_HAL_RTC_EX_H +#define __STM32L0xx_HAL_RTC_EX_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal_def.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @addtogroup RTCEx + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ + +/** + * @brief RTC Tamper structure definition + */ +typedef struct +{ + uint32_t Tamper; /*!< Specifies the Tamper Pin. + This parameter can be a value of @ref RTCEx_Tamper_Pins_Definitions */ + + uint32_t Interrupt; /*!< Specifies the Tamper Interrupt. + This parameter can be a value of @ref RTCEx_Tamper_Interrupt_Definitions */ + + uint32_t Trigger; /*!< Specifies the Tamper Trigger. + This parameter can be a value of @ref RTCEx_Tamper_Trigger_Definitions */ + + uint32_t NoErase; /*!< Specifies the Tamper no erase mode. + This parameter can be a value of @ref RTCEx_Tamper_EraseBackUp_Definitions */ + + uint32_t MaskFlag; /*!< Specifies the Tamper Flag masking. + This parameter can be a value of @ref RTCEx_Tamper_MaskFlag_Definitions */ + + uint32_t Filter; /*!< Specifies the RTC Filter Tamper. + This parameter can be a value of @ref RTCEx_Tamper_Filter_Definitions */ + + uint32_t SamplingFrequency; /*!< Specifies the sampling frequency. + This parameter can be a value of @ref RTCEx_Tamper_SamplingFrequencies_Definitions */ + + uint32_t PrechargeDuration; /*!< Specifies the Precharge Duration . + This parameter can be a value of @ref RTCEx_Tamper_PinPrechargeDuration_Definitions */ + + uint32_t TamperPullUp; /*!< Specifies the Tamper PullUp . + This parameter can be a value of @ref RTCEx_Tamper_PullUP_Definitions */ + + uint32_t TimeStampOnTamperDetection; /*!< Specifies the TimeStampOnTamperDetection. + This parameter can be a value of @ref RTCEx_Tamper_TimeStampOnTamperDetection_Definitions */ +}RTC_TamperTypeDef; + +/* Exported constants --------------------------------------------------------*/ +/** @defgroup RTCEx_Exported_Constants + * @{ + */ + +/** @defgroup RTCEx_Backup_Registers_Definitions + * @{ + */ +#define RTC_BKP_DR0 ((uint32_t)0x00000000) +#define RTC_BKP_DR1 ((uint32_t)0x00000001) +#define RTC_BKP_DR2 ((uint32_t)0x00000002) +#define RTC_BKP_DR3 ((uint32_t)0x00000003) +#define RTC_BKP_DR4 ((uint32_t)0x00000004) + +#define IS_RTC_BKP(BKP) (((BKP) == RTC_BKP_DR0) || \ + ((BKP) == RTC_BKP_DR1) || \ + ((BKP) == RTC_BKP_DR2) || \ + ((BKP) == RTC_BKP_DR3) || \ + ((BKP) == RTC_BKP_DR4)) +/** + * @} + */ + +/** @defgroup RTCEx_Time_Stamp_Edges_definitions + * @{ + */ +#define RTC_TIMESTAMPEDGE_RISING ((uint32_t)0x00000000) +#define RTC_TIMESTAMPEDGE_FALLING ((uint32_t)0x00000008) + +#define IS_TIMESTAMP_EDGE(EDGE) (((EDGE) == RTC_TIMESTAMPEDGE_RISING) || \ + ((EDGE) == RTC_TIMESTAMPEDGE_FALLING)) +/** + * @} + */ + +/** @defgroup RTCEx_Tamper_Pins_Definitions + * @{ + */ +#define RTC_TAMPER_1 RTC_TAMPCR_TAMP1E +#define RTC_TAMPER_2 RTC_TAMPCR_TAMP2E + +#define IS_TAMPER(TAMPER) ((((TAMPER) & (uint32_t)0xFFFFFFF6) == 0x00) && ((TAMPER) != (uint32_t)RESET)) +/** + * @} + */ + +/** @defgroup RTCEx_Tamper_Interrupt_Definitions + * @{ + */ +#define RTC_TAMPER1_INTERRUPT RTC_TAMPCR_TAMP1IE +#define RTC_TAMPER2_INTERRUPT RTC_TAMPCR_TAMP2IE +#define RTC_TAMPER1_2_INTERRUPT RTC_TAMPCR_TAMPIE + +#define IS_TAMPER_INTERRUPT(INTERRUPT) (((INTERRUPT) == RTC_TAMPER1_INTERRUPT) || \ + ((INTERRUPT) == RTC_TAMPER2_INTERRUPT) || \ + ((INTERRUPT) == RTC_TAMPER1_2_INTERRUPT)) +/** + * @} + */ + +/** @defgroup RTCEx_TimeStamp_Pin_Selection + * @{ + */ +#define RTC_TIMESTAMPPIN_PC13 ((uint32_t)0x00000000) + +#define IS_RTC_TIMESTAMP_PIN(PIN) ((PIN) == RTC_TIMESTAMPPIN_PC13) +/** + * @} + */ + +/** @defgroup RTCEx_Tamper_Trigger_Definitions + * @{ + */ +#define RTC_TAMPERTRIGGER_RISINGEDGE ((uint32_t)0x00000000) +#define RTC_TAMPERTRIGGER_FALLINGEDGE ((uint32_t)0x00000002) +#define RTC_TAMPERTRIGGER_LOWLEVEL RTC_TAMPERTRIGGER_RISINGEDGE +#define RTC_TAMPERTRIGGER_HIGHLEVEL RTC_TAMPERTRIGGER_FALLINGEDGE + +#define IS_TAMPER_TRIGGER(TRIGGER) (((TRIGGER) == RTC_TAMPERTRIGGER_RISINGEDGE) || \ + ((TRIGGER) == RTC_TAMPERTRIGGER_FALLINGEDGE) || \ + ((TRIGGER) == RTC_TAMPERTRIGGER_LOWLEVEL) || \ + ((TRIGGER) == RTC_TAMPERTRIGGER_HIGHLEVEL)) + +/** + * @} + */ + +/** @defgroup RTCEx_Tamper_EraseBackUp_Definitions +* @{ +*/ +#define RTC_TAMPERERASEBACKUP_ENABLED ((uint32_t)0x00000000) +#define RTC_TAMPERERASEBACKUP_DISABLED ((uint32_t)0x00020000) + +#define IS_TAMPER_ERASE_MODE(MODE) (((MODE) == RTC_TAMPERERASEBACKUP_ENABLED) || \ + ((MODE) == RTC_TAMPERERASEBACKUP_DISABLED)) +/** + * @} + */ + +/** @defgroup RTCEx_Tamper_MaskFlag_Definitions +* @{ +*/ +#define RTC_MASKTAMPERFLAG_DISABLED ((uint32_t)0x00000000) +#define RTC_MASKTAMPERFLAG_ENABLED ((uint32_t)0x00040000) + +#define IS_TAMPER_MASKFLAG_STATE(STATE) (((STATE) == RTC_MASKTAMPERFLAG_ENABLED) || \ + ((STATE) == RTC_MASKTAMPERFLAG_DISABLED)) +/** + * @} + */ + +/** @defgroup RTCEx_Tamper_Filter_Definitions + * @{ + */ +#define RTC_TAMPERFILTER_DISABLE ((uint32_t)0x00000000) /*!< Tamper filter is disabled */ + +#define RTC_TAMPERFILTER_2SAMPLE ((uint32_t)0x00000800) /*!< Tamper is activated after 2 + consecutive samples at the active level */ +#define RTC_TAMPERFILTER_4SAMPLE ((uint32_t)0x00001000) /*!< Tamper is activated after 4 + consecutive samples at the active level */ +#define RTC_TAMPERFILTER_8SAMPLE ((uint32_t)0x00001800) /*!< Tamper is activated after 8 + consecutive samples at the active leve. */ + +#define IS_TAMPER_FILTER(FILTER) (((FILTER) == RTC_TAMPERFILTER_DISABLE) || \ + ((FILTER) == RTC_TAMPERFILTER_2SAMPLE) || \ + ((FILTER) == RTC_TAMPERFILTER_4SAMPLE) || \ + ((FILTER) == RTC_TAMPERFILTER_8SAMPLE)) +/** + * @} + */ + +/** @defgroup RTCEx_Tamper_Sampling_Frequencies_Definitions + * @{ + */ +#define RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV32768 ((uint32_t)0x00000000) /*!< Each of the tamper inputs are sampled + with a frequency = RTCCLK / 32768 */ +#define RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV16384 ((uint32_t)0x00000100) /*!< Each of the tamper inputs are sampled + with a frequency = RTCCLK / 16384 */ +#define RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV8192 ((uint32_t)0x00000200) /*!< Each of the tamper inputs are sampled + with a frequency = RTCCLK / 8192 */ +#define RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV4096 ((uint32_t)0x00000300) /*!< Each of the tamper inputs are sampled + with a frequency = RTCCLK / 4096 */ +#define RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV2048 ((uint32_t)0x00000400) /*!< Each of the tamper inputs are sampled + with a frequency = RTCCLK / 2048 */ +#define RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV1024 ((uint32_t)0x00000500) /*!< Each of the tamper inputs are sampled + with a frequency = RTCCLK / 1024 */ +#define RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV512 ((uint32_t)0x00000600) /*!< Each of the tamper inputs are sampled + with a frequency = RTCCLK / 512 */ +#define RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV256 ((uint32_t)0x00000700) /*!< Each of the tamper inputs are sampled + with a frequency = RTCCLK / 256 */ + +#define IS_TAMPER_SAMPLING_FREQ(FREQ) (((FREQ) == RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV32768)|| \ + ((FREQ) == RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV16384)|| \ + ((FREQ) == RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV8192) || \ + ((FREQ) == RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV4096) || \ + ((FREQ) == RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV2048) || \ + ((FREQ) == RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV1024) || \ + ((FREQ) == RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV512) || \ + ((FREQ) == RTC_TAMPERSAMPLINGFREQ_RTCCLK_DIV256)) +/** + * @} + */ + +/** @defgroup RTCEx_Tamper_Pin_Precharge_Duration_Definitions + * @{ + */ +#define RTC_TAMPERPRECHARGEDURATION_1RTCCLK ((uint32_t)0x00000000) /*!< Tamper pins are pre-charged before + sampling during 1 RTCCLK cycle */ +#define RTC_TAMPERPRECHARGEDURATION_2RTCCLK ((uint32_t)0x00002000) /*!< Tamper pins are pre-charged before + sampling during 2 RTCCLK cycles */ +#define RTC_TAMPERPRECHARGEDURATION_4RTCCLK ((uint32_t)0x00004000) /*!< Tamper pins are pre-charged before + sampling during 4 RTCCLK cycles */ +#define RTC_TAMPERPRECHARGEDURATION_8RTCCLK ((uint32_t)0x00006000) /*!< Tamper pins are pre-charged before + sampling during 8 RTCCLK cycles */ + +#define IS_TAMPER_PRECHARGE_DURATION(DURATION) (((DURATION) == RTC_TAMPERPRECHARGEDURATION_1RTCCLK) || \ + ((DURATION) == RTC_TAMPERPRECHARGEDURATION_2RTCCLK) || \ + ((DURATION) == RTC_TAMPERPRECHARGEDURATION_4RTCCLK) || \ + ((DURATION) == RTC_TAMPERPRECHARGEDURATION_8RTCCLK)) +/** + * @} + */ + +/** @defgroup RTCEx_Tamper_TimeStampOnTamperDetection_Definitions + * @{ + */ +#define RTC_TIMESTAMPONTAMPERDETECTION_ENABLE ((uint32_t)RTC_TAMPCR_TAMPTS) /*!< TimeStamp on Tamper Detection event saved */ +#define RTC_TIMESTAMPONTAMPERDETECTION_DISABLE ((uint32_t)0x00000000) /*!< TimeStamp on Tamper Detection event is not saved */ + +#define IS_TAMPER_TIMESTAMPONTAMPER_DETECTION(DETECTION) (((DETECTION) == RTC_TIMESTAMPONTAMPERDETECTION_ENABLE) || \ + ((DETECTION) == RTC_TIMESTAMPONTAMPERDETECTION_DISABLE)) +/** + * @} + */ + +/** @defgroup RTCEx_Tamper_PullUP_Definitions + * @{ + */ +#define RTC_TAMPER_PULLUP_ENABLE ((uint32_t)0x00000000) /*!< TimeStamp on Tamper Detection event saved */ +#define RTC_TAMPER_PULLUP_DISABLE ((uint32_t)RTC_TAMPCR_TAMPPUDIS) /*!< TimeStamp on Tamper Detection event is not saved */ + +#define IS_TAMPER_PULLUP_STATE(STATE) (((STATE) == RTC_TAMPER_PULLUP_ENABLE) || \ + ((STATE) == RTC_TAMPER_PULLUP_DISABLE)) +/** + * @} + */ + +/** @defgroup RTCEx_Wakeup_Timer_Definitions + * @{ + */ +#define RTC_WAKEUPCLOCK_RTCCLK_DIV16 ((uint32_t)0x00000000) +#define RTC_WAKEUPCLOCK_RTCCLK_DIV8 ((uint32_t)0x00000001) +#define RTC_WAKEUPCLOCK_RTCCLK_DIV4 ((uint32_t)0x00000002) +#define RTC_WAKEUPCLOCK_RTCCLK_DIV2 ((uint32_t)0x00000003) +#define RTC_WAKEUPCLOCK_CK_SPRE_16BITS ((uint32_t)0x00000004) +#define RTC_WAKEUPCLOCK_CK_SPRE_17BITS ((uint32_t)0x00000006) + +#define IS_WAKEUP_CLOCK(CLOCK) (((CLOCK) == RTC_WAKEUPCLOCK_RTCCLK_DIV16) || \ + ((CLOCK) == RTC_WAKEUPCLOCK_RTCCLK_DIV8) || \ + ((CLOCK) == RTC_WAKEUPCLOCK_RTCCLK_DIV4) || \ + ((CLOCK) == RTC_WAKEUPCLOCK_RTCCLK_DIV2) || \ + ((CLOCK) == RTC_WAKEUPCLOCK_CK_SPRE_16BITS) || \ + ((CLOCK) == RTC_WAKEUPCLOCK_CK_SPRE_17BITS)) + +#define IS_WAKEUP_COUNTER(COUNTER) ((COUNTER) <= 0xFFFF) +/** + * @} + */ + +/** @defgroup RTCEx_Digital_Calibration_Definitions + * @{ + */ +#define RTC_CALIBSIGN_POSITIVE ((uint32_t)0x00000000) +#define RTC_CALIBSIGN_NEGATIVE ((uint32_t)0x00000080) + +#define IS_RTC_CALIB_SIGN(SIGN) (((SIGN) == RTC_CALIBSIGN_POSITIVE) || \ + ((SIGN) == RTC_CALIBSIGN_NEGATIVE)) + +#define IS_RTC_CALIB_VALUE(VALUE) ((VALUE) < 0x20) +/** + * @} + */ + +/** @defgroup RTCEx_Smooth_calib_period_Definitions + * @{ + */ +#define RTC_SMOOTHCALIB_PERIOD_32SEC ((uint32_t)0x00000000) /*!< If RTCCLK = 32768 Hz, Smooth calibation + period is 32s, else 2exp20 RTCCLK seconds */ +#define RTC_SMOOTHCALIB_PERIOD_16SEC ((uint32_t)0x00002000) /*!< If RTCCLK = 32768 Hz, Smooth calibation + period is 16s, else 2exp19 RTCCLK seconds */ +#define RTC_SMOOTHCALIB_PERIOD_8SEC ((uint32_t)0x00004000) /*!< If RTCCLK = 32768 Hz, Smooth calibation + period is 8s, else 2exp18 RTCCLK seconds */ + +#define IS_RTC_SMOOTH_CALIB_PERIOD(PERIOD) (((PERIOD) == RTC_SMOOTHCALIB_PERIOD_32SEC) || \ + ((PERIOD) == RTC_SMOOTHCALIB_PERIOD_16SEC) || \ + ((PERIOD) == RTC_SMOOTHCALIB_PERIOD_8SEC)) +/** + * @} + */ + +/** @defgroup RTCEx_Smooth_calib_Plus_pulses_Definitions + * @{ + */ +#define RTC_SMOOTHCALIB_PLUSPULSES_SET ((uint32_t)0x00008000) /*!< The number of RTCCLK pulses added + during a X -second window = Y - CALM[8:0] + with Y = 512, 256, 128 when X = 32, 16, 8 */ +#define RTC_SMOOTHCALIB_PLUSPULSES_RESET ((uint32_t)0x00000000) /*!< The number of RTCCLK pulses subbstited + during a 32-second window = CALM[8:0] */ + +#define IS_RTC_SMOOTH_CALIB_PLUS(PLUS) (((PLUS) == RTC_SMOOTHCALIB_PLUSPULSES_SET) || \ + ((PLUS) == RTC_SMOOTHCALIB_PLUSPULSES_RESET)) +/** + * @} + */ + +/** @defgroup RTCEx_Smooth_calib_Minus_pulses_Definitions + * @{ + */ +#define IS_RTC_SMOOTH_CALIB_MINUS(VALUE) ((VALUE) <= 0x000001FF) +/** + * @} + */ + +/** @defgroup RTCEx_Add_1_Second_Parameter_Definitions + * @{ + */ +#define RTC_SHIFTADD1S_RESET ((uint32_t)0x00000000) +#define RTC_SHIFTADD1S_SET ((uint32_t)0x80000000) + +#define IS_RTC_SHIFT_ADD1S(SEL) (((SEL) == RTC_SHIFTADD1S_RESET) || \ + ((SEL) == RTC_SHIFTADD1S_SET)) +/** + * @} + */ + +/** @defgroup RTCEx_Substract_Fraction_Of_Second_Value + * @{ + */ +#define IS_RTC_SHIFT_SUBFS(FS) ((FS) <= 0x00007FFF) +/** + * @} + */ + + /** @defgroup RTCEx_Calib_Output_selection_Definitions + * @{ + */ +#define RTC_CALIBOUTPUT_512HZ ((uint32_t)0x00000000) +#define RTC_CALIBOUTPUT_1HZ ((uint32_t)0x00080000) + +#define IS_RTC_CALIB_OUTPUT(OUTPUT) (((OUTPUT) == RTC_CALIBOUTPUT_512HZ) || \ + ((OUTPUT) == RTC_CALIBOUTPUT_1HZ)) +/** + * @} + */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ +/** @defgroup RTCEx_Exported macro + * @{ + */ + +/** + * @brief Enable the RTC WakeUp Timer peripheral. + * @param __HANDLE__: specifies the RTC handle. + * @retval None + */ +#define __HAL_RTC_WAKEUPTIMER_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= (RTC_CR_WUTE)) + +/** + * @brief Disable the RTC WakeUp Timer peripheral. + * @param __HANDLE__: specifies the RTC handle. + * @retval None + */ +#define __HAL_RTC_WAKEUPTIMER_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~(RTC_CR_WUTE)) + +/** + * @brief Enable the RTC TimeStamp peripheral. + * @param __HANDLE__: specifies the RTC handle. + * @retval None + */ +#define __HAL_RTC_TIMESTAMP_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= (RTC_CR_TSE)) + +/** + * @brief Disable the RTC TimeStamp peripheral. + * @param __HANDLE__: specifies the RTC handle. + * @retval None + */ +#define __HAL_RTC_TIMESTAMP_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~(RTC_CR_TSE)) + +/** + * @brief Enable the RTC calibration output. + * @param __HANDLE__: specifies the RTC handle. + * @retval None + */ +#define __HAL_RTC_CALIBRATION_OUTPUT_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= (RTC_CR_COE)) + +/** + * @brief Disable the calibration output. + * @param __HANDLE__: specifies the RTC handle. + * @retval None + */ +#define __HAL_RTC_CALIBRATION_OUTPUT_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~(RTC_CR_COE)) + +/** + * @brief Enable the clock reference detection. + * @param __HANDLE__: specifies the RTC handle. + * @retval None + */ +#define __HAL_RTC_CLOCKREF_DETECTION_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= (RTC_CR_REFCKON)) + +/** + * @brief Disable the clock reference detection. + * @param __HANDLE__: specifies the RTC handle. + * @retval None + */ +#define __HAL_RTC_CLOCKREF_DETECTION_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= ~(RTC_CR_REFCKON)) + +/** + * @brief Enable the RTC TimeStamp interrupt. + * @param __HANDLE__: specifies the RTC handle. + * @param __INTERRUPT__: specifies the RTC TimeStamp interrupt sources to be enabled or disabled. + * This parameter can be: + * @arg RTC_IT_TS: TimeStamp interrupt + * @retval None + */ +#define __HAL_RTC_TIMESTAMP_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR |= (__INTERRUPT__)) + +/** + * @brief Disable the RTC TimeStamp interrupt. + * @param __HANDLE__: specifies the RTC handle. + * @param __INTERRUPT__: specifies the RTC TimeStamp interrupt sources to be enabled or disabled. + * This parameter can be: + * @arg RTC_IT_TS: TimeStamp interrupt + * @retval None + */ +#define __HAL_RTC_TIMESTAMP_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR &= ~(__INTERRUPT__)) + +/** + * @brief Enable the RTC WakeUpTimer interrupt. + * @param __HANDLE__: specifies the RTC handle. + * @param __INTERRUPT__: specifies the RTC WakeUpTimer interrupt sources to be enabled or disabled. + * This parameter can be: + * @arg RTC_IT_WUT: WakeUpTimer A interrupt + * @retval None + */ +#define __HAL_RTC_WAKEUPTIMER_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR |= (__INTERRUPT__)) + +/** + * @brief Disable the RTC WakeUpTimer interrupt. + * @param __HANDLE__: specifies the RTC handle. + * @param __INTERRUPT__: specifies the RTC WakeUpTimer interrupt sources to be enabled or disabled. + * This parameter can be: + * @arg RTC_IT_WUT: WakeUpTimer A interrupt + * @retval None + */ +#define __HAL_RTC_WAKEUPTIMER_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR &= ~(__INTERRUPT__)) + +/** + * @brief Check whether the specified RTC Tamper interrupt has occurred or not. + * @param __HANDLE__: specifies the RTC handle. + * @param __FLAG__: specifies the RTC Tamper interrupt sources to be enabled or disabled. + * This parameter can be: + * @arg RTC_IT_TAMP1 + * @retval None + */ +#define __HAL_RTC_TAMPER_GET_IT(__HANDLE__, __FLAG__) (((((__HANDLE__)->Instance->ISR) & ((__FLAG__)>> 4)) != RESET)? SET : RESET) + +/** + * @brief Check whether the specified RTC WakeUpTimer interrupt has occurred or not. + * @param __HANDLE__: specifies the RTC handle. + * @param __FLAG__: specifies the RTC WakeUpTimer interrupt sources to be enabled or disabled. + * This parameter can be: + * @arg RTC_IT_WUT: WakeUpTimer A interrupt + * @retval None + */ +#define __HAL_RTC_WAKEUPTIMER_GET_IT(__HANDLE__, __FLAG__) (((((__HANDLE__)->Instance->ISR) & ((__FLAG__)>> 4)) != RESET)? SET : RESET) + +/** + * @brief Check whether the specified RTC TimeStamp interrupt has occurred or not. + * @param __HANDLE__: specifies the RTC handle. + * @param __FLAG__: specifies the RTC TimeStamp interrupt sources to be enabled or disabled. + * This parameter can be: + * @arg RTC_IT_TS: TimeStamp interrupt + * @retval None + */ +#define __HAL_RTC_TIMESTAMP_GET_IT(__HANDLE__, __FLAG__) (((((__HANDLE__)->Instance->ISR) & ((__FLAG__)>> 4)) != RESET)? SET : RESET) + +/** + * @brief Get the selected RTC TimeStamp's flag status. + * @param __HANDLE__: specifies the RTC handle. + * @param __FLAG__: specifies the RTC TimeStamp Flag sources to be enabled or disabled. + * This parameter can be: + * @arg RTC_FLAG_TSF + * @arg RTC_FLAG_TSOVF + * @retval None + */ +#define __HAL_RTC_TIMESTAMP_GET_FLAG(__HANDLE__, __FLAG__) (((((__HANDLE__)->Instance->ISR) & (__FLAG__)) != RESET)? SET : RESET) + +/** + * @brief Get the selected RTC WakeUpTimer's flag status. + * @param __HANDLE__: specifies the RTC handle. + * @param __FLAG__: specifies the RTC WakeUpTimer Flag sources to be enabled or disabled. + * This parameter can be: + * @arg RTC_FLAG_WUTF + * @arg RTC_FLAG_WUTWF + * @retval None + */ +#define __HAL_RTC_WAKEUPTIMER_GET_FLAG(__HANDLE__, __FLAG__) (((((__HANDLE__)->Instance->ISR) & (__FLAG__)) != RESET)? SET : RESET) + +/** + * @brief Get the selected RTC Tamper's flag status. + * @param __HANDLE__: specifies the RTC handle. + * @param __FLAG__: specifies the RTC Tamper Flag sources to be enabled or disabled. + * This parameter can be: + * @arg RTC_FLAG_TAMP1F + * @retval None + */ +#define __HAL_RTC_TAMPER_GET_FLAG(__HANDLE__, __FLAG__) (((((__HANDLE__)->Instance->ISR) & (__FLAG__)) != RESET)? SET : RESET) + +/** + * @brief Get the selected RTC shift operation's flag status. + * @param __HANDLE__: specifies the RTC handle. + * @param __FLAG__: specifies the RTC shift operation Flag is pending or not. + * This parameter can be: + * @arg RTC_FLAG_SHPF + * @retval None + */ +#define __HAL_RTC_SHIFT_GET_FLAG(__HANDLE__, __FLAG__) (((((__HANDLE__)->Instance->ISR) & (__FLAG__)) != RESET)? SET : RESET) + +/** + * @brief Clear the RTC Time Stamp's pending flags. + * @param __HANDLE__: specifies the RTC handle. + * @param __FLAG__: specifies the RTC Alarm Flag sources to be enabled or disabled. + * This parameter can be: + * @arg RTC_FLAG_TSF + * @retval None + */ +#define __HAL_RTC_TIMESTAMP_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->ISR) = (~(((__FLAG__) | RTC_ISR_INIT)& 0x0000FFFF)|((__HANDLE__)->Instance->ISR & RTC_ISR_INIT)) + +/** + * @brief Clear the RTC Tamper's pending flags. + * @param __HANDLE__: specifies the RTC handle. + * @param __FLAG__: specifies the RTC Tamper Flag sources to be enabled or disabled. + * This parameter can be: + * @arg RTC_FLAG_TAMP1F + * @retval None + */ +#define __HAL_RTC_TAMPER_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->ISR) = (~(((__FLAG__) | RTC_ISR_INIT)& 0x0000FFFF)|((__HANDLE__)->Instance->ISR & RTC_ISR_INIT)) + +/** + * @brief Clear the RTC Wake Up timer's pending flags. + * @param __HANDLE__: specifies the RTC handle. + * @param __FLAG__: specifies the RTC Tamper Flag sources to be enabled or disabled. + * This parameter can be: + * @arg RTC_FLAG_WUTF + * @retval None + */ +#define __HAL_RTC_WAKEUPTIMER_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->ISR) = (~(((__FLAG__) | RTC_ISR_INIT)& 0x0000FFFF)|((__HANDLE__)->Instance->ISR & RTC_ISR_INIT)) + +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ + +/* RTC TimeStamp and Tamper functions *****************************************/ +HAL_StatusTypeDef HAL_RTCEx_SetTimeStamp(RTC_HandleTypeDef *hrtc, uint32_t TimeStampEdge, uint32_t RTC_TimeStampPin); +HAL_StatusTypeDef HAL_RTCEx_SetTimeStamp_IT(RTC_HandleTypeDef *hrtc, uint32_t TimeStampEdge, uint32_t RTC_TimeStampPin); +HAL_StatusTypeDef HAL_RTCEx_DeactivateTimeStamp(RTC_HandleTypeDef *hrtc); +HAL_StatusTypeDef HAL_RTCEx_GetTimeStamp(RTC_HandleTypeDef *hrtc, RTC_TimeTypeDef *sTimeStamp, RTC_DateTypeDef *sTimeStampDate, uint32_t Format); + +HAL_StatusTypeDef HAL_RTCEx_SetTamper(RTC_HandleTypeDef *hrtc, RTC_TamperTypeDef* sTamper); +HAL_StatusTypeDef HAL_RTCEx_SetTamper_IT(RTC_HandleTypeDef *hrtc, RTC_TamperTypeDef* sTamper); +HAL_StatusTypeDef HAL_RTCEx_DeactivateTamper(RTC_HandleTypeDef *hrtc, uint32_t Tamper); + +HAL_StatusTypeDef HAL_RTCEx_SetWakeUpTimer(RTC_HandleTypeDef *hrtc, uint32_t WakeUpCounter, uint32_t WakeUpClock); +HAL_StatusTypeDef HAL_RTCEx_SetWakeUpTimer_IT(RTC_HandleTypeDef *hrtc, uint32_t WakeUpCounter, uint32_t WakeUpClock); +uint32_t HAL_RTCEx_DeactivateWakeUpTimer(RTC_HandleTypeDef *hrtc); +uint32_t HAL_RTCEx_GetWakeUpTimer(RTC_HandleTypeDef *hrtc); + +void HAL_RTCEx_BKUPWrite(RTC_HandleTypeDef *hrtc, uint32_t BackupRegister, uint32_t Data); +uint32_t HAL_RTCEx_BKUPRead(RTC_HandleTypeDef *hrtc, uint32_t BackupRegister); + +HAL_StatusTypeDef HAL_RTCEx_SetSmoothCalib(RTC_HandleTypeDef *hrtc, uint32_t SmoothCalibPeriod, uint32_t SmoothCalibPlusPulses, uint32_t SmouthCalibMinusPulsesValue); +HAL_StatusTypeDef HAL_RTCEx_SetSynchroShift(RTC_HandleTypeDef *hrtc, uint32_t ShiftAdd1S, uint32_t ShiftSubFS); +HAL_StatusTypeDef HAL_RTCEx_SetCalibrationOutPut(RTC_HandleTypeDef *hrtc, uint32_t CalibOutput); +HAL_StatusTypeDef HAL_RTCEx_DeactivateCalibrationOutPut(RTC_HandleTypeDef *hrtc); +HAL_StatusTypeDef HAL_RTCEx_SetRefClock(RTC_HandleTypeDef *hrtc); +HAL_StatusTypeDef HAL_RTCEx_DeactivateRefClock(RTC_HandleTypeDef *hrtc); +HAL_StatusTypeDef HAL_RTCEx_EnableBypassShadow(RTC_HandleTypeDef *hrtc); +HAL_StatusTypeDef HAL_RTCEx_DisableBypassShadow(RTC_HandleTypeDef *hrtc); + +/* Peripheral State functions ***************************************************/ +void HAL_RTCEx_TamperTimeStampIRQHandler(RTC_HandleTypeDef *hrtc); +void HAL_RTCEx_WakeUpTimerIRQHandler(RTC_HandleTypeDef *hrtc); + +void HAL_RTCEx_AlarmBEventCallback(RTC_HandleTypeDef *hrtc); +void HAL_RTCEx_TimeStampEventCallback(RTC_HandleTypeDef *hrtc); +void HAL_RTCEx_WakeUpTimerEventCallback(RTC_HandleTypeDef *hrtc); +void HAL_RTCEx_Tamper1EventCallback(RTC_HandleTypeDef *hrtc); +void HAL_RTCEx_Tamper2EventCallback(RTC_HandleTypeDef *hrtc); + +HAL_StatusTypeDef HAL_RTCEx_PollForAlarmBEvent(RTC_HandleTypeDef *hrtc, uint32_t Timeout); +HAL_StatusTypeDef HAL_RTCEx_PollForTimeStampEvent(RTC_HandleTypeDef *hrtc, uint32_t Timeout); +HAL_StatusTypeDef HAL_RTCEx_PollForTamper1Event(RTC_HandleTypeDef *hrtc, uint32_t Timeout); +HAL_StatusTypeDef HAL_RTCEx_PollForTamper2Event(RTC_HandleTypeDef *hrtc, uint32_t Timeout); +HAL_StatusTypeDef HAL_RTCEx_PollForWakeUpTimerEvent(RTC_HandleTypeDef *hrtc, uint32_t Timeout); + + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __STM32L0xx_HAL_PWR_EX_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_smartcard.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_smartcard.c new file mode 100644 index 0000000000..31e0d10c6a --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_smartcard.c @@ -0,0 +1,1308 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_smartcard.c + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief SMARTCARD HAL module driver. + * + * This file provides firmware functions to manage the following + * functionalities of the SmartCard. + * + Initialization and de-initialization methods + * + IO operation methods + * + Peripheral Control methods + * + * + @verbatim + =============================================================================== + ##### How to use this driver ##### + =============================================================================== + [..] + The SMARTCARD HAL driver can be used as follow: + + (#) Declare a SMARTCARD_HandleTypeDef handle structure. + (#) Associate a USART to the SMARTCARD handle hsc. + (#) Initialize the SMARTCARD low level resources by implementing the HAL_SMARTCARD_MspInit ()API: + (##) Enable the USARTx interface clock. + (##) USART pins configuration: + (+) Enable the clock for the USART GPIOs. + (+) Configure these USART pins as alternate function pull-up. + (##) NVIC configuration if you need to use interrupt process (HAL_SMARTCARD_Transmit_IT() + and HAL_SMARTCARD_Receive_IT() APIs): + (+) Configure the USARTx interrupt priority. + (+) Enable the NVIC USART IRQ handle. + (@) The specific USART interrupts (Transmission complete interrupt, + RXNE interrupt and Error Interrupts) will be managed using the macros + __HAL_SMARTCARD_ENABLE_IT() and __HAL_SMARTCARD_DISABLE_IT() inside the transmit and receive process. + (##) DMA Configuration if you need to use DMA process (HAL_SMARTCARD_Transmit_DMA() + and HAL_SMARTCARD_Receive_DMA() APIs): + (+) Declare a DMA handle structure for the Tx/Rx stream. + (+) Enable the DMAx interface clock. + (+) Configure the declared DMA handle structure with the required Tx/Rx parameters. + (+) Configure the DMA Tx/Rx Stream. + (+) Associate the initialized DMA handle to the SMARTCARD DMA Tx/Rx handle. + (+) Configure the priority and enable the NVIC for the transfer complete interrupt on the DMA Tx/Rx Stream. + + (#) Program the Baud Rate, Parity, Mode(Receiver/Transmitter), clock enabling/disabling and accordingly, + the clock parameters (parity, phase, last bit), prescaler value, guard time and NACK on transmission + error enabling or disabling in the hsc Init structure. + + (#) If required, program SMARTCARD advanced features (TX/RX pins swap, TimeOut, auto-retry counter,...) + in the hsc AdvancedInit structure. + + (#) Initialize the SMARTCARD associated USART registers by calling + the HAL_SMARTCARD_Init() API. + + (@) HAL_SMARTCARD_Init() API also configure also the low level Hardware GPIO, CLOCK, CORTEX...etc) by + calling the customized HAL_SMARTCARD_MspInit() API. + + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @defgroup SMARTCARD + * @brief HAL SMARTCARD module driver + * @{ + */ +#ifdef HAL_SMARTCARD_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +#define TEACK_REACK_TIMEOUT 1000 +#define HAL_SMARTCARD_TXDMA_TIMEOUTVALUE 22000 +#define USART_CR1_FIELDS ((uint32_t)(USART_CR1_M | USART_CR1_PCE | USART_CR1_PS | \ + USART_CR1_TE | USART_CR1_RE | USART_CR1_OVER8)) +#define USART_CR2_CLK_FIELDS ((uint32_t)(USART_CR2_CLKEN|USART_CR2_CPOL|USART_CR2_CPHA|USART_CR2_LBCL)) +#define USART_CR2_FIELDS ((uint32_t)(USART_CR2_RTOEN|USART_CR2_CLK_FIELDS|USART_CR2_STOP)) +#define USART_CR3_FIELDS ((uint32_t)(USART_CR3_ONEBIT|USART_CR3_NACK|USART_CR3_SCARCNT)) +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +static void SMARTCARD_DMATransmitCplt(DMA_HandleTypeDef *hdma); +static void SMARTCARD_DMAReceiveCplt(DMA_HandleTypeDef *hdma); +static void SMARTCARD_DMAError(DMA_HandleTypeDef *hdma); +static void SMARTCARD_SetConfig(SMARTCARD_HandleTypeDef *hsc); +static HAL_StatusTypeDef SMARTCARD_WaitOnFlagUntilTimeout(SMARTCARD_HandleTypeDef *hsc, uint32_t Flag, FlagStatus Status, uint32_t Timeout); +static HAL_StatusTypeDef SMARTCARD_CheckIdleState(SMARTCARD_HandleTypeDef *hsc); +static HAL_StatusTypeDef SMARTCARD_Transmit_IT(SMARTCARD_HandleTypeDef *hsc); +static HAL_StatusTypeDef SMARTCARD_Receive_IT(SMARTCARD_HandleTypeDef *hsc); +static void SMARTCARD_AdvFeatureConfig(SMARTCARD_HandleTypeDef *hsc); +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup SMARTCARD_Private_Functions + * @{ + */ + +/** @defgroup HAL_SMARTCARD_Group1 Initialization/de-initialization methods + * @brief Initialization and Configuration functions + * +@verbatim +=============================================================================== + ##### Initialization and Configuration functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to initialize the USARTx + associated to the SmartCard. + (+) These parameters can be configured: + (++) Baud Rate + (++) Parity: parity should be enabled, + Frame Length is fixed to 8 bits plus parity: + the USART frame format is given in the following table: + +---------------------------------------------------------------+ + | M1M0 bits | PCE bit | USART frame | + |-----------------------|---------------------------------------| + | 01 | 1 | | SB | 8 bit data | PB | STB | | + +---------------------------------------------------------------+ + (++) Receiver/transmitter modes + (++) Synchronous mode (and if enabled, phase, polarity and last bit parameters) + (++) Prescaler value + (++) Guard bit time + (++) NACK enabling or disabling on transmission error + + (+) The following advanced features can be configured as well: + (++) TX and/or RX pin level inversion + (++) data logical level inversion + (++) RX and TX pins swap + (++) RX overrun detection disabling + (++) DMA disabling on RX error + (++) MSB first on communication line + (++) Time out enabling (and if activated, timeout value) + (++) Block length + (++) Auto-retry counter + + [..] + The HAL_SMARTCARD_Init() API follow respectively the USART (a)synchronous configuration procedures + (details for the procedures are available in reference manual). + +@endverbatim + * @{ + */ + +/** + * @brief Initializes the SMARTCARD mode according to the specified + * parameters in the SMARTCARD_InitTypeDef and creates the associated handle . + * @param hsc: SMARTCARD handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMARTCARD_Init(SMARTCARD_HandleTypeDef *hsc) +{ + /* Check the SMARTCARD handle allocation */ + if(hsc == NULL) + { + return HAL_ERROR; + } + + /* Check the USART associated to the SmartCard */ + assert_param(IS_SMARTCARD_INSTANCE(hsc->Instance)); + + if(hsc->State == HAL_SMARTCARD_STATE_RESET) + { + /* Init the low level hardware : GPIO, CLOCK, CORTEX */ + HAL_SMARTCARD_MspInit(hsc); + } + + hsc->State = HAL_SMARTCARD_STATE_BUSY; + + /* Disable the Peripheral */ + __HAL_SMARTCARD_DISABLE(hsc); + + /* Set the SMARTCARD Communication parameters */ + SMARTCARD_SetConfig(hsc); + + if(hsc->AdvancedInit.AdvFeatureInit != SMARTCARD_ADVFEATURE_NO_INIT) + { + SMARTCARD_AdvFeatureConfig(hsc); + } + + /* In SmartCard mode, the following bits must be kept cleared: + - LINEN in the USART_CR2 register, + - HDSEL and IREN bits in the USART_CR3 register.*/ + hsc->Instance->CR2 &= ~(USART_CR2_LINEN); + hsc->Instance->CR3 &= ~(USART_CR3_HDSEL | USART_CR3_IREN); + + /* set the USART in SMARTCARD mode */ + hsc->Instance->CR3 |= USART_CR3_SCEN; + + /* Enable the Peripheral */ + __HAL_SMARTCARD_ENABLE(hsc); + + /* TEACK and/or REACK to check before moving hsc->State to Ready */ + return (SMARTCARD_CheckIdleState(hsc)); +} + +/** + * @brief DeInitializes the SMARTCARD peripheral + * @param hsc: SMARTCARD handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMARTCARD_DeInit(SMARTCARD_HandleTypeDef *hsc) +{ + /* Check the SMARTCARD handle allocation */ + if(hsc == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_SMARTCARD_INSTANCE(hsc->Instance)); + + hsc->State = HAL_SMARTCARD_STATE_BUSY; + + /* DeInit the low level hardware */ + HAL_SMARTCARD_MspDeInit(hsc); + + hsc->ErrorCode = HAL_SMARTCARD_ERROR_NONE; + hsc->State = HAL_SMARTCARD_STATE_RESET; + + /* Release Lock */ + __HAL_UNLOCK(hsc); + + return HAL_OK; +} + +/** + * @brief SMARTCARD MSP Init + * @param hsc: SMARTCARD handle + * @retval None + */ + __weak void HAL_SMARTCARD_MspInit(SMARTCARD_HandleTypeDef *hsc) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_SMARTCARD_MspInit could be implenetd in the user file + */ +} + +/** + * @brief SMARTCARD MSP DeInit + * @param hsc: SMARTCARD handle + * @retval None + */ + __weak void HAL_SMARTCARD_MspDeInit(SMARTCARD_HandleTypeDef *hsc) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_SMARTCARD_MspDeInit could be implenetd in the user file + */ +} + +/** + * @} + */ + +/** @defgroup HAL_SMARTCARD_Group2 IO operation methods + * @brief SMARTCARD Transmit/Receive functions + * +@verbatim + =============================================================================== + ##### I/O operation methods ##### + =============================================================================== + This subsection provides a set of functions allowing to manage the SMARTCARD data transfers. + + (#) There are two mode of transfer: + (+) Blocking mode: The communication is performed in polling mode. + The HAL status of all data processing is returned by the same function + after finishing transfer. + (+) No-Blocking mode: The communication is performed using Interrupts + or DMA, These API's return the HAL status. + The end of the data processing will be indicated through the + dedicated SMARTCARD IRQ when using Interrupt mode or the DMA IRQ when + using DMA mode. + The HAL_SMARTCARD_TxCpltCallback(), HAL_SMARTCARD_RxCpltCallback() user callbacks + will be executed respectivelly at the end of the transmit or Receive process + The HAL_SMARTCARD_ErrorCallback()user callback will be executed when a communication error is detected + + (#) Blocking mode API's are : + (+) HAL_SMARTCARD_Transmit() + (+) HAL_SMARTCARD_Receive() + + (#) Non-Blocking mode API's with Interrupt are : + (+) HAL_SMARTCARD_Transmit_IT() + (+) HAL_SMARTCARD_Receive_IT() + (+) HAL_SMARTCARD_IRQHandler() + (+) SMARTCARD_Transmit_IT() + (+) SMARTCARD_Receive_IT() + + (#) No-Blocking mode functions with DMA are : + (+) HAL_SMARTCARD_Transmit_DMA() + (+) HAL_SMARTCARD_Receive_DMA() + + (#) A set of Transfer Complete Callbacks are provided in No_Blocking mode: + (+) HAL_SMARTCARD_TxCpltCallback() + (+) HAL_SMARTCARD_RxCpltCallback() + (+) HAL_SMARTCARD_ErrorCallback() + +@endverbatim + * @{ + */ + +/** + * @brief Send an amount of data in blocking mode + * @param hsc: SMARTCARD handle + * @param pData: pointer to data buffer + * @param Size: amount of data to be sent + * @param Timeout : Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMARTCARD_Transmit(SMARTCARD_HandleTypeDef *hsc, uint8_t *pData, uint16_t Size, uint32_t Timeout) +{ + if((hsc->State == HAL_SMARTCARD_STATE_READY) || (hsc->State == HAL_SMARTCARD_STATE_BUSY_RX)) + { + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(hsc); + hsc->ErrorCode = HAL_SMARTCARD_ERROR_NONE; + /* Check if a non-blocking receive process is ongoing or not */ + if(hsc->State == HAL_SMARTCARD_STATE_BUSY_RX) + { + hsc->State = HAL_SMARTCARD_STATE_BUSY_TX_RX; + } + else + { + hsc->State = HAL_SMARTCARD_STATE_BUSY_TX; + } + + hsc->TxXferSize = Size; + hsc->TxXferCount = Size; + while(hsc->TxXferCount > 0) + { + hsc->TxXferCount--; + if(SMARTCARD_WaitOnFlagUntilTimeout(hsc, SMARTCARD_FLAG_TXE, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + hsc->Instance->TDR = (*pData++ & (uint8_t)0xFF); + } + if(SMARTCARD_WaitOnFlagUntilTimeout(hsc, SMARTCARD_FLAG_TC, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + /* Check if a non-blocking receive Process is ongoing or not */ + if(hsc->State == HAL_SMARTCARD_STATE_BUSY_TX_RX) + { + hsc->State = HAL_SMARTCARD_STATE_BUSY_RX; + } + else + { + hsc->State = HAL_SMARTCARD_STATE_READY; + } + + /* Process Unlocked */ + __HAL_UNLOCK(hsc); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive an amount of data in blocking mode + * @param hsc: SMARTCARD handle + * @param pData: pointer to data buffer + * @param Size: amount of data to be received + * @param Timeout : Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMARTCARD_Receive(SMARTCARD_HandleTypeDef *hsc, uint8_t *pData, uint16_t Size, uint32_t Timeout) +{ + if((hsc->State == HAL_SMARTCARD_STATE_READY) || (hsc->State == HAL_SMARTCARD_STATE_BUSY_TX)) + { + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(hsc); + + hsc->ErrorCode = HAL_SMARTCARD_ERROR_NONE; + /* Check if a non-blocking transmit process is ongoing or not */ + if(hsc->State == HAL_SMARTCARD_STATE_BUSY_TX) + { + hsc->State = HAL_SMARTCARD_STATE_BUSY_TX_RX; + } + else + { + hsc->State = HAL_SMARTCARD_STATE_BUSY_RX; + } + + hsc->RxXferSize = Size; + hsc->RxXferCount = Size; + /* Check the remain data to be received */ + while(hsc->RxXferCount > 0) + { + hsc->RxXferCount--; + if(SMARTCARD_WaitOnFlagUntilTimeout(hsc, SMARTCARD_FLAG_RXNE, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + *pData++ = (uint8_t)(hsc->Instance->RDR & (uint8_t)0x00FF); + } + + /* Check if a non-blocking transmit Process is ongoing or not */ + if(hsc->State == HAL_SMARTCARD_STATE_BUSY_TX_RX) + { + hsc->State = HAL_SMARTCARD_STATE_BUSY_TX; + } + else + { + hsc->State = HAL_SMARTCARD_STATE_READY; + } + + /* Process Unlocked */ + __HAL_UNLOCK(hsc); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Send an amount of data in interrupt mode + * @param hsc: SMARTCARD handle + * @param pData: pointer to data buffer + * @param Size: amount of data to be sent + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMARTCARD_Transmit_IT(SMARTCARD_HandleTypeDef *hsc, uint8_t *pData, uint16_t Size) +{ + if((hsc->State == HAL_SMARTCARD_STATE_READY) || (hsc->State == HAL_SMARTCARD_STATE_BUSY_RX)) + { + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(hsc); + + hsc->pTxBuffPtr = pData; + hsc->TxXferSize = Size; + hsc->TxXferCount = Size; + + hsc->ErrorCode = HAL_SMARTCARD_ERROR_NONE; + /* Check if a receive process is ongoing or not */ + if(hsc->State == HAL_SMARTCARD_STATE_BUSY_RX) + { + hsc->State = HAL_SMARTCARD_STATE_BUSY_TX_RX; + } + else + { + hsc->State = HAL_SMARTCARD_STATE_BUSY_TX; + } + + /* Enable the SMARTCARD Error Interrupt: (Frame error, noise error, overrun error) */ + __HAL_SMARTCARD_ENABLE_IT(hsc, SMARTCARD_IT_ERR); + + /* Process Unlocked */ + __HAL_UNLOCK(hsc); + + /* Enable the SMARTCARD Transmit Complete Interrupt */ + __HAL_SMARTCARD_ENABLE_IT(hsc, SMARTCARD_IT_TC); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive an amount of data in interrupt mode + * @param hsc: SMARTCARD handle + * @param pData: pointer to data buffer + * @param Size: amount of data to be received + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMARTCARD_Receive_IT(SMARTCARD_HandleTypeDef *hsc, uint8_t *pData, uint16_t Size) +{ + if((hsc->State == HAL_SMARTCARD_STATE_READY) || (hsc->State == HAL_SMARTCARD_STATE_BUSY_TX)) + { + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(hsc); + + hsc->pRxBuffPtr = pData; + hsc->RxXferSize = Size; + hsc->RxXferCount = Size; + + hsc->ErrorCode = HAL_SMARTCARD_ERROR_NONE; + /* Check if a transmit process is ongoing or not */ + if(hsc->State == HAL_SMARTCARD_STATE_BUSY_TX) + { + hsc->State = HAL_SMARTCARD_STATE_BUSY_TX_RX; + } + else + { + hsc->State = HAL_SMARTCARD_STATE_BUSY_RX; + } + + /* Enable the SMARTCARD Parity Error Interrupt */ + __HAL_SMARTCARD_ENABLE_IT(hsc, SMARTCARD_IT_PE); + + /* Enable the SMARTCARD Error Interrupt: (Frame error, noise error, overrun error) */ + __HAL_SMARTCARD_ENABLE_IT(hsc, SMARTCARD_IT_ERR); + + /* Process Unlocked */ + __HAL_UNLOCK(hsc); + + /* Enable the SMARTCARD Data Register not empty Interrupt */ + __HAL_SMARTCARD_ENABLE_IT(hsc, SMARTCARD_IT_RXNE); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Send an amount of data in DMA mode + * @param hsc: SMARTCARD handle + * @param pData: pointer to data buffer + * @param Size: amount of data to be sent + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMARTCARD_Transmit_DMA(SMARTCARD_HandleTypeDef *hsc, uint8_t *pData, uint16_t Size) +{ + uint32_t *tmp; + + if((hsc->State == HAL_SMARTCARD_STATE_READY) || (hsc->State == HAL_SMARTCARD_STATE_BUSY_RX)) + { + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(hsc); + + hsc->pTxBuffPtr = pData; + hsc->TxXferSize = Size; + hsc->TxXferCount = Size; + + hsc->ErrorCode = HAL_SMARTCARD_ERROR_NONE; + /* Check if a receive process is ongoing or not */ + if(hsc->State == HAL_SMARTCARD_STATE_BUSY_RX) + { + hsc->State = HAL_SMARTCARD_STATE_BUSY_TX_RX; + } + else + { + hsc->State = HAL_SMARTCARD_STATE_BUSY_TX; + } + + /* Set the SMARTCARD DMA transfert complete callback */ + hsc->hdmatx->XferCpltCallback = SMARTCARD_DMATransmitCplt; + + /* Set the SMARTCARD error callback */ + hsc->hdmatx->XferErrorCallback = SMARTCARD_DMAError; + + /* Enable the SMARTCARD transmit DMA Stream */ + tmp = (uint32_t*)&pData; + HAL_DMA_Start_IT(hsc->hdmatx, *(uint32_t*)tmp, (uint32_t)&hsc->Instance->TDR, Size); + + /* Enable the DMA transfer for transmit request by setting the DMAT bit + in the SMARTCARD associated USART CR3 register */ + hsc->Instance->CR3 |= USART_CR3_DMAT; + + /* Process Unlocked */ + __HAL_UNLOCK(hsc); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive an amount of data in DMA mode + * @param hsc: SMARTCARD handle + * @param pData: pointer to data buffer + * @param Size: amount of data to be received + * @note The SMARTCARD-associated USART parity is enabled (PCE = 1), + * the received data contain the parity bit (MSB position) + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMARTCARD_Receive_DMA(SMARTCARD_HandleTypeDef *hsc, uint8_t *pData, uint16_t Size) +{ + uint32_t *tmp; + + if((hsc->State == HAL_SMARTCARD_STATE_READY) || (hsc->State == HAL_SMARTCARD_STATE_BUSY_TX)) + { + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(hsc); + + hsc->pRxBuffPtr = pData; + hsc->RxXferSize = Size; + + hsc->ErrorCode = HAL_SMARTCARD_ERROR_NONE; + /* Check if a transmit rocess is ongoing or not */ + if(hsc->State == HAL_SMARTCARD_STATE_BUSY_TX) + { + hsc->State = HAL_SMARTCARD_STATE_BUSY_TX_RX; + } + else + { + hsc->State = HAL_SMARTCARD_STATE_BUSY_RX; + } + + /* Set the SMARTCARD DMA transfert complete callback */ + hsc->hdmarx->XferCpltCallback = SMARTCARD_DMAReceiveCplt; + + /* Set the SMARTCARD DMA error callback */ + hsc->hdmarx->XferErrorCallback = SMARTCARD_DMAError; + + /* Enable the DMA Stream */ + tmp = (uint32_t*)&pData; + HAL_DMA_Start_IT(hsc->hdmarx, (uint32_t)&hsc->Instance->RDR, *(uint32_t*)tmp, Size); + + /* Enable the DMA transfer for the receiver request by setting the DMAR bit + in the SMARTCARD associated USART CR3 register */ + hsc->Instance->CR3 |= USART_CR3_DMAR; + + /* Process Unlocked */ + __HAL_UNLOCK(hsc); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief SMARTCARD interrupt requests handling. + * @param hsc: SMARTCARD handle + * @retval None + */ +void HAL_SMARTCARD_IRQHandler(SMARTCARD_HandleTypeDef *hsc) +{ + /* SMARTCARD parity error interrupt occurred -------------------------------*/ + if((__HAL_SMARTCARD_GET_IT(hsc, SMARTCARD_IT_PE) != RESET) && (__HAL_SMARTCARD_GET_IT_SOURCE(hsc, SMARTCARD_IT_PE) != RESET)) + { + __HAL_SMARTCARD_CLEAR_IT(hsc, SMARTCARD_CLEAR_PEF); + hsc->ErrorCode |= HAL_SMARTCARD_ERROR_PE; + /* Set the SMARTCARD state ready to be able to start again the process */ + hsc->State = HAL_SMARTCARD_STATE_READY; + } + + /* SMARTCARD frame error interrupt occured ---------------------------------*/ + if((__HAL_SMARTCARD_GET_IT(hsc, SMARTCARD_IT_FE) != RESET) && (__HAL_SMARTCARD_GET_IT_SOURCE(hsc, SMARTCARD_IT_ERR) != RESET)) + { + __HAL_SMARTCARD_CLEAR_IT(hsc, SMARTCARD_CLEAR_FEF); + hsc->ErrorCode |= HAL_SMARTCARD_ERROR_FE; + /* Set the SMARTCARD state ready to be able to start again the process */ + hsc->State = HAL_SMARTCARD_STATE_READY; + } + + /* SMARTCARD noise error interrupt occured ---------------------------------*/ + if((__HAL_SMARTCARD_GET_IT(hsc, SMARTCARD_IT_NE) != RESET) && (__HAL_SMARTCARD_GET_IT_SOURCE(hsc, SMARTCARD_IT_ERR) != RESET)) + { + __HAL_SMARTCARD_CLEAR_IT(hsc, SMARTCARD_CLEAR_NEF); + hsc->ErrorCode |= HAL_SMARTCARD_ERROR_NE; + /* Set the SMARTCARD state ready to be able to start again the process */ + hsc->State = HAL_SMARTCARD_STATE_READY; + } + + /* SMARTCARD Over-Run interrupt occured ------------------------------------*/ + if((__HAL_SMARTCARD_GET_IT(hsc, SMARTCARD_IT_ORE) != RESET) && (__HAL_SMARTCARD_GET_IT_SOURCE(hsc, SMARTCARD_IT_ERR) != RESET)) + { + __HAL_SMARTCARD_CLEAR_IT(hsc, SMARTCARD_CLEAR_OREF); + hsc->ErrorCode |= HAL_SMARTCARD_ERROR_ORE; + /* Set the SMARTCARD state ready to be able to start again the process */ + hsc->State = HAL_SMARTCARD_STATE_READY; + } + + /* SMARTCARD receiver timeout interrupt occured ----------------------------*/ + if((__HAL_SMARTCARD_GET_IT(hsc, SMARTCARD_IT_RTO) != RESET) && (__HAL_SMARTCARD_GET_IT_SOURCE(hsc, SMARTCARD_IT_RTO) != RESET)) + { + __HAL_SMARTCARD_CLEAR_IT(hsc, SMARTCARD_CLEAR_RTOF); + hsc->ErrorCode |= HAL_SMARTCARD_ERROR_RTO; + /* Set the SMARTCARD state ready to be able to start again the process */ + hsc->State = HAL_SMARTCARD_STATE_READY; + } + + /* Call SMARTCARD Error Call back function if need be ----------------------*/ + if(hsc->ErrorCode != HAL_SMARTCARD_ERROR_NONE) + { + HAL_SMARTCARD_ErrorCallback(hsc); + } + + /* SMARTCARD in mode Receiver ----------------------------------------------*/ + if((__HAL_SMARTCARD_GET_IT(hsc, SMARTCARD_IT_RXNE) != RESET) && (__HAL_SMARTCARD_GET_IT_SOURCE(hsc, SMARTCARD_IT_RXNE) != RESET)) + { + SMARTCARD_Receive_IT(hsc); + /* Clear RXNE interrupt flag */ + __HAL_SMARTCARD_SEND_REQ(hsc, SMARTCARD_RXDATA_FLUSH_REQUEST); + } + + /* SMARTCARD in mode Receiver, end of block interruption -------------------*/ + if((__HAL_SMARTCARD_GET_IT(hsc, SMARTCARD_IT_EOB) != RESET) && (__HAL_SMARTCARD_GET_IT_SOURCE(hsc, SMARTCARD_IT_EOB) != RESET)) + { + hsc->State = HAL_SMARTCARD_STATE_READY; + HAL_SMARTCARD_RxCpltCallback(hsc); + /* Clear EOBF interrupt after HAL_SMARTCARD_RxCpltCallback() call for the End of Block information + * to be available during HAL_SMARTCARD_RxCpltCallback() processing */ + __HAL_SMARTCARD_CLEAR_IT(hsc, SMARTCARD_CLEAR_EOBF); + } + + /* SMARTCARD in mode Transmitter -------------------------------------------*/ + if((__HAL_SMARTCARD_GET_IT(hsc, SMARTCARD_IT_TC) != RESET) && (__HAL_SMARTCARD_GET_IT_SOURCE(hsc, SMARTCARD_IT_TC) != RESET)) + { + SMARTCARD_Transmit_IT(hsc); + } +} + +/** + * @brief This function handles SMARTCARD Communication Timeout. + * @param hsc: SMARTCARD handle + * @param Flag: specifies the SMARTCARD flag to check. + * @param Status: The new Flag status (SET or RESET). + * @param Timeout: Timeout duration + * @retval HAL status + */ +static HAL_StatusTypeDef SMARTCARD_WaitOnFlagUntilTimeout(SMARTCARD_HandleTypeDef *hsc, uint32_t Flag, FlagStatus Status, uint32_t Timeout) +{ + uint32_t tickstart = 0x00; + tickstart = HAL_GetTick(); + + /* Wait until flag is set */ + if(Status == RESET) + { + while(__HAL_SMARTCARD_GET_FLAG(hsc, Flag) == RESET) + { + /* Check for the Timeout */ + if(Timeout != HAL_MAX_DELAY) + { + if((HAL_GetTick() - tickstart ) > Timeout) + { + /* Disable TXE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts for the interrupt process */ + __HAL_SMARTCARD_DISABLE_IT(hsc, SMARTCARD_IT_TXE); + __HAL_SMARTCARD_DISABLE_IT(hsc, SMARTCARD_IT_RXNE); + __HAL_SMARTCARD_DISABLE_IT(hsc, SMARTCARD_IT_PE); + __HAL_SMARTCARD_DISABLE_IT(hsc, SMARTCARD_IT_ERR); + + hsc->State= HAL_SMARTCARD_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hsc); + + return HAL_TIMEOUT; + } + } + } + } + else + { + while(__HAL_SMARTCARD_GET_FLAG(hsc, Flag) != RESET) + { + /* Check for the Timeout */ + if(Timeout != HAL_MAX_DELAY) + { + if((HAL_GetTick() - tickstart ) > Timeout) + { + /* Disable TXE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts for the interrupt process */ + __HAL_SMARTCARD_DISABLE_IT(hsc, SMARTCARD_IT_TXE); + __HAL_SMARTCARD_DISABLE_IT(hsc, SMARTCARD_IT_RXNE); + __HAL_SMARTCARD_DISABLE_IT(hsc, SMARTCARD_IT_PE); + __HAL_SMARTCARD_DISABLE_IT(hsc, SMARTCARD_IT_ERR); + + hsc->State= HAL_SMARTCARD_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hsc); + + return HAL_TIMEOUT; + } + } + } + } + return HAL_OK; +} + +/** + * @brief DMA SMARTCARD transmit process complete callback + * @param hdma: DMA handle + * @retval None + */ +static void SMARTCARD_DMATransmitCplt(DMA_HandleTypeDef *hdma) +{ + SMARTCARD_HandleTypeDef* hsc = ( SMARTCARD_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + hsc->TxXferCount = 0; + + /* Disable the DMA transfer for transmit request by setting the DMAT bit + in the SMARTCARD associated USART CR3 register */ + hsc->Instance->CR3 &= (uint16_t)~((uint16_t)USART_CR3_DMAT); + + /* Wait for SMARTCARD TC Flag */ + if(SMARTCARD_WaitOnFlagUntilTimeout(hsc, SMARTCARD_FLAG_TC, RESET, HAL_SMARTCARD_TXDMA_TIMEOUTVALUE) != HAL_OK) + { + /* Timeout Occured */ + hsc->State = HAL_SMARTCARD_STATE_TIMEOUT; + HAL_SMARTCARD_ErrorCallback(hsc); + } + else + { + /* No Timeout */ + /* Check if a receive Process is ongoing or not */ + if(hsc->State == HAL_SMARTCARD_STATE_BUSY_TX_RX) + { + hsc->State = HAL_SMARTCARD_STATE_BUSY_RX; + } + else + { + hsc->State = HAL_SMARTCARD_STATE_READY; + } + HAL_SMARTCARD_TxCpltCallback(hsc); + } +} + +/** + * @brief DMA SMARTCARD receive process complete callback + * @param hdma: DMA handle + * @retval None + */ +static void SMARTCARD_DMAReceiveCplt(DMA_HandleTypeDef *hdma) +{ + SMARTCARD_HandleTypeDef* hsc = ( SMARTCARD_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + hsc->RxXferCount = 0; + + /* Disable the DMA transfer for the receiver request by setting the DMAR bit + in the SMARTCARD associated USART CR3 register */ + hsc->Instance->CR3 &= (uint16_t)~((uint16_t)USART_CR3_DMAR); + + /* Check if a transmit Process is ongoing or not */ + if(hsc->State == HAL_SMARTCARD_STATE_BUSY_TX_RX) + { + hsc->State = HAL_SMARTCARD_STATE_BUSY_TX; + } + else + { + hsc->State = HAL_SMARTCARD_STATE_READY; + } + + HAL_SMARTCARD_RxCpltCallback(hsc); +} + +/** + * @brief DMA SMARTCARD communication error callback + * @param hdma: DMA handle + * @retval None + */ +static void SMARTCARD_DMAError(DMA_HandleTypeDef *hdma) +{ + SMARTCARD_HandleTypeDef* hsc = ( SMARTCARD_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + hsc->RxXferCount = 0; + hsc->TxXferCount = 0; + hsc->State= HAL_SMARTCARD_STATE_READY; + hsc->ErrorCode |= HAL_SMARTCARD_ERROR_DMA; + HAL_SMARTCARD_ErrorCallback(hsc); +} + +/** + * @brief Tx Transfer completed callbacks + * @param hsc: SMARTCARD handle + * @retval None + */ + __weak void HAL_SMARTCARD_TxCpltCallback(SMARTCARD_HandleTypeDef *hsc) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_SMARTCARD_TxCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Rx Transfer completed callbacks + * @param hsc: SMARTCARD handle + * @retval None + */ +__weak void HAL_SMARTCARD_RxCpltCallback(SMARTCARD_HandleTypeDef *hsc) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_SMARTCARD_TxCpltCallback could be implemented in the user file + */ +} + +/** + * @brief SMARTCARD error callbacks + * @param hsc: SMARTCARD handle + * @retval None + */ + __weak void HAL_SMARTCARD_ErrorCallback(SMARTCARD_HandleTypeDef *hsc) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_SMARTCARD_ErrorCallback could be implemented in the user file + */ +} + +/** + * @brief Send an amount of data in non blocking mode + * @param hsc: SMARTCARD handle. + * Function called under interruption only, once + * interruptions have been enabled by HAL_SMARTCARD_Transmit_IT() + * @retval HAL status + */ +static HAL_StatusTypeDef SMARTCARD_Transmit_IT(SMARTCARD_HandleTypeDef *hsc) +{ + if((hsc->State == HAL_SMARTCARD_STATE_BUSY_TX) || (hsc->State == HAL_SMARTCARD_STATE_BUSY_TX_RX)) + { + if(hsc->TxXferCount == 0) + { + /* Disable the SMARTCARD Transmit Complete Interrupt */ + __HAL_SMARTCARD_DISABLE_IT(hsc, SMARTCARD_IT_TC); + + /* Check if a receive Process is ongoing or not */ + if(hsc->State == HAL_SMARTCARD_STATE_BUSY_TX_RX) + { + hsc->State = HAL_SMARTCARD_STATE_BUSY_RX; + } + else + { + /* Disable the SMARTCARD Error Interrupt: (Frame error, noise error, overrun error) */ + __HAL_SMARTCARD_DISABLE_IT(hsc, SMARTCARD_IT_ERR); + + hsc->State = HAL_SMARTCARD_STATE_READY; + } + + HAL_SMARTCARD_TxCpltCallback(hsc); + + return HAL_OK; + } + else + { + hsc->Instance->TDR = (*hsc->pTxBuffPtr++ & (uint8_t)0xFF); + hsc->TxXferCount--; + + return HAL_OK; + } + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive an amount of data in non blocking mode + * @param hsc: SMARTCARD handle. + * Function called under interruption only, once + * interruptions have been enabled by HAL_SMARTCARD_Receive_IT() + * @retval HAL status + */ +static HAL_StatusTypeDef SMARTCARD_Receive_IT(SMARTCARD_HandleTypeDef *hsc) +{ + if((hsc->State == HAL_SMARTCARD_STATE_BUSY_RX) || (hsc->State == HAL_SMARTCARD_STATE_BUSY_TX_RX)) + { + *hsc->pRxBuffPtr++ = (uint8_t)(hsc->Instance->RDR & (uint8_t)0xFF); + + if(--hsc->RxXferCount == 0) + { + while(HAL_IS_BIT_SET(hsc->Instance->ISR, SMARTCARD_FLAG_RXNE)) + { + } + __HAL_SMARTCARD_DISABLE_IT(hsc, SMARTCARD_IT_RXNE); + + /* Check if a transmit Process is ongoing or not */ + if(hsc->State == HAL_SMARTCARD_STATE_BUSY_TX_RX) + { + hsc->State = HAL_SMARTCARD_STATE_BUSY_TX; + } + else + { + /* Disable the SMARTCARD Parity Error Interrupt */ + __HAL_SMARTCARD_DISABLE_IT(hsc, SMARTCARD_IT_PE); + + /* Disable the SMARTCARD Error Interrupt: (Frame error, noise error, overrun error) */ + __HAL_SMARTCARD_DISABLE_IT(hsc, SMARTCARD_IT_ERR); + + hsc->State = HAL_SMARTCARD_STATE_READY; + } + + HAL_SMARTCARD_RxCpltCallback(hsc); + + return HAL_OK; + } + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Configure the SMARTCARD associated USART peripheral + * @param hsc: SMARTCARD handle + * @retval None + */ +static void SMARTCARD_SetConfig(SMARTCARD_HandleTypeDef *hsc) +{ + uint32_t tmpreg = 0x00000000; + uint32_t clocksource = 0x00000000; + + /* Check the parameters */ + assert_param(IS_SMARTCARD_INSTANCE(hsc->Instance)); + assert_param(IS_SMARTCARD_BAUDRATE(hsc->Init.BaudRate)); + assert_param(IS_SMARTCARD_WORD_LENGTH(hsc->Init.WordLength)); + assert_param(IS_SMARTCARD_STOPBITS(hsc->Init.StopBits)); + assert_param(IS_SMARTCARD_PARITY(hsc->Init.Parity)); + assert_param(IS_SMARTCARD_MODE(hsc->Init.Mode)); + assert_param(IS_SMARTCARD_POLARITY(hsc->Init.CLKPolarity)); + assert_param(IS_SMARTCARD_PHASE(hsc->Init.CLKPhase)); + assert_param(IS_SMARTCARD_LASTBIT(hsc->Init.CLKLastBit)); + assert_param(IS_SMARTCARD_ONEBIT_SAMPLING(hsc->Init.OneBitSampling)); + assert_param(IS_SMARTCARD_NACK(hsc->Init.NACKState)); + assert_param(IS_SMARTCARD_TIMEOUT(hsc->Init.TimeOutEnable)); + assert_param(IS_SMARTCARD_AUTORETRY_COUNT(hsc->Init.AutoRetryCount)); + + /*-------------------------- USART CR1 Configuration -----------------------*/ + /* In SmartCard mode, M and PCE are forced to 1 (8 bits + parity). + * Oversampling is forced to 16 (OVER8 = 0). + * Configure the Parity and Mode: + * set PS bit according to hsc->Init.Parity value + * set TE and RE bits according to hsc->Init.Mode value */ + tmpreg = (uint32_t) hsc->Init.Parity | hsc->Init.Mode; + /* in case of TX-only mode, if NACK is enabled, the USART must be able to monitor + the bidirectional line to detect a NACK signal in case of parity error. + Therefore, the receiver block must be enabled as well (RE bit must be set). */ + if((hsc->Init.Mode == SMARTCARD_MODE_TX) && (hsc->Init.NACKState == SMARTCARD_NACK_ENABLED)) + { + tmpreg |= USART_CR1_RE; + } + tmpreg |= (uint32_t) hsc->Init.WordLength; + MODIFY_REG(hsc->Instance->CR1, USART_CR1_FIELDS, tmpreg); + + /*-------------------------- USART CR2 Configuration -----------------------*/ + /* Stop bits are forced to 1.5 (STOP = 11) */ + tmpreg = hsc->Init.StopBits; + /* Synchronous mode is activated by default */ + tmpreg |= (uint32_t) USART_CR2_CLKEN | hsc->Init.CLKPolarity; + tmpreg |= (uint32_t) hsc->Init.CLKPhase | hsc->Init.CLKLastBit; + tmpreg |= (uint32_t) hsc->Init.TimeOutEnable; + MODIFY_REG(hsc->Instance->CR2, USART_CR2_FIELDS, tmpreg); + + /*-------------------------- USART CR3 Configuration -----------------------*/ + /* Configure + * - one-bit sampling method versus three samples' majority rule + * according to hsc->Init.OneBitSampling + * - NACK transmission in case of parity error according + * to hsc->Init.NACKEnable + * - autoretry counter according to hsc->Init.AutoRetryCount */ + tmpreg = (uint32_t) hsc->Init.OneBitSampling | hsc->Init.NACKState; + tmpreg |= (uint32_t) (hsc->Init.AutoRetryCount << SMARTCARD_CR3_SCARCNT_LSB_POS); + MODIFY_REG(hsc->Instance-> CR3,USART_CR3_FIELDS, tmpreg); + + /*-------------------------- USART GTPR Configuration ----------------------*/ + tmpreg = (uint32_t) (hsc->Init.Prescaler | (hsc->Init.GuardTime << SMARTCARD_GTPR_GT_LSB_POS)); + MODIFY_REG(hsc->Instance->GTPR, (uint32_t)(USART_GTPR_GT|USART_GTPR_PSC), tmpreg); + + /*-------------------------- USART RTOR Configuration ----------------------*/ + tmpreg = (uint32_t) (hsc->Init.BlockLength << SMARTCARD_RTOR_BLEN_LSB_POS); + if(hsc->Init.TimeOutEnable == SMARTCARD_TIMEOUT_ENABLED) + { + assert_param(IS_SMARTCARD_TIMEOUT_VALUE(hsc->Init.TimeOutValue)); + tmpreg |= (uint32_t) hsc->Init.TimeOutValue; + } + MODIFY_REG(hsc->Instance->RTOR, (USART_RTOR_RTO|USART_RTOR_BLEN), tmpreg); + + /*-------------------------- USART BRR Configuration -----------------------*/ + __HAL_SMARTCARD_GETCLOCKSOURCE(hsc, clocksource); + switch (clocksource) + { + case SMARTCARD_CLOCKSOURCE_PCLK1: + hsc->Instance->BRR = (uint16_t)(HAL_RCC_GetPCLK1Freq() / hsc->Init.BaudRate); + break; + case SMARTCARD_CLOCKSOURCE_PCLK2: + hsc->Instance->BRR = (uint16_t)(HAL_RCC_GetPCLK2Freq() / hsc->Init.BaudRate); + break; + case SMARTCARD_CLOCKSOURCE_HSI: + hsc->Instance->BRR = (uint16_t)(HSI_VALUE / hsc->Init.BaudRate); + break; + case SMARTCARD_CLOCKSOURCE_SYSCLK: + hsc->Instance->BRR = (uint16_t)(HAL_RCC_GetSysClockFreq() / hsc->Init.BaudRate); + break; + case SMARTCARD_CLOCKSOURCE_LSE: + hsc->Instance->BRR = (uint16_t)(LSE_VALUE / hsc->Init.BaudRate); + break; + default: + break; + } +} + +/** + * @brief Check the SMARTCARD Idle State + * @param hsc: SMARTCARD handle + * @retval HAL status + */ +static HAL_StatusTypeDef SMARTCARD_CheckIdleState(SMARTCARD_HandleTypeDef *hsc) +{ + + /* Initialize the SMARTCARD ErrorCode */ + hsc->ErrorCode = HAL_SMARTCARD_ERROR_NONE; + + /* Check if the Transmitter is enabled */ + if((hsc->Instance->CR1 & USART_CR1_TE) == USART_CR1_TE) + { + /* Wait until TEACK flag is set */ + if(SMARTCARD_WaitOnFlagUntilTimeout(hsc, USART_ISR_TEACK, RESET, TEACK_REACK_TIMEOUT) != HAL_OK) + { + return HAL_TIMEOUT; + } + } + /* Check if the Receiver is enabled */ + if((hsc->Instance->CR1 & USART_CR1_RE) == USART_CR1_RE) + { + /* Wait until REACK flag is set */ + if(SMARTCARD_WaitOnFlagUntilTimeout(hsc, USART_ISR_REACK, RESET, TEACK_REACK_TIMEOUT) != HAL_OK) + { + return HAL_TIMEOUT; + } + } + + /* Process Unlocked */ + __HAL_UNLOCK(hsc); + + /* Initialize the SMARTCARD state*/ + hsc->State= HAL_SMARTCARD_STATE_READY; + + return HAL_OK; +} + +/** + * @brief Configure the SMARTCARD associated USART peripheral advanced feautures + * @param hsc: SMARTCARD handle + * @retval None + */ +static void SMARTCARD_AdvFeatureConfig(SMARTCARD_HandleTypeDef *hsc) +{ + /* Check whether the set of advanced features to configure is properly set */ + assert_param(IS_SMARTCARD_ADVFEATURE_INIT(hsc->AdvancedInit.AdvFeatureInit)); + + /* if required, configure TX pin active level inversion */ + if(HAL_IS_BIT_SET(hsc->AdvancedInit.AdvFeatureInit, SMARTCARD_ADVFEATURE_TXINVERT_INIT)) + { + assert_param(IS_SMARTCARD_ADVFEATURE_TXINV(hsc->AdvancedInit.TxPinLevelInvert)); + MODIFY_REG(hsc->Instance->CR2, USART_CR2_TXINV, hsc->AdvancedInit.TxPinLevelInvert); + } + + /* if required, configure RX pin active level inversion */ + if(HAL_IS_BIT_SET(hsc->AdvancedInit.AdvFeatureInit, SMARTCARD_ADVFEATURE_RXINVERT_INIT)) + { + assert_param(IS_SMARTCARD_ADVFEATURE_RXINV(hsc->AdvancedInit.RxPinLevelInvert)); + MODIFY_REG(hsc->Instance->CR2, USART_CR2_RXINV, hsc->AdvancedInit.RxPinLevelInvert); + } + + /* if required, configure data inversion */ + if(HAL_IS_BIT_SET(hsc->AdvancedInit.AdvFeatureInit, SMARTCARD_ADVFEATURE_DATAINVERT_INIT)) + { + assert_param(IS_SMARTCARD_ADVFEATURE_DATAINV(hsc->AdvancedInit.DataInvert)); + MODIFY_REG(hsc->Instance->CR2, USART_CR2_DATAINV, hsc->AdvancedInit.DataInvert); + } + + /* if required, configure RX/TX pins swap */ + if(HAL_IS_BIT_SET(hsc->AdvancedInit.AdvFeatureInit, SMARTCARD_ADVFEATURE_SWAP_INIT)) + { + assert_param(IS_SMARTCARD_ADVFEATURE_SWAP(hsc->AdvancedInit.Swap)); + MODIFY_REG(hsc->Instance->CR2, USART_CR2_SWAP, hsc->AdvancedInit.Swap); + } + + /* if required, configure RX overrun detection disabling */ + if(HAL_IS_BIT_SET(hsc->AdvancedInit.AdvFeatureInit, SMARTCARD_ADVFEATURE_RXOVERRUNDISABLE_INIT)) + { + assert_param(IS_SMARTCARD_OVERRUN(hsc->AdvancedInit.OverrunDisable)); + MODIFY_REG(hsc->Instance->CR3, USART_CR3_OVRDIS, hsc->AdvancedInit.OverrunDisable); + } + + /* if required, configure DMA disabling on reception error */ + if(HAL_IS_BIT_SET(hsc->AdvancedInit.AdvFeatureInit, SMARTCARD_ADVFEATURE_DMADISABLEONERROR_INIT)) + { + assert_param(IS_SMARTCARD_ADVFEATURE_DMAONRXERROR(hsc->AdvancedInit.DMADisableonRxError)); + MODIFY_REG(hsc->Instance->CR3, USART_CR3_DDRE, hsc->AdvancedInit.DMADisableonRxError); + } + + /* if required, configure MSB first on communication line */ + if(HAL_IS_BIT_SET(hsc->AdvancedInit.AdvFeatureInit, SMARTCARD_ADVFEATURE_MSBFIRST_INIT)) + { + assert_param(IS_SMARTCARD_ADVFEATURE_MSBFIRST(hsc->AdvancedInit.MSBFirst)); + MODIFY_REG(hsc->Instance->CR2, USART_CR2_MSBFIRST, hsc->AdvancedInit.MSBFirst); + } +} + +/** + * @} + */ + +/** @defgroup HAL_SMARTCARD_Group3 Peripheral Control methods + * @brief SMARTCARD control functions + * +@verbatim + =============================================================================== + ##### Peripheral Control methods ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to initialize the SMARTCARD. + (+) HAL_SMARTCARD_GetState() API is helpful to check in run-time the state of the SMARTCARD peripheral + (+) SMARTCARD_SetConfig() API configures the SMARTCARD peripheral + (+) SMARTCARD_CheckIdleState() API ensures that TEACK and/or REACK are set after initialization + +@endverbatim + * @{ + */ + + +/** + * @brief return the SMARTCARD state + * @param hsc: SMARTCARD handle + * @retval HAL state + */ +HAL_SMARTCARD_StateTypeDef HAL_SMARTCARD_GetState(SMARTCARD_HandleTypeDef *hsc) +{ + return hsc->State; +} + +/** +* @brief Return the SMARTCARD error code +* @param hsc : pointer to a SMARTCARD_HandleTypeDef structure that contains + * the configuration information for the specified SMARTCARD. +* @retval SMARTCARD Error Code +*/ +uint32_t HAL_SMARTCARD_GetError(SMARTCARD_HandleTypeDef *hsc) +{ + return hsc->ErrorCode; +} + +/** + * @} + */ + +/** + * @} + */ + +#endif /* HAL_SMARTCARD_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_smartcard.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_smartcard.h new file mode 100644 index 0000000000..8f42011c9b --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_smartcard.h @@ -0,0 +1,800 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_smartcard.h + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief Header file of SMARTCARD HAL module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32L0xx_HAL_SMARTCARD_H +#define __STM32L0xx_HAL_SMARTCARD_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal_def.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @addtogroup SMARTCARD + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/** + * @brief SMARTCARD Init Structure definition + */ +typedef struct +{ + uint32_t BaudRate; /*!< Configures the SmartCard communication baud rate. + The baud rate register is computed using the following formula: + Baud Rate Register = ((PCLKx) / ((hsc->Init.BaudRate))) */ + + uint32_t WordLength; /*!< Specifies the number of data bits transmitted or received in a frame. + This parameter @ref SMARTCARD_Word_Length can only be set to 9 (8 data + 1 parity bits). */ + + uint32_t StopBits; /*!< Specifies the number of stop bits @ref SMARTCARD_Stop_Bits. + Only 1.5 stop bits are authorized in SmartCard mode. */ + + uint32_t Parity; /*!< Specifies the parity mode. + This parameter can be a value of @ref SMARTCARD_Parity + @note The parity is enabled by default (PCE is forced to 1). + Since the WordLength is forced to 8 bits + parity, M is + forced to 1 and the parity bit is the 9th bit. */ + + uint32_t Mode; /*!< Specifies whether the Receive or Transmit mode is enabled or disabled. + This parameter can be a value of @ref SMARTCARD_Mode */ + + uint32_t CLKPolarity; /*!< Specifies the steady state of the serial clock. + This parameter can be a value of @ref SMARTCARD_Clock_Polarity */ + + uint32_t CLKPhase; /*!< Specifies the clock transition on which the bit capture is made. + This parameter can be a value of @ref SMARTCARD_Clock_Phase */ + + uint32_t CLKLastBit; /*!< Specifies whether the clock pulse corresponding to the last transmitted + data bit (MSB) has to be output on the SCLK pin in synchronous mode. + This parameter can be a value of @ref SMARTCARD_Last_Bit */ + + uint32_t OneBitSampling; /*!< Specifies wether a single sample or three samples' majority vote is selected. + Selecting the single sample method increases the receiver tolerance to clock + deviations. This parameter can be a value of @ref SMARTCARD_OneBit_Sampling. */ + + uint32_t Prescaler; /*!< Specifies the SmartCard Prescaler */ + + uint32_t GuardTime; /*!< Specifies the SmartCard Guard Time */ + + uint32_t NACKState; /*!< Specifies whether the SmartCard NACK transmission is enabled + in case of parity error. + This parameter can be a value of @ref SMARTCARD_NACK_Enable */ + + uint32_t TimeOutEnable; /*!< Specifies whether the receiver timeout is enabled. + This parameter can be a value of @ref SMARTCARD_Timeout_Enable*/ + + uint32_t TimeOutValue; /*!< Specifies the receiver time out value in number of baud blocks: + it is used to implement the Character Wait Time (CWT) and + Block Wait Time (BWT). It is coded over 24 bits. */ + + uint32_t BlockLength; /*!< Specifies the SmartCard Block Length in T=1 Reception mode. + This parameter can be any value from 0x0 to 0xFF */ + + uint32_t AutoRetryCount; /*!< Specifies the SmartCard auto-retry count (number of retries in + receive and transmit mode). When set to 0, retransmission is + disabled. Otherwise, its maximum value is 7 (before signalling + an error) */ + +}SMARTCARD_InitTypeDef; + +/** + * @brief SMARTCARD advanced features initalization structure definition + */ +typedef struct +{ + uint32_t AdvFeatureInit; /*!< Specifies which advanced SMARTCARD features is initialized. Several + advanced features may be initialized at the same time. This parameter + can be a value of @ref SMARTCARD_Advanced_Features_Initialization_Type */ + + uint32_t TxPinLevelInvert; /*!< Specifies whether the TX pin active level is inverted. + This parameter can be a value of @ref SMARTCARD_Tx_Inv */ + + uint32_t RxPinLevelInvert; /*!< Specifies whether the RX pin active level is inverted. + This parameter can be a value of @ref SMARTCARD_Rx_Inv */ + + uint32_t DataInvert; /*!< Specifies whether data are inverted (positive/direct logic + vs negative/inverted logic). + This parameter can be a value of @ref SMARTCARD_Data_Inv */ + + uint32_t Swap; /*!< Specifies whether TX and RX pins are swapped. + This parameter can be a value of @ref SMARTCARD_Rx_Tx_Swap */ + + uint32_t OverrunDisable; /*!< Specifies whether the reception overrun detection is disabled. + This parameter can be a value of @ref SMARTCARD_Overrun_Disable */ + + uint32_t DMADisableonRxError; /*!< Specifies whether the DMA is disabled in case of reception error. + This parameter can be a value of @ref SMARTCARD_DMA_Disable_on_Rx_Error */ + + uint32_t MSBFirst; /*!< Specifies whether MSB is sent first on UART line. + This parameter can be a value of @ref SMARTCARD_MSB_First */ +}SMARTCARD_AdvFeatureInitTypeDef; + +/** + * @brief HAL State structures definition + */ +typedef enum +{ + HAL_SMARTCARD_STATE_RESET = 0x00, /*!< Peripheral is not yet Initialized */ + HAL_SMARTCARD_STATE_READY = 0x01, /*!< Peripheral Initialized and ready for use */ + HAL_SMARTCARD_STATE_BUSY = 0x02, /*!< an internal process is ongoing */ + HAL_SMARTCARD_STATE_BUSY_TX = 0x12, /*!< Data Transmission process is ongoing */ + HAL_SMARTCARD_STATE_BUSY_RX = 0x22, /*!< Data Reception process is ongoing */ + HAL_SMARTCARD_STATE_BUSY_TX_RX = 0x32, /*!< Data Transmission and Reception process is ongoing */ + HAL_SMARTCARD_STATE_TIMEOUT = 0x03, /*!< Timeout state */ + HAL_SMARTCARD_STATE_ERROR = 0x04 /*!< Error */ +}HAL_SMARTCARD_StateTypeDef; + +/** + * @brief HAL SMARTCARD Error Code structure definition + */ +typedef enum +{ + HAL_SMARTCARD_ERROR_NONE = 0x00, /*!< No error */ + HAL_SMARTCARD_ERROR_PE = 0x01, /*!< Parity error */ + HAL_SMARTCARD_ERROR_NE = 0x02, /*!< Noise error */ + HAL_SMARTCARD_ERROR_FE = 0x04, /*!< frame error */ + HAL_SMARTCARD_ERROR_ORE = 0x08, /*!< Overrun error */ + HAL_SMARTCARD_ERROR_DMA = 0x10, /*!< DMA transfer error */ + HAL_SMARTCARD_ERROR_RTO = 0x20 /*!< Receiver TimeOut error */ +}HAL_SMARTCARD_ErrorTypeDef; + +/** + * @brief SMARTCARD clock sources definition + */ +typedef enum +{ + SMARTCARD_CLOCKSOURCE_PCLK1 = 0x00, /*!< PCLK1 clock source */ + SMARTCARD_CLOCKSOURCE_PCLK2 = 0x01, /*!< PCLK2 clock source */ + SMARTCARD_CLOCKSOURCE_HSI = 0x02, /*!< HSI clock source */ + SMARTCARD_CLOCKSOURCE_SYSCLK = 0x04, /*!< SYSCLK clock source */ + SMARTCARD_CLOCKSOURCE_LSE = 0x08 /*!< LSE clock source */ +}SMARTCARD_ClockSourceTypeDef; + +/** + * @brief SMARTCARD handle Structure definition + */ +typedef struct +{ + USART_TypeDef *Instance; /* USART registers base address */ + + SMARTCARD_InitTypeDef Init; /* SmartCard communication parameters */ + + SMARTCARD_AdvFeatureInitTypeDef AdvancedInit; /* SmartCard advanced features initialization parameters */ + + uint8_t *pTxBuffPtr; /* Pointer to SmartCard Tx transfer Buffer */ + + uint16_t TxXferSize; /* SmartCard Tx Transfer size */ + + uint16_t TxXferCount; /* SmartCard Tx Transfer Counter */ + + uint8_t *pRxBuffPtr; /* Pointer to SmartCard Rx transfer Buffer */ + + uint16_t RxXferSize; /* SmartCard Rx Transfer size */ + + uint16_t RxXferCount; /* SmartCard Rx Transfer Counter */ + + DMA_HandleTypeDef *hdmatx; /* SmartCard Tx DMA Handle parameters */ + + DMA_HandleTypeDef *hdmarx; /* SmartCard Rx DMA Handle parameters */ + + HAL_LockTypeDef Lock; /* Locking object */ + + __IO HAL_SMARTCARD_StateTypeDef State; /* SmartCard communication state */ + + __IO HAL_SMARTCARD_ErrorTypeDef ErrorCode; /* SmartCard Error code */ + +}SMARTCARD_HandleTypeDef; + +/* Exported constants --------------------------------------------------------*/ +/** @defgroup SMARTCARD_Exported_Constants + * @{ + */ + +/** @defgroup SMARTCARD_Word_Length SMARTCARD Word Length + * @{ + */ +#define SMARTCARD_WORDLENGTH_9B ((uint32_t)USART_CR1_M_0) +#define IS_SMARTCARD_WORD_LENGTH(LENGTH) ((LENGTH) == SMARTCARD_WORDLENGTH_9B) +/** + * @} + */ + +/** @defgroup SMARTCARD_Stop_Bits SMARTCARD Stop Bits + * @{ + */ +#define SMARTCARD_STOPBITS_1_5 ((uint32_t)(USART_CR2_STOP)) +#define IS_SMARTCARD_STOPBITS(STOPBITS) ((STOPBITS) == SMARTCARD_STOPBITS_1_5) +/** + * @} + */ + +/** @defgroup SMARTCARD_Parity SMARTCARD Parity + * @{ + */ +#define SMARTCARD_PARITY_EVEN ((uint32_t)USART_CR1_PCE) +#define SMARTCARD_PARITY_ODD ((uint32_t)(USART_CR1_PCE | USART_CR1_PS)) +#define IS_SMARTCARD_PARITY(PARITY) (((PARITY) == SMARTCARD_PARITY_EVEN) || \ + ((PARITY) == SMARTCARD_PARITY_ODD)) +/** + * @} + */ + +/** @defgroup SMARTCARD_Mode SMARTCARD Transfer Mode + * @{ + */ +#define SMARTCARD_MODE_RX ((uint32_t)USART_CR1_RE) +#define SMARTCARD_MODE_TX ((uint32_t)USART_CR1_TE) +#define SMARTCARD_MODE_TX_RX ((uint32_t)(USART_CR1_TE |USART_CR1_RE)) +#define IS_SMARTCARD_MODE(MODE) ((((MODE) & (uint32_t)0xFFF3) == 0x00) && ((MODE) != (uint32_t)0x00)) +/** + * @} + */ + +/** @defgroup SMARTCARD_Clock_Polarity SMARTCARD Clock Polarity + * @{ + */ +#define SMARTCARD_POLARITY_LOW ((uint32_t)0x0000) +#define SMARTCARD_POLARITY_HIGH ((uint32_t)USART_CR2_CPOL) +#define IS_SMARTCARD_POLARITY(CPOL) (((CPOL) == SMARTCARD_POLARITY_LOW) || ((CPOL) == SMARTCARD_POLARITY_HIGH)) +/** + * @} + */ + +/** @defgroup SMARTCARD_Clock_Phase SMARTCARD Clock Phase + * @{ + */ +#define SMARTCARD_PHASE_1EDGE ((uint32_t)0x0000) +#define SMARTCARD_PHASE_2EDGE ((uint32_t)USART_CR2_CPHA) +#define IS_SMARTCARD_PHASE(CPHA) (((CPHA) == SMARTCARD_PHASE_1EDGE) || ((CPHA) == SMARTCARD_PHASE_2EDGE)) +/** + * @} + */ + +/** @defgroup SMARTCARD_Last_Bit SMARTCARD Last Bit + * @{ + */ +#define SMARTCARD_LASTBIT_DISABLE ((uint32_t)0x0000) +#define SMARTCARD_LASTBIT_ENABLE ((uint32_t)USART_CR2_LBCL) +#define IS_SMARTCARD_LASTBIT(LASTBIT) (((LASTBIT) == SMARTCARD_LASTBIT_DISABLE) || \ + ((LASTBIT) == SMARTCARD_LASTBIT_ENABLE)) +/** + * @} + */ + +/** @defgroup SMARTCARD_OneBit_Sampling SMARTCARD One Bit Sampling Method + * @{ + */ +#define SMARTCARD_ONEBIT_SAMPLING_DISABLED ((uint32_t)0x0000) +#define SMARTCARD_ONEBIT_SAMPLING_ENABLED ((uint32_t)USART_CR3_ONEBIT) +#define IS_SMARTCARD_ONEBIT_SAMPLING(ONEBIT) (((ONEBIT) == SMARTCARD_ONEBIT_SAMPLING_DISABLED) || \ + ((ONEBIT) == SMARTCARD_ONEBIT_SAMPLING_ENABLED)) +/** + * @} + */ + + +/** @defgroup SMARTCARD_NACK_Enable SMARTCARD NACK Enable + * @{ + */ +#define SMARTCARD_NACK_ENABLED ((uint32_t)USART_CR3_NACK) +#define SMARTCARD_NACK_DISABLED ((uint32_t)0x0000) +#define IS_SMARTCARD_NACK(NACK) (((NACK) == SMARTCARD_NACK_ENABLED) || \ + ((NACK) == SMARTCARD_NACK_DISABLED)) +/** + * @} + */ + +/** @defgroup SMARTCARD_Timeout_Enable SMARTCARD Timeout Enable + * @{ + */ +#define SMARTCARD_TIMEOUT_DISABLED ((uint32_t)0x00000000) +#define SMARTCARD_TIMEOUT_ENABLED ((uint32_t)USART_CR2_RTOEN) +#define IS_SMARTCARD_TIMEOUT(TIMEOUT) (((TIMEOUT) == SMARTCARD_TIMEOUT_DISABLED) || \ + ((TIMEOUT) == SMARTCARD_TIMEOUT_ENABLED)) +/** + * @} + */ + +/** @defgroup SmartCard_DMA_Requests + * @{ + */ + +#define SMARTCARD_DMAREQ_TX ((uint32_t)USART_CR3_DMAT) +#define SMARTCARD_DMAREQ_RX ((uint32_t)USART_CR3_DMAR) + +/** + * @} + */ + +/** @defgroup SMARTCARD_Advanced_Features_Initialization_Type SMARTCARD advanced feature initialization type + * @{ + */ +#define SMARTCARD_ADVFEATURE_NO_INIT ((uint32_t)0x00000000) +#define SMARTCARD_ADVFEATURE_TXINVERT_INIT ((uint32_t)0x00000001) +#define SMARTCARD_ADVFEATURE_RXINVERT_INIT ((uint32_t)0x00000002) +#define SMARTCARD_ADVFEATURE_DATAINVERT_INIT ((uint32_t)0x00000004) +#define SMARTCARD_ADVFEATURE_SWAP_INIT ((uint32_t)0x00000008) +#define SMARTCARD_ADVFEATURE_RXOVERRUNDISABLE_INIT ((uint32_t)0x00000010) +#define SMARTCARD_ADVFEATURE_DMADISABLEONERROR_INIT ((uint32_t)0x00000020) +#define SMARTCARD_ADVFEATURE_MSBFIRST_INIT ((uint32_t)0x00000080) +#define IS_SMARTCARD_ADVFEATURE_INIT(INIT) ((INIT) <= (SMARTCARD_ADVFEATURE_NO_INIT | \ + SMARTCARD_ADVFEATURE_TXINVERT_INIT | \ + SMARTCARD_ADVFEATURE_RXINVERT_INIT | \ + SMARTCARD_ADVFEATURE_DATAINVERT_INIT | \ + SMARTCARD_ADVFEATURE_SWAP_INIT | \ + SMARTCARD_ADVFEATURE_RXOVERRUNDISABLE_INIT | \ + SMARTCARD_ADVFEATURE_DMADISABLEONERROR_INIT | \ + SMARTCARD_ADVFEATURE_MSBFIRST_INIT)) +/** + * @} + */ + +/** @defgroup SMARTCARD_Tx_Inv SMARTCARD advanced feature TX pin active level inversion + * @{ + */ +#define SMARTCARD_ADVFEATURE_TXINV_DISABLE ((uint32_t)0x00000000) +#define SMARTCARD_ADVFEATURE_TXINV_ENABLE ((uint32_t)USART_CR2_TXINV) +#define IS_SMARTCARD_ADVFEATURE_TXINV(TXINV) (((TXINV) == SMARTCARD_ADVFEATURE_TXINV_DISABLE) || \ + ((TXINV) == SMARTCARD_ADVFEATURE_TXINV_ENABLE)) +/** + * @} + */ + +/** @defgroup SMARTCARD_Rx_Inv SMARTCARD advanced feature RX pin active level inversion + * @{ + */ +#define SMARTCARD_ADVFEATURE_RXINV_DISABLE ((uint32_t)0x00000000) +#define SMARTCARD_ADVFEATURE_RXINV_ENABLE ((uint32_t)USART_CR2_RXINV) +#define IS_SMARTCARD_ADVFEATURE_RXINV(RXINV) (((RXINV) == SMARTCARD_ADVFEATURE_RXINV_DISABLE) || \ + ((RXINV) == SMARTCARD_ADVFEATURE_RXINV_ENABLE)) +/** + * @} + */ + +/** @defgroup SMARTCARD_Data_Inv SMARTCARD advanced feature Binary Data inversion + * @{ + */ +#define SMARTCARD_ADVFEATURE_DATAINV_DISABLE ((uint32_t)0x00000000) +#define SMARTCARD_ADVFEATURE_DATAINV_ENABLE ((uint32_t)USART_CR2_DATAINV) +#define IS_SMARTCARD_ADVFEATURE_DATAINV(DATAINV) (((DATAINV) == SMARTCARD_ADVFEATURE_DATAINV_DISABLE) || \ + ((DATAINV) == SMARTCARD_ADVFEATURE_DATAINV_ENABLE)) +/** + * @} + */ + +/** @defgroup SMARTCARD_Rx_Tx_Swap SMARTCARD advanced feature RX TX pins swap + * @{ + */ +#define SMARTCARD_ADVFEATURE_SWAP_DISABLE ((uint32_t)0x00000000) +#define SMARTCARD_ADVFEATURE_SWAP_ENABLE ((uint32_t)USART_CR2_SWAP) +#define IS_SMARTCARD_ADVFEATURE_SWAP(SWAP) (((SWAP) == SMARTCARD_ADVFEATURE_SWAP_DISABLE) || \ + ((SWAP) == SMARTCARD_ADVFEATURE_SWAP_ENABLE)) +/** + * @} + */ + +/** @defgroup SMARTCARD_Overrun_Disable SMARTCARD advanced feature Overrun Disable + * @{ + */ +#define SMARTCARD_ADVFEATURE_OVERRUN_ENABLE ((uint32_t)0x00000000) +#define SMARTCARD_ADVFEATURE_OVERRUN_DISABLE ((uint32_t)USART_CR3_OVRDIS) +#define IS_SMARTCARD_OVERRUN(OVERRUN) (((OVERRUN) == SMARTCARD_ADVFEATURE_OVERRUN_ENABLE) || \ + ((OVERRUN) == SMARTCARD_ADVFEATURE_OVERRUN_DISABLE)) +/** + * @} + */ + +/** @defgroup SMARTCARD_DMA_Disable_on_Rx_Error SMARTCARD advanced feature DMA Disable on Rx Error + * @{ + */ +#define SMARTCARD_ADVFEATURE_DMA_ENABLEONRXERROR ((uint32_t)0x00000000) +#define SMARTCARD_ADVFEATURE_DMA_DISABLEONRXERROR ((uint32_t)USART_CR3_DDRE) +#define IS_SMARTCARD_ADVFEATURE_DMAONRXERROR(DMA) (((DMA) == SMARTCARD_ADVFEATURE_DMA_ENABLEONRXERROR) || \ + ((DMA) == SMARTCARD_ADVFEATURE_DMA_DISABLEONRXERROR)) +/** + * @} + */ + +/** @defgroup SMARTCARD_MSB_First SMARTCARD advanced feature MSB first + * @{ + */ +#define SMARTCARD_ADVFEATURE_MSBFIRST_DISABLE ((uint32_t)0x00000000) +#define SMARTCARD_ADVFEATURE_MSBFIRST_ENABLE ((uint32_t)USART_CR2_MSBFIRST) +#define IS_SMARTCARD_ADVFEATURE_MSBFIRST(MSBFIRST) (((MSBFIRST) == SMARTCARD_ADVFEATURE_MSBFIRST_DISABLE) || \ + ((MSBFIRST) == SMARTCARD_ADVFEATURE_MSBFIRST_ENABLE)) +/** + * @} + */ + +/** @defgroup SmartCard_Flags SMARTCARD Flags + * Elements values convention: 0xXXXX + * - 0xXXXX : Flag mask in the ISR register + * @{ + */ +#define SMARTCARD_FLAG_REACK ((uint32_t)0x00400000) +#define SMARTCARD_FLAG_TEACK ((uint32_t)0x00200000) +#define SMARTCARD_FLAG_BUSY ((uint32_t)0x00010000) +#define SMARTCARD_FLAG_EOBF ((uint32_t)0x00001000) +#define SMARTCARD_FLAG_RTOF ((uint32_t)0x00000800) +#define SMARTCARD_FLAG_TXE ((uint32_t)0x00000080) +#define SMARTCARD_FLAG_TC ((uint32_t)0x00000040) +#define SMARTCARD_FLAG_RXNE ((uint32_t)0x00000020) +#define SMARTCARD_FLAG_ORE ((uint32_t)0x00000008) +#define SMARTCARD_FLAG_NE ((uint32_t)0x00000004) +#define SMARTCARD_FLAG_FE ((uint32_t)0x00000002) +#define SMARTCARD_FLAG_PE ((uint32_t)0x00000001) +/** + * @} + */ + +/** @defgroup SMARTCARD_Interrupt_definition SMARTCARD Interrupts Definition + * Elements values convention: 0000ZZZZ0XXYYYYYb + * - YYYYY : Interrupt source position in the XX register (5bits) + * - XX : Interrupt source register (2bits) + * - 01: CR1 register + * - 10: CR2 register + * - 11: CR3 register + * - ZZZZ : Flag position in the ISR register(4bits) + * @{ + */ + +#define SMARTCARD_IT_PE ((uint16_t)0x0028) +#define SMARTCARD_IT_TXE ((uint16_t)0x0727) +#define SMARTCARD_IT_TC ((uint16_t)0x0626) +#define SMARTCARD_IT_RXNE ((uint16_t)0x0525) + +#define SMARTCARD_IT_ERR ((uint16_t)0x0060) +#define SMARTCARD_IT_ORE ((uint16_t)0x0300) +#define SMARTCARD_IT_NE ((uint16_t)0x0200) +#define SMARTCARD_IT_FE ((uint16_t)0x0100) + +#define SMARTCARD_IT_EOB ((uint16_t)0x0C3B) +#define SMARTCARD_IT_RTO ((uint16_t)0x0B3A) +/** + * @} + */ + + +/** @defgroup SMARTCARD_IT_CLEAR_Flags SMARTCARD Interruption Clear Flags + * @{ + */ +#define SMARTCARD_CLEAR_PEF USART_ICR_PECF /*!< Parity Error Clear Flag */ +#define SMARTCARD_CLEAR_FEF USART_ICR_FECF /*!< Framing Error Clear Flag */ +#define SMARTCARD_CLEAR_NEF USART_ICR_NCF /*!< Noise detected Clear Flag */ +#define SMARTCARD_CLEAR_OREF USART_ICR_ORECF /*!< OverRun Error Clear Flag */ +#define SMARTCARD_CLEAR_TCF USART_ICR_TCCF /*!< Transmission Complete Clear Flag */ +#define SMARTCARD_CLEAR_RTOF USART_ICR_RTOCF /*!< Receiver Time Out Clear Flag */ +#define SMARTCARD_CLEAR_EOBF USART_ICR_EOBCF /*!< End Of Block Clear Flag */ +/** + * @} + */ + +/** @defgroup SMARTCARD_Request_Parameters SMARTCARD Request Parameters + * @{ + */ +#define SMARTCARD_RXDATA_FLUSH_REQUEST ((uint32_t)USART_RQR_RXFRQ) /*!< Receive Data flush Request */ +#define SMARTCARD_TXDATA_FLUSH_REQUEST ((uint32_t)USART_RQR_TXFRQ) /*!< Transmit data flush Request */ +#define IS_SMARTCARD_REQUEST_PARAMETER(PARAM) (((PARAM) == SMARTCARD_RXDATA_FLUSH_REQUEST) || \ + ((PARAM) == SMARTCARD_TXDATA_FLUSH_REQUEST)) +/** + * @} + */ + + +/** @defgroup SMARTCARD_CR3_SCARCNT_LSB_POS SMARTCARD auto retry counter LSB position in CR3 register + * @{ + */ +#define SMARTCARD_CR3_SCARCNT_LSB_POS ((uint32_t) 17) +/** + * @} + */ + +/** @defgroup SMARTCARD_GTPR_GT_LSB_POS SMARTCARD guard time value LSB position in GTPR register + * @{ + */ +#define SMARTCARD_GTPR_GT_LSB_POS ((uint32_t) 8) +/** + * @} + */ + +/** @defgroup SMARTCARD_RTOR_BLEN_LSB_POS SMARTCARD block length LSB position in RTOR register + * @{ + */ +#define SMARTCARD_RTOR_BLEN_LSB_POS ((uint32_t) 24) +/** + * @} + */ + +/** @defgroup SMARTCARD_Interruption_Mask SMARTCARD interruptions flag mask + * @{ + */ +#define SMARTCARD_IT_MASK ((uint16_t)0x001F) +/** + * @} + */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ +/** @defgroup SMARTCARD_Exported_Macros + * @{ + */ + +/** @brief Reset SMARTCARD handle state + * @param __HANDLE__: specifies the SMARTCARD Handle. + * The Handle Instance which can be USART1 or USART2 + * @retval None + */ +#define __HAL_SMARTCARD_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_SMARTCARD_STATE_RESET) + +/** @brief Flushs the Smartcard DR register + * @param __HANDLE__: specifies the SMARTCARD Handle. + * The Handle Instance which can be USART1 or USART2. + * @retval None + */ +#define __HAL_SMARTCARD_FLUSH_DRREGISTER(__HANDLE__) (__HAL_SMARTCARD_SEND_REQ((__HANDLE__), SMARTCARD_RXDATA_FLUSH_REQUEST)) + +/** @brief Checks whether the specified Smartcard flag is set or not. + * @param __HANDLE__: specifies the SMARTCARD Handle. + * The Handle Instance which can be USART1 or USART2. + * @param __FLAG__: specifies the flag to check. + * This parameter can be one of the following values: + * @arg SMARTCARD_FLAG_REACK: Receive enable ackowledge flag + * @arg SMARTCARD_FLAG_TEACK: Transmit enable ackowledge flag + * @arg SMARTCARD_FLAG_BUSY: Busy flag + * @arg SMARTCARD_FLAG_EOBF: End of block flag + * @arg SMARTCARD_FLAG_RTOF: Receiver timeout flag + * @arg SMARTCARD_FLAG_TXE: Transmit data register empty flag + * @arg SMARTCARD_FLAG_TC: Transmission Complete flag + * @arg SMARTCARD_FLAG_RXNE: Receive data register not empty flag + * @arg SMARTCARD_FLAG_ORE: OverRun Error flag + * @arg SMARTCARD_FLAG_NE: Noise Error flag + * @arg SMARTCARD_FLAG_FE: Framing Error flag + * @arg SMARTCARD_FLAG_PE: Parity Error flag + * @retval The new state of __FLAG__ (TRUE or FALSE). + */ +#define __HAL_SMARTCARD_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->ISR & (__FLAG__)) == (__FLAG__)) + +/** @brief Enables the specified SmartCard interrupt. + * @param __HANDLE__: specifies the SMARTCARD Handle. + * The Handle Instance which can be USART1 or USART2. + * @param __INTERRUPT__: specifies the SMARTCARD interrupt to enable. + * This parameter can be one of the following values: + * @arg SMARTCARD_IT_EOBF: End Of Block interrupt + * @arg SMARTCARD_IT_RTOF: Receive TimeOut interrupt + * @arg SMARTCARD_IT_TXE: Transmit Data Register empty interrupt + * @arg SMARTCARD_IT_TC: Transmission complete interrupt + * @arg SMARTCARD_IT_RXNE: Receive Data register not empty interrupt + * @arg SMARTCARD_IT_PE: Parity Error interrupt + * @arg SMARTCARD_IT_ERR: Error interrupt(Frame error, noise error, overrun error) + * @retval None + */ +#define __HAL_SMARTCARD_ENABLE_IT(__HANDLE__, __INTERRUPT__) (((((uint8_t)(__INTERRUPT__)) >> 5) == 1)? ((__HANDLE__)->Instance->CR1 |= (1 << ((__INTERRUPT__) & SMARTCARD_IT_MASK))): \ + ((((uint8_t)(__INTERRUPT__)) >> 5) == 2)? ((__HANDLE__)->Instance->CR2 |= (1 << ((__INTERRUPT__) & SMARTCARD_IT_MASK))): \ + ((__HANDLE__)->Instance->CR3 |= (1 << ((__INTERRUPT__) & SMARTCARD_IT_MASK)))) +/** @brief Disables the specified SmartCard interrupt. + * @param __HANDLE__: specifies the SMARTCARD Handle. + * The Handle Instance which can be USART1 or USART2. + * @param __INTERRUPT__: specifies the SMARTCARD interrupt to enable. + * This parameter can be one of the following values: + * @arg SMARTCARD_IT_EOBF: End Of Block interrupt + * @arg SMARTCARD_IT_RTOF: Receive TimeOut interrupt + * @arg SMARTCARD_IT_TXE: Transmit Data Register empty interrupt + * @arg SMARTCARD_IT_TC: Transmission complete interrupt + * @arg SMARTCARD_IT_RXNE: Receive Data register not empty interrupt + * @arg SMARTCARD_IT_PE: Parity Error interrupt + * @arg SMARTCARD_IT_ERR: Error interrupt(Frame error, noise error, overrun error) + * @retval None + */ +#define __HAL_SMARTCARD_DISABLE_IT(__HANDLE__, __INTERRUPT__) (((((uint8_t)(__INTERRUPT__)) >> 5) == 1)? ((__HANDLE__)->Instance->CR1 &= ~ ((uint32_t)1 << ((__INTERRUPT__) & SMARTCARD_IT_MASK))): \ + ((((uint8_t)(__INTERRUPT__)) >> 5) == 2)? ((__HANDLE__)->Instance->CR2 &= ~ ((uint32_t)1 << ((__INTERRUPT__) & SMARTCARD_IT_MASK))): \ + ((__HANDLE__)->Instance->CR3 &= ~ ((uint32_t)1 << ((__INTERRUPT__) & SMARTCARD_IT_MASK)))) + +/** @brief Checks whether the specified SmartCard interrupt has occurred or not. + * @param __HANDLE__: specifies the SMARTCARD Handle. + * The Handle Instance which can be USART1 or USART2. + * @param __IT__: specifies the SMARTCARD interrupt to check. + * This parameter can be one of the following values: + * @arg SMARTCARD_IT_EOBF: End Of Block interrupt + * @arg SMARTCARD_IT_RTOF: Receive TimeOut interrupt + * @arg SMARTCARD_IT_TXE: Transmit Data Register empty interrupt + * @arg SMARTCARD_IT_TC: Transmission complete interrupt + * @arg SMARTCARD_IT_RXNE: Receive Data register not empty interrupt + * @arg SMARTCARD_IT_ORE: OverRun Error interrupt + * @arg SMARTCARD_IT_NE: Noise Error interrupt + * @arg SMARTCARD_IT_FE: Framing Error interrupt + * @arg SMARTCARD_IT_PE: Parity Error interrupt + * @retval The new state of __IT__ (TRUE or FALSE). + */ +#define __HAL_SMARTCARD_GET_IT(__HANDLE__, __IT__) ((__HANDLE__)->Instance->ISR & ((uint32_t)1 << ((__IT__)>> 0x08))) + +/** @brief Checks whether the specified SmartCard interrupt interrupt source is enabled. + * @param __HANDLE__: specifies the SMARTCARD Handle. + * The Handle Instance which can be USART1 or USART2. + * @param __IT__: specifies the SMARTCARD interrupt source to check. + * This parameter can be one of the following values: + * @arg SMARTCARD_IT_EOBF: End Of Block interrupt + * @arg SMARTCARD_IT_RTOF: Receive TimeOut interrupt + * @arg SMARTCARD_IT_TXE: Transmit Data Register empty interrupt + * @arg SMARTCARD_IT_TC: Transmission complete interrupt + * @arg SMARTCARD_IT_RXNE: Receive Data register not empty interrupt + * @arg SMARTCARD_IT_ORE: OverRun Error interrupt + * @arg SMARTCARD_IT_NE: Noise Error interrupt + * @arg SMARTCARD_IT_FE: Framing Error interrupt + * @arg SMARTCARD_IT_PE: Parity Error interrupt + * @retval The new state of __IT__ (TRUE or FALSE). + */ +#define __HAL_SMARTCARD_GET_IT_SOURCE(__HANDLE__, __IT__) ((((((uint8_t)(__IT__)) >> 5) == 1)? (__HANDLE__)->Instance->CR1:(((((uint8_t)(__IT__)) >> 5) == 2)? \ + (__HANDLE__)->Instance->CR2 : (__HANDLE__)->Instance->CR3)) & ((uint32_t)1 << \ + (((uint16_t)(__IT__)) & SMARTCARD_IT_MASK))) + + +/** @brief Clears the specified SMARTCARD ISR flag, in setting the proper ICR register flag. + * @param __HANDLE__: specifies the SMARTCARD Handle. + * The Handle Instance which can be USART1 or USART2. + * @param __IT_CLEAR__: specifies the interrupt clear register flag that needs to be set + * to clear the corresponding interrupt + * This parameter can be one of the following values: + * @arg USART_CLEAR_PEF: Parity Error Clear Flag + * @arg USART_CLEAR_FEF: Framing Error Clear Flag + * @arg USART_CLEAR_NEF: Noise detected Clear Flag + * @arg USART_CLEAR_OREF: OverRun Error Clear Flag + * @arg USART_CLEAR_TCF: Transmission Complete Clear Flag + * @arg USART_CLEAR_RTOF: Receiver Time Out Clear Flag + * @arg USART_CLEAR_EOBF: End Of Block Clear Flag + * @retval None + */ +#define __HAL_SMARTCARD_CLEAR_IT(__HANDLE__, __IT_CLEAR__) ((__HANDLE__)->Instance->ICR |= (uint32_t)(__IT_CLEAR__)) + +/** @brief Set a specific SMARTCARD request flag. + * @param __HANDLE__: specifies the SMARTCARD Handle. + * The Handle Instance which can be USART1 or USART2. + * @param __REQ__: specifies the request flag to set + * This parameter can be one of the following values: + * @arg SMARTCARD_RXDATA_FLUSH_REQUEST: Receive Data flush Request + * @arg SMARTCARD_TXDATA_FLUSH_REQUEST: Transmit data flush Request + * + * @retval None + */ +#define __HAL_SMARTCARD_SEND_REQ(__HANDLE__, __REQ__) ((__HANDLE__)->Instance->RQR |= (uint32_t)(__REQ__)) + +/** @brief Enable the USART associated to the SMARTCARD Handle + * @param __HANDLE__: specifies the SMARTCARD Handle. + * The Handle Instance which can be USART1 or USART2. + * @retval None + */ +#define __HAL_SMARTCARD_ENABLE(__HANDLE__) ( (__HANDLE__)->Instance->CR1 |= USART_CR1_UE) + +/** @brief Disable the USART associated to the SMARTCARD Handle + * @param __HANDLE__: specifies the SMARTCARD Handle. + * The Handle Instance which can be USART1 or USART2. + * @retval None + */ +#define __HAL_SMARTCARD_DISABLE(__HANDLE__) ( (__HANDLE__)->Instance->CR1 &= ~USART_CR1_UE) + +/** @brief Macros to enable or disable the SmartCard DMA request. + * @param __HANDLE__: specifies the SMARTCARD Handle. + * The Handle Instance which can be USART1 or USART2. + * @param __REQUEST__: specifies the SmartCard DMA request. + * This parameter can be one of the following values: + * @arg SMARTCARD_DMAREQ_TX: SmartCard DMA transmit request + * @arg SMARTCARD_DMAREQ_RX: SmartCard DMA receive request + */ +#define __HAL_SMARTCARD_DMA_REQUEST_ENABLE(__HANDLE__, __REQUEST__) ((__HANDLE__)->Instance->CR3 |= (__REQUEST__)) +#define __HAL_SMARTCARD_DMA_REQUEST_DISABLE(__HANDLE__, __REQUEST__) ((__HANDLE__)->Instance->CR3 &= ~(__REQUEST__)) + +/** @brief Check the Baud rate range. The maximum Baud Rate is derived from the + * maximum clock on F3 (i.e. 72 MHz) divided by the oversampling used + * on the SMARTCARD (i.e. 16) + * @param __BAUDRATE__: Baud rate set by the configuration function. + * @retval Test result (TRUE or FALSE) + */ +#define IS_SMARTCARD_BAUDRATE(__BAUDRATE__) ((__BAUDRATE__) < 4500001) + +/** @brief Check the block length range. The maximum SMARTCARD block length is 0xFF. + * @param __LENGTH__: block length. + * @retval Test result (TRUE or FALSE) + */ +#define IS_SMARTCARD_BLOCKLENGTH(__LENGTH__) ((__LENGTH__) <= 0xFF) + +/** @brief Check the receiver timeout value. The maximum SMARTCARD receiver timeout + * value is 0xFFFFFF. + * @param __TIMEOUTVALUE__: receiver timeout value. + * @retval Test result (TRUE or FALSE) + */ +#define IS_SMARTCARD_TIMEOUT_VALUE(__TIMEOUTVALUE__) ((__TIMEOUTVALUE__) <= 0xFFFFFF) + +/** @brief Check the SMARTCARD autoretry counter value. The maximum number of + * retransmissions is 0x7. + * @param __COUNT__: number of retransmissions + * @retval Test result (TRUE or FALSE) + */ +#define IS_SMARTCARD_AUTORETRY_COUNT(__COUNT__) ((__COUNT__) <= 0x7) + +/** + * @} + */ + +/* Include SMARTCARD HAL Extension module */ +#include "stm32l0xx_hal_smartcard_ex.h" +/* Exported functions --------------------------------------------------------*/ +/* Initialization/de-initialization functions **********************************/ +HAL_StatusTypeDef HAL_SMARTCARD_Init(SMARTCARD_HandleTypeDef *hsc); +HAL_StatusTypeDef HAL_SMARTCARD_DeInit(SMARTCARD_HandleTypeDef *hsc); +void HAL_SMARTCARD_MspInit(SMARTCARD_HandleTypeDef *hsc); +void HAL_SMARTCARD_MspDeInit(SMARTCARD_HandleTypeDef *hsc); + +/* IO operation functions *******************************************************/ +HAL_StatusTypeDef HAL_SMARTCARD_Transmit(SMARTCARD_HandleTypeDef *hsc, uint8_t *pData, uint16_t Size, uint32_t Timeout); +HAL_StatusTypeDef HAL_SMARTCARD_Receive(SMARTCARD_HandleTypeDef *hsc, uint8_t *pData, uint16_t Size, uint32_t Timeout); +HAL_StatusTypeDef HAL_SMARTCARD_Transmit_IT(SMARTCARD_HandleTypeDef *hsc, uint8_t *pData, uint16_t Size); +HAL_StatusTypeDef HAL_SMARTCARD_Receive_IT(SMARTCARD_HandleTypeDef *hsc, uint8_t *pData, uint16_t Size); +HAL_StatusTypeDef HAL_SMARTCARD_Transmit_DMA(SMARTCARD_HandleTypeDef *hsc, uint8_t *pData, uint16_t Size); +HAL_StatusTypeDef HAL_SMARTCARD_Receive_DMA(SMARTCARD_HandleTypeDef *hsc, uint8_t *pData, uint16_t Size); +void HAL_SMARTCARD_IRQHandler(SMARTCARD_HandleTypeDef *hsc); +void HAL_SMARTCARD_TxCpltCallback(SMARTCARD_HandleTypeDef *hsc); +void HAL_SMARTCARD_RxCpltCallback(SMARTCARD_HandleTypeDef *hsc); +void HAL_SMARTCARD_ErrorCallback(SMARTCARD_HandleTypeDef *hsc); + +/* Peripheral Control functions ************************************************/ +/* Peripheral State functions **************************************************/ +HAL_SMARTCARD_StateTypeDef HAL_SMARTCARD_GetState(SMARTCARD_HandleTypeDef *hsc); +uint32_t HAL_SMARTCARD_GetError(SMARTCARD_HandleTypeDef *hsc); +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __STM32L0xx_HAL_SMARTCARD_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_smartcard_ex.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_smartcard_ex.c new file mode 100644 index 0000000000..bc888539cf --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_smartcard_ex.c @@ -0,0 +1,184 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_smartcard_ex.c + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief SMARTCARD HAL module driver. + * + * This file provides extended firmware functions to manage the following + * functionalities of the SmartCard. + * + Initialization and de-initialization functions + * + Peripheral Control functions + @verbatim + =============================================================================== + ##### How to use this driver ##### + =============================================================================== + [..] + The Extended SMARTCARD HAL driver can be used as follow: + + (#) After having configured the SMARTCARD basic features with HAL_SMARTCARD_Init(), + then if required, program SMARTCARD advanced features (TX/RX pins swap, TimeOut, + auto-retry counter,...) in the hsc AdvancedInit structure. + + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @defgroup SMARTCARDEx + * @brief SMARTCARD Extended HAL module driver + * @{ + */ +#ifdef HAL_SMARTCARD_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup SMARTCARDEx_Private_Functions + * @{ + */ + +/** @defgroup SMARTCARDEx_Group1 Extended Peripheral Control functions + * @brief Extended control functions + * +@verbatim + =============================================================================== + ##### Peripheral Control functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to initialize the SMARTCARD. + (+) HAL_SMARTCARDEx_BlockLength_Config() API allows to configure the Block Length on the fly + (+) HAL_SMARTCARDEx_TimeOut_Config() API allows to configure the receiver timeout value on the fly + (+) HAL_SMARTCARDEx_EnableReceiverTimeOut() API enables the receiver timeout feature + (+) HAL_SMARTCARDEx_DisableReceiverTimeOut() API disables the receiver timeout feature + +@endverbatim + * @{ + */ + +/** + * @brief Update on the fly the SMARTCARD block length in RTOR register + * @param hsc: SMARTCARD handle + * @param BlockLength: SMARTCARD block length (8-bit long at most) + * @retval None + */ +void HAL_SMARTCARDEx_BlockLength_Config(SMARTCARD_HandleTypeDef *hsc, uint8_t BlockLength) +{ + MODIFY_REG(hsc->Instance->RTOR, USART_RTOR_BLEN, ((uint32_t)BlockLength << SMARTCARD_RTOR_BLEN_LSB_POS)); +} + +/** + * @brief Update on the fly the receiver timeout value in RTOR register + * @param hsc: SMARTCARD handle + * @param TimeOutValue: receiver timeout value in number of baud blocks. The timeout + * value must be less or equal to 0x0FFFFFFFF. + * @retval None + */ +void HAL_SMARTCARDEx_TimeOut_Config(SMARTCARD_HandleTypeDef *hsc, uint32_t TimeOutValue) +{ + assert_param(IS_SMARTCARD_TIMEOUT_VALUE(hsc->Init.TimeOutValue)); + MODIFY_REG(hsc->Instance->RTOR, USART_RTOR_RTO, TimeOutValue); +} + +/** + * @brief Enable the SMARTCARD receiver timeout feature + * @param hsc: SMARTCARD handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMARTCARDEx_EnableReceiverTimeOut(SMARTCARD_HandleTypeDef *hsc) +{ + /* Process Locked */ + __HAL_LOCK(hsc); + + hsc->State = HAL_SMARTCARD_STATE_BUSY; + + /* Set the USART RTOEN bit */ + hsc->Instance->CR2 |= USART_CR2_RTOEN; + + hsc->State = HAL_SMARTCARD_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hsc); + + return HAL_OK; +} + +/** + * @brief Disable the SMARTCARD receiver timeout feature + * @param hsc: SMARTCARD handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMARTCARDEx_DisableReceiverTimeOut(SMARTCARD_HandleTypeDef *hsc) +{ + /* Process Locked */ + __HAL_LOCK(hsc); + + hsc->State = HAL_SMARTCARD_STATE_BUSY; + + /* Clear the USART RTOEN bit */ + hsc->Instance->CR2 &= ~(USART_CR2_RTOEN); + + hsc->State = HAL_SMARTCARD_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hsc); + + return HAL_OK; +} + +/** + * @} + */ + +/** + * @} + */ + +#endif /* HAL_SMARTCARD_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_smartcard_ex.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_smartcard_ex.h new file mode 100644 index 0000000000..0c971312a1 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_smartcard_ex.h @@ -0,0 +1,135 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_smartcard_ex.h + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief Header file of SMARTCARD HAL module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32L0xx_HAL_SMARTCARD_EX_H +#define __STM32L0xx_HAL_SMARTCARD_EX_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal_def.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @addtogroup SMARTCARDEx + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/* Exported constants --------------------------------------------------------*/ +/* Exported macro ------------------------------------------------------------*/ + +/** @brief Reports the SMARTCARD clock source. + * @param __HANDLE__: specifies the USART Handle + * @param __CLOCKSOURCE__ : output variable + * @retval the USART clocking source, written in __CLOCKSOURCE__. + */ +#define __HAL_SMARTCARD_GETCLOCKSOURCE(__HANDLE__,__CLOCKSOURCE__) \ + do { \ + if((__HANDLE__)->Instance == USART1) \ + { \ + switch(__HAL_RCC_GET_USART1_SOURCE()) \ + { \ + case RCC_USART1CLKSOURCE_PCLK2: \ + (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_PCLK2; \ + break; \ + case RCC_USART1CLKSOURCE_HSI: \ + (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_HSI; \ + break; \ + case RCC_USART1CLKSOURCE_SYSCLK: \ + (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_SYSCLK; \ + break; \ + case RCC_USART1CLKSOURCE_LSE: \ + (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_LSE; \ + break; \ + default: \ + break; \ + } \ + } \ + else if((__HANDLE__)->Instance == USART2) \ + { \ + switch(__HAL_RCC_GET_USART2_SOURCE()) \ + { \ + case RCC_USART2CLKSOURCE_PCLK1: \ + (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_PCLK1; \ + break; \ + case RCC_USART2CLKSOURCE_HSI: \ + (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_HSI; \ + break; \ + case RCC_USART2CLKSOURCE_SYSCLK: \ + (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_SYSCLK; \ + break; \ + case RCC_USART2CLKSOURCE_LSE: \ + (__CLOCKSOURCE__) = SMARTCARD_CLOCKSOURCE_LSE; \ + break; \ + default: \ + break; \ + } \ + } \ + } while(0) + +/* Exported functions --------------------------------------------------------*/ +/* Initialization and de-initialization functions ****************************/ +/* IO operation functions *****************************************************/ +/* Peripheral Control functions ***********************************************/ +void HAL_SMARTCARDEx_BlockLength_Config(SMARTCARD_HandleTypeDef *hsc, uint8_t BlockLength); +void HAL_SMARTCARDEx_TimeOut_Config(SMARTCARD_HandleTypeDef *hsc, uint32_t TimeOutValue); +HAL_StatusTypeDef HAL_SMARTCARDEx_EnableReceiverTimeOut(SMARTCARD_HandleTypeDef *hsc); +HAL_StatusTypeDef HAL_SMARTCARDEx_DisableReceiverTimeOut(SMARTCARD_HandleTypeDef *hsc); + +/* Peripheral State and Error functions ***************************************/ + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __STM32L0xx_HAL_SMARTCARD_EX_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_smbus.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_smbus.c new file mode 100644 index 0000000000..af2b4003af --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_smbus.c @@ -0,0 +1,1825 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_smbus.c + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief SMBUS HAL module driver. + * + * This file provides firmware functions to manage the following + * functionalities of the System Management Bus (SMBus) peripheral, + * based on I2C principales of operation : + * + Initialization/de-initialization functions + * + I/O operation functions + * + Peripheral Control functions + * + Peripheral State functions + * + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + The SMBUS HAL driver can be used as follows: + + (#) Declare a SMBUS_HandleTypeDef handle structure, for example: + SMBUS_HandleTypeDef hsmbus; + + (#)Initialize the SMBUS low level resources by implement the HAL_SMBUS_MspInit ()API: + (##) Enable the SMBUSx interface clock + (##) SMBUS pins configuration + (+) Enable the clock for the SMBUS GPIOs + (+) Configure SMBUS pins as alternate function open-drain + (##) NVIC configuration if you need to use interrupt process + (+) Configure the SMBUSx interrupt priority + (+) Enable the NVIC SMBUS IRQ Channel + + (#) Configure the Communication Clock Timing, Bus Timeout, Own Address1, Master Adressing Mode, + Dual Addressing mode, Own Address2, Own Address2 Mask, General call, Nostretch mode, + Peripheral mode and Packet Error Check mode in the hsmbus Init structure. + + (#) Initialize the SMBUS registers by calling the HAL_SMBUS_Init() API: + (+) These API's configures also the low level Hardware GPIO, CLOCK, CORTEX...etc) + by calling the customed HAL_SMBUS_MspInit(&hsmbus) API. + + (#) To check if target device is ready for communication, use the function HAL_SMBUS_IsDeviceReady() + + (#) For SMBUS IO operations, only one mode of operations is available within this driver : + + *** Interrupt mode IO operation *** + =================================== + [..] + (+) Transmit in master/host SMBUS mode an amount of data in non blocking mode using HAL_SMBUS_Master_Transmit_IT() + (++) At transmission end of transfer HAL_SMBUS_MasterTxCpltCallback is executed and user can + add his own code by customization of function pointer HAL_SMBUS_MasterTxCpltCallback + (+) Receive in master/host SMBUS mode an amount of data in non blocking mode using HAL_SMBUS_Master_Receive_IT() + (++) At reception end of transfer HAL_SMBUS_MasterRxCpltCallback is executed and user can + add his own code by customization of function pointer HAL_SMBUS_MasterRxCpltCallback + (+) Abort a master/host SMBUS process commnunication with Interrupt using HAL_SMBUS_Master_Abort_IT() + (++) The associated previous transfer callback is called at the end of abort process + (++) mean HAL_SMBUS_MasterTxCpltCallback in case of previous state was master transmit + (++) mean HAL_SMBUS_MasterRxCpltCallback in case of previous state was master receive + (+) Enable the Address listen mode in slave/device SMBUS mode using HAL_SMBUS_Slave_Listen_IT() + (++) When address slave/device SMBUS match, HAL_SMBUS_SlaveAddrCallback is executed and user can + add his own code to check the Address Match Code and the transmission direction request by master/host (Write/Read). + (++) At Listen mode end HAL_SMBUS_SlaveListenCpltCallback is executed and user can + add his own code by customization of function pointer HAL_SMBUS_SlaveListenCpltCallback + (+) Transmit in slave/device SMBUS mode an amount of data in non blocking mode using HAL_SMBUS_Slave_Transmit_IT() + (++) At transmission end of transfer HAL_SMBUS_SlaveTxCpltCallback is executed and user can + add his own code by customization of function pointer HAL_SMBUS_SlaveTxCpltCallback + (+) Receive in slave/device SMBUS mode an amount of data in non blocking mode using HAL_SMBUS_Slave_Receive_IT() + (++) At reception end of transfer HAL_SMBUS_SlaveRxCpltCallback is executed and user can + add his own code by customization of function pointer HAL_SMBUS_SlaveRxCpltCallback + (+) Enable/Disable the SMBUS alert mode using HAL_SMBUS_EnableAlert_IT() HAL_SMBUS_DisableAlert_IT() + (++) When SMBUS Alert is generated HAL_SMBUS_ErrorCallback() is executed and user can + add his own code by customization of function pointer HAL_SMBUS_ErrorCallback + to check the Alert Error Code using function HAL_SMBUS_GetError() + (+) Get HAL state machine or error values using HAL_SMBUS_GetState() or HAL_SMBUS_GetError() + (+) In case of transfer Error, HAL_SMBUS_ErrorCallback() function is executed and user can + add his own code by customization of function pointer HAL_SMBUS_ErrorCallback + to check the Error Code using function HAL_SMBUS_GetError() + + *** SMBUS HAL driver macros list *** + ================================== + [..] + Below the list of most used macros in SMBUS HAL driver. + + (+) __HAL_SMBUS_ENABLE: Enable the SMBUS peripheral + (+) __HAL_SMBUS_DISABLE: Disable the SMBUS peripheral + (+) __HAL_SMBUS_GET_FLAG : Checks whether the specified SMBUS flag is set or not + (+) __HAL_SMBUS_CLEAR_FLAG : Clears the specified SMBUS pending flag + (+) __HAL_SMBUS_ENABLE_IT: Enables the specified SMBUS interrupt + (+) __HAL_SMBUS_DISABLE_IT: Disables the specified SMBUS interrupt + + [..] + (@) You can refer to the SMBUS HAL driver header file for more useful macros + + + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @defgroup SMBUS + * @brief SMBUS HAL module driver + * @{ + */ + +#ifdef HAL_SMBUS_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +#define TIMING_CLEAR_MASK ((uint32_t)0xF0FFFFFF) /*Instance->ISR) +#define __SMBUS_CHECK_FLAG(__ISR__, __FLAG__) ((((__ISR__) & ((__FLAG__) & SMBUS_FLAG_MASK)) == ((__FLAG__) & SMBUS_FLAG_MASK))) + +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +static HAL_StatusTypeDef SMBUS_WaitOnFlagUntilTimeout(SMBUS_HandleTypeDef *hsmbus, uint32_t Flag, FlagStatus Status, uint32_t Timeout); + +static HAL_StatusTypeDef SMBUS_Enable_IRQ(SMBUS_HandleTypeDef *hsmbus, uint16_t InterruptRequest); +static HAL_StatusTypeDef SMBUS_Disable_IRQ(SMBUS_HandleTypeDef *hsmbus, uint16_t InterruptRequest); +static HAL_StatusTypeDef SMBUS_Master_ISR(SMBUS_HandleTypeDef *hsmbus); +static HAL_StatusTypeDef SMBUS_Slave_ISR(SMBUS_HandleTypeDef *hsmbus); + +static void SMBUS_TransferConfig(SMBUS_HandleTypeDef *hsmbus, uint16_t DevAddress, uint8_t Size, uint32_t Mode, uint32_t Request); + +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup SMBUS_Private_Functions + * @{ + */ + +/** @defgroup HAL_SMBUS_Group1 Initialization and de-initialization functions + * @brief Initialization and Configuration functions + * +@verbatim + =============================================================================== + ##### Initialization and de-initialization functions ##### + =============================================================================== + [..] This subsection provides a set of functions allowing to initialize and + de-initialiaze the SMBUSx peripheral: + + (+) User must Implement HAL_SMBUS_MspInit() function in which he configures + all related peripherals resources (CLOCK, GPIO, IT and NVIC ). + + (+) Call the function HAL_SMBUS_Init() to configure the selected device with + the selected configuration: + (++) Clock Timing + (++) Bus Timeout + (++) Analog Filer mode + (++) Own Address 1 + (++) Addressing mode (Master, Slave) + (++) Dual Addressing mode + (++) Own Address 2 + (++) Own Address 2 Mask + (++) General call mode + (++) Nostretch mode + (++) Packet Error Check mode + (++) Peripheral mode + + (+) Call the function HAL_SMBUS_DeInit() to restore the default configuration + of the selected SMBUSx periperal. + +@endverbatim + * @{ + */ + +/** + * @brief Initializes the SMBUS according to the specified parameters + * in the SMBUS_InitTypeDef and create the associated handle. + * @param hsmbus : Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMBUS_Init(SMBUS_HandleTypeDef *hsmbus) +{ + /* Check the SMBUS handle allocation */ + if(hsmbus == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_SMBUS_INSTANCE(hsmbus->Instance)); + assert_param(IS_SMBUS_ANALOG_FILTER(hsmbus->Init.AnalogFilter)); + assert_param(IS_SMBUS_OWN_ADDRESS1(hsmbus->Init.OwnAddress1)); + assert_param(IS_SMBUS_ADDRESSING_MODE(hsmbus->Init.AddressingMode)); + assert_param(IS_SMBUS_DUAL_ADDRESS(hsmbus->Init.DualAddressMode)); + assert_param(IS_SMBUS_OWN_ADDRESS2(hsmbus->Init.OwnAddress2)); + assert_param(IS_SMBUS_OWN_ADDRESS2_MASK(hsmbus->Init.OwnAddress2Masks)); + assert_param(IS_SMBUS_GENERAL_CALL(hsmbus->Init.GeneralCallMode)); + assert_param(IS_SMBUS_NO_STRETCH(hsmbus->Init.NoStretchMode)); + assert_param(IS_SMBUS_PEC(hsmbus->Init.PacketErrorCheckMode)); + assert_param(IS_SMBUS_PERIPHERAL_MODE(hsmbus->Init.PeripheralMode)); + + if(hsmbus->State == HAL_SMBUS_STATE_RESET) + { + /* Init the low level hardware : GPIO, CLOCK, NVIC */ + HAL_SMBUS_MspInit(hsmbus); + } + + hsmbus->State = HAL_SMBUS_STATE_BUSY; + + /* Disable the selected SMBUS peripheral */ + __HAL_SMBUS_DISABLE(hsmbus); + + /*---------------------------- SMBUSx TIMINGR Configuration ----------------*/ + /* Configure SMBUSx: Frequency range */ + hsmbus->Instance->TIMINGR = hsmbus->Init.Timing & TIMING_CLEAR_MASK; + + /*---------------------------- SMBUSx TIMEOUTR Configuration ---------------*/ + /* Configure SMBUSx: Bus Timeout */ + hsmbus->Instance->TIMEOUTR = hsmbus->Init.SMBusTimeout; + + /*---------------------------- SMBUSx OAR1 Configuration -------------------*/ + /* Configure SMBUSx: Own Address1 and ack own address1 mode */ + hsmbus->Instance->OAR1 &= ~I2C_OAR1_OA1EN; + if(hsmbus->Init.OwnAddress1 != 0) + { + if(hsmbus->Init.AddressingMode == SMBUS_ADDRESSINGMODE_7BIT) + { + hsmbus->Instance->OAR1 = (I2C_OAR1_OA1EN | hsmbus->Init.OwnAddress1); + } + else /* SMBUS_ADDRESSINGMODE_10BIT */ + { + hsmbus->Instance->OAR1 = (I2C_OAR1_OA1EN | I2C_OAR1_OA1MODE | hsmbus->Init.OwnAddress1); + } + } + + /*---------------------------- SMBUSx CR2 Configuration --------------------*/ + /* Configure SMBUSx: Addressing Master mode */ + if(hsmbus->Init.AddressingMode == SMBUS_ADDRESSINGMODE_10BIT) + { + hsmbus->Instance->CR2 = (I2C_CR2_ADD10); + } + /* Enable the AUTOEND by default, and enable NACK (should be disable only during Slave process) */ + /* AUTOEND and NACK bit will be manage during Transfer process */ + hsmbus->Instance->CR2 |= (I2C_CR2_AUTOEND | I2C_CR2_NACK); + + /*---------------------------- SMBUSx OAR2 Configuration -----------------------*/ + /* Configure SMBUSx: Dual mode and Own Address2 */ + hsmbus->Instance->OAR2 = (hsmbus->Init.DualAddressMode | hsmbus->Init.OwnAddress2 | (hsmbus->Init.OwnAddress2Masks << 8)); + + /*---------------------------- SMBUSx CR1 Configuration ------------------------*/ + /* Configure SMBUSx: Generalcall and NoStretch mode */ + hsmbus->Instance->CR1 = (hsmbus->Init.GeneralCallMode | hsmbus->Init.NoStretchMode | hsmbus->Init.PacketErrorCheckMode | hsmbus->Init.PeripheralMode | hsmbus->Init.AnalogFilter); + + /* Enable Slave Byte Control only in case of Packet Error Check is enabled and SMBUS Peripheral is set in Slave mode */ + if( (hsmbus->Init.PacketErrorCheckMode == SMBUS_PEC_ENABLED) + && ( (hsmbus->Init.PeripheralMode == SMBUS_PERIPHERAL_MODE_SMBUS_SLAVE) || (hsmbus->Init.PeripheralMode == SMBUS_PERIPHERAL_MODE_SMBUS_SLAVE_ARP) ) ) + { + hsmbus->Instance->CR1 |= I2C_CR1_SBC; + } + + /* Enable the selected SMBUS peripheral */ + __HAL_SMBUS_ENABLE(hsmbus); + + hsmbus->ErrorCode = HAL_SMBUS_ERROR_NONE; + hsmbus->PreviousState = HAL_SMBUS_STATE_READY; + hsmbus->State = HAL_SMBUS_STATE_READY; + + return HAL_OK; +} + +/** + * @brief DeInitializes the SMBUS peripheral. + * @param hsmbus : Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMBUS_DeInit(SMBUS_HandleTypeDef *hsmbus) +{ + /* Check the SMBUS handle allocation */ + if(hsmbus == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_SMBUS_INSTANCE(hsmbus->Instance)); + + hsmbus->State = HAL_SMBUS_STATE_BUSY; + + /* Disable the SMBUS Peripheral Clock */ + __HAL_SMBUS_DISABLE(hsmbus); + + /* DeInit the low level hardware: GPIO, CLOCK, NVIC */ + HAL_SMBUS_MspDeInit(hsmbus); + + hsmbus->ErrorCode = HAL_SMBUS_ERROR_NONE; + hsmbus->PreviousState = HAL_SMBUS_STATE_RESET; + hsmbus->State = HAL_SMBUS_STATE_RESET; + + /* Release Lock */ + __HAL_UNLOCK(hsmbus); + + return HAL_OK; +} + +/** + * @brief SMBUS MSP Init. + * @param hsmbus : Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @retval None + */ + __weak void HAL_SMBUS_MspInit(SMBUS_HandleTypeDef *hsmbus) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_SMBUS_MspInit could be implemented in the user file + */ +} + +/** + * @brief SMBUS MSP DeInit + * @param hsmbus : Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @retval None + */ + __weak void HAL_SMBUS_MspDeInit(SMBUS_HandleTypeDef *hsmbus) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_SMBUS_MspDeInit could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup HAL_SMBUS_Group2 IO operation functions + * @brief Data transfers functions + * +@verbatim + =============================================================================== + ##### IO operation functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to manage the SMBUS data + transfers. + + (#) Blocking mode function to check if device is ready for usage is : + (++) HAL_SMBUS_IsDeviceReady() + + (#) There is only one mode of transfer: + (++) No-Blocking mode : The communication is performed using Interrupts. + These functions return the status of the transfer startup. + The end of the data processing will be indicated through the + dedicated SMBUS IRQ when using Interrupt mode. + + (#) No-Blocking mode functions with Interrupt are : + (++) HAL_SMBUS_Master_Transmit_IT() + (++) HAL_SMBUS_Master_Receive_IT() + (++) HAL_SMBUS_Slave_Transmit_IT() + (++) HAL_SMBUS_Slave_Receive_IT() + (++) HAL_SMBUS_Slave_Listen_IT() + (++) HAL_SMBUS_EnableAlert_IT() + (++) HAL_SMBUS_DisableAlert_IT() + + (#) A set of Transfer Complete Callbacks are provided in No_Blocking mode: + (++) HAL_SMBUS_MasterTxCpltCallback() + (++) HAL_SMBUS_MasterRxCpltCallback() + (++) HAL_SMBUS_SlaveTxCpltCallback() + (++) HAL_SMBUS_SlaveRxCpltCallback() + (++) HAL_SMBUS_SlaveAddrCallback() + (++) HAL_SMBUS_SlaveListenCpltCallback() + (++) HAL_SMBUS_ErrorCallback() + +@endverbatim + * @{ + */ + +/** + * @brief Transmit in master/host SMBUS mode an amount of data in no-blocking mode with Interrupt + * @param hsmbus : Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @param DevAddress: Target device address + * @param pData: Pointer to data buffer + * @param Size: Amount of data to be sent + * @param XferOptions: Options of Transfer, value of @ref SMBUS_XferOptions_definition + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMBUS_Master_Transmit_IT(SMBUS_HandleTypeDef *hsmbus, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t XferOptions) +{ + /* Check the parameters */ + assert_param(IS_SMBUS_TRANSFER_OPTIONS_REQUEST(XferOptions)); + + if(hsmbus->State == HAL_SMBUS_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hsmbus); + + hsmbus->State = HAL_SMBUS_STATE_MASTER_BUSY_TX; + hsmbus->ErrorCode = HAL_SMBUS_ERROR_NONE; + /* Prepare transfer parameters */ + hsmbus->pBuffPtr = pData; + hsmbus->XferCount = Size; + hsmbus->XferOptions = XferOptions; + + /* In case of Quick command, remove autoend mode */ + /* Manage the stop generation by software */ + if(hsmbus->pBuffPtr == NULL) + { + hsmbus->XferOptions &= ~SMBUS_AUTOEND_MODE; + } + + if(Size > MAX_NBYTE_SIZE) + { + hsmbus->XferSize = MAX_NBYTE_SIZE; + } + else + { + hsmbus->XferSize = Size; + } + + /* Send Slave Address */ + /* Set NBYTES to write and reload if size > MAX_NBYTE_SIZE and generate RESTART */ + if( (hsmbus->XferSize == MAX_NBYTE_SIZE) && (hsmbus->XferSize < hsmbus->XferCount) ) + { + SMBUS_TransferConfig(hsmbus,DevAddress,hsmbus->XferSize, SMBUS_RELOAD_MODE, SMBUS_GENERATE_START_WRITE); + } + else + { + /* If transfer direction not change, do not generate Restart Condition */ + /* Mean Previous state is same as current state */ + if(hsmbus->PreviousState == HAL_SMBUS_STATE_MASTER_BUSY_TX) + { + SMBUS_TransferConfig(hsmbus,DevAddress,hsmbus->XferSize, hsmbus->XferOptions, SMBUS_NO_STARTSTOP); + } + /* Else transfer direction change, so generate Restart with new transfer direction */ + else + { + SMBUS_TransferConfig(hsmbus,DevAddress,hsmbus->XferSize, hsmbus->XferOptions, SMBUS_GENERATE_START_WRITE); + } + + /* If PEC mode is enable, size to transmit manage by SW part should be Size-1 byte, corresponding to PEC byte */ + /* PEC byte is automatically sent by HW block, no need to manage it in Transmit process */ + if(__HAL_SMBUS_GET_PEC_MODE(hsmbus) != RESET) + { + hsmbus->XferSize--; + hsmbus->XferCount--; + } + } + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + /* Note : The SMBUS interrupts must be enabled after unlocking current process + to avoid the risk of SMBUS interrupt handle execution before current + process unlock */ + SMBUS_Enable_IRQ(hsmbus, SMBUS_IT_TX); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive in master/host SMBUS mode an amount of data in no-blocking mode with Interrupt + * @param hsmbus : Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @param DevAddress: Target device address + * @param pData: Pointer to data buffer + * @param Size: Amount of data to be sent + * @param XferOptions: Options of Transfer, value of @ref SMBUS_XferOptions_definition + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMBUS_Master_Receive_IT(SMBUS_HandleTypeDef *hsmbus, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t XferOptions) +{ + /* Check the parameters */ + assert_param(IS_SMBUS_TRANSFER_OPTIONS_REQUEST(XferOptions)); + + if(hsmbus->State == HAL_SMBUS_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hsmbus); + + hsmbus->State = HAL_SMBUS_STATE_MASTER_BUSY_RX; + hsmbus->ErrorCode = HAL_SMBUS_ERROR_NONE; + + /* Prepare transfer parameters */ + hsmbus->pBuffPtr = pData; + hsmbus->XferCount = Size; + hsmbus->XferOptions = XferOptions; + + /* In case of Quick command, remove autoend mode */ + /* Manage the stop generation by software */ + if(hsmbus->pBuffPtr == NULL) + { + hsmbus->XferOptions &= ~SMBUS_AUTOEND_MODE; + } + + if(Size > MAX_NBYTE_SIZE) + { + hsmbus->XferSize = MAX_NBYTE_SIZE; + } + else + { + hsmbus->XferSize = Size; + } + + /* Send Slave Address */ + /* Set NBYTES to write and reload if size > MAX_NBYTE_SIZE and generate RESTART */ + if( (hsmbus->XferSize == MAX_NBYTE_SIZE) && (hsmbus->XferSize < hsmbus->XferCount) ) + { + SMBUS_TransferConfig(hsmbus,DevAddress,hsmbus->XferSize, SMBUS_RELOAD_MODE, SMBUS_GENERATE_START_READ); + } + else + { + /* If transfer direction not change, do not generate Restart Condition */ + /* Mean Previous state is same as current state */ + if(hsmbus->PreviousState == HAL_SMBUS_STATE_MASTER_BUSY_RX) + { + SMBUS_TransferConfig(hsmbus,DevAddress,hsmbus->XferSize, hsmbus->XferOptions, SMBUS_NO_STARTSTOP); + } + /* Else transfer direction change, so generate Restart with new transfer direction */ + else + { + SMBUS_TransferConfig(hsmbus,DevAddress,hsmbus->XferSize, hsmbus->XferOptions, SMBUS_GENERATE_START_READ); + } + } + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + /* Note : The SMBUS interrupts must be enabled after unlocking current process + to avoid the risk of SMBUS interrupt handle execution before current + process unlock */ + SMBUS_Enable_IRQ(hsmbus, SMBUS_IT_RX); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Abort a master/host SMBUS process commnunication with Interrupt + * @note : This abort can be called only if state is ready + * @param hsmbus : Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @param DevAddress: Target device address + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMBUS_Master_Abort_IT(SMBUS_HandleTypeDef *hsmbus, uint16_t DevAddress) +{ + if(hsmbus->State == HAL_SMBUS_STATE_READY) + { + /* Process Locked */ + __HAL_LOCK(hsmbus); + + /* Keep the same state as previous */ + /* to perform as well the call of the corresponding end of transfer callback */ + if(hsmbus->PreviousState == HAL_SMBUS_STATE_MASTER_BUSY_TX) + { + hsmbus->State = HAL_SMBUS_STATE_MASTER_BUSY_TX; + } + else if(hsmbus->PreviousState == HAL_SMBUS_STATE_MASTER_BUSY_RX) + { + hsmbus->State = HAL_SMBUS_STATE_MASTER_BUSY_RX; + } + else + { + /* Wrong usage of abort function */ + /* This function should be used only in case of abort monitored by master device */ + return HAL_ERROR; + } + hsmbus->ErrorCode = HAL_SMBUS_ERROR_NONE; + + /* Set NBYTES to 1 to generate a dummy read on SMBUS peripheral */ + /* Set AUTOEND mode, this will generate a NACK then STOP condition to abort the current transfer */ + SMBUS_TransferConfig(hsmbus, DevAddress, 1, SMBUS_AUTOEND_MODE, SMBUS_NO_STARTSTOP); + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + /* Note : The SMBUS interrupts must be enabled after unlocking current process + to avoid the risk of SMBUS interrupt handle execution before current + process unlock */ + if(hsmbus->State == HAL_SMBUS_STATE_MASTER_BUSY_TX) + { + SMBUS_Enable_IRQ(hsmbus, SMBUS_IT_TX); + } + else if(hsmbus->State == HAL_SMBUS_STATE_MASTER_BUSY_RX) + { + SMBUS_Enable_IRQ(hsmbus, SMBUS_IT_RX); + } + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Transmit in slave/device SMBUS mode an amount of data in no-blocking mode with Interrupt + * @param hsmbus : Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @param pData: Pointer to data buffer + * @param Size: Amount of data to be sent + * @param XferOptions: Options of Transfer, value of @ref SMBUS_XferOptions_definition + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMBUS_Slave_Transmit_IT(SMBUS_HandleTypeDef *hsmbus, uint8_t *pData, uint16_t Size, uint32_t XferOptions) +{ + /* Check the parameters */ + assert_param(IS_SMBUS_TRANSFER_OPTIONS_REQUEST(XferOptions)); + + if(hsmbus->State == HAL_SMBUS_STATE_SLAVE_LISTEN) + { + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + /* Disable Interrupts, to prevent preemption during treatment in case of multicall */ + SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_ADDR | SMBUS_IT_TX); + + /* Process Locked */ + __HAL_LOCK(hsmbus); + + hsmbus->State |= HAL_SMBUS_STATE_SLAVE_BUSY_TX; + hsmbus->ErrorCode = HAL_SMBUS_ERROR_NONE; + + /* Enable Address Acknowledge */ + hsmbus->Instance->CR2 &= ~I2C_CR2_NACK; + + /* Prepare transfer parameters */ + hsmbus->pBuffPtr = pData; + hsmbus->XferSize = Size; + hsmbus->XferCount = Size; + hsmbus->XferOptions = XferOptions; + + /* Set NBYTE to transmit */ + SMBUS_TransferConfig(hsmbus,0,hsmbus->XferSize, hsmbus->XferOptions, SMBUS_NO_STARTSTOP); + + /* If PEC mode is enable, size to transmit should be Size-1 byte, corresponding to PEC byte */ + /* PEC byte is automatically sent by HW block, no need to manage it in Transmit process */ + if(__HAL_SMBUS_GET_PEC_MODE(hsmbus) != RESET) + { + hsmbus->XferSize--; + hsmbus->XferCount--; + } + + /* Clear ADDR flag after prepare the transfer parameters */ + /* This action will generate an acknowledge to the HOST */ + __HAL_SMBUS_CLEAR_FLAG(hsmbus,SMBUS_FLAG_ADDR); + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + /* Note : The SMBUS interrupts must be enabled after unlocking current process + to avoid the risk of SMBUS interrupt handle execution before current + process unlock */ + /* REnable ADDR interrupt */ + SMBUS_Enable_IRQ(hsmbus, SMBUS_IT_TX | SMBUS_IT_ADDR); + + return HAL_OK; + } + else + { + return HAL_ERROR; + } +} + +/** + * @brief Receive in slave/device SMBUS mode an amount of data in no-blocking mode with Interrupt + * @param hsmbus : Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @param pData: Pointer to data buffer + * @param Size: Amount of data to be sent + * @param XferOptions: Options of Transfer, value of @ref SMBUS_XferOptions_definition + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMBUS_Slave_Receive_IT(SMBUS_HandleTypeDef *hsmbus, uint8_t *pData, uint16_t Size, uint32_t XferOptions) +{ + /* Check the parameters */ + assert_param(IS_SMBUS_TRANSFER_OPTIONS_REQUEST(XferOptions)); + + if(hsmbus->State == HAL_SMBUS_STATE_SLAVE_LISTEN) + { + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + /* Disable Interrupts, to prevent preemption during treatment in case of multicall */ + SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_ADDR | SMBUS_IT_RX); + + /* Process Locked */ + __HAL_LOCK(hsmbus); + + hsmbus->State |= HAL_SMBUS_STATE_SLAVE_BUSY_RX; + hsmbus->ErrorCode = HAL_SMBUS_ERROR_NONE; + + /* Enable Address Acknowledge */ + hsmbus->Instance->CR2 &= ~I2C_CR2_NACK; + + /* Prepare transfer parameters */ + hsmbus->pBuffPtr = pData; + hsmbus->XferSize = Size; + hsmbus->XferCount = Size; + hsmbus->XferOptions = XferOptions; + + /* Set NBYTE to receive */ + /* If XferSize equal "1", or XferSize equal "2" with PEC requested (mean 1 data byte + 1 PEC byte */ + /* no need to set RELOAD bit mode, a ACK will be automatically generated in that case */ + /* else need to set RELOAD bit mode to generate an automatic ACK at each byte Received */ + /* This RELOAD bit will be reset for last BYTE to be receive in SMBUS_Slave_ISR */ + if((hsmbus->XferSize == 1) || ((hsmbus->XferSize == 2) && (__HAL_SMBUS_GET_PEC_MODE(hsmbus) != RESET))) + { + SMBUS_TransferConfig(hsmbus,0,hsmbus->XferSize, hsmbus->XferOptions, SMBUS_NO_STARTSTOP); + } + else + { + SMBUS_TransferConfig(hsmbus,0,/*hsmbus->XferSize*/1, hsmbus->XferOptions | SMBUS_RELOAD_MODE, SMBUS_NO_STARTSTOP); + } + + /* Clear ADDR flag after prepare the transfer parameters */ + /* This action will generate an acknowledge to the HOST */ + __HAL_SMBUS_CLEAR_FLAG(hsmbus,SMBUS_FLAG_ADDR); + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + /* Note : The SMBUS interrupts must be enabled after unlocking current process + to avoid the risk of SMBUS interrupt handle execution before current + process unlock */ + /* REnable ADDR interrupt */ + SMBUS_Enable_IRQ(hsmbus, SMBUS_IT_RX | SMBUS_IT_ADDR); + + return HAL_OK; + } + else + { + return HAL_ERROR; + } +} +/** + * @brief This function enable the Address listen mode in Slave mode + * @param hsmbus : Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMBUS_Slave_Listen_IT(SMBUS_HandleTypeDef *hsmbus) +{ + hsmbus->State = HAL_SMBUS_STATE_SLAVE_LISTEN; + + /* Enable the Address Match interrupt */ + SMBUS_Enable_IRQ(hsmbus, SMBUS_IT_ADDR); + + return HAL_OK; +} +/** + * @brief Enable SMBUS alert. + * @param hsmbus : pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUSx peripheral. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMBUS_EnableAlert_IT(SMBUS_HandleTypeDef *hsmbus) +{ + /* Enable SMBus alert */ + hsmbus->Instance->CR1 |= I2C_CR1_ALERTEN; + + /* Clear ALERT flag */ + __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_ALERT); + + /* Enable Alert Interrupt */ + SMBUS_Enable_IRQ(hsmbus, SMBUS_IT_ALERT); + + return HAL_OK; +} +/** + * @brief Disable SMBUS alert. + * @param hsmbus : pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUSx peripheral. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMBUS_DisableAlert_IT(SMBUS_HandleTypeDef *hsmbus) +{ + /* Enable SMBus alert */ + hsmbus->Instance->CR1 &= ~I2C_CR1_ALERTEN; + + /* Disable Alert Interrupt */ + SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_ALERT); + + return HAL_OK; +} +/** + * @brief Checks if target device is ready for communication. + * @note This function is used with Memory devices + * @param hsmbus : Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @param DevAddress: Target device address + * @param Trials: Number of trials + * @param Timeout: Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SMBUS_IsDeviceReady(SMBUS_HandleTypeDef *hsmbus, uint16_t DevAddress, uint32_t Trials, uint32_t Timeout) +{ + uint32_t tickstart = 0x00; + __IO uint32_t SMBUS_Trials = 0x00; + + if(hsmbus->State == HAL_SMBUS_STATE_READY) + { + if(__HAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_BUSY) != RESET) + { + return HAL_BUSY; + } + + /* Process Locked */ + __HAL_LOCK(hsmbus); + + hsmbus->State = HAL_SMBUS_STATE_BUSY; + hsmbus->ErrorCode = HAL_SMBUS_ERROR_NONE; + + do + { + /* Generate Start */ + hsmbus->Instance->CR2 = __HAL_SMBUS_GENERATE_START(hsmbus->Init.AddressingMode,DevAddress); + + /* No need to Check TC flag, with AUTOEND mode the stop is automatically generated */ + /* Wait until STOPF flag is set or a NACK flag is set*/ + tickstart = HAL_GetTick(); + while((__HAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_STOPF) == RESET) && (__HAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_AF) == RESET) && (hsmbus->State != HAL_SMBUS_STATE_TIMEOUT)) + { + if((HAL_GetTick() - tickstart ) > Timeout) + { + hsmbus->State = HAL_SMBUS_STATE_TIMEOUT; + } + } + + /* Check if the NACKF flag has not been set */ + if (__HAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_AF) == RESET) + { + /* Wait until STOPF flag is reset */ + if(SMBUS_WaitOnFlagUntilTimeout(hsmbus, SMBUS_FLAG_STOPF, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + /* Clear STOP Flag */ + __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_STOPF); + + /* Device is ready */ + hsmbus->State = HAL_SMBUS_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + return HAL_OK; + } + else + { + /* Wait until STOPF flag is reset */ + if(SMBUS_WaitOnFlagUntilTimeout(hsmbus, SMBUS_FLAG_STOPF, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + /* Clear NACK Flag */ + __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_AF); + + /* Clear STOP Flag, auto generated with autoend*/ + __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_STOPF); + } + + /* Check if the maximum allowed numbe of trials has bee reached */ + if (SMBUS_Trials++ == Trials) + { + /* Generate Stop */ + hsmbus->Instance->CR2 |= I2C_CR2_STOP; + + /* Wait until STOPF flag is reset */ + if(SMBUS_WaitOnFlagUntilTimeout(hsmbus, SMBUS_FLAG_STOPF, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + /* Clear STOP Flag */ + __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_STOPF); + } + }while(SMBUS_Trials++ < Trials); + + hsmbus->State = HAL_SMBUS_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + return HAL_TIMEOUT; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief This function handles SMBUS event interrupt request. + * @param hsmbus : Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @retval None + */ +void HAL_SMBUS_EV_IRQHandler(SMBUS_HandleTypeDef *hsmbus) +{ + uint32_t tmpisrvalue = 0; + + /* Use a local variable to store the current ISR flags */ + /* This action will avoid a wrong treatment due to ISR flags change during interrupt handler */ + tmpisrvalue = __SMBUS_GET_ISR_REG(hsmbus); + + /* SMBUS in mode Transmitter ---------------------------------------------------*/ + if (((__SMBUS_CHECK_FLAG(tmpisrvalue, SMBUS_FLAG_TXIS) != RESET) || (__SMBUS_CHECK_FLAG(tmpisrvalue, SMBUS_FLAG_TCR) != RESET) || (__SMBUS_CHECK_FLAG(tmpisrvalue, SMBUS_FLAG_TC) != RESET) || (__SMBUS_CHECK_FLAG(tmpisrvalue, SMBUS_FLAG_STOPF) != RESET) || (__SMBUS_CHECK_FLAG(tmpisrvalue, SMBUS_FLAG_AF) != RESET)) && (__HAL_SMBUS_GET_IT_SOURCE(hsmbus, (SMBUS_IT_TCI| SMBUS_IT_STOPI| SMBUS_IT_NACKI | SMBUS_IT_TXI)) != RESET)) + { + /* Slave mode selected */ + if ((hsmbus->State & HAL_SMBUS_STATE_SLAVE_BUSY_TX) == HAL_SMBUS_STATE_SLAVE_BUSY_TX) + { + SMBUS_Slave_ISR(hsmbus); + } + /* Master mode selected */ + else if((hsmbus->State & HAL_SMBUS_STATE_MASTER_BUSY_TX) == HAL_SMBUS_STATE_MASTER_BUSY_TX) + { + SMBUS_Master_ISR(hsmbus); + } + } + + /* SMBUS in mode Receiver ----------------------------------------------------*/ + if (((__SMBUS_CHECK_FLAG(tmpisrvalue, SMBUS_FLAG_RXNE) != RESET) || (__SMBUS_CHECK_FLAG(tmpisrvalue, SMBUS_FLAG_TCR) != RESET) || (__SMBUS_CHECK_FLAG(tmpisrvalue, SMBUS_FLAG_TC) != RESET) || (__SMBUS_CHECK_FLAG(tmpisrvalue, SMBUS_FLAG_STOPF) != RESET) || (__SMBUS_CHECK_FLAG(tmpisrvalue, SMBUS_FLAG_AF) != RESET)) && (__HAL_SMBUS_GET_IT_SOURCE(hsmbus, (SMBUS_IT_TCI| SMBUS_IT_STOPI| SMBUS_IT_NACKI | SMBUS_IT_RXI)) != RESET)) + { + /* Slave mode selected */ + if ((hsmbus->State & HAL_SMBUS_STATE_SLAVE_BUSY_RX) == HAL_SMBUS_STATE_SLAVE_BUSY_RX) + { + SMBUS_Slave_ISR(hsmbus); + } + /* Master mode selected */ + else if((hsmbus->State & HAL_SMBUS_STATE_MASTER_BUSY_RX) == HAL_SMBUS_STATE_MASTER_BUSY_RX) + { + SMBUS_Master_ISR(hsmbus); + } + } + + /* SMBUS in mode Listener Only --------------------------------------------------*/ + /* Slave mode selected */ + if (((__SMBUS_CHECK_FLAG(tmpisrvalue, SMBUS_FLAG_ADDR) != RESET) || (__SMBUS_CHECK_FLAG(tmpisrvalue, SMBUS_FLAG_STOPF) != RESET) || (__SMBUS_CHECK_FLAG(tmpisrvalue, SMBUS_FLAG_AF) != RESET)) + && ((__HAL_SMBUS_GET_IT_SOURCE(hsmbus, SMBUS_IT_ADDRI) != RESET) || (__HAL_SMBUS_GET_IT_SOURCE(hsmbus, SMBUS_IT_STOPI) != RESET) || (__HAL_SMBUS_GET_IT_SOURCE(hsmbus, SMBUS_IT_NACKI) != RESET))) + { + if (hsmbus->State == HAL_SMBUS_STATE_SLAVE_LISTEN) + { + SMBUS_Slave_ISR(hsmbus); + } + } +} + +/** + * @brief This function handles SMBUS error interrupt request. + * @param hsmbus : Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @retval None + */ +void HAL_SMBUS_ER_IRQHandler(SMBUS_HandleTypeDef *hsmbus) +{ + /* SMBUS Bus error interrupt occurred ------------------------------------*/ + if((__HAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_BERR) != RESET) && (__HAL_SMBUS_GET_IT_SOURCE(hsmbus, SMBUS_IT_ERRI) != RESET)) + { + hsmbus->ErrorCode |= HAL_SMBUS_ERROR_BERR; + + /* Clear BERR flag */ + __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_BERR); + } + + /* SMBUS Over-Run/Under-Run interrupt occurred ----------------------------------------*/ + if((__HAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_OVR) != RESET) && (__HAL_SMBUS_GET_IT_SOURCE(hsmbus, SMBUS_IT_ERRI) != RESET)) + { + hsmbus->ErrorCode |= HAL_SMBUS_ERROR_OVR; + + /* Clear OVR flag */ + __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_OVR); + } + + /* SMBUS Arbitration Loss error interrupt occurred ------------------------------------*/ + if((__HAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_ARLO) != RESET) && (__HAL_SMBUS_GET_IT_SOURCE(hsmbus, SMBUS_IT_ERRI) != RESET)) + { + hsmbus->ErrorCode |= HAL_SMBUS_ERROR_ARLO; + + /* Clear ARLO flag */ + __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_ARLO); + } + + /* SMBUS Timeout error interrupt occurred ---------------------------------------------*/ + if((__HAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_TIMEOUT) != RESET) && (__HAL_SMBUS_GET_IT_SOURCE(hsmbus, SMBUS_IT_ERRI) != RESET)) + { + hsmbus->ErrorCode |= HAL_SMBUS_ERROR_BUSTIMEOUT; + + /* Clear TIMEOUT flag */ + __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_TIMEOUT); + } + + /* SMBUS Alert error interrupt occurred -----------------------------------------------*/ + if((__HAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_ALERT) != RESET) && (__HAL_SMBUS_GET_IT_SOURCE(hsmbus, SMBUS_IT_ERRI) != RESET)) + { + hsmbus->ErrorCode |= HAL_SMBUS_ERROR_ALERT; + + /* Clear ALERT flag */ + __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_ALERT); + } + + /* SMBUS Packet Error Check error interrupt occurred ----------------------------------*/ + if((__HAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_PECERR) != RESET) && (__HAL_SMBUS_GET_IT_SOURCE(hsmbus, SMBUS_IT_ERRI) != RESET)) + { + hsmbus->ErrorCode |= HAL_SMBUS_ERROR_PECERR; + + /* Clear PEC error flag */ + __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_PECERR); + } + + /* Call the Error Callback in case of Error detected */ + if((hsmbus->ErrorCode != HAL_SMBUS_ERROR_NONE)&&(hsmbus->ErrorCode != HAL_SMBUS_ERROR_ACKF)) + { + /* Do not Reset the the HAL state in case of ALERT error */ + if((hsmbus->ErrorCode & HAL_SMBUS_ERROR_ALERT) != HAL_SMBUS_ERROR_ALERT) + { + /* Reset only HAL_SMBUS_STATE_SLAVE_BUSY_XX and HAL_SMBUS_STATE_MASTER_BUSY_XX */ + /* keep HAL_SMBUS_STATE_SLAVE_LISTEN if set */ + hsmbus->State &= (uint32_t)~((uint32_t)HAL_SMBUS_STATE_MASTER_BUSY_RX | HAL_SMBUS_STATE_MASTER_BUSY_TX | HAL_SMBUS_STATE_SLAVE_BUSY_RX | HAL_SMBUS_STATE_SLAVE_BUSY_TX); + } + + /* Call the Error callback to prevent upper layer */ + HAL_SMBUS_ErrorCallback(hsmbus); + } +} + +/** + * @brief Master Tx Transfer completed callbacks. + * @param hsmbus : Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @retval None + */ + __weak void HAL_SMBUS_MasterTxCpltCallback(SMBUS_HandleTypeDef *hsmbus) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_SMBUS_TxCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Master Rx Transfer completed callbacks. + * @param hsmbus : Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @retval None + */ +__weak void HAL_SMBUS_MasterRxCpltCallback(SMBUS_HandleTypeDef *hsmbus) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_SMBUS_TxCpltCallback could be implemented in the user file + */ +} + +/** @brief Slave Tx Transfer completed callbacks. + * @param hsmbus : Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @retval None + */ + __weak void HAL_SMBUS_SlaveTxCpltCallback(SMBUS_HandleTypeDef *hsmbus) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_SMBUS_TxCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Slave Rx Transfer completed callbacks. + * @param hsmbus : Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @retval None + */ +__weak void HAL_SMBUS_SlaveRxCpltCallback(SMBUS_HandleTypeDef *hsmbus) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_SMBUS_TxCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Slave Address Match callbacks. + * @param hsmbus : Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @param TransferDirection: Master request Transfer Direction (Write/Read) + * @param AddrMatchCode: Address Match Code + * @retval None + */ +__weak void HAL_SMBUS_SlaveAddrCallback(SMBUS_HandleTypeDef *hsmbus, uint8_t TransferDirection, uint16_t AddrMatchCode) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_SMBUS_SlaveAddrCallback could be implemented in the user file + */ +} + +/** + * @brief Slave Listen Complete callbacks. + * @param hsmbus : Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @retval None + */ +__weak void HAL_SMBUS_SlaveListenCpltCallback(SMBUS_HandleTypeDef *hsmbus) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_SMBUS_SlaveListenCpltCallback could be implemented in the user file + */ +} + +/** + * @brief SMBUS error callbacks. + * @param hsmbus : Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @retval None + */ + __weak void HAL_SMBUS_ErrorCallback(SMBUS_HandleTypeDef *hsmbus) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_SMBUS_ErrorCallback could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup HAL_SMBUS_Group3 Peripheral State and Errors functions + * @brief Peripheral State and Errors functions + * +@verbatim + =============================================================================== + ##### Peripheral State and Errors functions ##### + =============================================================================== + [..] + This subsection permit to get in run-time the status of the peripheral + and the data flow. + +@endverbatim + * @{ + */ + +/** + * @brief Returns the SMBUS state. + * @param hsmbus : SMBUS handle + * @retval HAL state + */ +HAL_SMBUS_StateTypeDef HAL_SMBUS_GetState(SMBUS_HandleTypeDef *hsmbus) +{ + return hsmbus->State; +} + +/** +* @brief Return the SMBUS error code +* @param hsmbus : pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. +* @retval SMBUS Error Code +*/ +uint32_t HAL_SMBUS_GetError(SMBUS_HandleTypeDef *hsmbus) +{ + return hsmbus->ErrorCode; +} + +/** + * @} + */ + +/** + * @brief Interrupt Sub-Routine which handle the Interrupt Flags Master Mode + * @param hsmbus : Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @retval HAL status + */ +static HAL_StatusTypeDef SMBUS_Master_ISR(SMBUS_HandleTypeDef *hsmbus) +{ + uint16_t DevAddress; + + /* Process Locked */ + __HAL_LOCK(hsmbus); + + if(__HAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_AF) != RESET) + { + /* Clear NACK Flag */ + __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_AF); + + /* Set corresponding Error Code */ + /* No need to generate STOP, it is automatically done */ + hsmbus->ErrorCode |= HAL_SMBUS_ERROR_ACKF; + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + /* Call the Error callback to prevent upper layer */ + HAL_SMBUS_ErrorCallback(hsmbus); + } + else if(__HAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_STOPF) != RESET) + { + + /* Call the corresponding callback to inform upper layer of End of Transfer */ + if(hsmbus->State == HAL_SMBUS_STATE_MASTER_BUSY_TX) + { + /* Disable Interrupt */ + SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_TX); + + /* Clear STOP Flag */ + __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_STOPF); + + /* Clear Configuration Register 2 */ + __HAL_SMBUS_RESET_CR2(hsmbus); + + + /* Flush remaining data in Fifo register in case of error occurs before TXEmpty */ + /* Disable the selected SMBUS peripheral */ + __HAL_SMBUS_DISABLE(hsmbus); + + hsmbus->PreviousState = HAL_SMBUS_STATE_READY; + hsmbus->State = HAL_SMBUS_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + /* REenable the selected SMBUS peripheral */ + __HAL_SMBUS_ENABLE(hsmbus); + + HAL_SMBUS_MasterTxCpltCallback(hsmbus); + } + else if(hsmbus->State == HAL_SMBUS_STATE_MASTER_BUSY_RX) + { + /* Disable Interrupt */ + SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_RX); + + /* Clear STOP Flag */ + __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_STOPF); + + /* Clear Configuration Register 2 */ + __HAL_SMBUS_RESET_CR2(hsmbus); + + hsmbus->PreviousState = HAL_SMBUS_STATE_READY; + hsmbus->State = HAL_SMBUS_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + HAL_SMBUS_MasterRxCpltCallback(hsmbus); + } + } + else if(__HAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_RXNE) != RESET) + { + /* Read data from RXDR */ + (*hsmbus->pBuffPtr++) = hsmbus->Instance->RXDR; + hsmbus->XferSize--; + hsmbus->XferCount--; + } + else if(__HAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_TXIS) != RESET) + { + /* Write data to TXDR */ + hsmbus->Instance->TXDR = (*hsmbus->pBuffPtr++); + hsmbus->XferSize--; + hsmbus->XferCount--; + } + else if(__HAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_TCR) != RESET) + { + if((hsmbus->XferSize == 0)&&(hsmbus->XferCount!=0)) + { + DevAddress = (hsmbus->Instance->CR2 & I2C_CR2_SADD); + + if(hsmbus->XferCount > MAX_NBYTE_SIZE) + { + SMBUS_TransferConfig(hsmbus,DevAddress,MAX_NBYTE_SIZE, SMBUS_RELOAD_MODE, SMBUS_NO_STARTSTOP); + hsmbus->XferSize = MAX_NBYTE_SIZE; + } + else + { + SMBUS_TransferConfig(hsmbus,DevAddress,hsmbus->XferSize, SMBUS_AUTOEND_MODE, SMBUS_GENERATE_START_WRITE); + /* If PEC mode is enable, size to transmit should be Size-1 byte, corresponding to PEC byte */ + /* PEC byte is automatically sent by HW block, no need to manage it in Transmit process */ + if(__HAL_SMBUS_GET_PEC_MODE(hsmbus) != RESET) + { + hsmbus->XferSize--; + hsmbus->XferCount--; + } + hsmbus->XferSize = hsmbus->XferCount; + } + } + else if((hsmbus->XferSize == 0)&&(hsmbus->XferCount==0)) + { + /* Call TxCpltCallback if no stop mode is set */ + if(__HAL_SMBUS_GET_STOP_MODE(hsmbus) != SMBUS_AUTOEND_MODE) + { + /* Call the corresponding callback to inform upper layer of End of Transfer */ + if(hsmbus->State == HAL_SMBUS_STATE_MASTER_BUSY_TX) + { + /* Disable Interrupt */ + SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_TX); + hsmbus->PreviousState = hsmbus->State; + hsmbus->State = HAL_SMBUS_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + HAL_SMBUS_MasterTxCpltCallback(hsmbus); + } + else if(hsmbus->State == HAL_SMBUS_STATE_MASTER_BUSY_RX) + { + SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_RX); + hsmbus->PreviousState = hsmbus->State; + hsmbus->State = HAL_SMBUS_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + HAL_SMBUS_MasterRxCpltCallback(hsmbus); + } + } + } + } + else if(__HAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_TC) != RESET) + { + if(hsmbus->XferCount == 0) + { + /* Specific use case for Quick command */ + if(hsmbus->pBuffPtr == NULL) + { + /* Generate a Stop command */ + hsmbus->Instance->CR2 |= I2C_CR2_STOP; + } + /* Call TxCpltCallback if no stop mode is set */ + else if(__HAL_SMBUS_GET_STOP_MODE(hsmbus) != SMBUS_AUTOEND_MODE) + { + /* No Generate Stop, to permit restart mode */ + /* The stop will be done at the end of transfer, when SMBUS_AUTOEND_MODE enable */ + + /* Call the corresponding callback to inform upper layer of End of Transfer */ + if(hsmbus->State == HAL_SMBUS_STATE_MASTER_BUSY_TX) + { + /* Disable Interrupt */ + SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_TX); + hsmbus->PreviousState = hsmbus->State; + hsmbus->State = HAL_SMBUS_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + HAL_SMBUS_MasterTxCpltCallback(hsmbus); + } + else if(hsmbus->State == HAL_SMBUS_STATE_MASTER_BUSY_RX) + { + SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_RX); + hsmbus->PreviousState = hsmbus->State; + hsmbus->State = HAL_SMBUS_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + HAL_SMBUS_MasterRxCpltCallback(hsmbus); + } + } + } + } + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + return HAL_OK; +} + +/** + * @brief Interrupt Sub-Routine which handle the Interrupt Flags Slave Mode + * @param hsmbus : Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @retval HAL status + */ +static HAL_StatusTypeDef SMBUS_Slave_ISR(SMBUS_HandleTypeDef *hsmbus) +{ + uint8_t TransferDirection = 0; + uint16_t SlaveAddrCode = 0; + + /* Process Locked */ + __HAL_LOCK(hsmbus); + + if(__HAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_AF) != RESET) + { + /* Check that SMBUS transfer finished */ + /* if yes, normal usecase, a NACK is sent by the HOST when Transfer is finished */ + /* Mean XferCount == 0*/ + /* So clear Flag NACKF only */ + if(hsmbus->XferCount == 0) + { + /* Clear NACK Flag */ + __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_AF); + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + } + else + { + /* if no, error usecase, a Non-Acknowledge of last Data is generated by the HOST*/ + /* Clear NACK Flag */ + __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_AF); + + /* Set HAL State to "Idle" State, mean to LISTEN state */ + /* So reset Slave Busy state */ + hsmbus->PreviousState = hsmbus->State; + hsmbus->State &= (uint32_t)~((uint32_t)HAL_SMBUS_STATE_SLAVE_BUSY_TX); + hsmbus->State &= (uint32_t)~((uint32_t)HAL_SMBUS_STATE_SLAVE_BUSY_RX); + + /* Disable RX/TX Interrupts, keep only ADDR Interrupt */ + SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_RX | SMBUS_IT_TX); + + /* Set ErrorCode corresponding to a Non-Acknowledge */ + hsmbus->ErrorCode |= HAL_SMBUS_ERROR_ACKF; + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + /* Call the Error callback to prevent upper layer */ + HAL_SMBUS_ErrorCallback(hsmbus); + } + } + else if(__HAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_ADDR) != RESET) + { + TransferDirection = __HAL_SMBUS_GET_DIR(hsmbus); + SlaveAddrCode = __HAL_SMBUS_GET_ADDR_MATCH(hsmbus); + + /* Disable ADDR interrupt to prevent multiple ADDRInterrupt*/ + /* Other ADDRInterrupt will be treat in next Listen usecase */ + __HAL_SMBUS_DISABLE_IT(hsmbus, SMBUS_IT_ADDRI); + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + /* Call Slave Addr callback */ + HAL_SMBUS_SlaveAddrCallback(hsmbus, TransferDirection, SlaveAddrCode); + } + else if((__HAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_RXNE) != RESET) || (__HAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_TCR) != RESET)) + { + /* Read data from RXDR */ + (*hsmbus->pBuffPtr++) = hsmbus->Instance->RXDR; + hsmbus->XferSize--; + hsmbus->XferCount--; + + if(hsmbus->XferCount == 1) + { + /* Receive last Byte, can be PEC byte in case of PEC BYTE enabled */ + /* or only the last Byte of Transfer */ + /* So reset the RELOAD bit mode */ + hsmbus->XferOptions &= ~SMBUS_RELOAD_MODE; + SMBUS_TransferConfig(hsmbus,0 ,1 , hsmbus->XferOptions, SMBUS_NO_STARTSTOP); + } + else if(hsmbus->XferCount == 0) + { + /* Last Byte is received, disable Interrupt */ + SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_RX); + + /* Remove HAL_SMBUS_STATE_SLAVE_BUSY_RX, keep only HAL_SMBUS_STATE_SLAVE_LISTEN */ + hsmbus->PreviousState = hsmbus->State; + hsmbus->State &= (uint32_t)~((uint32_t)HAL_SMBUS_STATE_SLAVE_BUSY_RX); + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + /* Call the Rx complete callback to inform upper layer of the end of receive process */ + HAL_SMBUS_SlaveRxCpltCallback(hsmbus); + } + else + { + /* Set Reload for next Bytes */ + SMBUS_TransferConfig(hsmbus,0, 1, SMBUS_RELOAD_MODE, SMBUS_NO_STARTSTOP); + + /* Ack last Byte Read */ + hsmbus->Instance->CR2 &= ~I2C_CR2_NACK; + } + } + else if(__HAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_TXIS) != RESET) + { + /* Write data to TXDR only if XferCount not reach "0" */ + /* A TXIS flag can be set, during STOP treatment */ + + /* Check if all Datas have already been sent */ + /* If it is the case, this last write in TXDR is not sent, correspond to a dummy TXIS event */ + if(hsmbus->XferCount > 0) + { + /* Write data to TXDR */ + hsmbus->Instance->TXDR = (*hsmbus->pBuffPtr++); + hsmbus->XferCount--; + hsmbus->XferSize--; + } + + if(hsmbus->XferSize == 0) + { + /* Last Byte is Transmitted */ + /* Remove HAL_SMBUS_STATE_SLAVE_BUSY_TX, keep only HAL_SMBUS_STATE_SLAVE_LISTEN */ + SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_TX); + hsmbus->PreviousState = hsmbus->State; + hsmbus->State &= (uint32_t)~((uint32_t)HAL_SMBUS_STATE_SLAVE_BUSY_TX); + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + /* Call the Tx complete callback to inform upper layer of the end of transmit process */ + HAL_SMBUS_SlaveTxCpltCallback(hsmbus); + } + } + + /* Check if STOPF is set */ + if(__HAL_SMBUS_GET_FLAG(hsmbus, SMBUS_FLAG_STOPF) != RESET) + { + if((hsmbus->State & HAL_SMBUS_STATE_SLAVE_LISTEN) == HAL_SMBUS_STATE_SLAVE_LISTEN) + { + /* Disable RX and TX Interrupts */ + SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_RX | SMBUS_IT_TX); + + /* Disable ADDR Interrupt */ + SMBUS_Disable_IRQ(hsmbus, SMBUS_IT_ADDR); + + /* Disable Address Acknowledge */ + hsmbus->Instance->CR2 |= I2C_CR2_NACK; + + /* Clear Configuration Register 2 */ + __HAL_SMBUS_RESET_CR2(hsmbus); + + /* Clear STOP Flag */ + __HAL_SMBUS_CLEAR_FLAG(hsmbus, SMBUS_FLAG_STOPF); + + /* Clear ADDR flag */ + __HAL_SMBUS_CLEAR_FLAG(hsmbus,SMBUS_FLAG_ADDR); + + hsmbus->XferOptions = 0; + hsmbus->PreviousState = hsmbus->State; + hsmbus->State = HAL_SMBUS_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + /* Call the Slave Complete callback, to prevent upper layer of the end of slave usecase */ + HAL_SMBUS_SlaveListenCpltCallback(hsmbus); + } + } + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + return HAL_OK; +} + +/** + * @brief Manage the enabling of Interrupts + * @param hsmbus : Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @param InterruptRequest : Value of @ref SMBUS_Interrupt_configuration_definition. + * @retval HAL status + */ +static HAL_StatusTypeDef SMBUS_Enable_IRQ(SMBUS_HandleTypeDef *hsmbus, uint16_t InterruptRequest) +{ + uint32_t tmpisr = 0; + + if((InterruptRequest & SMBUS_IT_ALERT) == SMBUS_IT_ALERT) + { + /* Enable ERR interrupt */ + tmpisr |= SMBUS_IT_ERRI; + } + + if((InterruptRequest & SMBUS_IT_ADDR) == SMBUS_IT_ADDR) + { + /* Enable ADDR, STOP interrupt */ + tmpisr |= SMBUS_IT_ADDRI | SMBUS_IT_STOPI | SMBUS_IT_NACKI | SMBUS_IT_ERRI; + } + + if((InterruptRequest & SMBUS_IT_TX) == SMBUS_IT_TX) + { + /* Enable ERR, TC, STOP, NACK, RXI interrupt */ + tmpisr |= SMBUS_IT_ERRI | SMBUS_IT_TCI | SMBUS_IT_STOPI | SMBUS_IT_NACKI | SMBUS_IT_TXI; + } + + if((InterruptRequest & SMBUS_IT_RX) == SMBUS_IT_RX) + { + /* Enable ERR, TC, STOP, NACK, TXI interrupt */ + tmpisr |= SMBUS_IT_ERRI | SMBUS_IT_TCI | SMBUS_IT_STOPI | SMBUS_IT_NACKI | SMBUS_IT_RXI; + } + + /* Enable interrupts only at the end */ + /* to avoid the risk of SMBUS interrupt handle execution before */ + /* all interrupts requested done */ + __HAL_SMBUS_ENABLE_IT(hsmbus, tmpisr); + + return HAL_OK; +} +/** + * @brief Manage the disabling of Interrupts + * @param hsmbus : Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @param InterruptRequest : Value of @ref SMBUS_Interrupt_configuration_definition. + * @retval HAL status + */ +static HAL_StatusTypeDef SMBUS_Disable_IRQ(SMBUS_HandleTypeDef *hsmbus, uint16_t InterruptRequest) +{ + uint32_t tmpisr = 0; + + if( ((InterruptRequest & SMBUS_IT_ALERT) == SMBUS_IT_ALERT) && (hsmbus->State == HAL_SMBUS_STATE_READY) ) + { + /* Disable ERR interrupt */ + tmpisr |= SMBUS_IT_ERRI; + } + + if((InterruptRequest & SMBUS_IT_TX) == SMBUS_IT_TX) + { + /* Disable TC, STOP, NACK, TXI interrupt */ + tmpisr |= SMBUS_IT_TCI | SMBUS_IT_TXI; + + if((__HAL_SMBUS_GET_ALERT_ENABLED(hsmbus) == RESET) + && ((hsmbus->State & HAL_SMBUS_STATE_SLAVE_LISTEN) != HAL_SMBUS_STATE_SLAVE_LISTEN)) + { + /* Disable ERR interrupt */ + tmpisr |= SMBUS_IT_ERRI; + } + + if((hsmbus->State & HAL_SMBUS_STATE_SLAVE_LISTEN) != HAL_SMBUS_STATE_SLAVE_LISTEN) + { + /* Disable STOPI, NACKI */ + tmpisr |= SMBUS_IT_STOPI | SMBUS_IT_NACKI; + } + } + + if((InterruptRequest & SMBUS_IT_RX) == SMBUS_IT_RX) + { + /* Disable TC, STOP, NACK, RXI interrupt */ + tmpisr |= SMBUS_IT_TCI | SMBUS_IT_RXI; + + if((__HAL_SMBUS_GET_ALERT_ENABLED(hsmbus) == RESET) + && ((hsmbus->State & HAL_SMBUS_STATE_SLAVE_LISTEN) != HAL_SMBUS_STATE_SLAVE_LISTEN)) + { + /* Disable ERR interrupt */ + tmpisr |= SMBUS_IT_ERRI; + } + + if((hsmbus->State & HAL_SMBUS_STATE_SLAVE_LISTEN) != HAL_SMBUS_STATE_SLAVE_LISTEN) + { + /* Disable STOPI, NACKI */ + tmpisr |= SMBUS_IT_STOPI | SMBUS_IT_NACKI; + } + } + + if((InterruptRequest & SMBUS_IT_ADDR) == SMBUS_IT_ADDR) + { + /* Enable ADDR, STOP interrupt */ + tmpisr |= SMBUS_IT_ADDRI | SMBUS_IT_STOPI | SMBUS_IT_NACKI; + + if(__HAL_SMBUS_GET_ALERT_ENABLED(hsmbus) == RESET) + { + /* Disable ERR interrupt */ + tmpisr |= SMBUS_IT_ERRI; + } + } + + /* Disable interrupts only at the end */ + /* to avoid a breaking situation like at "t" time */ + /* all disable interrupts request are not done */ + __HAL_SMBUS_DISABLE_IT(hsmbus, tmpisr); + + return HAL_OK; +} +/** + * @brief This function handles SMBUS Communication Timeout. + * @param hsmbus : Pointer to a SMBUS_HandleTypeDef structure that contains + * the configuration information for the specified SMBUS. + * @param Flag: specifies the SMBUS flag to check. + * @param Status: The new Flag status (SET or RESET). + * @param Timeout: Timeout duration + * @retval HAL status + */ +static HAL_StatusTypeDef SMBUS_WaitOnFlagUntilTimeout(SMBUS_HandleTypeDef *hsmbus, uint32_t Flag, FlagStatus Status, uint32_t Timeout) +{ + uint32_t tickstart = 0x00; + tickstart = HAL_GetTick(); + + /* Wait until flag is set */ + if(Status == RESET) + { + while(__HAL_SMBUS_GET_FLAG(hsmbus, Flag) == RESET) + { + /* Check for the Timeout */ + if(Timeout != HAL_MAX_DELAY) + { + if((HAL_GetTick() - tickstart ) > Timeout) + { + hsmbus->PreviousState = hsmbus->State; + hsmbus->State= HAL_SMBUS_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + return HAL_TIMEOUT; + } + } + } + } + else + { + while(__HAL_SMBUS_GET_FLAG(hsmbus, Flag) != RESET) + { + /* Check for the Timeout */ + if(Timeout != HAL_MAX_DELAY) + { + if((HAL_GetTick() - tickstart ) > Timeout) + { + hsmbus->PreviousState = hsmbus->State; + hsmbus->State= HAL_SMBUS_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hsmbus); + + return HAL_TIMEOUT; + } + } + } + } + return HAL_OK; +} + +/** + * @brief Handles SMBUSx communication when starting transfer or during transfer (TC or TCR flag are set). + * @param hsmbus: SMBUS handle. + * @param DevAddress: specifies the slave address to be programmed. + * @param Size: specifies the number of bytes to be programmed. + * This parameter must be a value between 0 and 255. + * @param Mode: new state of the SMBUS START condition generation. + * This parameter can be one or a combination of the following values: + * @arg SMBUS_NO_MODE: No specific mode enabled. + * @arg SMBUS_RELOAD_MODE: Enable Reload mode. + * @arg SMBUS_AUTOEND_MODE: Enable Automatic end mode. + * @arg SMBUS_SOFTEND_MODE: Enable Software end mode and Reload mode. + * @param Request: new state of the SMBUS START condition generation. + * This parameter can be one of the following values: + * @arg SMBUS_NO_STARTSTOP: Don't Generate stop and start condition. + * @arg SMBUS_GENERATE_STOP: Generate stop condition (Size should be set to 0). + * @arg SMBUS_GENERATE_START_READ: Generate Restart for read request. + * @arg SMBUS_GENERATE_START_WRITE: Generate Restart for write request. + * @retval None + */ +static void SMBUS_TransferConfig(SMBUS_HandleTypeDef *hsmbus, uint16_t DevAddress, uint8_t Size, uint32_t Mode, uint32_t Request) +{ + uint32_t tmpreg = 0; + + /* Check the parameters */ + assert_param(IS_SMBUS_INSTANCE(hsmbus->Instance)); + assert_param(IS_SMBUS_TRANSFER_MODE(Mode)); + assert_param(IS_SMBUS_TRANSFER_REQUEST(Request)); + + /* Get the CR2 register value */ + tmpreg = hsmbus->Instance->CR2; + + /* clear tmpreg specific bits */ + tmpreg &= (uint32_t)~((uint32_t)(I2C_CR2_SADD | I2C_CR2_NBYTES | I2C_CR2_RELOAD | I2C_CR2_AUTOEND | I2C_CR2_RD_WRN | I2C_CR2_START | I2C_CR2_STOP | I2C_CR2_PECBYTE)); + + /* update tmpreg */ + tmpreg |= (uint32_t)(((uint32_t)DevAddress & I2C_CR2_SADD) | (((uint32_t)Size << 16 ) & I2C_CR2_NBYTES) | \ + (uint32_t)Mode | (uint32_t)Request); + + /* update CR2 register */ + hsmbus->Instance->CR2 = tmpreg; +} + +/** + * @} + */ + +#endif /* HAL_SMBUS_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_smbus.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_smbus.h new file mode 100644 index 0000000000..94c45c21ba --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_smbus.h @@ -0,0 +1,562 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_smbus.h + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief Header file of SMBUS HAL module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32L0xx_HAL_SMBUS_H +#define __STM32L0xx_HAL_SMBUS_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal_def.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @addtogroup SMBUS + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ + +/** + * @brief SMBUS Configuration Structure definition + */ +typedef struct +{ + uint32_t Timing; /*!< Specifies the SMBUS_TIMINGR_register value. + This parameter calculated by referring to SMBUS initialization + section in Reference manual */ + + uint32_t AnalogFilter; /*!< Specifies if Analog Filter is enable or not. + This parameter can be a a value of @ref SMBUS_Analog_Filter */ + + uint32_t OwnAddress1; /*!< Specifies the first device own address. + This parameter can be a 7-bit or 10-bit address. */ + + uint32_t AddressingMode; /*!< Specifies if 7-bit or 10-bit addressing mode for master is selected. + This parameter can be a value of @ref SMBUS_addressing_mode */ + + uint32_t DualAddressMode; /*!< Specifies if dual addressing mode is selected. + This parameter can be a value of @ref SMBUS_dual_addressing_mode */ + + uint32_t OwnAddress2; /*!< Specifies the second device own address if dual addressing mode is selected + This parameter can be a 7-bit address. */ + + uint32_t OwnAddress2Masks; /*!< Specifies the acknoledge mask address second device own address if dual addressing mode is selected + This parameter can be a value of @ref SMBUS_own_address2_masks. */ + + uint32_t GeneralCallMode; /*!< Specifies if general call mode is selected. + This parameter can be a value of @ref SMBUS_general_call_addressing_mode. */ + + uint32_t NoStretchMode; /*!< Specifies if nostretch mode is selected. + This parameter can be a value of @ref SMBUS_nostretch_mode */ + + uint32_t PacketErrorCheckMode; /*!< Specifies if Packet Error Check mode is selected. + This parameter can be a value of @ref SMBUS_packet_error_check_mode */ + + uint32_t PeripheralMode; /*!< Specifies which mode of Periphal is selected. + This parameter can be a value of @ref SMBUS_peripheral_mode */ + + uint32_t SMBusTimeout; /*!< Specifies the content of the 32 Bits SMBUS_TIMEOUT_register value. + (Enable bits and different timeout values) + This parameter calculated by referring to SMBUS initialization + section in Reference manual */ +} SMBUS_InitTypeDef; + +/** + * @brief HAL State structures definition + */ +typedef enum +{ + HAL_SMBUS_STATE_RESET = 0x00, /*!< SMBUS not yet initialized or disabled */ + HAL_SMBUS_STATE_READY = 0x01, /*!< SMBUS initialized and ready for use */ + HAL_SMBUS_STATE_BUSY = 0x02, /*!< SMBUS internal process is ongoing */ + HAL_SMBUS_STATE_MASTER_BUSY_TX = 0x12, /*!< Master Data Transmission process is ongoing */ + HAL_SMBUS_STATE_MASTER_BUSY_RX = 0x22, /*!< Master Data Reception process is ongoing */ + HAL_SMBUS_STATE_SLAVE_BUSY_TX = 0x32, /*!< Slave Data Transmission process is ongoing */ + HAL_SMBUS_STATE_SLAVE_BUSY_RX = 0x42, /*!< Slave Data Reception process is ongoing */ + HAL_SMBUS_STATE_TIMEOUT = 0x03, /*!< Timeout state */ + HAL_SMBUS_STATE_ERROR = 0x04, /*!< Reception process is ongoing */ + HAL_SMBUS_STATE_SLAVE_LISTEN = 0x08 /*!< Slave Address Listen Mode is ongoing */ +}HAL_SMBUS_StateTypeDef; + +/** + * @brief HAL SMBUS Error Code structure definition + */ +typedef enum +{ + HAL_SMBUS_ERROR_NONE = 0x00, /*!< No error */ + HAL_SMBUS_ERROR_BERR = 0x01, /*!< BERR error */ + HAL_SMBUS_ERROR_ARLO = 0x02, /*!< ARLO error */ + HAL_SMBUS_ERROR_ACKF = 0x04, /*!< ACKF error */ + HAL_SMBUS_ERROR_OVR = 0x08, /*!< OVR error */ + HAL_SMBUS_ERROR_HALTIMEOUT = 0x10, /*!< Timeout error */ + HAL_SMBUS_ERROR_BUSTIMEOUT = 0x20, /*!< Bus Timeout error */ + HAL_SMBUS_ERROR_ALERT = 0x40, /*!< Alert error */ + HAL_SMBUS_ERROR_PECERR = 0x80 /*!< PEC error */ + +}HAL_SMBUS_ErrorTypeDef; + +/** + * @brief SMBUS handle Structure definition + */ +typedef struct +{ + I2C_TypeDef *Instance; /*!< SMBUS registers base address */ + + SMBUS_InitTypeDef Init; /*!< SMBUS communication parameters */ + + uint8_t *pBuffPtr; /*!< Pointer to SMBUS transfer buffer */ + + uint16_t XferSize; /*!< SMBUS transfer size */ + + __IO uint16_t XferCount; /*!< SMBUS transfer counter */ + + __IO uint32_t XferOptions; /*!< SMBUS transfer options */ + + __IO HAL_SMBUS_StateTypeDef PreviousState; /*!< SMBUS communication Previous tate */ + + HAL_LockTypeDef Lock; /*!< SMBUS locking object */ + + __IO HAL_SMBUS_StateTypeDef State; /*!< SMBUS communication state */ + + __IO HAL_SMBUS_ErrorTypeDef ErrorCode; /*!< SMBUS Error code */ + +}SMBUS_HandleTypeDef; + +/* Exported constants --------------------------------------------------------*/ + +/** @defgroup SMBUS_Exported_Constants + * @{ + */ + +/** @defgroup SMBUS_Analog_Filter + * @{ + */ +#define SMBUS_ANALOGFILTER_ENABLED ((uint32_t)0x00000000) +#define SMBUS_ANALOGFILTER_DISABLED I2C_CR1_ANFOFF + +#define IS_SMBUS_ANALOG_FILTER(FILTER) (((FILTER) == SMBUS_ANALOGFILTER_ENABLED) || \ + ((FILTER) == SMBUS_ANALOGFILTER_DISABLED)) +/** + * @} + */ + +/** @defgroup SMBUS_addressing_mode + * @{ + */ +#define SMBUS_ADDRESSINGMODE_7BIT ((uint32_t)0x00000001) +#define SMBUS_ADDRESSINGMODE_10BIT ((uint32_t)0x00000002) + +#define IS_SMBUS_ADDRESSING_MODE(MODE) (((MODE) == SMBUS_ADDRESSINGMODE_7BIT) || \ + ((MODE) == SMBUS_ADDRESSINGMODE_10BIT)) +/** + * @} + */ + +/** @defgroup SMBUS_dual_addressing_mode + * @{ + */ + +#define SMBUS_DUALADDRESS_DISABLED ((uint32_t)0x00000000) +#define SMBUS_DUALADDRESS_ENABLED I2C_OAR2_OA2EN + +#define IS_SMBUS_DUAL_ADDRESS(ADDRESS) (((ADDRESS) == SMBUS_DUALADDRESS_DISABLED) || \ + ((ADDRESS) == SMBUS_DUALADDRESS_ENABLED)) +/** + * @} + */ + +/** @defgroup SMBUS_own_address2_masks + * @{ + */ + +#define SMBUS_OA2_NOMASK ((uint8_t)0x00) +#define SMBUS_OA2_MASK01 ((uint8_t)0x01) +#define SMBUS_OA2_MASK02 ((uint8_t)0x02) +#define SMBUS_OA2_MASK03 ((uint8_t)0x03) +#define SMBUS_OA2_MASK04 ((uint8_t)0x04) +#define SMBUS_OA2_MASK05 ((uint8_t)0x05) +#define SMBUS_OA2_MASK06 ((uint8_t)0x06) +#define SMBUS_OA2_MASK07 ((uint8_t)0x07) + +#define IS_SMBUS_OWN_ADDRESS2_MASK(MASK) (((MASK) == SMBUS_OA2_NOMASK) || \ + ((MASK) == SMBUS_OA2_MASK01) || \ + ((MASK) == SMBUS_OA2_MASK02) || \ + ((MASK) == SMBUS_OA2_MASK03) || \ + ((MASK) == SMBUS_OA2_MASK04) || \ + ((MASK) == SMBUS_OA2_MASK05) || \ + ((MASK) == SMBUS_OA2_MASK06) || \ + ((MASK) == SMBUS_OA2_MASK07)) +/** + * @} + */ + + +/** @defgroup SMBUS_general_call_addressing_mode + * @{ + */ +#define SMBUS_GENERALCALL_DISABLED ((uint32_t)0x00000000) +#define SMBUS_GENERALCALL_ENABLED I2C_CR1_GCEN + +#define IS_SMBUS_GENERAL_CALL(CALL) (((CALL) == SMBUS_GENERALCALL_DISABLED) || \ + ((CALL) == SMBUS_GENERALCALL_ENABLED)) +/** + * @} + */ + +/** @defgroup SMBUS_nostretch_mode + * @{ + */ +#define SMBUS_NOSTRETCH_DISABLED ((uint32_t)0x00000000) +#define SMBUS_NOSTRETCH_ENABLED I2C_CR1_NOSTRETCH + +#define IS_SMBUS_NO_STRETCH(STRETCH) (((STRETCH) == SMBUS_NOSTRETCH_DISABLED) || \ + ((STRETCH) == SMBUS_NOSTRETCH_ENABLED)) +/** + * @} + */ + +/** @defgroup SMBUS_packet_error_check_mode + * @{ + */ +#define SMBUS_PEC_DISABLED ((uint32_t)0x00000000) +#define SMBUS_PEC_ENABLED I2C_CR1_PECEN + +#define IS_SMBUS_PEC(PEC) (((PEC) == SMBUS_PEC_DISABLED) || \ + ((PEC) == SMBUS_PEC_ENABLED)) +/** + * @} + */ + +/** @defgroup SMBUS_peripheral_mode + * @{ + */ +#define SMBUS_PERIPHERAL_MODE_SMBUS_HOST (uint32_t)(I2C_CR1_SMBHEN) +#define SMBUS_PERIPHERAL_MODE_SMBUS_SLAVE (uint32_t)(0x00000000) +#define SMBUS_PERIPHERAL_MODE_SMBUS_SLAVE_ARP (uint32_t)(I2C_CR1_SMBDEN) + +#define IS_SMBUS_PERIPHERAL_MODE(MODE) (((MODE) == SMBUS_PERIPHERAL_MODE_SMBUS_HOST) || \ + ((MODE) == SMBUS_PERIPHERAL_MODE_SMBUS_SLAVE) || \ + ((MODE) == SMBUS_PERIPHERAL_MODE_SMBUS_SLAVE_ARP)) +/** + * @} + */ + +/** @defgroup SMBUS_ReloadEndMode_definition + * @{ + */ + +#define SMBUS_SOFTEND_MODE ((uint32_t)0x00000000) +#define SMBUS_RELOAD_MODE I2C_CR2_RELOAD +#define SMBUS_AUTOEND_MODE I2C_CR2_AUTOEND +#define SMBUS_SENDPEC_MODE I2C_CR2_PECBYTE + +#define IS_SMBUS_TRANSFER_MODE(MODE) (((MODE) == SMBUS_RELOAD_MODE) || \ + ((MODE) == SMBUS_AUTOEND_MODE) || \ + ((MODE) == SMBUS_SOFTEND_MODE) || \ + ((MODE) == (SMBUS_AUTOEND_MODE | SMBUS_SENDPEC_MODE)) || \ + ((MODE) == (SMBUS_AUTOEND_MODE | SMBUS_RELOAD_MODE)) || \ + ((MODE) == (SMBUS_AUTOEND_MODE | SMBUS_SENDPEC_MODE | SMBUS_RELOAD_MODE ))) + +/** + * @} + */ + +/** @defgroup SMBUS_StartStopMode_definition + * @{ + */ + +#define SMBUS_NO_STARTSTOP ((uint32_t)0x00000000) +#define SMBUS_GENERATE_STOP I2C_CR2_STOP +#define SMBUS_GENERATE_START_READ (uint32_t)(I2C_CR2_START | I2C_CR2_RD_WRN) +#define SMBUS_GENERATE_START_WRITE I2C_CR2_START + +#define IS_SMBUS_TRANSFER_REQUEST(REQUEST) (((REQUEST) == SMBUS_GENERATE_STOP) || \ + ((REQUEST) == SMBUS_GENERATE_START_READ) || \ + ((REQUEST) == SMBUS_GENERATE_START_WRITE) || \ + ((REQUEST) == SMBUS_NO_STARTSTOP)) +/** + * @} + */ + +/** @defgroup SMBUS_XferOptions_definition + * @{ + */ + +#define SMBUS_FIRST_FRAME ((uint32_t)(SMBUS_SOFTEND_MODE)) +#define SMBUS_NEXT_FRAME ((uint32_t)(SMBUS_RELOAD_MODE | SMBUS_SOFTEND_MODE)) +#define SMBUS_FIRST_AND_LAST_FRAME_NO_PEC SMBUS_AUTOEND_MODE +#define SMBUS_LAST_FRAME_NO_PEC SMBUS_AUTOEND_MODE +#define SMBUS_FIRST_AND_LAST_FRAME_WITH_PEC ((uint32_t)(SMBUS_AUTOEND_MODE | SMBUS_SENDPEC_MODE)) +#define SMBUS_LAST_FRAME_WITH_PEC ((uint32_t)(SMBUS_AUTOEND_MODE | SMBUS_SENDPEC_MODE)) + +#define IS_SMBUS_TRANSFER_OPTIONS_REQUEST(REQUEST) (((REQUEST) == SMBUS_FIRST_FRAME) || \ + ((REQUEST) == SMBUS_NEXT_FRAME) || \ + ((REQUEST) == SMBUS_FIRST_AND_LAST_FRAME_NO_PEC) || \ + ((REQUEST) == SMBUS_LAST_FRAME_NO_PEC) || \ + ((REQUEST) == SMBUS_FIRST_AND_LAST_FRAME_WITH_PEC) || \ + ((REQUEST) == SMBUS_LAST_FRAME_WITH_PEC)) + +/** + * @} + */ + +/** @defgroup SMBUS_Interrupt_configuration_definition + * @brief SMBUS Interrupt definition + * Elements values convention: 0xXXXXXXXX + * - XXXXXXXX : Interrupt control mask + * @{ + */ +#define SMBUS_IT_ERRI I2C_CR1_ERRIE +#define SMBUS_IT_TCI I2C_CR1_TCIE +#define SMBUS_IT_STOPI I2C_CR1_STOPIE +#define SMBUS_IT_NACKI I2C_CR1_NACKIE +#define SMBUS_IT_ADDRI I2C_CR1_ADDRIE +#define SMBUS_IT_RXI I2C_CR1_RXIE +#define SMBUS_IT_TXI I2C_CR1_TXIE +#define SMBUS_IT_TX (SMBUS_IT_ERRI | SMBUS_IT_TCI | SMBUS_IT_STOPI | SMBUS_IT_NACKI | SMBUS_IT_TXI) +#define SMBUS_IT_RX (SMBUS_IT_ERRI | SMBUS_IT_TCI | SMBUS_IT_NACKI | SMBUS_IT_RXI) +#define SMBUS_IT_ALERT (SMBUS_IT_ERRI) +#define SMBUS_IT_ADDR (SMBUS_IT_ADDRI | SMBUS_IT_STOPI | SMBUS_IT_NACKI) +/** + * @} + */ + +/** @defgroup SMBUS_Flag_definition + * @brief Flag definition + * Elements values convention: 0xXXXXYYYY + * - XXXXXXXX : Flag mask + * @{ + */ + +#define SMBUS_FLAG_TXE I2C_ISR_TXE +#define SMBUS_FLAG_TXIS I2C_ISR_TXIS +#define SMBUS_FLAG_RXNE I2C_ISR_RXNE +#define SMBUS_FLAG_ADDR I2C_ISR_ADDR +#define SMBUS_FLAG_AF I2C_ISR_NACKF +#define SMBUS_FLAG_STOPF I2C_ISR_STOPF +#define SMBUS_FLAG_TC I2C_ISR_TC +#define SMBUS_FLAG_TCR I2C_ISR_TCR +#define SMBUS_FLAG_BERR I2C_ISR_BERR +#define SMBUS_FLAG_ARLO I2C_ISR_ARLO +#define SMBUS_FLAG_OVR I2C_ISR_OVR +#define SMBUS_FLAG_PECERR I2C_ISR_PECERR +#define SMBUS_FLAG_TIMEOUT I2C_ISR_TIMEOUT +#define SMBUS_FLAG_ALERT I2C_ISR_ALERT +#define SMBUS_FLAG_BUSY I2C_ISR_BUSY +#define SMBUS_FLAG_DIR I2C_ISR_DIR +/** + * @} + */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ +/** @defgroup SMBUS_Exported_Macros + * @{ + */ + +/** @brief Reset SMBUS handle state + * @param __HANDLE__: specifies the SMBUS Handle. + * This parameter can be SMBUSx where x: 1 or 2 to select the SMBUS peripheral. + * @retval None + */ +#define __HAL_SMBUS_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_SMBUS_STATE_RESET) + +/** @brief Enable or disable the specified SMBUS interrupts. + * @param __HANDLE__: specifies the SMBUS Handle. + * This parameter can be SMBUSx where x: 1 or 2 to select the SMBUS peripheral. + * @param __INTERRUPT__: specifies the interrupt source to enable or disable. + * This parameter can be one of the following values: + * @arg SMBUS_IT_ERRI: Errors interrupt enable + * @arg SMBUS_IT_TCI: Transfer complete interrupt enable + * @arg SMBUS_IT_STOPI: STOP detection interrupt enable + * @arg SMBUS_IT_NACKI: NACK received interrupt enable + * @arg SMBUS_IT_ADDRI: Address match interrupt enable + * @arg SMBUS_IT_RXI: RX interrupt enable + * @arg SMBUS_IT_TXI: TX interrupt enable + * + * @retval None + */ + +#define __HAL_SMBUS_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR1 |= (__INTERRUPT__)) +#define __HAL_SMBUS_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR1 &= (~(__INTERRUPT__))) + +/** @brief Checks if the specified SMBUS interrupt source is enabled or disabled. + * @param __HANDLE__: specifies the SMBUS Handle. + * This parameter can be SMBUSx where x: 1 or 2 to select the SMBUS peripheral. + * @param __INTERRUPT__: specifies the SMBUS interrupt source to check. + * This parameter can be one of the following values: + * @arg SMBUS_IT_ERRI: Errors interrupt enable + * @arg SMBUS_IT_TCI: Transfer complete interrupt enable + * @arg SMBUS_IT_STOPI: STOP detection interrupt enable + * @arg SMBUS_IT_NACKI: NACK received interrupt enable + * @arg SMBUS_IT_ADDRI: Address match interrupt enable + * @arg SMBUS_IT_RXI: RX interrupt enable + * @arg SMBUS_IT_TXI: TX interrupt enable + * + * @retval The new state of __IT__ (TRUE or FALSE). + */ +#define __HAL_SMBUS_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((((__HANDLE__)->Instance->CR1 & (__INTERRUPT__)) == (__INTERRUPT__)) ? SET : RESET) + +/** @brief Checks whether the specified SMBUS flag is set or not. + * @param __HANDLE__: specifies the SMBUS Handle. + * This parameter can be SMBUSx where x: 1 or 2 to select the SMBUS peripheral. + * @param __FLAG__: specifies the flag to check. + * This parameter can be one of the following values: + * @arg SMBUS_FLAG_TXE: Transmit data register empty + * @arg SMBUS_FLAG_TXIS: Transmit interrupt status + * @arg SMBUS_FLAG_RXNE: Receive data register not empty + * @arg SMBUS_FLAG_ADDR: Address matched (slave mode) + * @arg SMBUS_FLAG_AF NACK received flag + * @arg SMBUS_FLAG_STOPF: STOP detection flag + * @arg SMBUS_FLAG_TC: Transfer complete (master mode) + * @arg SMBUS_FLAG_TCR: Transfer complete reload + * @arg SMBUS_FLAG_BERR: Bus error + * @arg SMBUS_FLAG_ARLO: Arbitration lost + * @arg SMBUS_FLAG_OVR: Overrun/Underrun + * @arg SMBUS_FLAG_PECERR: PEC error in reception + * @arg SMBUS_FLAG_TIMEOUT: Timeout or Tlow detection flag + * @arg SMBUS_FLAG_ALERT: SMBus alert + * @arg SMBUS_FLAG_BUSY: Bus busy + * @arg SMBUS_FLAG_DIR: Transfer direction (slave mode) + * @retval The new state of __FLAG__ (TRUE or FALSE). + */ +#define SMBUS_FLAG_MASK ((uint32_t)0x0001FFFF) +#define __HAL_SMBUS_GET_FLAG(__HANDLE__, __FLAG__) (((((__HANDLE__)->Instance->ISR) & ((__FLAG__) & SMBUS_FLAG_MASK)) == ((__FLAG__) & SMBUS_FLAG_MASK))) + +/** @brief Clears the SMBUS pending flags which are cleared by writing 1 in a specific bit. + * @param __HANDLE__: specifies the SMBUS Handle. + * This parameter can be SMBUSx where x: 1 or 2 to select the SMBUS peripheral. + * @param __FLAG__: specifies the flag to clear. + * This parameter can be any combination of the following values: + * @arg SMBUS_FLAG_ADDR: Address matched (slave mode) + * @arg SMBUS_FLAG_AF: NACK received flag + * @arg SMBUS_FLAG_STOPF: STOP detection flag + * @arg SMBUS_FLAG_BERR: Bus error + * @arg SMBUS_FLAG_ARLO: Arbitration lost + * @arg SMBUS_FLAG_OVR: Overrun/Underrun + * @arg SMBUS_FLAG_PECERR: PEC error in reception + * @arg SMBUS_FLAG_TIMEOUT: Timeout or Tlow detection flag + * @arg SMBUS_FLAG_ALERT: SMBus alert + * @retval None + */ +#define __HAL_SMBUS_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->ICR |= ((__FLAG__) & SMBUS_FLAG_MASK)) + + +#define __HAL_SMBUS_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 |= I2C_CR1_PE) +#define __HAL_SMBUS_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 &= ~I2C_CR1_PE) + +#define __HAL_SMBUS_RESET_CR1(__HANDLE__) ((__HANDLE__)->Instance->CR1 &= (uint32_t)~((uint32_t)(I2C_CR1_SMBHEN | I2C_CR1_SMBDEN | I2C_CR1_PECEN))) +#define __HAL_SMBUS_RESET_CR2(__HANDLE__) ((__HANDLE__)->Instance->CR2 &= (uint32_t)~((uint32_t)(I2C_CR2_SADD | I2C_CR2_HEAD10R | I2C_CR2_NBYTES | I2C_CR2_RELOAD | I2C_CR2_RD_WRN))) + +#define __HAL_SMBUS_GENERATE_START(__ADDMODE__,__ADDRESS__) (((__ADDMODE__) == SMBUS_ADDRESSINGMODE_7BIT) ? (uint32_t)((((uint32_t)(__ADDRESS__) & (I2C_CR2_SADD)) | (I2C_CR2_START) | (I2C_CR2_AUTOEND)) & (~I2C_CR2_RD_WRN)) : \ + (uint32_t)((((uint32_t)(__ADDRESS__) & (I2C_CR2_SADD)) | (I2C_CR2_ADD10) | (I2C_CR2_START)) & (~I2C_CR2_RD_WRN))) + +#define __HAL_SMBUS_GET_ADDR_MATCH(__HANDLE__) (((__HANDLE__)->Instance->ISR & I2C_ISR_ADDCODE) >> 17) +#define __HAL_SMBUS_GET_DIR(__HANDLE__) (((__HANDLE__)->Instance->ISR & I2C_ISR_DIR) >> 16) +#define __HAL_SMBUS_GET_STOP_MODE(__HANDLE__) ((__HANDLE__)->Instance->CR2 & I2C_CR2_AUTOEND) +#define __HAL_SMBUS_GET_PEC_MODE(__HANDLE__) ((__HANDLE__)->Instance->CR2 & I2C_CR2_PECBYTE) +#define __HAL_SMBUS_GET_ALERT_ENABLED(__HANDLE__) ((__HANDLE__)->Instance->CR1 & I2C_CR1_ALERTEN) +#define __HAL_SMBUS_GENERATE_NACK(__HANDLE__) ((__HANDLE__)->Instance->CR2 |= I2C_CR2_NACK) + +#define IS_SMBUS_OWN_ADDRESS1(ADDRESS1) ((ADDRESS1) <= (uint32_t)0x000003FF) +#define IS_SMBUS_OWN_ADDRESS2(ADDRESS2) ((ADDRESS2) <= (uint16_t)0x00FF) +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/* Initialization and de-initialization functions ****************************/ +HAL_StatusTypeDef HAL_SMBUS_Init(SMBUS_HandleTypeDef *hsmbus); +HAL_StatusTypeDef HAL_SMBUS_DeInit (SMBUS_HandleTypeDef *hsmbus); +void HAL_SMBUS_MspInit(SMBUS_HandleTypeDef *hsmbus); +void HAL_SMBUS_MspDeInit(SMBUS_HandleTypeDef *hsmbus); + +/* IO operation functions ****************************************************/ +HAL_StatusTypeDef HAL_SMBUS_EnableAlert_IT(SMBUS_HandleTypeDef *hsmbus); +HAL_StatusTypeDef HAL_SMBUS_DisableAlert_IT(SMBUS_HandleTypeDef *hsmbus); + +/******* Blocking mode: Polling */ +HAL_StatusTypeDef HAL_SMBUS_IsDeviceReady(SMBUS_HandleTypeDef *hsmbus, uint16_t DevAddress, uint32_t Trials, uint32_t Timeout); + + /******* Non-Blocking mode: Interrupt */ +HAL_StatusTypeDef HAL_SMBUS_Master_Transmit_IT(SMBUS_HandleTypeDef *hsmbus, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t XferOptions); +HAL_StatusTypeDef HAL_SMBUS_Master_Receive_IT(SMBUS_HandleTypeDef *hsmbus, uint16_t DevAddress, uint8_t *pData, uint16_t Size, uint32_t XferOptions); +HAL_StatusTypeDef HAL_SMBUS_Master_Abort_IT(SMBUS_HandleTypeDef *hsmbus, uint16_t DevAddress); +HAL_StatusTypeDef HAL_SMBUS_Slave_Transmit_IT(SMBUS_HandleTypeDef *hsmbus, uint8_t *pData, uint16_t Size, uint32_t XferOptions); +HAL_StatusTypeDef HAL_SMBUS_Slave_Receive_IT(SMBUS_HandleTypeDef *hsmbus, uint8_t *pData, uint16_t Size, uint32_t XferOptions); +HAL_StatusTypeDef HAL_SMBUS_Slave_Listen_IT(SMBUS_HandleTypeDef *hsmbus); + + /******* SMBUS IRQHandler and Callbacks used in non blocking modes (Interrupt) */ +void HAL_SMBUS_EV_IRQHandler(SMBUS_HandleTypeDef *hsmbus); +void HAL_SMBUS_ER_IRQHandler(SMBUS_HandleTypeDef *hsmbus); +void HAL_SMBUS_MasterTxCpltCallback(SMBUS_HandleTypeDef *hsmbus); +void HAL_SMBUS_MasterRxCpltCallback(SMBUS_HandleTypeDef *hsmbus); +void HAL_SMBUS_SlaveTxCpltCallback(SMBUS_HandleTypeDef *hsmbus); +void HAL_SMBUS_SlaveRxCpltCallback(SMBUS_HandleTypeDef *hsmbus); +void HAL_SMBUS_SlaveAddrCallback(SMBUS_HandleTypeDef *hsmbus, uint8_t TransferDirection, uint16_t AddrMatchCode); +void HAL_SMBUS_SlaveListenCpltCallback(SMBUS_HandleTypeDef *hsmbus); +void HAL_SMBUS_ErrorCallback(SMBUS_HandleTypeDef *hsmbus); + +/* Peripheral State and Errors functions *************************************/ +HAL_SMBUS_StateTypeDef HAL_SMBUS_GetState(SMBUS_HandleTypeDef *hsmbus); +uint32_t HAL_SMBUS_GetError(SMBUS_HandleTypeDef *hsmbus); + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + + +#endif /* __STM32L0xx_HAL_SMBUS_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_spi.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_spi.c new file mode 100644 index 0000000000..7bdd593ddd --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_spi.c @@ -0,0 +1,2096 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_spi.c + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief SPI HAL module driver. + * + * This file provides firmware functions to manage the following + * functionalities of the Serial Peripheral Interface (SPI) peripheral: + * + Initialization and de-initialization functions + * + IO operation functions + * + Peripheral Control functions + * + Peripheral State functions + @verbatim + ============================================================================== + ##### How to use this driver ##### + ============================================================================== + [..] + The SPI HAL driver can be used as follows: + + (#) Declare a SPI_HandleTypeDef handle structure, for example: + SPI_HandleTypeDef hspi; + + (#)Initialize the SPI low level resources by implement the HAL_SPI_MspInit ()API: + (##) Enable the SPIx interface clock + (##) SPI pins configuration + (+) Enable the clock for the SPI GPIOs + (+) Configure these SPI pins as alternate function push-pull + (##) NVIC configuration if you need to use interrupt process + (+) Configure the SPIx interrupt priority + (+) Enable the NVIC SPI IRQ handle + (##) DMA Configuration if you need to use DMA process + (+) Declare a DMA_HandleTypeDef handle structure for the transmit or receive stream + (+) Enable the DMAx interface clock using + (+) Configure the DMA handle parameters + (+) Configure the DMA Tx or Rx Stream + (+) Associate the initilalized hdma_tx handle to the hspi DMA Tx or Rx handle + (+) Configure the priority and enable the NVIC for the transfer complete interrupt on the DMA Tx or Rx Stream + + (#) Program the Mode, Direction , Data size, Baudrate Prescaler, NSS + management, Clock polarity and phase, FirstBit and CRC configuration in the hspi Init structure. + + (#) Initialize the SPI registers by calling the HAL_SPI_Init() API: + (+) This API configures also the low level Hardware GPIO, CLOCK, CORTEX...etc) + by calling the customed HAL_SPI_MspInit(&hspi) API. + [..] + Using the HAL it is not possible to reach all supported SPI frequency with the differents SPI Modes, + the following table resume the max SPI frequency reached with data size 8bits/16bits: + +-----------------------------------------------------------------------------------------+ + | | | 2Lines Fullduplex | 2Lines RxOnly | 1Line | + | Process | Tranfert mode |--------------------|--------------------|--------------------| + | | | Master | Slave | Master | Slave | Master | Slave | + |=========================================================================================| + | T | Polling | Fcpu/4 | Fcpu/8 | NA | NA | NA | NA | + | X |----------------|----------|---------|----------|---------|----------|---------| + | / | Interrupt | Fcpu/4 | Fcpu/16 | NA | NA | NA | NA | + | R |----------------|----------|---------|----------|---------|----------|---------| + | X | DMA | Fcpu/2 | Fcpu/2 | NA | NA | NA | NA | + |=========|================|==========|=========|==========|=========|==========|=========| + | | Polling | Fcpu/4 | Fcpu/8 | Fcpu/16 | Fcpu/8 | Fcpu/8 | Fcpu/8 | + | |----------------|----------|---------|----------|---------|----------|---------| + | R | Interrupt | Fcpu/8 | Fcpu/16 | Fcpu/8 | Fcpu/8 | Fcpu/8 | Fcpu/4 | + | X |----------------|----------|---------|----------|---------|----------|---------| + | | DMA | Fcpu/4 | Fcpu/2 | Fcpu/4 | Fcpu/16 | Fcpu/2 | Fcpu/16 | + |=========|================|==========|=========|==========|=========|==========|=========| + | | Polling | Fcpu/8 | Fcpu/2 | NA | NA | Fcpu/8 | Fcpu/8 | + | |----------------|----------|---------|----------|---------|----------|---------| + | T | Interrupt | Fcpu/2 | Fcpu/4 | NA | NA | Fcpu/16 | Fcpu/8 | + | X |----------------|----------|---------|----------|---------|----------|---------| + | | DMA | Fcpu/2 | Fcpu/2 | NA | NA | Fcpu/8 | Fcpu/16 | + +-----------------------------------------------------------------------------------------+ + @note The max SPI frequency depend on SPI data size (4bits, 5bits,..., 8bits,...15bits, 16bits), + SPI mode(2 Lines fullduplex, 2 lines RxOnly, 1 line TX/RX) and Process mode (Polling, IT, DMA). + @note + (#) TX/RX processes are HAL_SPI_TransmitReceive(), HAL_SPI_TransmitReceive_IT() and HAL_SPI_TransmitReceive_DMA() + (#) RX processes are HAL_SPI_Receive(), HAL_SPI_Receive_IT() and HAL_SPI_Receive_DMA() + (#) TX processes are HAL_SPI_Transmit(), HAL_SPI_Transmit_IT() and HAL_SPI_Transmit_DMA() + + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @defgroup SPI + * @brief SPI HAL module driver + * @{ + */ + +#ifdef HAL_SPI_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +#define SPI_TIMEOUT_VALUE 100 +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +static void SPI_TxCloseIRQHandler(SPI_HandleTypeDef *hspi); +static void SPI_TxISR(SPI_HandleTypeDef *hspi); +static void SPI_RxCloseIRQHandler(SPI_HandleTypeDef *hspi); +static void SPI_2LinesRxISR(SPI_HandleTypeDef *hspi); +static void SPI_RxISR(SPI_HandleTypeDef *hspi); +static void SPI_DMATransmitCplt(DMA_HandleTypeDef *hdma); +static void SPI_DMAReceiveCplt(DMA_HandleTypeDef *hdma); +static void SPI_DMATransmitReceiveCplt(DMA_HandleTypeDef *hdma); +static void SPI_DMAError(DMA_HandleTypeDef *hdma); +static HAL_StatusTypeDef SPI_WaitOnFlagUntilTimeout(SPI_HandleTypeDef *hspi, uint32_t Flag, FlagStatus Status, uint32_t Timeout); + +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup SPI_Private_Functions + * @{ + */ + +/** @defgroup SPI_Group1 Initialization and de-initialization functions + * @brief Initialization and Configuration functions + * +@verbatim + =============================================================================== + ##### Initialization and de-initialization functions ##### + =============================================================================== + [..] This subsection provides a set of functions allowing to initialize and + de-initialiaze the SPIx peripheral: + + (+) User must Implement HAL_SPI_MspInit() function in which he configures + all related peripherals resources (CLOCK, GPIO, DMA, IT and NVIC ). + + (+) Call the function HAL_SPI_Init() to configure the selected device with + the selected configuration: + (++) Mode + (++) Direction + (++) Data Size + (++) Clock Polarity and Phase + (++) NSS Management + (++) BaudRate Prescaler + (++) FirstBit + (++) TIMode + (++) CRC Calculation + (++) CRC Polynomial if CRC enabled + + (+) Call the function HAL_SPI_DeInit() to restore the default configuration + of the selected SPIx periperal. + +@endverbatim + * @{ + */ + +/** + * @brief Initializes the SPI according to the specified parameters + * in the SPI_InitTypeDef and create the associated handle. + * @param hspi: pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SPI_Init(SPI_HandleTypeDef *hspi) +{ + /* Check the SPI handle allocation */ + if(hspi == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_SPI_MODE(hspi->Init.Mode)); + assert_param(IS_SPI_DIRECTION_MODE(hspi->Init.Direction)); + assert_param(IS_SPI_DATASIZE(hspi->Init.DataSize)); + assert_param(IS_SPI_CPOL(hspi->Init.CLKPolarity)); + assert_param(IS_SPI_CPHA(hspi->Init.CLKPhase)); + assert_param(IS_SPI_NSS(hspi->Init.NSS)); + assert_param(IS_SPI_BAUDRATE_PRESCALER(hspi->Init.BaudRatePrescaler)); + assert_param(IS_SPI_FIRST_BIT(hspi->Init.FirstBit)); + assert_param(IS_SPI_TIMODE(hspi->Init.TIMode)); + assert_param(IS_SPI_CRC_CALCULATION(hspi->Init.CRCCalculation)); + assert_param(IS_SPI_CRC_POLYNOMIAL(hspi->Init.CRCPolynomial)); + + if(hspi->State == HAL_SPI_STATE_RESET) + { + /* Init the low level hardware : GPIO, CLOCK, NVIC... */ + HAL_SPI_MspInit(hspi); + } + + hspi->State = HAL_SPI_STATE_BUSY; + + /* Disble the selected SPI peripheral */ + __HAL_SPI_DISABLE(hspi); + + /*----------------------- SPIx CR1 & CR2 Configuration ---------------------*/ + /* Configure : SPI Mode, Communication Mode, Data size, Clock polarity and phase, NSS management, + Communication speed, First bit and CRC calculation state */ + hspi->Instance->CR1 = (hspi->Init.Mode | hspi->Init.Direction | hspi->Init.DataSize | + hspi->Init.CLKPolarity | hspi->Init.CLKPhase | (hspi->Init.NSS & SPI_CR1_SSM) | + hspi->Init.BaudRatePrescaler | hspi->Init.FirstBit | hspi->Init.CRCCalculation); + + /* Configure : NSS management */ + hspi->Instance->CR2 = (((hspi->Init.NSS >> 16) & SPI_CR2_SSOE) | hspi->Init.TIMode); + + /*---------------------------- SPIx CRCPOLY Configuration ------------------*/ + /* Configure : CRC Polynomial */ + hspi->Instance->CRCPR = hspi->Init.CRCPolynomial; + + /* Activate the SPI mode (Make sure that I2SMOD bit in I2SCFGR register is reset) */ + hspi->Instance->I2SCFGR &= (uint32_t)~((uint32_t)SPI_I2SCFGR_I2SMOD); + + hspi->ErrorCode = HAL_SPI_ERROR_NONE; + hspi->State = HAL_SPI_STATE_READY; + + return HAL_OK; +} + +/** + * @brief DeInitializes the SPI peripheral + * @param hspi: pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SPI_DeInit(SPI_HandleTypeDef *hspi) +{ + /* Check the SPI handle allocation */ + if(hspi == NULL) + { + return HAL_ERROR; + } + + hspi->State = HAL_SPI_STATE_BUSY; + + /* Disable the SPI Peripheral Clock */ + __HAL_SPI_DISABLE(hspi); + + /* DeInit the low level hardware: GPIO, CLOCK, NVIC... */ + HAL_SPI_MspDeInit(hspi); + + hspi->ErrorCode = HAL_SPI_ERROR_NONE; + hspi->State = HAL_SPI_STATE_RESET; + + /* Release Lock */ + __HAL_UNLOCK(hspi); + + return HAL_OK; +} + +/** + * @brief SPI MSP Init + * @param hspi: pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @retval None + */ + __weak void HAL_SPI_MspInit(SPI_HandleTypeDef *hspi) + { + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_SPI_MspInit could be implenetd in the user file + */ +} + +/** + * @brief SPI MSP DeInit + * @param hspi: pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @retval None + */ + __weak void HAL_SPI_MspDeInit(SPI_HandleTypeDef *hspi) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_SPI_MspDeInit could be implenetd in the user file + */ +} + +/** + * @} + */ + +/** @defgroup SPI_Group2 IO operation functions + * @brief Data transfers functions + * +@verbatim + ============================================================================== + ##### IO operation functions ##### + =============================================================================== + This subsection provides a set of functions allowing to manage the SPI + data transfers. + + [..] The SPI supports master and slave mode : + + (#) There are two mode of transfer: + (+) Blocking mode: The communication is performed in polling mode. + The HAL status of all data processing is returned by the same function + after finishing transfer. + (+) No-Blocking mode: The communication is performed using Interrupts + or DMA, These API's return the HAL status. + The end of the data processing will be indicated through the + dedicated SPI IRQ when using Interrupt mode or the DMA IRQ when + using DMA mode. + The HAL_SPI_TxCpltCallback(), HAL_SPI_RxCpltCallback() and HAL_SPI_TxRxCpltCallback() user callbacks + will be executed respectivelly at the end of the transmit or Receive process + The HAL_SPI_ErrorCallback()user callback will be executed when a communication error is detected + + (#) Blocking mode API's are : + (+) HAL_SPI_Transmit()in 1Line (simplex) and 2Lines (full duplex) mode + (+) HAL_SPI_Receive() in 1Line (simplex) and 2Lines (full duplex) mode + (+) HAL_SPI_TransmitReceive() in full duplex mode + + (#) Non-Blocking mode API's with Interrupt are : + (+) HAL_SPI_Transmit_IT()in 1Line (simplex) and 2Lines (full duplex) mode + (+) HAL_SPI_Receive_IT() in 1Line (simplex) and 2Lines (full duplex) mode + (+) HAL_SPI_TransmitReceive_IT()in full duplex mode + (+) HAL_SPI_IRQHandler() + + (#) No-Blocking mode functions with DMA are : + (+) HAL_SPI_Transmit_DMA()in 1Line (simplex) and 2Lines (full duplex) mode + (+) HAL_SPI_Receive_DMA() in 1Line (simplex) and 2Lines (full duplex) mode + (+) HAL_SPI_TransmitReceie_DMA() in full duplex mode + + (#) A set of Transfer Complete Callbacks are provided in No_Blocking mode: + (+) HAL_SPI_TxCpltCallback() + (+) HAL_SPI_RxCpltCallback() + (+) HAL_SPI_ErrorCallback() + (+) HAL_SPI_TxRxCpltCallback() + +@endverbatim + * @{ + */ + +/** + * @brief Transmit an amount of data in blocking mode + * @param hspi: pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @param pData: pointer to data buffer + * @param Size: amount of data to be sent + * @param Timeout: Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SPI_Transmit(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size, uint32_t Timeout) +{ + + if(hspi->State == HAL_SPI_STATE_READY) + { + if((pData == NULL ) || (Size == 0)) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_SPI_DIRECTION_2LINES_OR_1LINE(hspi->Init.Direction)); + + /* Process Locked */ + __HAL_LOCK(hspi); + + /* Configure communication */ + hspi->State = HAL_SPI_STATE_BUSY_TX; + hspi->ErrorCode = HAL_SPI_ERROR_NONE; + + hspi->pTxBuffPtr = pData; + hspi->TxXferSize = Size; + hspi->TxXferCount = Size; + + /*Init field not used in handle to zero */ + hspi->TxISR = 0; + hspi->RxISR = 0; + hspi->RxXferSize = 0; + hspi->RxXferCount = 0; + + /* Reset CRC Calculation */ + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED) + { + __HAL_SPI_RESET_CRC(hspi); + } + + if(hspi->Init.Direction == SPI_DIRECTION_1LINE) + { + /* Configure communication direction : 1Line */ + __HAL_SPI_1LINE_TX(hspi); + } + + /* Check if the SPI is already enabled */ + if((hspi->Instance->CR1 &SPI_CR1_SPE) != SPI_CR1_SPE) + { + /* Enable SPI peripheral */ + __HAL_SPI_ENABLE(hspi); + } + + /* Transmit data in 8 Bit mode */ + if(hspi->Init.DataSize == SPI_DATASIZE_8BIT) + { + + hspi->Instance->DR = (*hspi->pTxBuffPtr++); + hspi->TxXferCount--; + + while(hspi->TxXferCount > 0) + { + /* Wait until TXE flag is set to send data */ + if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_TXE, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + hspi->Instance->DR = (*hspi->pTxBuffPtr++); + hspi->TxXferCount--; + } + /* Enable CRC Transmission */ + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED) + { + hspi->Instance->CR1 |= SPI_CR1_CRCNEXT; + } + } + /* Transmit data in 16 Bit mode */ + else + { + hspi->Instance->DR = *((uint16_t*)hspi->pTxBuffPtr); + hspi->pTxBuffPtr+=2; + hspi->TxXferCount--; + + while(hspi->TxXferCount > 0) + { + /* Wait until TXE flag is set to send data */ + if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_TXE, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + hspi->Instance->DR = *((uint16_t*)hspi->pTxBuffPtr); + hspi->pTxBuffPtr+=2; + hspi->TxXferCount--; + } + /* Enable CRC Transmission */ + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED) + { + hspi->Instance->CR1 |= SPI_CR1_CRCNEXT; + } + } + + /* Wait until TXE flag is set to send data */ + if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_TXE, RESET, Timeout) != HAL_OK) + { + hspi->ErrorCode |= HAL_SPI_ERROR_FLAG; + return HAL_TIMEOUT; + } + + /* Wait until Busy flag is reset before disabling SPI */ + if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_BSY, SET, Timeout) != HAL_OK) + { + hspi->ErrorCode |= HAL_SPI_ERROR_FLAG; + return HAL_TIMEOUT; + } + + /* Clear OVERUN flag in 2 Lines communication mode because received is not read */ + if(hspi->Init.Direction == SPI_DIRECTION_2LINES) + { + __HAL_SPI_CLEAR_OVRFLAG(hspi); + } + + hspi->State = HAL_SPI_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hspi); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive an amount of data in blocking mode + * @param hspi: pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @param pData: pointer to data buffer + * @param Size: amount of data to be sent + * @param Timeout: Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SPI_Receive(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size, uint32_t Timeout) +{ + __IO uint16_t tmpreg; + uint32_t tmp = 0; + + if(hspi->State == HAL_SPI_STATE_READY) + { + if((pData == NULL ) || (Size == 0)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(hspi); + + /* Configure communication */ + hspi->State = HAL_SPI_STATE_BUSY_RX; + hspi->ErrorCode = HAL_SPI_ERROR_NONE; + + hspi->pRxBuffPtr = pData; + hspi->RxXferSize = Size; + hspi->RxXferCount = Size; + + /*Init field not used in handle to zero */ + hspi->RxISR = 0; + hspi->TxISR = 0; + hspi->TxXferSize = 0; + hspi->TxXferCount = 0; + + /* Configure communication direction : 1Line */ + if(hspi->Init.Direction == SPI_DIRECTION_1LINE) + { + __HAL_SPI_1LINE_RX(hspi); + } + + /* Reset CRC Calculation */ + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED) + { + __HAL_SPI_RESET_CRC(hspi); + } + + if((hspi->Init.Mode == SPI_MODE_MASTER) && (hspi->Init.Direction == SPI_DIRECTION_2LINES)) + { + /* Process Unlocked */ + __HAL_UNLOCK(hspi); + + /* Call transmit-receive function to send Dummy data on Tx line and generate clock on CLK line */ + return HAL_SPI_TransmitReceive(hspi, pData, pData, Size, Timeout); + } + + /* Check if the SPI is already enabled */ + if((hspi->Instance->CR1 &SPI_CR1_SPE) != SPI_CR1_SPE) + { + /* Enable SPI peripheral */ + __HAL_SPI_ENABLE(hspi); + } + + /* Receive data in 8 Bit mode */ + if(hspi->Init.DataSize == SPI_DATASIZE_8BIT) + { + while(hspi->RxXferCount > 1) + { + /* Wait until RXNE flag is set */ + if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_RXNE, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + (*hspi->pRxBuffPtr++) = hspi->Instance->DR; + hspi->RxXferCount--; + } + /* Enable CRC Transmission */ + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED) + { + hspi->Instance->CR1 |= SPI_CR1_CRCNEXT; + } + } + /* Receive data in 16 Bit mode */ + else + { + while(hspi->RxXferCount > 1) + { + /* Wait until RXNE flag is set to read data */ + if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_RXNE, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + *((uint16_t*)hspi->pRxBuffPtr) = hspi->Instance->DR; + hspi->pRxBuffPtr+=2; + hspi->RxXferCount--; + } + /* Enable CRC Transmission */ + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED) + { + hspi->Instance->CR1 |= SPI_CR1_CRCNEXT; + } + } + + /* Wait until RXNE flag is set */ + if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_RXNE, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + /* Receive last data in 8 Bit mode */ + if(hspi->Init.DataSize == SPI_DATASIZE_8BIT) + { + (*hspi->pRxBuffPtr++) = hspi->Instance->DR; + } + /* Receive last data in 16 Bit mode */ + else + { + *((uint16_t*)hspi->pRxBuffPtr) = hspi->Instance->DR; + hspi->pRxBuffPtr+=2; + } + hspi->RxXferCount--; + + /* Wait until RXNE flag is set: CRC Received */ + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED) + { + if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_RXNE, RESET, Timeout) != HAL_OK) + { + hspi->ErrorCode |= HAL_SPI_ERROR_CRC; + return HAL_TIMEOUT; + } + + /* Read CRC to Flush RXNE flag */ + tmpreg = hspi->Instance->DR; + } + + if((hspi->Init.Mode == SPI_MODE_MASTER)&&((hspi->Init.Direction == SPI_DIRECTION_1LINE)||(hspi->Init.Direction == SPI_DIRECTION_2LINES_RXONLY))) + { + /* Disable SPI peripheral */ + __HAL_SPI_DISABLE(hspi); + } + + hspi->State = HAL_SPI_STATE_READY; + + tmp = __HAL_SPI_GET_FLAG(hspi, SPI_FLAG_CRCERR); + /* Check if CRC error occurred */ + if((hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED) && (tmp != RESET)) + { + hspi->ErrorCode |= HAL_SPI_ERROR_CRC; + + /* Reset CRC Calculation */ + __HAL_SPI_RESET_CRC(hspi); + + /* Process Unlocked */ + __HAL_UNLOCK(hspi); + + return HAL_ERROR; + } + + /* Process Unlocked */ + __HAL_UNLOCK(hspi); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Transmit and Receive an amount of data in blocking mode + * @param hspi: pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @param pTxData: pointer to transmission data buffer + * @param pRxData: pointer to reception data buffer to be + * @param Size: amount of data to be sent + * @param Timeout: Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size, uint32_t Timeout) +{ + __IO uint16_t tmpreg; + uint32_t tmp = 0; + + tmp = hspi->State; + if((tmp == HAL_SPI_STATE_READY) || (tmp == HAL_SPI_STATE_BUSY_RX)) + { + if((pTxData == NULL ) || (pRxData == NULL ) || (Size == 0)) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_SPI_DIRECTION_2LINES(hspi->Init.Direction)); + + /* Process Locked */ + __HAL_LOCK(hspi); + + /* Don't overwrite in case of HAL_SPI_STATE_BUSY_RX */ + if(hspi->State == HAL_SPI_STATE_READY) + { + hspi->State = HAL_SPI_STATE_BUSY_TX_RX; + } + + /* Configure communication */ + hspi->ErrorCode = HAL_SPI_ERROR_NONE; + + hspi->pRxBuffPtr = pRxData; + hspi->RxXferSize = Size; + hspi->RxXferCount = Size; + + hspi->pTxBuffPtr = pTxData; + hspi->TxXferSize = Size; + hspi->TxXferCount = Size; + + /*Init field not used in handle to zero */ + hspi->RxISR = 0; + hspi->TxISR = 0; + + /* Reset CRC Calculation */ + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED) + { + __HAL_SPI_RESET_CRC(hspi); + } + + /* Check if the SPI is already enabled */ + if((hspi->Instance->CR1 &SPI_CR1_SPE) != SPI_CR1_SPE) + { + /* Enable SPI peripheral */ + __HAL_SPI_ENABLE(hspi); + } + + /* Transmit and Receive data in 16 Bit mode */ + if(hspi->Init.DataSize == SPI_DATASIZE_16BIT) + { + hspi->Instance->DR = *((uint16_t*)hspi->pTxBuffPtr); + hspi->pTxBuffPtr+=2; + hspi->TxXferCount--; + + if(hspi->TxXferCount == 0) + { + /* Enable CRC Transmission */ + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED) + { + hspi->Instance->CR1 |= SPI_CR1_CRCNEXT; + } + + /* Wait until RXNE flag is set */ + if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_RXNE, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + *((uint16_t*)hspi->pRxBuffPtr) = hspi->Instance->DR; + hspi->pRxBuffPtr+=2; + hspi->RxXferCount--; + } + else + { + while(hspi->TxXferCount > 0) + { + /* Wait until TXE flag is set to send data */ + if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_TXE, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + hspi->Instance->DR = *((uint16_t*)hspi->pTxBuffPtr); + hspi->pTxBuffPtr+=2; + hspi->TxXferCount--; + + /* Enable CRC Transmission */ + if((hspi->TxXferCount == 0) && (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED)) + { + hspi->Instance->CR1 |= SPI_CR1_CRCNEXT; + } + + /* Wait until RXNE flag is set */ + if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_RXNE, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + *((uint16_t*)hspi->pRxBuffPtr) = hspi->Instance->DR; + hspi->pRxBuffPtr+=2; + hspi->RxXferCount--; + } + + /* Wait until RXNE flag is set */ + if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_RXNE, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + *((uint16_t*)hspi->pRxBuffPtr) = hspi->Instance->DR; + hspi->pRxBuffPtr+=2; + hspi->RxXferCount--; + } + } + /* Transmit and Receive data in 8 Bit mode */ + else + { + + hspi->Instance->DR = (*hspi->pTxBuffPtr++); + hspi->TxXferCount--; + + if(hspi->TxXferCount == 0) + { + /* Enable CRC Transmission */ + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED) + { + hspi->Instance->CR1 |= SPI_CR1_CRCNEXT; + } + + /* Wait until RXNE flag is set */ + if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_RXNE, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + (*hspi->pRxBuffPtr) = hspi->Instance->DR; + hspi->RxXferCount--; + } + else + { + while(hspi->TxXferCount > 0) + { + /* Wait until TXE flag is set to send data */ + if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_TXE, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + hspi->Instance->DR = (*hspi->pTxBuffPtr++); + hspi->TxXferCount--; + + /* Enable CRC Transmission */ + if((hspi->TxXferCount == 0) && (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED)) + { + hspi->Instance->CR1 |= SPI_CR1_CRCNEXT; + } + + /* Wait until RXNE flag is set */ + if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_RXNE, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + (*hspi->pRxBuffPtr++) = hspi->Instance->DR; + hspi->RxXferCount--; + } + + /* Wait until RXNE flag is set */ + if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_RXNE, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + (*hspi->pRxBuffPtr++) = hspi->Instance->DR; + hspi->RxXferCount--; + } + } + + /* Read CRC from DR to close CRC calculation process */ + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED) + { + /* Wait until RXNE flag is set */ + if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_RXNE, RESET, Timeout) != HAL_OK) + { + hspi->ErrorCode |= HAL_SPI_ERROR_CRC; + return HAL_TIMEOUT; + } + /* Read CRC */ + tmpreg = hspi->Instance->DR; + } + + /* Wait until Busy flag is reset before disabling SPI */ + if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_BSY, SET, Timeout) != HAL_OK) + { + hspi->ErrorCode |= HAL_SPI_ERROR_FLAG; + return HAL_TIMEOUT; + } + + hspi->State = HAL_SPI_STATE_READY; + + tmp = __HAL_SPI_GET_FLAG(hspi, SPI_FLAG_CRCERR); + /* Check if CRC error occurred */ + if((hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED) && (tmp != RESET)) + { + hspi->ErrorCode |= HAL_SPI_ERROR_CRC; + + /* Reset CRC Calculation */ + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED) + { + __HAL_SPI_RESET_CRC(hspi); + } + + /* Process Unlocked */ + __HAL_UNLOCK(hspi); + + return HAL_ERROR; + } + + /* Process Unlocked */ + __HAL_UNLOCK(hspi); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Transmit an amount of data in no-blocking mode with Interrupt + * @param hspi: pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @param pData: pointer to data buffer + * @param Size: amount of data to be sent + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SPI_Transmit_IT(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size) +{ + if(hspi->State == HAL_SPI_STATE_READY) + { + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_SPI_DIRECTION_2LINES_OR_1LINE(hspi->Init.Direction)); + + /* Process Locked */ + __HAL_LOCK(hspi); + + /* Configure communication */ + hspi->State = HAL_SPI_STATE_BUSY_TX; + hspi->ErrorCode = HAL_SPI_ERROR_NONE; + + hspi->TxISR = &SPI_TxISR; + hspi->pTxBuffPtr = pData; + hspi->TxXferSize = Size; + hspi->TxXferCount = Size; + + /*Init field not used in handle to zero */ + hspi->RxISR = 0; + hspi->RxXferSize = 0; + hspi->RxXferCount = 0; + + /* Configure communication direction : 1Line */ + if(hspi->Init.Direction == SPI_DIRECTION_1LINE) + { + __HAL_SPI_1LINE_TX(hspi); + } + + /* Reset CRC Calculation */ + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED) + { + __HAL_SPI_RESET_CRC(hspi); + } + + if (hspi->Init.Direction == SPI_DIRECTION_2LINES) + { + __HAL_SPI_ENABLE_IT(hspi, (SPI_IT_TXE)); + }else + { + /* Enable TXE and ERR interrupt */ + __HAL_SPI_ENABLE_IT(hspi, (SPI_IT_TXE | SPI_IT_ERR)); + } + /* Process Unlocked */ + __HAL_UNLOCK(hspi); + + /* Check if the SPI is already enabled */ + if((hspi->Instance->CR1 &SPI_CR1_SPE) != SPI_CR1_SPE) + { + /* Enable SPI peripheral */ + __HAL_SPI_ENABLE(hspi); + } + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive an amount of data in no-blocking mode with Interrupt + * @param hspi: pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @param pData: pointer to data buffer + * @param Size: amount of data to be sent + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SPI_Receive_IT(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size) +{ + if(hspi->State == HAL_SPI_STATE_READY) + { + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(hspi); + + /* Configure communication */ + hspi->State = HAL_SPI_STATE_BUSY_RX; + hspi->ErrorCode = HAL_SPI_ERROR_NONE; + + hspi->RxISR = &SPI_RxISR; + hspi->pRxBuffPtr = pData; + hspi->RxXferSize = Size; + hspi->RxXferCount = Size ; + + /*Init field not used in handle to zero */ + hspi->TxISR = 0; + hspi->TxXferSize = 0; + hspi->TxXferCount = 0; + + /* Configure communication direction : 1Line */ + if(hspi->Init.Direction == SPI_DIRECTION_1LINE) + { + __HAL_SPI_1LINE_RX(hspi); + } + else if((hspi->Init.Direction == SPI_DIRECTION_2LINES) && (hspi->Init.Mode == SPI_MODE_MASTER)) + { + /* Process Unlocked */ + __HAL_UNLOCK(hspi); + + /* Call transmit-receive function to send Dummy data on Tx line and generate clock on CLK line */ + return HAL_SPI_TransmitReceive_IT(hspi, pData, pData, Size); + } + + /* Reset CRC Calculation */ + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED) + { + __HAL_SPI_RESET_CRC(hspi); + } + + /* Enable TXE and ERR interrupt */ + __HAL_SPI_ENABLE_IT(hspi, (SPI_IT_RXNE | SPI_IT_ERR)); + + /* Process Unlocked */ + __HAL_UNLOCK(hspi); + + /* Note : The SPI must be enabled after unlocking current process + to avoid the risk of SPI interrupt handle execution before current + process unlock */ + + /* Check if the SPI is already enabled */ + if((hspi->Instance->CR1 &SPI_CR1_SPE) != SPI_CR1_SPE) + { + /* Enable SPI peripheral */ + __HAL_SPI_ENABLE(hspi); + } + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Transmit and Receive an amount of data in no-blocking mode with Interrupt + * @param hspi: pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @param pTxData: pointer to transmission data buffer + * @param pRxData: pointer to reception data buffer to be + * @param Size: amount of data to be sent + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SPI_TransmitReceive_IT(SPI_HandleTypeDef *hspi, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size) +{ + uint32_t tmp = 0; + + tmp = hspi->State; + if((tmp == HAL_SPI_STATE_READY) || (tmp == HAL_SPI_STATE_BUSY_RX)) + { + if((pTxData == NULL ) || (pRxData == NULL ) || (Size == 0)) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_SPI_DIRECTION_2LINES(hspi->Init.Direction)); + + /* Process locked */ + __HAL_LOCK(hspi); + + /* Don't overwrite in case of HAL_SPI_STATE_BUSY_RX */ + if(hspi->State == HAL_SPI_STATE_READY) + { + hspi->State = HAL_SPI_STATE_BUSY_TX_RX; + } + + /* Configure communication */ + hspi->ErrorCode = HAL_SPI_ERROR_NONE; + + hspi->TxISR = &SPI_TxISR; + hspi->pTxBuffPtr = pTxData; + hspi->TxXferSize = Size; + hspi->TxXferCount = Size; + + hspi->RxISR = &SPI_2LinesRxISR; + hspi->pRxBuffPtr = pRxData; + hspi->RxXferSize = Size; + hspi->RxXferCount = Size; + + /* Reset CRC Calculation */ + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED) + { + __HAL_SPI_RESET_CRC(hspi); + } + + /* Enable TXE, RXNE and ERR interrupt */ + __HAL_SPI_ENABLE_IT(hspi, (SPI_IT_TXE | SPI_IT_RXNE | SPI_IT_ERR)); + + /* Process Unlocked */ + __HAL_UNLOCK(hspi); + + /* Check if the SPI is already enabled */ + if((hspi->Instance->CR1 &SPI_CR1_SPE) != SPI_CR1_SPE) + { + /* Enable SPI peripheral */ + __HAL_SPI_ENABLE(hspi); + } + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Transmit an amount of data in no-blocking mode with DMA + * @param hspi: pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @param pData: pointer to data buffer + * @param Size: amount of data to be sent + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SPI_Transmit_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size) +{ + if(hspi->State == HAL_SPI_STATE_READY) + { + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_SPI_DIRECTION_2LINES_OR_1LINE(hspi->Init.Direction)); + + /* Process Locked */ + __HAL_LOCK(hspi); + + /* Configure communication */ + hspi->State = HAL_SPI_STATE_BUSY_TX; + hspi->ErrorCode = HAL_SPI_ERROR_NONE; + + hspi->pTxBuffPtr = pData; + hspi->TxXferSize = Size; + hspi->TxXferCount = Size; + + /*Init field not used in handle to zero */ + hspi->TxISR = 0; + hspi->RxISR = 0; + hspi->RxXferSize = 0; + hspi->RxXferCount = 0; + + /* Configure communication direction : 1Line */ + if(hspi->Init.Direction == SPI_DIRECTION_1LINE) + { + __HAL_SPI_1LINE_TX(hspi); + } + + /* Reset CRC Calculation */ + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED) + { + __HAL_SPI_RESET_CRC(hspi); + } + + /* Set the SPI TxDMA transfer complete callback */ + hspi->hdmatx->XferCpltCallback = SPI_DMATransmitCplt; + + /* Set the DMA error callback */ + hspi->hdmatx->XferErrorCallback = SPI_DMAError; + + /* Enable the Tx DMA Stream */ + HAL_DMA_Start_IT(hspi->hdmatx, (uint32_t)hspi->pTxBuffPtr, (uint32_t)&hspi->Instance->DR, hspi->TxXferCount); + + /* Enable Tx DMA Request */ + hspi->Instance->CR2 |= SPI_CR2_TXDMAEN; + + /* Process Unlocked */ + __HAL_UNLOCK(hspi); + + /* Check if the SPI is already enabled */ + if((hspi->Instance->CR1 &SPI_CR1_SPE) != SPI_CR1_SPE) + { + /* Enable SPI peripheral */ + __HAL_SPI_ENABLE(hspi); + } + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive an amount of data in no-blocking mode with DMA + * @param hspi: pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @param pData: pointer to data buffer + * @note When the CRC feature is enabled the pData Length must be Size + 1. + * @param Size: amount of data to be sent + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SPI_Receive_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size) +{ + if(hspi->State == HAL_SPI_STATE_READY) + { + if((pData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(hspi); + + /* Configure communication */ + hspi->State = HAL_SPI_STATE_BUSY_RX; + hspi->ErrorCode = HAL_SPI_ERROR_NONE; + + hspi->pRxBuffPtr = pData; + hspi->RxXferSize = Size; + hspi->RxXferCount = Size; + + /*Init field not used in handle to zero */ + hspi->RxISR = 0; + hspi->TxISR = 0; + hspi->TxXferSize = 0; + hspi->TxXferCount = 0; + + /* Configure communication direction : 1Line */ + if(hspi->Init.Direction == SPI_DIRECTION_1LINE) + { + __HAL_SPI_1LINE_RX(hspi); + } + else if((hspi->Init.Direction == SPI_DIRECTION_2LINES)&&(hspi->Init.Mode == SPI_MODE_MASTER)) + { + /* Process Unlocked */ + __HAL_UNLOCK(hspi); + + /* Call transmit-receive function to send Dummy data on Tx line and generate clock on CLK line */ + return HAL_SPI_TransmitReceive_DMA(hspi, pData, pData, Size); + } + + /* Reset CRC Calculation */ + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED) + { + __HAL_SPI_RESET_CRC(hspi); + } + + /* Set the SPI Rx DMA transfer complete callback */ + hspi->hdmarx->XferCpltCallback = SPI_DMAReceiveCplt; + + /* Set the DMA error callback */ + hspi->hdmarx->XferErrorCallback = SPI_DMAError; + + /* Enable the Rx DMA Stream */ + HAL_DMA_Start_IT(hspi->hdmarx, (uint32_t)&hspi->Instance->DR, (uint32_t)hspi->pRxBuffPtr, hspi->RxXferCount); + + /* Enable Rx DMA Request */ + hspi->Instance->CR2 |= SPI_CR2_RXDMAEN; + + /* Process Unlocked */ + __HAL_UNLOCK(hspi); + + /* Check if the SPI is already enabled */ + if((hspi->Instance->CR1 &SPI_CR1_SPE) != SPI_CR1_SPE) + { + /* Enable SPI peripheral */ + __HAL_SPI_ENABLE(hspi); + } + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Transmit and Receive an amount of data in no-blocking mode with DMA + * @param hspi: pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @param pTxData: pointer to transmission data buffer + * @param pRxData: pointer to reception data buffer + * @note When the CRC feature is enabled the pRxData Length must be Size + 1 + * @param Size: amount of data to be sent + * @retval HAL status + */ +HAL_StatusTypeDef HAL_SPI_TransmitReceive_DMA(SPI_HandleTypeDef *hspi, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size) +{ + uint32_t tmpstate = 0; + tmpstate = hspi->State; + if((tmpstate == HAL_SPI_STATE_READY) || (tmpstate == HAL_SPI_STATE_BUSY_RX)) + { + if((pTxData == NULL ) || (pRxData == NULL ) || (Size == 0)) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_SPI_DIRECTION_2LINES(hspi->Init.Direction)); + + /* Process locked */ + __HAL_LOCK(hspi); + + /* Don't overwrite in case of HAL_SPI_STATE_BUSY_RX */ + if(hspi->State == HAL_SPI_STATE_READY) + { + hspi->State = HAL_SPI_STATE_BUSY_TX_RX; + } + + /* Configure communication */ + hspi->ErrorCode = HAL_SPI_ERROR_NONE; + + hspi->pTxBuffPtr = (uint8_t*)pTxData; + hspi->TxXferSize = Size; + hspi->TxXferCount = Size; + + hspi->pRxBuffPtr = (uint8_t*)pRxData; + hspi->RxXferSize = Size; + hspi->RxXferCount = Size; + + /*Init field not used in handle to zero */ + hspi->RxISR = 0; + hspi->TxISR = 0; + + /* Reset CRC Calculation */ + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED) + { + __HAL_SPI_RESET_CRC(hspi); + } + + /* Check if we are in Rx only or in Rx/Tx Mode and configure the DMA transfer complete callback */ + if(hspi->State == HAL_SPI_STATE_BUSY_RX) + { + hspi->hdmarx->XferCpltCallback = SPI_DMAReceiveCplt; + } + else + { + hspi->hdmarx->XferCpltCallback = SPI_DMATransmitReceiveCplt; + } + + /* Set the DMA error callback */ + hspi->hdmarx->XferErrorCallback = SPI_DMAError; + + /* Enable the Rx DMA Stream */ + HAL_DMA_Start_IT(hspi->hdmarx, (uint32_t)&hspi->Instance->DR, (uint32_t)hspi->pRxBuffPtr, hspi->RxXferCount); + + /* Enable Rx DMA Request */ + hspi->Instance->CR2 |= SPI_CR2_RXDMAEN; + + /* Set the SPI Tx DMA transfer complete callback as NULL because the communication closing + is performed in DMA reception complete callback */ + hspi->hdmatx->XferCpltCallback = NULL; + + /* Set the DMA error callback */ + hspi->hdmatx->XferErrorCallback = SPI_DMAError; + + /* Enable the Tx DMA Stream */ + HAL_DMA_Start_IT(hspi->hdmatx, (uint32_t)hspi->pTxBuffPtr, (uint32_t)&hspi->Instance->DR, hspi->TxXferCount); + + /* Enable Tx DMA Request */ + hspi->Instance->CR2 |= SPI_CR2_TXDMAEN; + + /* Process Unlocked */ + __HAL_UNLOCK(hspi); + + /* Check if the SPI is already enabled */ + if((hspi->Instance->CR1 &SPI_CR1_SPE) != SPI_CR1_SPE) + { + /* Enable SPI peripheral */ + __HAL_SPI_ENABLE(hspi); + } + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief This function handles SPI interrupt request. + * @param hspi: pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @retval HAL status + */ +void HAL_SPI_IRQHandler(SPI_HandleTypeDef *hspi) +{ + uint32_t tmp1 = 0, tmp2 = 0, tmp3 = 0; + + tmp1 = __HAL_SPI_GET_FLAG(hspi, SPI_FLAG_RXNE); + tmp2 = __HAL_SPI_GET_IT_SOURCE(hspi, SPI_IT_RXNE); + tmp3 = __HAL_SPI_GET_FLAG(hspi, SPI_FLAG_OVR); + /* SPI in mode Receiver and Overrun not occurred ---------------------------*/ + if((tmp1 != RESET) && (tmp2 != RESET) && (tmp3 == RESET)) + { + hspi->RxISR(hspi); + return; + } + + tmp1 = __HAL_SPI_GET_FLAG(hspi, SPI_FLAG_TXE); + tmp2 = __HAL_SPI_GET_IT_SOURCE(hspi, SPI_IT_TXE); + /* SPI in mode Tramitter ---------------------------------------------------*/ + if((tmp1 != RESET) && (tmp2 != RESET)) + { + hspi->TxISR(hspi); + return; + } + + if(__HAL_SPI_GET_IT_SOURCE(hspi, SPI_IT_ERR) != RESET) + { + /* SPI CRC error interrupt occured ---------------------------------------*/ + if(__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_CRCERR) != RESET) + { + hspi->ErrorCode |= HAL_SPI_ERROR_CRC; + __HAL_SPI_CLEAR_CRCERRFLAG(hspi); + } + /* SPI Mode Fault error interrupt occured --------------------------------*/ + if(__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_MODF) != RESET) + { + hspi->ErrorCode |= HAL_SPI_ERROR_MODF; + __HAL_SPI_CLEAR_MODFFLAG(hspi); + } + + /* SPI Overrun error interrupt occured -----------------------------------*/ + if(__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_OVR) != RESET) + { + if(hspi->State != HAL_SPI_STATE_BUSY_TX) + { + hspi->ErrorCode |= HAL_SPI_ERROR_OVR; + __HAL_SPI_CLEAR_OVRFLAG(hspi); + } + } + + /* SPI Frame error interrupt occured -------------------------------------*/ + if(__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_FRE) != RESET) + { + hspi->ErrorCode |= HAL_SPI_ERROR_FRE; + __HAL_SPI_CLEAR_FREFLAG(hspi); + } + + /* Call the Error call Back in case of Errors */ + if(hspi->ErrorCode!=HAL_SPI_ERROR_NONE) + { + hspi->State = HAL_SPI_STATE_READY; + HAL_SPI_ErrorCallback(hspi); + } + } +} + +/** + * @brief Tx Transfer completed callbacks + * @param hspi: pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @retval None + */ +__weak void HAL_SPI_TxCpltCallback(SPI_HandleTypeDef *hspi) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_SPI_TxCpltCallback could be implenetd in the user file + */ +} + +/** + * @brief Rx Transfer completed callbacks + * @param hspi: pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @retval None + */ +__weak void HAL_SPI_RxCpltCallback(SPI_HandleTypeDef *hspi) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_SPI_RxCpltCallback() could be implenetd in the user file + */ +} + +/** + * @brief Tx and Rx Transfer completed callbacks + * @param hspi: pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @retval None + */ +__weak void HAL_SPI_TxRxCpltCallback(SPI_HandleTypeDef *hspi) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_SPI_TxRxCpltCallback() could be implenetd in the user file + */ +} + +/** + * @brief SPI error callbacks + * @param hspi: pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @retval None + */ + __weak void HAL_SPI_ErrorCallback(SPI_HandleTypeDef *hspi) +{ + /* NOTE : - This function Should not be modified, when the callback is needed, + the HAL_SPI_ErrorCallback() could be implenetd in the user file. + - The ErrorCode parameter in the hspi handle is updated by the SPI processes + and user can use HAL_SPI_GetError() API to check the latest error occured. + */ +} + +/** + * @} + */ + +/** @defgroup SPI_Group3 Peripheral State and Errors functions + * @brief SPI control functions + * +@verbatim + =============================================================================== + ##### Peripheral State and Errors functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to control the SPI. + (+) HAL_SPI_GetState() API can be helpful to check in run-time the state of the SPI peripheral + (+) HAL_SPI_GetError() check in run-time Errors occurring during communication +@endverbatim + * @{ + */ + +/** + * @brief Return the SPI state + * @param hspi : SPI handle + * @retval SPI state + */ +HAL_SPI_StateTypeDef HAL_SPI_GetState(SPI_HandleTypeDef *hspi) +{ + return hspi->State; +} + +/** + * @brief Return the SPI error code + * @param hspi : SPI handle + * @retval SPI Error Code + */ +HAL_SPI_ErrorTypeDef HAL_SPI_GetError(SPI_HandleTypeDef *hspi) +{ + return hspi->ErrorCode; +} + +/** + * @} + */ + + /** + * @brief Interrupt Handler to close Tx transfer + * @param hspi: pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @retval void + */ +static void SPI_TxCloseIRQHandler(SPI_HandleTypeDef *hspi) +{ + /* Wait until TXE flag is set to send data */ + if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_TXE, RESET, SPI_TIMEOUT_VALUE) != HAL_OK) + { + hspi->ErrorCode |= HAL_SPI_ERROR_FLAG; + } + + /* Disable TXE interrupt */ + __HAL_SPI_DISABLE_IT(hspi, (uint32_t)SPI_IT_TXE); + + /* Disable ERR interrupt if Receive process is finished */ + if(__HAL_SPI_GET_IT_SOURCE(hspi, SPI_IT_RXNE) == RESET) + { + __HAL_SPI_DISABLE_IT(hspi, (uint32_t)SPI_IT_ERR); + + /* Wait until Busy flag is reset before disabling SPI */ + if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_BSY, SET, SPI_TIMEOUT_VALUE) != HAL_OK) + { + hspi->ErrorCode |= HAL_SPI_ERROR_FLAG; + } + + /* Clear OVERUN flag in 2 Lines communication mode because received is not read */ + if(hspi->Init.Direction == SPI_DIRECTION_2LINES) + { + __HAL_SPI_CLEAR_OVRFLAG(hspi); + } + + /* Check if Errors has been detected during transfer */ + if(hspi->ErrorCode == HAL_SPI_ERROR_NONE) + { + /* Check if we are in Tx or in Rx/Tx Mode */ + if(hspi->State == HAL_SPI_STATE_BUSY_TX_RX) + { + /* Set state to READY before run the Callback Complete */ + hspi->State = HAL_SPI_STATE_READY; + HAL_SPI_TxRxCpltCallback(hspi); + } + else + { + /* Set state to READY before run the Callback Complete */ + hspi->State = HAL_SPI_STATE_READY; + HAL_SPI_TxCpltCallback(hspi); + } + } + else + { + /* Set state to READY before run the Callback Complete */ + hspi->State = HAL_SPI_STATE_READY; + /* Call Error call back in case of Error */ + HAL_SPI_ErrorCallback(hspi); + } + } +} + +/** + * @brief Interrupt Handler to transmit amount of data in no-blocking mode + * @param hspi: pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @retval void + */ +static void SPI_TxISR(SPI_HandleTypeDef *hspi) +{ + /* Transmit data in 8 Bit mode */ + if(hspi->Init.DataSize == SPI_DATASIZE_8BIT) + { + hspi->Instance->DR = (*hspi->pTxBuffPtr++); + } + /* Transmit data in 16 Bit mode */ + else + { + hspi->Instance->DR = *((uint16_t*)hspi->pTxBuffPtr); + hspi->pTxBuffPtr+=2; + } + hspi->TxXferCount--; + + if(hspi->TxXferCount == 0) + { + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED) + { + /* calculate and transfer CRC on Tx line */ + hspi->Instance->CR1 |= SPI_CR1_CRCNEXT; + } + SPI_TxCloseIRQHandler(hspi); + } +} + +/** + * @brief Interrupt Handler to close Rx transfer + * @param hspi: pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @retval void + */ +static void SPI_RxCloseIRQHandler(SPI_HandleTypeDef *hspi) +{ + __IO uint16_t tmpreg; + + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED) + { + /* Wait until RXNE flag is set to send data */ + if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_RXNE, RESET, SPI_TIMEOUT_VALUE) != HAL_OK) + { + hspi->ErrorCode |= HAL_SPI_ERROR_FLAG; + } + + /* Read CRC to reset RXNE flag */ + tmpreg = hspi->Instance->DR; + + /* Wait until RXNE flag is set to send data */ + if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_RXNE, SET, SPI_TIMEOUT_VALUE) != HAL_OK) + { + hspi->ErrorCode |= HAL_SPI_ERROR_FLAG; + } + + /* Check if CRC error occurred */ + if(__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_CRCERR) != RESET) + { + hspi->ErrorCode |= HAL_SPI_ERROR_CRC; + + /* Reset CRC Calculation */ + __HAL_SPI_RESET_CRC(hspi); + } + } + + /* Disable RXNE and ERR interrupt */ + __HAL_SPI_DISABLE_IT(hspi, (uint32_t)(SPI_IT_RXNE)); + + /* if Transmit process is finished */ + if(__HAL_SPI_GET_IT_SOURCE(hspi, SPI_IT_TXE) == RESET) + { + /* Disable ERR interrupt */ + __HAL_SPI_DISABLE_IT(hspi, (uint32_t)(SPI_IT_ERR)); + + if((hspi->Init.Mode == SPI_MODE_MASTER)&&((hspi->Init.Direction == SPI_DIRECTION_1LINE)||(hspi->Init.Direction == SPI_DIRECTION_2LINES_RXONLY))) + { + /* Disable SPI peripheral */ + __HAL_SPI_DISABLE(hspi); + } + + /* Check if Errors has been detected during transfer */ + if(hspi->ErrorCode == HAL_SPI_ERROR_NONE) + { + /* Check if we are in Rx or in Rx/Tx Mode */ + if(hspi->State == HAL_SPI_STATE_BUSY_TX_RX) + { + /* Set state to READY before run the Callback Complete */ + hspi->State = HAL_SPI_STATE_READY; + HAL_SPI_TxRxCpltCallback(hspi); + }else + { + /* Set state to READY before run the Callback Complete */ + hspi->State = HAL_SPI_STATE_READY; + HAL_SPI_RxCpltCallback(hspi); + } + } + else + { + /* Set state to READY before run the Callback Complete */ + hspi->State = HAL_SPI_STATE_READY; + /* Call Error call back in case of Error */ + HAL_SPI_ErrorCallback(hspi); + } + } +} + +/** + * @brief Interrupt Handler to receive amount of data in 2Lines mode + * @param hspi: pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @retval void + */ +static void SPI_2LinesRxISR(SPI_HandleTypeDef *hspi) +{ + /* Receive data in 8 Bit mode */ + if(hspi->Init.DataSize == SPI_DATASIZE_8BIT) + { + (*hspi->pRxBuffPtr++) = hspi->Instance->DR; + } + /* Receive data in 16 Bit mode */ + else + { + *((uint16_t*)hspi->pRxBuffPtr) = hspi->Instance->DR; + hspi->pRxBuffPtr+=2; + } + hspi->RxXferCount--; + + if(hspi->RxXferCount==0) + { + SPI_RxCloseIRQHandler(hspi); + } +} + +/** + * @brief Interrupt Handler to receive amount of data in no-blocking mode + * @param hspi: pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @retval void + */ +static void SPI_RxISR(SPI_HandleTypeDef *hspi) +{ + /* Receive data in 8 Bit mode */ + if(hspi->Init.DataSize == SPI_DATASIZE_8BIT) + { + (*hspi->pRxBuffPtr++) = hspi->Instance->DR; + } + /* Receive data in 16 Bit mode */ + else + { + *((uint16_t*)hspi->pRxBuffPtr) = hspi->Instance->DR; + hspi->pRxBuffPtr+=2; + } + hspi->RxXferCount--; + + /* Enable CRC Transmission */ + if((hspi->RxXferCount == 1) && (hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED)) + { + /* Set CRC Next to calculate CRC on Rx side */ + hspi->Instance->CR1 |= SPI_CR1_CRCNEXT; + } + + if(hspi->RxXferCount == 0) + { + SPI_RxCloseIRQHandler(hspi); + } +} + +/** + * @brief DMA SPI transmit process complete callback + * @param hdma: pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void SPI_DMATransmitCplt(DMA_HandleTypeDef *hdma) +{ + SPI_HandleTypeDef* hspi = ( SPI_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + + /* Wait until TXE flag is set to send data */ + if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_TXE, RESET, SPI_TIMEOUT_VALUE) != HAL_OK) + { + hspi->ErrorCode |= HAL_SPI_ERROR_FLAG; + } + + /* Disable Tx DMA Request */ + hspi->Instance->CR2 &= (uint32_t)~((uint32_t)SPI_CR2_TXDMAEN); + + /* Wait until Busy flag is reset before disabling SPI */ + if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_BSY, SET, SPI_TIMEOUT_VALUE) != HAL_OK) + { + hspi->ErrorCode |= HAL_SPI_ERROR_FLAG; + } + + hspi->TxXferCount = 0; + + hspi->State = HAL_SPI_STATE_READY; + + /* Clear OVERUN flag in 2 Lines communication mode because received is not read */ + if(hspi->Init.Direction == SPI_DIRECTION_2LINES) + { + __HAL_SPI_CLEAR_OVRFLAG(hspi); + } + + /* Check if Errors has been detected during transfer */ + if(hspi->ErrorCode != HAL_SPI_ERROR_NONE) + { + HAL_SPI_ErrorCallback(hspi); + } + else + { + HAL_SPI_TxCpltCallback(hspi); + } +} + +/** + * @brief DMA SPI receive process complete callback + * @param hdma: pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void SPI_DMAReceiveCplt(DMA_HandleTypeDef *hdma) +{ + __IO uint16_t tmpreg; + + SPI_HandleTypeDef* hspi = ( SPI_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + + if((hspi->Init.Mode == SPI_MODE_MASTER)&&((hspi->Init.Direction == SPI_DIRECTION_1LINE)||(hspi->Init.Direction == SPI_DIRECTION_2LINES_RXONLY))) + { + /* Disable SPI peripheral */ + __HAL_SPI_DISABLE(hspi); + } + + /* Disable Rx DMA Request */ + hspi->Instance->CR2 &= (uint32_t)~((uint32_t)SPI_CR2_RXDMAEN); + + /* Reset CRC Calculation */ + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED) + { + /* Wait until RXNE flag is set to send data */ + if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_RXNE, RESET, SPI_TIMEOUT_VALUE) != HAL_OK) + { + hspi->ErrorCode |= HAL_SPI_ERROR_FLAG; + } + + /* Read CRC */ + tmpreg = hspi->Instance->DR; + + /* Wait until RXNE flag is set to send data */ + if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_RXNE, SET, SPI_TIMEOUT_VALUE) != HAL_OK) + { + hspi->ErrorCode |= HAL_SPI_ERROR_FLAG; + } + } + + hspi->RxXferCount = 0; + hspi->State = HAL_SPI_STATE_READY; + + /* Check if CRC error occurred */ + if(__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_CRCERR) != RESET) + { + hspi->ErrorCode |= HAL_SPI_ERROR_CRC; + __HAL_SPI_CLEAR_CRCERRFLAG(hspi); + } + + /* Check if Errors has been detected during transfer */ + if(hspi->ErrorCode != HAL_SPI_ERROR_NONE) + { + HAL_SPI_ErrorCallback(hspi); + } + else + { + HAL_SPI_RxCpltCallback(hspi); + } +} + +/** + * @brief DMA SPI transmit receive process complete callback + * @param hdma: pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void SPI_DMATransmitReceiveCplt(DMA_HandleTypeDef *hdma) +{ + __IO uint16_t tmpreg; + + SPI_HandleTypeDef* hspi = ( SPI_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + + /* Reset CRC Calculation */ + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED) + { + /* Check if CRC is done on going (RXNE flag set) */ + if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_RXNE, SET, SPI_TIMEOUT_VALUE) == HAL_OK) + { + /* Wait until RXNE flag is set to send data */ + if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_RXNE, RESET, SPI_TIMEOUT_VALUE) != HAL_OK) + { + hspi->ErrorCode |= HAL_SPI_ERROR_FLAG; + } + } + /* Read CRC */ + tmpreg = hspi->Instance->DR; + } + + /* Wait until TXE flag is set to send data */ + if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_TXE, RESET, SPI_TIMEOUT_VALUE) != HAL_OK) + { + hspi->ErrorCode |= HAL_SPI_ERROR_FLAG; + } + /* Disable Tx DMA Request */ + hspi->Instance->CR2 &= (uint32_t)~((uint32_t)SPI_CR2_TXDMAEN); + + /* Wait until Busy flag is reset before disabling SPI */ + if(SPI_WaitOnFlagUntilTimeout(hspi, SPI_FLAG_BSY, SET, SPI_TIMEOUT_VALUE) != HAL_OK) + { + hspi->ErrorCode |= HAL_SPI_ERROR_FLAG; + } + + /* Disable Rx DMA Request */ + hspi->Instance->CR2 &= (uint32_t)~((uint32_t)SPI_CR2_RXDMAEN); + + hspi->TxXferCount = 0; + hspi->RxXferCount = 0; + + hspi->State = HAL_SPI_STATE_READY; + + /* Check if CRC error occurred */ + if(__HAL_SPI_GET_FLAG(hspi, SPI_FLAG_CRCERR) != RESET) + { + hspi->ErrorCode |= HAL_SPI_ERROR_CRC; + __HAL_SPI_CLEAR_CRCERRFLAG(hspi); + } + + /* Check if Errors has been detected during transfer */ + if(hspi->ErrorCode != HAL_SPI_ERROR_NONE) + { + HAL_SPI_ErrorCallback(hspi); + } + else + { + HAL_SPI_TxRxCpltCallback(hspi); + } +} + +/** + * @brief DMA SPI communication error callback + * @param hdma: pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +static void SPI_DMAError(DMA_HandleTypeDef *hdma) +{ + SPI_HandleTypeDef* hspi = (SPI_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + hspi->TxXferCount = 0; + hspi->RxXferCount = 0; + hspi->State= HAL_SPI_STATE_READY; + hspi->ErrorCode |= HAL_SPI_ERROR_DMA; + HAL_SPI_ErrorCallback(hspi); +} + +/** + * @brief This function handles SPI Communication Timeout. + * @param hspi: pointer to a SPI_HandleTypeDef structure that contains + * the configuration information for SPI module. + * @retval HAL status + */ +static HAL_StatusTypeDef SPI_WaitOnFlagUntilTimeout(SPI_HandleTypeDef *hspi, uint32_t Flag, FlagStatus Status, uint32_t Timeout) +{ + uint32_t tickstart = 0x00; + tickstart = HAL_GetTick(); + + /* Wait until flag is set */ + if(Status == RESET) + { + while(__HAL_SPI_GET_FLAG(hspi, Flag) == RESET) + { + /* Check for the Timeout */ + if(Timeout != HAL_MAX_DELAY) + { + if((HAL_GetTick() - tickstart ) > Timeout) + { + /* Disable the SPI and reset the CRC: the CRC value should be cleared + on both master and slave sides in order to resynchronize the master + and slave for their respective CRC calculation */ + + /* Disable TXE, RXNE and ERR interrupts for the interrupt process */ + __HAL_SPI_DISABLE_IT(hspi, (uint32_t)(SPI_IT_TXE | SPI_IT_RXNE | SPI_IT_ERR)); + + /* Disable SPI peripheral */ + __HAL_SPI_DISABLE(hspi); + + /* Reset CRC Calculation */ + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED) + { + __HAL_SPI_RESET_CRC(hspi); + } + + hspi->State= HAL_SPI_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hspi); + + return HAL_TIMEOUT; + } + } + } + } + else + { + while(__HAL_SPI_GET_FLAG(hspi, Flag) != RESET) + { + if(Timeout != HAL_MAX_DELAY) + { + if((HAL_GetTick() - tickstart ) > Timeout) + { + /* Disable the SPI and reset the CRC: the CRC value should be cleared + on both master and slave sides in order to resynchronize the master + and slave for their respective CRC calculation */ + + /* Disable TXE, RXNE and ERR interrupts for the interrupt process */ + __HAL_SPI_DISABLE_IT(hspi, (uint32_t)(SPI_IT_TXE | SPI_IT_RXNE | SPI_IT_ERR)); + + /* Disable SPI peripheral */ + __HAL_SPI_DISABLE(hspi); + + /* Reset CRC Calculation */ + if(hspi->Init.CRCCalculation == SPI_CRCCALCULATION_ENABLED) + { + __HAL_SPI_RESET_CRC(hspi); + } + + hspi->State= HAL_SPI_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hspi); + + return HAL_TIMEOUT; + } + } + } + } + return HAL_OK; +} + + +/** + * @} + */ + +#endif /* HAL_SPI_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_spi.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_spi.h new file mode 100644 index 0000000000..c7b84e4523 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_spi.h @@ -0,0 +1,481 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_spi.h + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief Header file of SPI HAL module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32L0xx_HAL_SPI_H +#define __STM32L0xx_HAL_SPI_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal_def.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @addtogroup SPI + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ + +/** + * @brief SPI Configuration Structure definition + */ +typedef struct +{ + uint32_t Mode; /*!< Specifies the SPI operating mode. + This parameter can be a value of @ref SPI_mode */ + + uint32_t Direction; /*!< Specifies the SPI Directional mode state. + This parameter can be a value of @ref SPI_Direction_mode */ + + uint32_t DataSize; /*!< Specifies the SPI data size. + This parameter can be a value of @ref SPI_data_size */ + + uint32_t CLKPolarity; /*!< Specifies the serial clock steady state. + This parameter can be a value of @ref SPI_Clock_Polarity */ + + uint32_t CLKPhase; /*!< Specifies the clock active edge for the bit capture. + This parameter can be a value of @ref SPI_Clock_Phase */ + + uint32_t NSS; /*!< Specifies whether the NSS signal is managed by + hardware (NSS pin) or by software using the SSI bit. + This parameter can be a value of @ref SPI_Slave_Select_management */ + + uint32_t BaudRatePrescaler; /*!< Specifies the Baud Rate prescaler value which will be + used to configure the transmit and receive SCK clock. + This parameter can be a value of @ref SPI_BaudRate_Prescaler + @note The communication clock is derived from the master + clock. The slave clock does not need to be set */ + + uint32_t FirstBit; /*!< Specifies whether data transfers start from MSB or LSB bit. + This parameter can be a value of @ref SPI_MSB_LSB_transmission */ + + uint32_t TIMode; /*!< Specifies if the TI mode is enabled or not. + This parameter can be a value of @ref SPI_TI_mode */ + + uint32_t CRCCalculation; /*!< Specifies if the CRC calculation is enabled or not. + This parameter can be a value of @ref SPI_CRC_Calculation */ + + uint32_t CRCPolynomial; /*!< Specifies the polynomial used for the CRC calculation. + This parameter must be a number between Min_Data = 0 and Max_Data = 65535 */ + +}SPI_InitTypeDef; + +/** + * @brief HAL SPI State structure definition + */ +typedef enum +{ + HAL_SPI_STATE_RESET = 0x00, /*!< SPI not yet initialized or disabled */ + HAL_SPI_STATE_READY = 0x01, /*!< SPI initialized and ready for use */ + HAL_SPI_STATE_BUSY = 0x02, /*!< SPI process is ongoing */ + HAL_SPI_STATE_BUSY_TX = 0x12, /*!< Data Transmission process is ongoing */ + HAL_SPI_STATE_BUSY_RX = 0x22, /*!< Data Reception process is ongoing */ + HAL_SPI_STATE_BUSY_TX_RX = 0x32, /*!< Data Transmission and Reception process is ongoing */ + HAL_SPI_STATE_ERROR = 0x03 /*!< SPI error state */ + +}HAL_SPI_StateTypeDef; + +/** + * @brief HAL SPI Error Code structure definition + */ +typedef enum +{ + HAL_SPI_ERROR_NONE = 0x00, /*!< No error */ + HAL_SPI_ERROR_MODF = 0x01, /*!< MODF error */ + HAL_SPI_ERROR_CRC = 0x02, /*!< CRC error */ + HAL_SPI_ERROR_OVR = 0x04, /*!< OVR error */ + HAL_SPI_ERROR_FRE = 0x08, /*!< FRE error */ + HAL_SPI_ERROR_DMA = 0x10, /*!< DMA transfer error */ + HAL_SPI_ERROR_FLAG = 0x20 /*!< Flag: RXNE,TXE, BSY */ + +}HAL_SPI_ErrorTypeDef; + +/** + * @brief SPI handle Structure definition + */ +typedef struct __SPI_HandleTypeDef +{ + SPI_TypeDef *Instance; /* SPI registers base address */ + + SPI_InitTypeDef Init; /* SPI communication parameters */ + + uint8_t *pTxBuffPtr; /* Pointer to SPI Tx transfer Buffer */ + + uint16_t TxXferSize; /* SPI Tx transfer size */ + + uint16_t TxXferCount; /* SPI Tx Transfer Counter */ + + uint8_t *pRxBuffPtr; /* Pointer to SPI Rx transfer Buffer */ + + uint16_t RxXferSize; /* SPI Rx transfer size */ + + uint16_t RxXferCount; /* SPI Rx Transfer Counter */ + + DMA_HandleTypeDef *hdmatx; /* SPI Tx DMA handle parameters */ + + DMA_HandleTypeDef *hdmarx; /* SPI Rx DMA handle parameters */ + + void (*RxISR)(struct __SPI_HandleTypeDef * hspi); /* function pointer on Rx ISR */ + + void (*TxISR)(struct __SPI_HandleTypeDef * hspi); /* function pointer on Tx ISR */ + + HAL_LockTypeDef Lock; /* SPI locking object */ + + __IO HAL_SPI_StateTypeDef State; /* SPI communication state */ + + __IO HAL_SPI_ErrorTypeDef ErrorCode; /* SPI Error code */ + +}SPI_HandleTypeDef; + +/* Exported constants --------------------------------------------------------*/ + +/** @defgroup SPI_Exported_Constants + * @{ + */ + +/** @defgroup SPI_mode + * @{ + */ +#define SPI_MODE_SLAVE ((uint32_t)0x00000000) +#define SPI_MODE_MASTER (SPI_CR1_MSTR | SPI_CR1_SSI) + +#define IS_SPI_MODE(MODE) (((MODE) == SPI_MODE_SLAVE) || \ + ((MODE) == SPI_MODE_MASTER)) +/** + * @} + */ + +/** @defgroup SPI_Direction_mode + * @{ + */ +#define SPI_DIRECTION_2LINES ((uint32_t)0x00000000) +#define SPI_DIRECTION_2LINES_RXONLY SPI_CR1_RXONLY +#define SPI_DIRECTION_1LINE SPI_CR1_BIDIMODE + +#define IS_SPI_DIRECTION_MODE(MODE) (((MODE) == SPI_DIRECTION_2LINES) || \ + ((MODE) == SPI_DIRECTION_2LINES_RXONLY) || \ + ((MODE) == SPI_DIRECTION_1LINE)) + +#define IS_SPI_DIRECTION_2LINES_OR_1LINE(MODE) (((MODE) == SPI_DIRECTION_2LINES) || \ + ((MODE) == SPI_DIRECTION_1LINE)) + +#define IS_SPI_DIRECTION_2LINES(MODE) ((MODE) == SPI_DIRECTION_2LINES) + +/** + * @} + */ + +/** @defgroup SPI_data_size + * @{ + */ +#define SPI_DATASIZE_8BIT ((uint32_t)0x00000000) +#define SPI_DATASIZE_16BIT SPI_CR1_DFF + +#define IS_SPI_DATASIZE(DATASIZE) (((DATASIZE) == SPI_DATASIZE_16BIT) || \ + ((DATASIZE) == SPI_DATASIZE_8BIT)) +/** + * @} + */ + +/** @defgroup SPI_Clock_Polarity + * @{ + */ +#define SPI_POLARITY_LOW ((uint32_t)0x00000000) +#define SPI_POLARITY_HIGH SPI_CR1_CPOL + +#define IS_SPI_CPOL(CPOL) (((CPOL) == SPI_POLARITY_LOW) || \ + ((CPOL) == SPI_POLARITY_HIGH)) +/** + * @} + */ + +/** @defgroup SPI_Clock_Phase + * @{ + */ +#define SPI_PHASE_1EDGE ((uint32_t)0x00000000) +#define SPI_PHASE_2EDGE SPI_CR1_CPHA + +#define IS_SPI_CPHA(CPHA) (((CPHA) == SPI_PHASE_1EDGE) || \ + ((CPHA) == SPI_PHASE_2EDGE)) +/** + * @} + */ + +/** @defgroup SPI_Slave_Select_management + * @{ + */ +#define SPI_NSS_SOFT SPI_CR1_SSM +#define SPI_NSS_HARD_INPUT ((uint32_t)0x00000000) +#define SPI_NSS_HARD_OUTPUT ((uint32_t)0x00040000) + +#define IS_SPI_NSS(NSS) (((NSS) == SPI_NSS_SOFT) || \ + ((NSS) == SPI_NSS_HARD_INPUT) || \ + ((NSS) == SPI_NSS_HARD_OUTPUT)) +/** + * @} + */ + +/** @defgroup SPI_BaudRate_Prescaler + * @{ + */ +#define SPI_BAUDRATEPRESCALER_2 ((uint32_t)0x00000000) +#define SPI_BAUDRATEPRESCALER_4 ((uint32_t)0x00000008) +#define SPI_BAUDRATEPRESCALER_8 ((uint32_t)0x00000010) +#define SPI_BAUDRATEPRESCALER_16 ((uint32_t)0x00000018) +#define SPI_BAUDRATEPRESCALER_32 ((uint32_t)0x00000020) +#define SPI_BAUDRATEPRESCALER_64 ((uint32_t)0x00000028) +#define SPI_BAUDRATEPRESCALER_128 ((uint32_t)0x00000030) +#define SPI_BAUDRATEPRESCALER_256 ((uint32_t)0x00000038) + +#define IS_SPI_BAUDRATE_PRESCALER(PRESCALER) (((PRESCALER) == SPI_BAUDRATEPRESCALER_2) || \ + ((PRESCALER) == SPI_BAUDRATEPRESCALER_4) || \ + ((PRESCALER) == SPI_BAUDRATEPRESCALER_8) || \ + ((PRESCALER) == SPI_BAUDRATEPRESCALER_16) || \ + ((PRESCALER) == SPI_BAUDRATEPRESCALER_32) || \ + ((PRESCALER) == SPI_BAUDRATEPRESCALER_64) || \ + ((PRESCALER) == SPI_BAUDRATEPRESCALER_128) || \ + ((PRESCALER) == SPI_BAUDRATEPRESCALER_256)) +/** + * @} + */ + +/** @defgroup SPI_MSB_LSB_transmission + * @{ + */ +#define SPI_FIRSTBIT_MSB ((uint32_t)0x00000000) +#define SPI_FIRSTBIT_LSB SPI_CR1_LSBFIRST + +#define IS_SPI_FIRST_BIT(BIT) (((BIT) == SPI_FIRSTBIT_MSB) || \ + ((BIT) == SPI_FIRSTBIT_LSB)) +/** + * @} + */ + +/** @defgroup SPI_TI_mode + * @{ + */ +#define SPI_TIMODE_DISABLED ((uint32_t)0x00000000) +#define SPI_TIMODE_ENABLED SPI_CR2_FRF + +#define IS_SPI_TIMODE(MODE) (((MODE) == SPI_TIMODE_DISABLED) || \ + ((MODE) == SPI_TIMODE_ENABLED)) +/** + * @} + */ + +/** @defgroup SPI_CRC_Calculation + * @{ + */ +#define SPI_CRCCALCULATION_DISABLED ((uint32_t)0x00000000) +#define SPI_CRCCALCULATION_ENABLED SPI_CR1_CRCEN + +#define IS_SPI_CRC_CALCULATION(CALCULATION) (((CALCULATION) == SPI_CRCCALCULATION_DISABLED) || \ + ((CALCULATION) == SPI_CRCCALCULATION_ENABLED)) +/** + * @} + */ + +/** @defgroup SPI_Interrupt_configuration_definition + * @{ + */ +#define SPI_IT_TXE SPI_CR2_TXEIE +#define SPI_IT_RXNE SPI_CR2_RXNEIE +#define SPI_IT_ERR SPI_CR2_ERRIE +/** + * @} + */ + +/** @defgroup SPI_Flag_definition + * @{ + */ +#define SPI_FLAG_RXNE SPI_SR_RXNE +#define SPI_FLAG_TXE SPI_SR_TXE +#define SPI_FLAG_CRCERR SPI_SR_CRCERR +#define SPI_FLAG_MODF SPI_SR_MODF +#define SPI_FLAG_OVR SPI_SR_OVR +#define SPI_FLAG_BSY SPI_SR_BSY +#define SPI_FLAG_FRE SPI_SR_FRE + +/** + * @} + */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ + +/** @brief Reset SPI handle state + * @param __HANDLE__: specifies the SPI handle. + * This parameter can be SPIx where x: 1, 2, or 3 to select the SPI peripheral. + * @retval None + */ +#define __HAL_SPI_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_SPI_STATE_RESET) + +/** @brief Enable or disable the specified SPI interrupts. + * @param __HANDLE__: specifies the SPI handle. + * This parameter can be SPIx where x: 1, 2, or 3 to select the SPI peripheral. + * @param __INTERRUPT__: specifies the interrupt source to enable or disable. + * This parameter can be one of the following values: + * @arg SPI_IT_TXE: Tx buffer empty interrupt enable + * @arg SPI_IT_RXNE: RX buffer not empty interrupt enable + * @arg SPI_IT_ERR: Error interrupt enable + * @retval None + */ +#define __HAL_SPI_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR2 |= (__INTERRUPT__)) +#define __HAL_SPI_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->CR2 &= (~(__INTERRUPT__))) + +/** @brief Check if the specified SPI interrupt source is enabled or disabled. + * @param __HANDLE__: specifies the SPI handle. + * This parameter can be SPIx where x: 1, 2, or 3 to select the SPI peripheral. + * @param __INTERRUPT__: specifies the SPI interrupt source to check. + * This parameter can be one of the following values: + * @arg SPI_IT_TXE: Tx buffer empty interrupt enable + * @arg SPI_IT_RXNE: RX buffer not empty interrupt enable + * @arg SPI_IT_ERR: Error interrupt enable + * @retval The new state of __IT__ (TRUE or FALSE). + */ +#define __HAL_SPI_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((((__HANDLE__)->Instance->CR2 & (__INTERRUPT__)) == (__INTERRUPT__)) ? SET : RESET) + +/** @brief Check whether the specified SPI flag is set or not. + * @param __HANDLE__: specifies the SPI handle. + * This parameter can be SPIx where x: 1, 2, or 3 to select the SPI peripheral. + * @param __FLAG__: specifies the flag to check. + * This parameter can be one of the following values: + * @arg SPI_FLAG_RXNE: Receive buffer not empty flag + * @arg SPI_FLAG_TXE: Transmit buffer empty flag + * @arg SPI_FLAG_CRCERR: CRC error flag + * @arg SPI_FLAG_MODF: Mode fault flag + * @arg SPI_FLAG_OVR: Overrun flag + * @arg SPI_FLAG_BSY: Busy flag + * @arg SPI_FLAG_FRE: Frame format error flag + * @retval The new state of __FLAG__ (TRUE or FALSE). + */ +#define __HAL_SPI_GET_FLAG(__HANDLE__, __FLAG__) ((((__HANDLE__)->Instance->SR) & (__FLAG__)) == (__FLAG__)) + +/** @brief Clear the SPI CRCERR pending flag. + * @param __HANDLE__: specifies the SPI handle. + * This parameter can be SPIx where x: 1, 2, or 3 to select the SPI peripheral. + * @retval None + */ +#define __HAL_SPI_CLEAR_CRCERRFLAG(__HANDLE__) ((__HANDLE__)->Instance->SR &= (uint32_t)~((uint32_t)SPI_FLAG_CRCERR)) + +/** @brief Clear the SPI MODF pending flag. + * @param __HANDLE__: specifies the SPI handle. + * This parameter can be SPIx where x: 1, 2, or 3 to select the SPI peripheral. + * @retval None + */ +#define __HAL_SPI_CLEAR_MODFFLAG(__HANDLE__) do{(__HANDLE__)->Instance->SR;\ + (__HANDLE__)->Instance->CR1 &= (uint32_t)~((uint32_t)SPI_CR1_SPE);}while(0) + +/** @brief Clear the SPI OVR pending flag. + * @param __HANDLE__: specifies the SPI handle. + * This parameter can be SPIx where x: 1, 2, or 3 to select the SPI peripheral. + * @retval None + */ +#define __HAL_SPI_CLEAR_OVRFLAG(__HANDLE__) do{(__HANDLE__)->Instance->DR;\ + (__HANDLE__)->Instance->SR;}while(0) + +/** @brief Clear the SPI FRE pending flag. + * @param __HANDLE__: specifies the SPI handle. + * This parameter can be SPIx where x: 1, 2, or 3 to select the SPI peripheral. + * @retval None + */ +#define __HAL_SPI_CLEAR_FREFLAG(__HANDLE__) ((__HANDLE__)->Instance->SR) + +#define __HAL_SPI_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 |= SPI_CR1_SPE) +#define __HAL_SPI_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 &= (uint32_t)~((uint32_t)SPI_CR1_SPE)) + +#define IS_SPI_CRC_POLYNOMIAL(POLYNOMIAL) (((POLYNOMIAL) >= 0x1) && ((POLYNOMIAL) <= 0xFFFF)) + +#define __HAL_SPI_1LINE_TX(__HANDLE__) ((__HANDLE__)->Instance->CR1 |= SPI_CR1_BIDIOE) + +#define __HAL_SPI_1LINE_RX(__HANDLE__) ((__HANDLE__)->Instance->CR1 &= (uint32_t)~((uint32_t)SPI_CR1_BIDIOE)) + +#define __HAL_SPI_RESET_CRC(__HANDLE__) do{(__HANDLE__)->Instance->CR1 &= (uint32_t)~((uint32_t)SPI_CR1_CRCEN);\ + (__HANDLE__)->Instance->CR1 |= SPI_CR1_CRCEN;}while(0) + +/* Exported functions --------------------------------------------------------*/ + +/* Initialization/de-initialization functions **********************************/ +HAL_StatusTypeDef HAL_SPI_Init(SPI_HandleTypeDef *hspi); +HAL_StatusTypeDef HAL_SPI_DeInit (SPI_HandleTypeDef *hspi); +void HAL_SPI_MspInit(SPI_HandleTypeDef *hspi); +void HAL_SPI_MspDeInit(SPI_HandleTypeDef *hspi); + +/* I/O operation functions *****************************************************/ +HAL_StatusTypeDef HAL_SPI_Transmit(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size, uint32_t Timeout); +HAL_StatusTypeDef HAL_SPI_Receive(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size, uint32_t Timeout); +HAL_StatusTypeDef HAL_SPI_TransmitReceive(SPI_HandleTypeDef *hspi, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size, uint32_t Timeout); +HAL_StatusTypeDef HAL_SPI_Transmit_IT(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size); +HAL_StatusTypeDef HAL_SPI_Receive_IT(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size); +HAL_StatusTypeDef HAL_SPI_TransmitReceive_IT(SPI_HandleTypeDef *hspi, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size); +HAL_StatusTypeDef HAL_SPI_Transmit_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size); +HAL_StatusTypeDef HAL_SPI_Receive_DMA(SPI_HandleTypeDef *hspi, uint8_t *pData, uint16_t Size); +HAL_StatusTypeDef HAL_SPI_TransmitReceive_DMA(SPI_HandleTypeDef *hspi, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size); +void HAL_SPI_IRQHandler(SPI_HandleTypeDef *hspi); +void HAL_SPI_TxCpltCallback(SPI_HandleTypeDef *hspi); +void HAL_SPI_RxCpltCallback(SPI_HandleTypeDef *hspi); +void HAL_SPI_TxRxCpltCallback(SPI_HandleTypeDef *hspi); +void HAL_SPI_ErrorCallback(SPI_HandleTypeDef *hspi); + +/* Peripheral State and Control functions **************************************/ +HAL_SPI_StateTypeDef HAL_SPI_GetState(SPI_HandleTypeDef *hspi); +HAL_SPI_ErrorTypeDef HAL_SPI_GetError(SPI_HandleTypeDef *hspi); + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __STM32L0xx_HAL_SPI_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_tim.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_tim.c new file mode 100644 index 0000000000..60647c903d --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_tim.c @@ -0,0 +1,4783 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_tim.c + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief TIM HAL module driver. + * @brief This file provides firmware functions to manage the following + * functionalities of the Timer (TIM) peripheral: + * + Time Base Initialization + * + Time Base Start + * + Time Base Start Interruption + * + Time Base Start DMA + * + Time Output Compare/PWM Initialization + * + Time Output Compare/PWM Channel Configuration + * + Time Output Compare/PWM Start + * + Time Output Compare/PWM Start Interruption + * + Time Output Compare/PWM Start DMA + * + Time Input Capture Initialization + * + Time Input Capture Channel Configuration + * + Time Input Capture Start + * + Time Input Capture Start Interruption + * + Time Input Capture Start DMA + * + Time One Pulse Initialization + * + Time One Pulse Channel Configuration + * + Time One Pulse Start + * + Time Encoder Interface Initialization + * + Time Encoder Interface Start + * + Time Encoder Interface Start Interruption + * + Time Encoder Interface Start DMA + * + Time OCRef clear configuration + * + Time External Clock configuration + * + Time Complementary signal bread and dead time configuration + * + Time Master and Slave synchronization configuration + @verbatim + ============================================================================== + ##### TIMER Generic features ##### + ============================================================================== + [..] The Timer features include: + (#) 16-bit up, down, up/down auto-reload counter. + (#) 16-bit programmable prescaler allowing dividing (also “on the fly”) the counter clock + frequency either by any factor between 1 and 65536. + (#) Up to 4 independent channels for: + Input Capture + Output Compare + PWM generation (Edge and Center-aligned Mode) + One-pulse mode output + (#) Synchronization circuit to control the timer with external signals and to interconnect + several timers together. + (#) Supports incremental (quadrature) encoder and hall-sensor circuitry for positioning + purposes + + ##### How to use this driver ##### +================================================================================ + [..] + (#) Enable the TIM interface clock using + __TIMx_CLK_ENABLE(); + + (#) TIM pins configuration + (++) Enable the clock for the TIM GPIOs using the following function: + __GPIOx_CLK_ENABLE(); + (++) Configure these TIM pins in Alternate function mode using HAL_GPIO_Init(); + + (#) The external Clock can be configured, if needed (the default clock is the internal clock from the APBx), + using the following function: + HAL_TIM_ConfigClockSource, the clock configuration should be done before any start function. + + (#) Configure the TIM in the desired functioning mode using one of the + initialization function of this driver: + (++) HAL_TIM_Base_Init: to use the Timer to generate a simple time base + (++) HAL_TIM_OC_Init and HAL_TIM_OC_ConfigChannel: to use the Timer to generate an + Output Compare signal. + (++) HAL_TIM_PWM_Init and HAL_TIM_PWM_ConfigChannel: to use the Timer to generate a + PWM signal. + (++) HAL_TIM_IC_Init and HAL_TIM_IC_ConfigChannel: to use the Timer to measure an + external signal. + (++) HAL_TIM_OnePulse_Init and HAL_TIM_OnePulse_ConfigChannel: to use the Timer in One Pulse Mode. + (++) HAL_TIM_Encoder_Init: to use the Timer Encoder Interface. + + (#) Activate the TIM peripheral using one of the start functions: + HAL_TIM_Base_Start(), HAL_TIM_Base_Start_DMA(), HAL_TIM_Base_Start_IT(), + HAL_TIM_OC_Start(), HAL_TIM_OC_Start_DMA(), HAL_TIM_OC_Start_IT(), + HAL_TIM_IC_Start(), HAL_TIM_IC_Start_DMA(), HAL_TIM_IC_Start_IT(), + HAL_TIM_PWM_Start(), HAL_TIM_PWM_Start_DMA(), HAL_TIM_PWM_Start_IT(), + HAL_TIM_OnePulse_Start(), HAL_TIM_OnePulse_Start_IT(), + HAL_TIM_Encoder_Start(), HAL_TIM_Encoder_Start_DMA() or HAL_TIM_Encoder_Start_IT() + + (#) The DMA Burst is managed with the two following functions: + HAL_TIM_DMABurst_WriteStart + HAL_TIM_DMABurst_ReadStart + + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @defgroup TIM + * @brief TIM HAL module driver + * @{ + */ + +#ifdef HAL_TIM_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +static void TIM_Base_SetConfig(TIM_TypeDef *TIMx, TIM_Base_InitTypeDef *Structure); +static void TIM_OC1_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config); +static void TIM_OC2_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config); +static void TIM_OC3_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config); +static void TIM_OC4_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config); +static void TIM_TI1_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICSelection, + uint32_t TIM_ICFilter); +static void TIM_TI1_ConfigInputStage(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICFilter); +static void TIM_TI2_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICSelection, + uint32_t TIM_ICFilter); +static void TIM_TI2_ConfigInputStage(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICFilter); +static void TIM_TI3_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICSelection, + uint32_t TIM_ICFilter); +static void TIM_TI4_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICSelection, + uint32_t TIM_ICFilter); + +static void TIM_ETR_SetConfig(TIM_TypeDef* TIMx, uint32_t TIM_ExtTRGPrescaler, + uint32_t TIM_ExtTRGPolarity, uint32_t ExtTRGFilter); + +static void TIM_ITRx_SetConfig(TIM_TypeDef* TIMx, uint16_t TIM_ITRx); +static void TIM_CCxChannelCmd(TIM_TypeDef* TIMx, uint32_t Channel, uint32_t ChannelState); +static void TIM_DMAPeriodElapsedCplt(DMA_HandleTypeDef *hdma); +static void TIM_DMATriggerCplt(DMA_HandleTypeDef *hdma); +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup TIM_Private_Functions + * @{ + */ + +/** @defgroup HAL_TIM_Group1 Initialization/de-initialization functions + * @brief Initialization and Configuration functions + * +@verbatim + =============================================================================== + ##### Initialization/de-initialization functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Initialize and configure the TIM. + (+) De-initialize the TIM. + +@endverbatim + * @{ + */ +/** + * @brief Initializes the TIM Time base Unit according to the specified + * parameters in the TIM_HandleTypeDef and create the associated handle. + * @param htim: pointer to a TIM_HandleTypeDef structure that contains + * the configuration information for TIM module. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_Base_Init(TIM_HandleTypeDef *htim) +{ + /* Check the TIM handle allocation */ + if(htim == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_TIM_INSTANCE(htim->Instance)); + assert_param(IS_TIM_COUNTER_MODE(htim->Init.CounterMode)); + assert_param(IS_TIM_CLOCKDIVISION_DIV(htim->Init.ClockDivision)); + + if(htim->State == HAL_TIM_STATE_RESET) + { + /* Init the low level hardware : GPIO, CLOCK, NVIC */ + HAL_TIM_Base_MspInit(htim); + } + + /* Set the TIM state */ + htim->State= HAL_TIM_STATE_BUSY; + + /* Set the Time Base configuration */ + TIM_Base_SetConfig(htim->Instance, &htim->Init); + + /* Initialize the TIM state*/ + htim->State= HAL_TIM_STATE_READY; + + return HAL_OK; +} + +/** + * @brief Initializes the TIM Output Compare according to the specified + * parameters in the TIM_HandleTypeDef and create the associated handle. + * @param htim: TIM Output Compare handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_OC_Init(TIM_HandleTypeDef* htim) +{ + /* Check the TIM handle allocation */ + if(htim == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_TIM_INSTANCE(htim->Instance)); + assert_param(IS_TIM_COUNTER_MODE(htim->Init.CounterMode)); + assert_param(IS_TIM_CLOCKDIVISION_DIV(htim->Init.ClockDivision)); + + if(htim->State == HAL_TIM_STATE_RESET) + { + /* Init the low level hardware : GPIO, CLOCK, NVIC */ + HAL_TIM_OC_MspInit(htim); + } + /* Set the TIM state */ + htim->State= HAL_TIM_STATE_BUSY; + + /* Init the base time for the Output Compare */ + TIM_Base_SetConfig(htim->Instance, &htim->Init); + + /* Initialize the TIM state*/ + htim->State= HAL_TIM_STATE_READY; + + return HAL_OK; +} + +/** + * @brief Initializes the TIM PWM Time Base according to the specified + * parameters in the TIM_HandleTypeDef and create the associated handle. + * @param htim: TIM handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_PWM_Init(TIM_HandleTypeDef *htim) +{ + /* Check the TIM handle allocation */ + if(htim == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_TIM_INSTANCE(htim->Instance)); + assert_param(IS_TIM_COUNTER_MODE(htim->Init.CounterMode)); + assert_param(IS_TIM_CLOCKDIVISION_DIV(htim->Init.ClockDivision)); + + if(htim->State == HAL_TIM_STATE_RESET) + { + /* Init the low level hardware : GPIO, CLOCK, NVIC and DMA */ + HAL_TIM_PWM_MspInit(htim); + } + + /* Set the TIM state */ + htim->State= HAL_TIM_STATE_BUSY; + + /* Init the base time for the PWM */ + TIM_Base_SetConfig(htim->Instance, &htim->Init); + + /* Initialize the TIM state*/ + htim->State= HAL_TIM_STATE_READY; + + return HAL_OK; +} + +/** + * @brief Initializes the TIM Input Capture Time base according to the specified + * parameters in the TIM_HandleTypeDef and create the associated handle. + * @param htim: TIM Input Capture handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_IC_Init(TIM_HandleTypeDef *htim) +{ + /* Check the TIM handle allocation */ + if(htim == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_TIM_INSTANCE(htim->Instance)); + assert_param(IS_TIM_COUNTER_MODE(htim->Init.CounterMode)); + assert_param(IS_TIM_CLOCKDIVISION_DIV(htim->Init.ClockDivision)); + + if(htim->State == HAL_TIM_STATE_RESET) + { + /* Init the low level hardware : GPIO, CLOCK, NVIC and DMA */ + HAL_TIM_IC_MspInit(htim); + } + + /* Set the TIM state */ + htim->State= HAL_TIM_STATE_BUSY; + + /* Init the base time for the input capture */ + TIM_Base_SetConfig(htim->Instance, &htim->Init); + + /* Initialize the TIM state*/ + htim->State= HAL_TIM_STATE_READY; + + return HAL_OK; +} + +/** + * @brief Initializes the TIM One Pulse Time Base according to the specified + * parameters in the TIM_HandleTypeDef and create the associated handle. + * @param htim: TIM OnePulse handle + * @param OnePulseMode: Select the One pulse mode. + * This parameter can be one of the following values: + * @arg TIM_OPMODE_SINGLE: Only one pulse will be generated. + * @arg TIM_OPMODE_REPETITIVE: Repetitive pulses wil be generated. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_OnePulse_Init(TIM_HandleTypeDef *htim, uint32_t OnePulseMode) +{ + /* Check the TIM handle allocation */ + if(htim == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_TIM_CC2_INSTANCE(htim->Instance)); + assert_param(IS_TIM_COUNTER_MODE(htim->Init.CounterMode)); + assert_param(IS_TIM_CLOCKDIVISION_DIV(htim->Init.ClockDivision)); + assert_param(IS_TIM_OPM_MODE(OnePulseMode)); + + if(htim->State == HAL_TIM_STATE_RESET) + { + /* Init the low level hardware : GPIO, CLOCK, NVIC and DMA */ + HAL_TIM_OnePulse_MspInit(htim); + } + + /* Set the TIM state */ + htim->State= HAL_TIM_STATE_BUSY; + + /* Configure the Time base in the One Pulse Mode */ + TIM_Base_SetConfig(htim->Instance, &htim->Init); + + /* Reset the OPM Bit */ + htim->Instance->CR1 &= ~TIM_CR1_OPM; + + /* Configure the OPM Mode */ + htim->Instance->CR1 |= OnePulseMode; + + /* Initialize the TIM state*/ + htim->State= HAL_TIM_STATE_READY; + + return HAL_OK; +} + +/** + * @brief Initializes the TIM Encoder Interface and create the associated handle. + * @param htim: TIM Encoder Interface handle + * @param sConfig: TIM Encoder Interface configuration structure + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_Encoder_Init(TIM_HandleTypeDef *htim, TIM_Encoder_InitTypeDef* sConfig) +{ + uint32_t tmpsmcr = 0; + uint32_t tmpccmr1 = 0; + uint32_t tmpccer = 0; + + /* Check the TIM handle allocation */ + if(htim == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_TIM_CC2_INSTANCE(htim->Instance)); + assert_param(IS_TIM_ENCODER_MODE(sConfig->EncoderMode)); + assert_param(IS_TIM_IC_SELECTION(sConfig->IC1Selection)); + assert_param(IS_TIM_IC_SELECTION(sConfig->IC2Selection)); + assert_param(IS_TIM_IC_POLARITY(sConfig->IC1Polarity)); + assert_param(IS_TIM_IC_POLARITY(sConfig->IC2Polarity)); + assert_param(IS_TIM_IC_PRESCALER(sConfig->IC1Prescaler)); + assert_param(IS_TIM_IC_PRESCALER(sConfig->IC2Prescaler)); + assert_param(IS_TIM_IC_FILTER(sConfig->IC1Filter)); + assert_param(IS_TIM_IC_FILTER(sConfig->IC2Filter)); + + if(htim->State == HAL_TIM_STATE_RESET) + { + /* Init the low level hardware : GPIO, CLOCK, NVIC and DMA */ + HAL_TIM_Encoder_MspInit(htim); + } + + /* Set the TIM state */ + htim->State= HAL_TIM_STATE_BUSY; + + /* Reset the SMS bits */ + htim->Instance->SMCR &= ~TIM_SMCR_SMS; + + /* Configure the Time base in the Encoder Mode */ + TIM_Base_SetConfig(htim->Instance, &htim->Init); + + /* Get the TIMx SMCR register value */ + tmpsmcr = htim->Instance->SMCR; + + /* Get the TIMx CCMR1 register value */ + tmpccmr1 = htim->Instance->CCMR1; + + /* Get the TIMx CCER register value */ + tmpccer = htim->Instance->CCER; + + /* Set the encoder Mode */ + tmpsmcr |= sConfig->EncoderMode; + + /* Select the Capture Compare 1 and the Capture Compare 2 as input */ + tmpccmr1 &= ~(TIM_CCMR1_CC1S | TIM_CCMR1_CC2S); + tmpccmr1 |= (sConfig->IC1Selection | (sConfig->IC2Selection << 8)); + + /* Set the the Capture Compare 1 and the Capture Compare 2 prescalers and filters */ + tmpccmr1 &= ~(TIM_CCMR1_IC1PSC | TIM_CCMR1_IC2PSC); + tmpccmr1 &= ~(TIM_CCMR1_IC1F | TIM_CCMR1_IC2F); + tmpccmr1 |= sConfig->IC1Prescaler | (sConfig->IC2Prescaler << 8); + tmpccmr1 |= (sConfig->IC1Filter << 4) | (sConfig->IC2Filter << 12); + + /* Set the TI1 and the TI2 Polarities */ + tmpccer &= ~(TIM_CCER_CC1P | TIM_CCER_CC2P); + tmpccer &= ~(TIM_CCER_CC1NP | TIM_CCER_CC2NP); + tmpccer |= sConfig->IC1Polarity | (sConfig->IC2Polarity << 4); + + /* Write to TIMx SMCR */ + htim->Instance->SMCR = tmpsmcr; + + /* Write to TIMx CCMR1 */ + htim->Instance->CCMR1 = tmpccmr1; + + /* Write to TIMx CCER */ + htim->Instance->CCER = tmpccer; + + /* Initialize the TIM state*/ + htim->State= HAL_TIM_STATE_READY; + + return HAL_OK; +} + +/** + * @brief DeInitializes the TIM Base peripheral + * @param htim: pointer to a TIM_HandleTypeDef structure that contains + * the configuration information for TIM module. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_Base_DeInit(TIM_HandleTypeDef *htim) +{ + /* Check the parameters */ + assert_param(IS_TIM_INSTANCE(htim->Instance)); + + htim->State = HAL_TIM_STATE_BUSY; + + /* Disable the TIM Peripheral Clock */ + __HAL_TIM_DISABLE(htim); + + /* DeInit the low level hardware: GPIO, CLOCK, NVIC */ + HAL_TIM_Base_MspDeInit(htim); + + /* Change TIM state */ + htim->State = HAL_TIM_STATE_RESET; + + /* Release Lock */ + __HAL_UNLOCK(htim); + + return HAL_OK; +} + +/** + * @brief DeInitializes the TIM peripheral + * @param htim: TIM Output Compare handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_OC_DeInit(TIM_HandleTypeDef *htim) +{ + /* Check the parameters */ + assert_param(IS_TIM_INSTANCE(htim->Instance)); + + htim->State = HAL_TIM_STATE_BUSY; + + /* Disable the TIM Peripheral Clock */ + __HAL_TIM_DISABLE(htim); + + /* DeInit the low level hardware: GPIO, CLOCK, NVIC and DMA */ + HAL_TIM_OC_MspDeInit(htim); + + /* Change TIM state */ + htim->State = HAL_TIM_STATE_RESET; + + /* Release Lock */ + __HAL_UNLOCK(htim); + + return HAL_OK; +} + +/** + * @brief DeInitializes the TIM peripheral + * @param htim: TIM handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_PWM_DeInit(TIM_HandleTypeDef *htim) +{ + /* Check the parameters */ + assert_param(IS_TIM_INSTANCE(htim->Instance)); + + htim->State = HAL_TIM_STATE_BUSY; + + /* Disable the TIM Peripheral Clock */ + __HAL_TIM_DISABLE(htim); + + /* DeInit the low level hardware: GPIO, CLOCK, NVIC and DMA */ + HAL_TIM_PWM_MspDeInit(htim); + + /* Change TIM state */ + htim->State = HAL_TIM_STATE_RESET; + + /* Release Lock */ + __HAL_UNLOCK(htim); + + return HAL_OK; +} + +/** + * @brief DeInitializes the TIM peripheral + * @param htim: TIM Input Capture handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_IC_DeInit(TIM_HandleTypeDef *htim) +{ + /* Check the parameters */ + assert_param(IS_TIM_INSTANCE(htim->Instance)); + + htim->State = HAL_TIM_STATE_BUSY; + + /* Disable the TIM Peripheral Clock */ + __HAL_TIM_DISABLE(htim); + + /* DeInit the low level hardware: GPIO, CLOCK, NVIC and DMA */ + HAL_TIM_IC_MspDeInit(htim); + + /* Change TIM state */ + htim->State = HAL_TIM_STATE_RESET; + + /* Release Lock */ + __HAL_UNLOCK(htim); + + return HAL_OK; +} + +/** + * @brief DeInitializes the TIM One Pulse + * @param htim: TIM One Pulse handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_OnePulse_DeInit(TIM_HandleTypeDef *htim) +{ + /* Check the parameters */ + assert_param(IS_TIM_INSTANCE(htim->Instance)); + + htim->State = HAL_TIM_STATE_BUSY; + + /* Disable the TIM Peripheral Clock */ + __HAL_TIM_DISABLE(htim); + + /* DeInit the low level hardware: GPIO, CLOCK, NVIC */ + HAL_TIM_OnePulse_MspDeInit(htim); + + /* Change TIM state */ + htim->State = HAL_TIM_STATE_RESET; + + /* Release Lock */ + __HAL_UNLOCK(htim); + + return HAL_OK; +} + +/** + * @brief DeInitializes the TIM Encoder interface + * @param htim: TIM Encoder handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_Encoder_DeInit(TIM_HandleTypeDef *htim) +{ + /* Check the parameters */ + assert_param(IS_TIM_INSTANCE(htim->Instance)); + + htim->State = HAL_TIM_STATE_BUSY; + + /* Disable the TIM Peripheral Clock */ + __HAL_TIM_DISABLE(htim); + + /* DeInit the low level hardware: GPIO, CLOCK, NVIC */ + HAL_TIM_Encoder_MspDeInit(htim); + + /* Change TIM state */ + htim->State = HAL_TIM_STATE_RESET; + + /* Release Lock */ + __HAL_UNLOCK(htim); + + return HAL_OK; +} + +/** + * @brief Initializes the TIM Base MSP. + * @param htim: pointer to a TIM_HandleTypeDef structure that contains + * the configuration information for TIM module. + * @retval None + */ +__weak void HAL_TIM_Base_MspInit(TIM_HandleTypeDef *htim) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_TIM_Base_MspInit could be implemented in the user file + */ +} + +/** + * @brief Initializes the TIM Output Compare MSP. + * @param htim: TIM handle + * @retval None + */ +__weak void HAL_TIM_OC_MspInit(TIM_HandleTypeDef *htim) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_TIM_OC_MspInit could be implemented in the user file + */ +} + +/** + * @brief Initializes the TIM PWM MSP. + * @param htim: TIM handle + * @retval None + */ +__weak void HAL_TIM_PWM_MspInit(TIM_HandleTypeDef *htim) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_TIM_PWM_MspInit could be implemented in the user file + */ +} + +/** + * @brief Initializes the TIM INput Capture MSP. + * @param htim: TIM handle + * @retval None + */ +__weak void HAL_TIM_IC_MspInit(TIM_HandleTypeDef *htim) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_TIM_IC_MspInit could be implemented in the user file + */ +} + +/** + * @brief Initializes the TIM One Pulse MSP. + * @param htim: TIM handle + * @retval None + */ +__weak void HAL_TIM_OnePulse_MspInit(TIM_HandleTypeDef *htim) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_TIM_OnePulse_MspInit could be implemented in the user file + */ +} + +/** + * @brief Initializes the TIM Encoder Interface MSP. + * @param htim: TIM handle + * @retval None + */ +__weak void HAL_TIM_Encoder_MspInit(TIM_HandleTypeDef *htim) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_TIM_Encoder_MspInit could be implemented in the user file + */ +} + +/** + * @brief DeInitializes TIM Base MSP. + * @param htim: pointer to a TIM_HandleTypeDef structure that contains + * the configuration information for TIM module. + * @retval None + */ +__weak void HAL_TIM_Base_MspDeInit(TIM_HandleTypeDef *htim) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_TIM_Base_MspDeInit could be implemented in the user file + */ +} + +/** + * @brief DeInitializes TIM Output Compare MSP. + * @param htim: TIM handle + * @retval None + */ +__weak void HAL_TIM_OC_MspDeInit(TIM_HandleTypeDef *htim) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_TIM_OC_MspDeInit could be implemented in the user file + */ +} + +/** + * @brief DeInitializes TIM PWM MSP. + * @param htim: TIM handle + * @retval None + */ +__weak void HAL_TIM_PWM_MspDeInit(TIM_HandleTypeDef *htim) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_TIM_PWM_MspDeInit could be implemented in the user file + */ +} + +/** + * @brief DeInitializes TIM Input Capture MSP. + * @param htim: TIM handle + * @retval None + */ +__weak void HAL_TIM_IC_MspDeInit(TIM_HandleTypeDef *htim) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_TIM_IC_MspDeInit could be implemented in the user file + */ +} + +/** + * @brief DeInitializes TIM One Pulse MSP. + * @param htim: TIM handle + * @retval None + */ +__weak void HAL_TIM_OnePulse_MspDeInit(TIM_HandleTypeDef *htim) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_TIM_OnePulse_MspDeInit could be implemented in the user file + */ +} + +/** + * @brief DeInitializes TIM Encoder Interface MSP. + * @param htim: TIM handle + * @retval None + */ +__weak void HAL_TIM_Encoder_MspDeInit(TIM_HandleTypeDef *htim) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_TIM_Encoder_MspDeInit could be implemented in the user file + */ +} + +/** + * @} + */ +/** @defgroup TIM_Group2 I/O operation functions + * @brief I/O operation functions + * +@verbatim + =============================================================================== + ##### IO operation functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Start the Time Base. + (+) Stop the Time Base. + (+) Start the Time Base and enable interrupt. + (+) Stop the Time Base and disable interrupt. + (+) Start the Time Base and enable DMA transfer. + (+) Stop the Time Base and disable DMA transfer. + (+) Start the Output Compare/PWM. + (+) Stop the Output Compare/PWM. + (+) Start the Output Compare/PWM and enable interrupts. + (+) Stop the Output Compare/PWM and disable interrupts. + (+) Start the Output Compare/PWM and enable DMA transfers. + (+) Stop the Output Compare/PWM and disable DMA transfers. + (+) Start the Input Capture measurement. + (+) Stop the Input Capture. + (+) Start the Input Capture and enable interrupts. + (+) Stop the Input Capture and disable interrupts. + (+) Start the Input Capture and enable DMA transfers. + (+) Stop the Input Capture and disable DMA transfers. + (+) Start the One Pulse generation. + (+) Stop the One Pulse. + (+) Start the One Pulse and enable interrupts. + (+) Stop the One Pulse and disable interrupts. + (+) Start the Encoder Interface. + (+) Stop the Encoder Interface. + (+) Start the Encoder Interface and enable interrupts. + (+) Stop the Encoder Interface and disable interrupts. + (+) Start the Encoder Interface and enable DMA transfers. + (+) Stop the Encoder Interface and disable DMA transfers. + (+) Start the Hall Sensor Interface. + (+) Stop the Hall Sensor Interface. + (+) Start the Hall Sensor Interface and enable interrupts. + (+) Stop the Hall Sensor Interface and disable interrupts. + (+) Start the Hall Sensor Interface and enable DMA transfers. + (+) Stop the Hall Sensor Interface and disable DMA transfers. + (+) Handle TIM interrupt request. + +@endverbatim + * @{ + */ +/** + * @brief Starts the TIM Base generation. + * @param htim: pointer to a TIM_HandleTypeDef structure that contains + * the configuration information for TIM module. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_Base_Start(TIM_HandleTypeDef *htim) +{ + /* Check the parameters */ + assert_param(IS_TIM_INSTANCE(htim->Instance)); + + /* Set the TIM state */ + htim->State= HAL_TIM_STATE_BUSY; + + /* Enable the Peripheral */ + __HAL_TIM_ENABLE(htim); + + /* Change the TIM state*/ + htim->State= HAL_TIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the TIM Base generation. + * @param htim: pointer to a TIM_HandleTypeDef structure that contains + * the configuration information for TIM module. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_Base_Stop(TIM_HandleTypeDef *htim) +{ + /* Check the parameters */ + assert_param(IS_TIM_INSTANCE(htim->Instance)); + + /* Set the TIM state */ + htim->State= HAL_TIM_STATE_BUSY; + + /* Disable the Peripheral */ + __HAL_TIM_DISABLE(htim); + + /* Change the TIM state*/ + htim->State= HAL_TIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Starts the TIM Base generation in interrupt mode. + * @param htim: pointer to a TIM_HandleTypeDef structure that contains + * the configuration information for TIM module. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_Base_Start_IT(TIM_HandleTypeDef *htim) +{ + /* Check the parameters */ + assert_param(IS_TIM_INSTANCE(htim->Instance)); + + /* Enable the TIM Update interrupt */ + __HAL_TIM_ENABLE_IT(htim, TIM_IT_UPDATE); + + /* Enable the Peripheral */ + __HAL_TIM_ENABLE(htim); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the TIM Base generation in interrupt mode. + * @param htim: pointer to a TIM_HandleTypeDef structure that contains + * the configuration information for TIM module. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_Base_Stop_IT(TIM_HandleTypeDef *htim) +{ + /* Check the parameters */ + assert_param(IS_TIM_INSTANCE(htim->Instance)); + /* Disable the TIM Update interrupt */ + __HAL_TIM_DISABLE_IT(htim, TIM_IT_UPDATE); + + /* Disable the Peripheral */ + __HAL_TIM_DISABLE(htim); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Starts the TIM Base generation in DMA mode. + * @param htim: pointer to a TIM_HandleTypeDef structure that contains + * the configuration information for TIM module. + * @param pData: The source Buffer address. + * @param Length: The length of data to be transferred from memory to peripheral. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_Base_Start_DMA(TIM_HandleTypeDef *htim, uint32_t *pData, uint16_t Length) +{ + /* Check the parameters */ + assert_param(IS_TIM_DMA_INSTANCE(htim->Instance)); + + if((htim->State == HAL_TIM_STATE_BUSY)) + { + return HAL_BUSY; + } + else if((htim->State == HAL_TIM_STATE_READY)) + { + if((pData == 0 ) && (Length > 0)) + { + return HAL_ERROR; + } + else + { + htim->State = HAL_TIM_STATE_BUSY; + } + } + /* Set the DMA Period elapsed callback */ + htim->hdma[TIM_DMA_ID_UPDATE]->XferCpltCallback = TIM_DMAPeriodElapsedCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_UPDATE]->XferErrorCallback = HAL_TIM_DMAError ; + + /* Enable the DMA Stream */ + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_UPDATE], (uint32_t)pData, (uint32_t)&htim->Instance->ARR, Length); + + /* Enable the TIM Update DMA request */ + __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_UPDATE); + + /* Enable the Peripheral */ + __HAL_TIM_ENABLE(htim); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the TIM Base generation in DMA mode. + * @param htim: pointer to a TIM_HandleTypeDef structure that contains + * the configuration information for TIM module. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_Base_Stop_DMA(TIM_HandleTypeDef *htim) +{ + /* Check the parameters */ + assert_param(IS_TIM_DMA_INSTANCE(htim->Instance)); + + /* Disable the TIM Update DMA request */ + __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_UPDATE); + + /* Disable the Peripheral */ + __HAL_TIM_DISABLE(htim); + + /* Change the htim state */ + htim->State = HAL_TIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Starts the TIM Output Compare signal generation. + * @param htim : pointer to a TIM_HandleTypeDef structure that contains + * the configuration information for TIM module. + * @param Channel: TIM Channel to be enabled. + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @arg TIM_CHANNEL_3: TIM Channel 3 selected + * @arg TIM_CHANNEL_4: TIM Channel 4 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_OC_Start(TIM_HandleTypeDef *htim, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel)); + + /* Enable the Output compare channel */ + TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_ENABLE); + + /* Enable the Peripheral */ + __HAL_TIM_ENABLE(htim); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the TIM Output Compare signal generation. + * @param htim: pointer to a TIM_HandleTypeDef structure that contains + * the configuration information for TIM module. + * @param Channel: TIM Channel to be disabled. + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @arg TIM_CHANNEL_3: TIM Channel 3 selected + * @arg TIM_CHANNEL_4: TIM Channel 4 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_OC_Stop(TIM_HandleTypeDef *htim, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel)); + + /* Disable the Output compare channel */ + TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_DISABLE); + + /* Disable the Peripheral */ + __HAL_TIM_DISABLE(htim); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Starts the TIM Output Compare signal generation in interrupt mode. + * @param htim: pointer to a TIM_HandleTypeDef structure that contains + * the configuration information for TIM module. + * @param Channel: TIM Channel to be enabled. + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @arg TIM_CHANNEL_3: TIM Channel 3 selected + * @arg TIM_CHANNEL_4: TIM Channel 4 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_OC_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel)); + + switch (Channel) + { + case TIM_CHANNEL_1: + { + /* Enable the TIM Capture/Compare 1 interrupt */ + __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC1); + } + break; + + case TIM_CHANNEL_2: + { + /* Enable the TIM Capture/Compare 2 interrupt */ + __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC2); + } + break; + + case TIM_CHANNEL_3: + { + /* Enable the TIM Capture/Compare 3 interrupt */ + __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC3); + } + break; + + case TIM_CHANNEL_4: + { + /* Enable the TIM Capture/Compare 4 interrupt */ + __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC4); + } + break; + + default: + break; + } + + /* Enable the Output compare channel */ + TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_ENABLE); + + /* Enable the Peripheral */ + __HAL_TIM_ENABLE(htim); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the TIM Output Compare signal generation in interrupt mode. + * @param htim: pointer to a TIM_HandleTypeDef structure that contains + * the configuration information for TIM module. + * @param Channel: TIM Channel to be disabled. + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @arg TIM_CHANNEL_3: TIM Channel 3 selected + * @arg TIM_CHANNEL_4: TIM Channel 4 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_OC_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel)); + + switch (Channel) + { + case TIM_CHANNEL_1: + { + /* Disable the TIM Capture/Compare 1 interrupt */ + __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC1); + } + break; + + case TIM_CHANNEL_2: + { + /* Disable the TIM Capture/Compare 2 interrupt */ + __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC2); + } + break; + + case TIM_CHANNEL_3: + { + /* Disable the TIM Capture/Compare 3 interrupt */ + __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC3); + } + break; + + case TIM_CHANNEL_4: + { + /* Disable the TIM Capture/Compare 4 interrupt */ + __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC4); + } + break; + + default: + break; + } + + /* Disable the Output compare channel */ + TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_DISABLE); + + /* Disable the Peripheral */ + __HAL_TIM_DISABLE(htim); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Starts the TIM Output Compare signal generation in DMA mode. + * @param htim: pointer to a TIM_HandleTypeDef structure that contains + * the configuration information for TIM module. + * @param Channel: TIM Channel to be enabled. + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @arg TIM_CHANNEL_3: TIM Channel 3 selected + * @arg TIM_CHANNEL_4: TIM Channel 4 selected + * @param pData: The source Buffer address. + * @param Length: The length of data to be transferred from memory to TIM peripheral + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_OC_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel, uint32_t *pData, uint16_t Length) +{ + /* Check the parameters */ + assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel)); + + if((htim->State == HAL_TIM_STATE_BUSY)) + { + return HAL_BUSY; + } + else if((htim->State == HAL_TIM_STATE_READY)) + { + if(((uint32_t)pData == 0 ) && (Length > 0)) + { + return HAL_ERROR; + } + else + { + htim->State = HAL_TIM_STATE_BUSY; + } + } + switch (Channel) + { + case TIM_CHANNEL_1: + { + /* Set the DMA Period elapsed callback */ + htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = HAL_TIM_DMADelayPulseCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = HAL_TIM_DMAError ; + + /* Enable the DMA Stream */ + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)pData, (uint32_t)&htim->Instance->CCR1, Length); + + /* Enable the TIM Capture/Compare 1 DMA request */ + __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC1); + } + break; + + case TIM_CHANNEL_2: + { + /* Set the DMA Period elapsed callback */ + htim->hdma[TIM_DMA_ID_CC2]->XferCpltCallback = HAL_TIM_DMADelayPulseCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC2]->XferErrorCallback = HAL_TIM_DMAError ; + + /* Enable the DMA Stream */ + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)pData, (uint32_t)&htim->Instance->CCR2, Length); + + /* Enable the TIM Capture/Compare 2 DMA request */ + __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC2); + } + break; + + case TIM_CHANNEL_3: + { + /* Set the DMA Period elapsed callback */ + htim->hdma[TIM_DMA_ID_CC3]->XferCpltCallback = HAL_TIM_DMADelayPulseCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC3]->XferErrorCallback = HAL_TIM_DMAError ; + + /* Enable the DMA Stream */ + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC3], (uint32_t)pData, (uint32_t)&htim->Instance->CCR3,Length); + + /* Enable the TIM Capture/Compare 3 DMA request */ + __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC3); + } + break; + + case TIM_CHANNEL_4: + { + /* Set the DMA Period elapsed callback */ + htim->hdma[TIM_DMA_ID_CC4]->XferCpltCallback = HAL_TIM_DMADelayPulseCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC4]->XferErrorCallback = HAL_TIM_DMAError ; + + /* Enable the DMA Stream */ + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC4], (uint32_t)pData, (uint32_t)&htim->Instance->CCR4, Length); + + /* Enable the TIM Capture/Compare 4 DMA request */ + __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC4); + } + break; + + default: + break; + } + + /* Enable the Output compare channel */ + TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_ENABLE); + + /* Enable the Peripheral */ + __HAL_TIM_ENABLE(htim); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the TIM Output Compare signal generation in DMA mode. + * @param htim: pointer to a TIM_HandleTypeDef structure that contains + * the configuration information for TIM module. + * @param Channel: TIM Channel to be disabled. + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @arg TIM_CHANNEL_3: TIM Channel 3 selected + * @arg TIM_CHANNEL_4: TIM Channel 4 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_OC_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel)); + + switch (Channel) + { + case TIM_CHANNEL_1: + { + /* Disable the TIM Capture/Compare 1 DMA request */ + __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC1); + } + break; + + case TIM_CHANNEL_2: + { + /* Disable the TIM Capture/Compare 2 DMA request */ + __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC2); + } + break; + + case TIM_CHANNEL_3: + { + /* Disable the TIM Capture/Compare 3 DMA request */ + __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC3); + } + break; + + case TIM_CHANNEL_4: + { + /* Disable the TIM Capture/Compare 4 interrupt */ + __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC4); + } + break; + + default: + break; + } + + /* Disable the Output compare channel */ + TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_DISABLE); + + /* Disable the Peripheral */ + __HAL_TIM_DISABLE(htim); + + /* Change the htim state */ + htim->State = HAL_TIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Starts the PWM signal generation. + * @param htim: pointer to a TIM_HandleTypeDef structure that contains + * the configuration information for TIM module. + * @param Channel: TIM Channels to be enabled. + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @arg TIM_CHANNEL_3: TIM Channel 3 selected + * @arg TIM_CHANNEL_4: TIM Channel 4 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_PWM_Start(TIM_HandleTypeDef *htim, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel)); + + /* Enable the Capture compare channel */ + TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_ENABLE); + + /* Enable the Peripheral */ + __HAL_TIM_ENABLE(htim); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the PWM signal generation. + * @param htim: pointer to a TIM_HandleTypeDef structure that contains + * the configuration information for TIM module. + * @param Channel: TIM Channels to be disabled. + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @arg TIM_CHANNEL_3: TIM Channel 3 selected + * @arg TIM_CHANNEL_4: TIM Channel 4 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_PWM_Stop(TIM_HandleTypeDef *htim, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel)); + + /* Disable the Capture compare channel */ + TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_DISABLE); + + /* Disable the Peripheral */ + __HAL_TIM_DISABLE(htim); + + /* Change the htim state */ + htim->State = HAL_TIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Starts the PWM signal generation in interrupt mode. + * @param htim: pointer to a TIM_HandleTypeDef structure that contains + * the configuration information for TIM module. + * @param Channel: TIM Channel to be disabled. + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @arg TIM_CHANNEL_3: TIM Channel 3 selected + * @arg TIM_CHANNEL_4: TIM Channel 4 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_PWM_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel)); + + switch (Channel) + { + case TIM_CHANNEL_1: + { + /* Enable the TIM Capture/Compare 1 interrupt */ + __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC1); + } + break; + + case TIM_CHANNEL_2: + { + /* Enable the TIM Capture/Compare 2 interrupt */ + __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC2); + } + break; + + case TIM_CHANNEL_3: + { + /* Enable the TIM Capture/Compare 3 interrupt */ + __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC3); + } + break; + + case TIM_CHANNEL_4: + { + /* Enable the TIM Capture/Compare 4 interrupt */ + __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC4); + } + break; + + default: + break; + } + + /* Enable the Capture compare channel */ + TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_ENABLE); + + /* Enable the Peripheral */ + __HAL_TIM_ENABLE(htim); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the PWM signal generation in interrupt mode. + * @param htim: pointer to a TIM_HandleTypeDef structure that contains + * the configuration information for TIM module. + * @param Channel: TIM Channels to be disabled. + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @arg TIM_CHANNEL_3: TIM Channel 3 selected + * @arg TIM_CHANNEL_4: TIM Channel 4 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_PWM_Stop_IT (TIM_HandleTypeDef *htim, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel)); + + switch (Channel) + { + case TIM_CHANNEL_1: + { + /* Disable the TIM Capture/Compare 1 interrupt */ + __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC1); + } + break; + + case TIM_CHANNEL_2: + { + /* Disable the TIM Capture/Compare 2 interrupt */ + __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC2); + } + break; + + case TIM_CHANNEL_3: + { + /* Disable the TIM Capture/Compare 3 interrupt */ + __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC3); + } + break; + + case TIM_CHANNEL_4: + { + /* Disable the TIM Capture/Compare 4 interrupt */ + __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC4); + } + break; + + default: + break; + } + + /* Disable the Capture compare channel */ + TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_DISABLE); + + /* Disable the Peripheral */ + __HAL_TIM_DISABLE(htim); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Starts the TIM PWM signal generation in DMA mode. + * @param htim: pointer to a TIM_HandleTypeDef structure that contains + * the configuration information for TIM module. + * @param Channel: TIM Channels to be enabled. + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @arg TIM_CHANNEL_3: TIM Channel 3 selected + * @arg TIM_CHANNEL_4: TIM Channel 4 selected + * @param pData: The source Buffer address. + * @param Length: The length of data to be transferred from memory to TIM peripheral + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_PWM_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel, uint32_t *pData, uint16_t Length) +{ + /* Check the parameters */ + assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel)); + + if((htim->State == HAL_TIM_STATE_BUSY)) + { + return HAL_BUSY; + } + else if((htim->State == HAL_TIM_STATE_READY)) + { + if(((uint32_t)pData == 0 ) && (Length > 0)) + { + return HAL_ERROR; + } + else + { + htim->State = HAL_TIM_STATE_BUSY; + } + } + switch (Channel) + { + case TIM_CHANNEL_1: + { + /* Set the DMA Period elapsed callback */ + htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = HAL_TIM_DMADelayPulseCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = HAL_TIM_DMAError ; + + /* Enable the DMA Stream */ + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)pData, (uint32_t)&htim->Instance->CCR1, Length); + + /* Enable the TIM Capture/Compare 1 DMA request */ + __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC1); + } + break; + + case TIM_CHANNEL_2: + { + /* Set the DMA Period elapsed callback */ + htim->hdma[TIM_DMA_ID_CC2]->XferCpltCallback = HAL_TIM_DMADelayPulseCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC2]->XferErrorCallback = HAL_TIM_DMAError ; + + /* Enable the DMA Stream */ + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)pData, (uint32_t)&htim->Instance->CCR2, Length); + + /* Enable the TIM Capture/Compare 2 DMA request */ + __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC2); + } + break; + + case TIM_CHANNEL_3: + { + /* Set the DMA Period elapsed callback */ + htim->hdma[TIM_DMA_ID_CC3]->XferCpltCallback = HAL_TIM_DMADelayPulseCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC3]->XferErrorCallback = HAL_TIM_DMAError ; + + /* Enable the DMA Stream */ + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC3], (uint32_t)pData, (uint32_t)&htim->Instance->CCR3,Length); + + /* Enable the TIM Output Capture/Compare 3 request */ + __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC3); + } + break; + + case TIM_CHANNEL_4: + { + /* Set the DMA Period elapsed callback */ + htim->hdma[TIM_DMA_ID_CC4]->XferCpltCallback = HAL_TIM_DMADelayPulseCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC4]->XferErrorCallback = HAL_TIM_DMAError ; + + /* Enable the DMA Stream */ + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC4], (uint32_t)pData, (uint32_t)&htim->Instance->CCR4, Length); + + /* Enable the TIM Capture/Compare 4 DMA request */ + __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC4); + } + break; + + default: + break; + } + + /* Enable the Capture compare channel */ + TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_ENABLE); + + /* Enable the Peripheral */ + __HAL_TIM_ENABLE(htim); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the TIM PWM signal generation in DMA mode. + * @param htim: pointer to a TIM_HandleTypeDef structure that contains + * the configuration information for TIM module. + * @param Channel: TIM Channels to be disabled. + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @arg TIM_CHANNEL_3: TIM Channel 3 selected + * @arg TIM_CHANNEL_4: TIM Channel 4 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_PWM_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel)); + + switch (Channel) + { + case TIM_CHANNEL_1: + { + /* Disable the TIM Capture/Compare 1 DMA request */ + __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC1); + } + break; + + case TIM_CHANNEL_2: + { + /* Disable the TIM Capture/Compare 2 DMA request */ + __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC2); + } + break; + + case TIM_CHANNEL_3: + { + /* Disable the TIM Capture/Compare 3 DMA request */ + __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC3); + } + break; + + case TIM_CHANNEL_4: + { + /* Disable the TIM Capture/Compare 4 interrupt */ + __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC4); + } + break; + + default: + break; + } + + /* Disable the Capture compare channel */ + TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_DISABLE); + + /* Disable the Peripheral */ + __HAL_TIM_DISABLE(htim); + + /* Change the htim state */ + htim->State = HAL_TIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Starts the TIM Input Capture measurement. + * @param htim: pointer to a TIM_HandleTypeDef structure that contains + * the configuration information for TIM module. + * @param Channel: TIM Channels to be enabled. + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @arg TIM_CHANNEL_3: TIM Channel 3 selected + * @arg TIM_CHANNEL_4: TIM Channel 4 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_IC_Start (TIM_HandleTypeDef *htim, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel)); + + /* Enable the Input Capture channel */ + TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_ENABLE); + + /* Enable the Peripheral */ + __HAL_TIM_ENABLE(htim); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the TIM Input Capture measurement. + * @param htim: pointer to a TIM_HandleTypeDef structure that contains + * the configuration information for TIM module. + * @param Channel: TIM Channels to be disabled. + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @arg TIM_CHANNEL_3: TIM Channel 3 selected + * @arg TIM_CHANNEL_4: TIM Channel 4 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_IC_Stop(TIM_HandleTypeDef *htim, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel)); + + /* Disable the Input Capture channel */ + TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_DISABLE); + + /* Disable the Peripheral */ + __HAL_TIM_DISABLE(htim); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Starts the TIM Input Capture measurement in interrupt mode. + * @param htim: pointer to a TIM_HandleTypeDef structure that contains + * the configuration information for TIM module. + * @param Channel: TIM Channels to be enabled. + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @arg TIM_CHANNEL_3: TIM Channel 3 selected + * @arg TIM_CHANNEL_4: TIM Channel 4 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_IC_Start_IT (TIM_HandleTypeDef *htim, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel)); + + switch (Channel) + { + case TIM_CHANNEL_1: + { + /* Enable the TIM Capture/Compare 1 interrupt */ + __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC1); + } + break; + + case TIM_CHANNEL_2: + { + /* Enable the TIM Capture/Compare 2 interrupt */ + __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC2); + } + break; + + case TIM_CHANNEL_3: + { + /* Enable the TIM Capture/Compare 3 interrupt */ + __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC3); + } + break; + + case TIM_CHANNEL_4: + { + /* Enable the TIM Capture/Compare 4 interrupt */ + __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC4); + } + break; + + default: + break; + } + /* Enable the Input Capture channel */ + TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_ENABLE); + + /* Enable the Peripheral */ + __HAL_TIM_ENABLE(htim); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the TIM Input Capture measurement in interrupt mode. + * @param htim: pointer to a TIM_HandleTypeDef structure that contains + * the configuration information for TIM module. + * @param Channel : TIM Channels to be disabled + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @arg TIM_CHANNEL_3: TIM Channel 3 selected + * @arg TIM_CHANNEL_4: TIM Channel 4 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_IC_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel)); + + switch (Channel) + { + case TIM_CHANNEL_1: + { + /* Disable the TIM Capture/Compare 1 interrupt */ + __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC1); + } + break; + + case TIM_CHANNEL_2: + { + /* Disable the TIM Capture/Compare 2 interrupt */ + __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC2); + } + break; + + case TIM_CHANNEL_3: + { + /* Disable the TIM Capture/Compare 3 interrupt */ + __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC3); + } + break; + + case TIM_CHANNEL_4: + { + /* Disable the TIM Capture/Compare 4 interrupt */ + __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC4); + } + break; + + default: + break; + } + + /* Disable the Input Capture channel */ + TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_DISABLE); + + /* Disable the Peripheral */ + __HAL_TIM_DISABLE(htim); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Starts the TIM Input Capture measurement on in DMA mode. + * @param htim: pointer to a TIM_HandleTypeDef structure that contains + * the configuration information for TIM module. + * @param Channel : TIM Channels to be enabled + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @arg TIM_CHANNEL_3: TIM Channel 3 selected + * @arg TIM_CHANNEL_4: TIM Channel 4 selected + * @param pData: The destination Buffer address. + * @param Length: The length of data to be transferred from TIM peripheral to memory. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_IC_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel, uint32_t *pData, uint16_t Length) +{ + /* Check the parameters */ + assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel)); + assert_param(IS_TIM_DMA_CC_INSTANCE(htim->Instance)); + + if((htim->State == HAL_TIM_STATE_BUSY)) + { + return HAL_BUSY; + } + else if((htim->State == HAL_TIM_STATE_READY)) + { + if((pData == 0 ) && (Length > 0)) + { + return HAL_ERROR; + } + else + { + htim->State = HAL_TIM_STATE_BUSY; + } + } + + switch (Channel) + { + case TIM_CHANNEL_1: + { + /* Set the DMA Period elapsed callback */ + htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = HAL_TIM_DMACaptureCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = HAL_TIM_DMAError ; + + /* Enable the DMA Stream */ + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)&htim->Instance->CCR1, (uint32_t)pData, Length); + + /* Enable the TIM Capture/Compare 1 DMA request */ + __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC1); + } + break; + + case TIM_CHANNEL_2: + { + /* Set the DMA Period elapsed callback */ + htim->hdma[TIM_DMA_ID_CC2]->XferCpltCallback = HAL_TIM_DMACaptureCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC2]->XferErrorCallback = HAL_TIM_DMAError ; + + /* Enable the DMA Stream */ + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)&htim->Instance->CCR2, (uint32_t)pData, Length); + + /* Enable the TIM Capture/Compare 2 DMA request */ + __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC2); + } + break; + + case TIM_CHANNEL_3: + { + /* Set the DMA Period elapsed callback */ + htim->hdma[TIM_DMA_ID_CC3]->XferCpltCallback = HAL_TIM_DMACaptureCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC3]->XferErrorCallback = HAL_TIM_DMAError ; + + /* Enable the DMA Stream */ + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC3], (uint32_t)&htim->Instance->CCR3, (uint32_t)pData, Length); + + /* Enable the TIM Capture/Compare 3 DMA request */ + __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC3); + } + break; + + case TIM_CHANNEL_4: + { + /* Set the DMA Period elapsed callback */ + htim->hdma[TIM_DMA_ID_CC4]->XferCpltCallback = HAL_TIM_DMACaptureCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC4]->XferErrorCallback = HAL_TIM_DMAError ; + + /* Enable the DMA Stream */ + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC4], (uint32_t)&htim->Instance->CCR4, (uint32_t)pData, Length); + + /* Enable the TIM Capture/Compare 4 DMA request */ + __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC4); + } + break; + + default: + break; + } + + /* Enable the Input Capture channel */ + TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_ENABLE); + + /* Enable the Peripheral */ + __HAL_TIM_ENABLE(htim); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the TIM Input Capture measurement on in DMA mode. + * @param htim: pointer to a TIM_HandleTypeDef structure that contains + * the configuration information for TIM module. + * @param Channel : TIM Channels to be disabled + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @arg TIM_CHANNEL_3: TIM Channel 3 selected + * @arg TIM_CHANNEL_4: TIM Channel 4 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_IC_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_TIM_CCX_INSTANCE(htim->Instance, Channel)); + assert_param(IS_TIM_DMA_CC_INSTANCE(htim->Instance)); + + switch (Channel) + { + case TIM_CHANNEL_1: + { + /* Disable the TIM Capture/Compare 1 DMA request */ + __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC1); + } + break; + + case TIM_CHANNEL_2: + { + /* Disable the TIM Capture/Compare 2 DMA request */ + __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC2); + } + break; + + case TIM_CHANNEL_3: + { + /* Disable the TIM Capture/Compare 3 DMA request */ + __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC3); + } + break; + + case TIM_CHANNEL_4: + { + /* Disable the TIM Capture/Compare 4 DMA request */ + __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC4); + } + break; + + default: + break; + } + + /* Disable the Input Capture channel */ + TIM_CCxChannelCmd(htim->Instance, Channel, TIM_CCx_DISABLE); + + /* Disable the Peripheral */ + __HAL_TIM_DISABLE(htim); + + /* Change the htim state */ + htim->State = HAL_TIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Starts the TIM One Pulse signal generation. + * @param htim: pointer to a TIM_HandleTypeDef structure that contains + * the configuration information for TIM module. + * @param OutputChannel : TIM Channels to be enabled. + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_OnePulse_Start(TIM_HandleTypeDef *htim, uint32_t OutputChannel) +{ + /* Enable the Capture compare and the Input Capture channels + (in the OPM Mode the two possible channels that can be used are TIM_CHANNEL_1 and TIM_CHANNEL_2) + if TIM_CHANNEL_1 is used as output, the TIM_CHANNEL_2 will be used as input and + if TIM_CHANNEL_1 is used as input, the TIM_CHANNEL_2 will be used as output + in all combinations, the TIM_CHANNEL_1 and TIM_CHANNEL_2 should be enabled together + + No need to enable the counter, it's enabled automatically by hardware + (the counter starts in response to a stimulus and generate a pulse */ + + TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_ENABLE); + TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_ENABLE); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the TIM One Pulse signal generation. + * @param htim: pointer to a TIM_HandleTypeDef structure that contains + * the configuration information for TIM module. + * @param OutputChannel : TIM Channels to be disable. + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_OnePulse_Stop(TIM_HandleTypeDef *htim, uint32_t OutputChannel) +{ + /* Disable the Capture compare and the Input Capture channels + (in the OPM Mode the two possible channels that can be used are TIM_CHANNEL_1 and TIM_CHANNEL_2) + if TIM_CHANNEL_1 is used as output, the TIM_CHANNEL_2 will be used as input and + if TIM_CHANNEL_1 is used as input, the TIM_CHANNEL_2 will be used as output + in all combinations, the TIM_CHANNEL_1 and TIM_CHANNEL_2 should be disabled together */ + + TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_DISABLE); + TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_DISABLE); + + /* Disable the Peripheral */ + __HAL_TIM_DISABLE(htim); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Starts the TIM One Pulse signal generation in interrupt mode. + * @param htim: pointer to a TIM_HandleTypeDef structure that contains + * the configuration information for TIM module. + * @param OutputChannel : TIM Channels to be enabled. + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_OnePulse_Start_IT(TIM_HandleTypeDef *htim, uint32_t OutputChannel) +{ + /* Enable the Capture compare and the Input Capture channels + (in the OPM Mode the two possible channels that can be used are TIM_CHANNEL_1 and TIM_CHANNEL_2) + if TIM_CHANNEL_1 is used as output, the TIM_CHANNEL_2 will be used as input and + if TIM_CHANNEL_1 is used as input, the TIM_CHANNEL_2 will be used as output + in all combinations, the TIM_CHANNEL_1 and TIM_CHANNEL_2 should be enabled together + + No need to enable the counter, it's enabled automatically by hardware + (the counter starts in response to a stimulus and generate a pulse */ + + /* Enable the TIM Capture/Compare 1 interrupt */ + __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC1); + + /* Enable the TIM Capture/Compare 2 interrupt */ + __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC2); + + TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_ENABLE); + TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_ENABLE); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the TIM One Pulse signal generation in interrupt mode. + * @param htim: pointer to a TIM_HandleTypeDef structure that contains + * the configuration information for TIM module. + * @param OutputChannel : TIM Channels to be enabled. + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_OnePulse_Stop_IT(TIM_HandleTypeDef *htim, uint32_t OutputChannel) +{ + /* Disable the TIM Capture/Compare 1 interrupt */ + __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC1); + + /* Disable the TIM Capture/Compare 2 interrupt */ + __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC2); + + /* Disable the Capture compare and the Input Capture channels + (in the OPM Mode the two possible channels that can be used are TIM_CHANNEL_1 and TIM_CHANNEL_2) + if TIM_CHANNEL_1 is used as output, the TIM_CHANNEL_2 will be used as input and + if TIM_CHANNEL_1 is used as input, the TIM_CHANNEL_2 will be used as output + in all combinations, the TIM_CHANNEL_1 and TIM_CHANNEL_2 should be disabled together */ + TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_DISABLE); + TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_DISABLE); + + /* Disable the Peripheral */ + __HAL_TIM_DISABLE(htim); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Starts the TIM Encoder Interface. + * @param htim: pointer to a TIM_HandleTypeDef structure that contains + * the configuration information for TIM module. + * @param Channel: TIM Channels to be enabled. + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_Encoder_Start(TIM_HandleTypeDef *htim, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_TIM_CC2_INSTANCE(htim->Instance)); + + /* Enable the encoder interface channels */ + switch (Channel) + { + case TIM_CHANNEL_1: + { + TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_ENABLE); + break; + } + case TIM_CHANNEL_2: + { + TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_ENABLE); + break; + } + default : + { + TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_ENABLE); + TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_ENABLE); + break; + } + } + /* Enable the Peripheral */ + __HAL_TIM_ENABLE(htim); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the TIM Encoder Interface. + * @param htim: pointer to a TIM_HandleTypeDef structure that contains + * the configuration information for TIM module. + * @param Channel: TIM Channels to be disabled. + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_Encoder_Stop(TIM_HandleTypeDef *htim, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_TIM_CC2_INSTANCE(htim->Instance)); + + /* Disable the Input Capture channels 1 and 2 + (in the EncoderInterface the two possible channels that can be used are TIM_CHANNEL_1 and TIM_CHANNEL_2) */ + switch (Channel) + { + case TIM_CHANNEL_1: + { + TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_DISABLE); + break; + } + case TIM_CHANNEL_2: + { + TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_DISABLE); + break; + } + default : + { + TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_DISABLE); + TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_DISABLE); + break; + } + } + /* Disable the Peripheral */ + __HAL_TIM_DISABLE(htim); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Starts the TIM Encoder Interface in interrupt mode. + * @param htim: pointer to a TIM_HandleTypeDef structure that contains + * the configuration information for TIM module. + * @param Channel: TIM Channels to be enabled. + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_Encoder_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_TIM_CC2_INSTANCE(htim->Instance)); + + /* Enable the encoder interface channels */ + /* Enable the capture compare Interrupts 1 and/or 2 */ + switch (Channel) + { + case TIM_CHANNEL_1: + { + TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_ENABLE); + __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC1); + break; + } + case TIM_CHANNEL_2: + { + TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_ENABLE); + __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC2); + break; + } + default : + { + TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_ENABLE); + TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_ENABLE); + __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC1); + __HAL_TIM_ENABLE_IT(htim, TIM_IT_CC2); + break; + } + } + + /* Enable the Peripheral */ + __HAL_TIM_ENABLE(htim); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the TIM Encoder Interface in interrupt mode. + * @param htim: pointer to a TIM_HandleTypeDef structure that contains + * the configuration information for TIM module. + * @param Channel: TIM Channels to be disabled. + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_Encoder_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_TIM_CC2_INSTANCE(htim->Instance)); + + /* Disable the Input Capture channels 1 and 2 + (in the EncoderInterface the two possible channels that can be used are TIM_CHANNEL_1 and TIM_CHANNEL_2) */ + if(Channel == TIM_CHANNEL_1) + { + TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_DISABLE); + + /* Disable the capture compare Interrupts 1 */ + __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC1); + } + else if(Channel == TIM_CHANNEL_2) + { + TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_DISABLE); + + /* Disable the capture compare Interrupts 2 */ + __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC2); + } + else + { + TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_DISABLE); + TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_DISABLE); + + /* Disable the capture compare Interrupts 1 and 2 */ + __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC1); + __HAL_TIM_DISABLE_IT(htim, TIM_IT_CC2); + } + + /* Disable the Peripheral */ + __HAL_TIM_DISABLE(htim); + + /* Change the htim state */ + htim->State = HAL_TIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Starts the TIM Encoder Interface in DMA mode. + * @param htim: pointer to a TIM_HandleTypeDef structure that contains + * the configuration information for TIM module. + * @param Channel: TIM Channels to be enabled. + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @param pData1: The destination Buffer address for IC1. + * @param pData2: The destination Buffer address for IC2. + * @param Length: The length of data to be transferred from TIM peripheral to memory. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_Encoder_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel, uint32_t *pData1, uint32_t *pData2, uint16_t Length) +{ + /* Check the parameters */ + assert_param(IS_TIM_DMA_CC_INSTANCE(htim->Instance)); + + if((htim->State == HAL_TIM_STATE_BUSY)) + { + return HAL_BUSY; + } + else if((htim->State == HAL_TIM_STATE_READY)) + { + if((((pData1 == 0) || (pData2 == 0) )) && (Length > 0)) + { + return HAL_ERROR; + } + else + { + htim->State = HAL_TIM_STATE_BUSY; + } + } + + switch (Channel) + { + case TIM_CHANNEL_1: + { + /* Set the DMA Period elapsed callback */ + htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = HAL_TIM_DMACaptureCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = HAL_TIM_DMAError ; + + /* Enable the DMA Stream */ + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)&htim->Instance->CCR1, (uint32_t )pData1, Length); + + /* Enable the TIM Input Capture DMA request */ + __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC1); + + /* Enable the Peripheral */ + __HAL_TIM_ENABLE(htim); + + /* Enable the Capture compare channel */ + TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_ENABLE); + } + break; + + case TIM_CHANNEL_2: + { + /* Set the DMA Period elapsed callback */ + htim->hdma[TIM_DMA_ID_CC2]->XferCpltCallback = HAL_TIM_DMACaptureCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC2]->XferErrorCallback = HAL_TIM_DMAError; + /* Enable the DMA Stream */ + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)&htim->Instance->CCR2, (uint32_t)pData2, Length); + + /* Enable the TIM Input Capture DMA request */ + __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC2); + + /* Enable the Peripheral */ + __HAL_TIM_ENABLE(htim); + + /* Enable the Capture compare channel */ + TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_ENABLE); + } + break; + + case TIM_CHANNEL_ALL: + { + /* Set the DMA Period elapsed callback */ + htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = HAL_TIM_DMACaptureCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = HAL_TIM_DMAError ; + + /* Enable the DMA Stream */ + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)&htim->Instance->CCR1, (uint32_t)pData1, Length); + + /* Set the DMA Period elapsed callback */ + htim->hdma[TIM_DMA_ID_CC2]->XferCpltCallback = HAL_TIM_DMACaptureCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC2]->XferErrorCallback = HAL_TIM_DMAError ; + + /* Enable the DMA Stream */ + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)&htim->Instance->CCR2, (uint32_t)pData2, Length); + + /* Enable the Peripheral */ + __HAL_TIM_ENABLE(htim); + + /* Enable the Capture compare channel */ + TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_ENABLE); + TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_ENABLE); + + /* Enable the TIM Input Capture DMA request */ + __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC1); + /* Enable the TIM Input Capture DMA request */ + __HAL_TIM_ENABLE_DMA(htim, TIM_DMA_CC2); + } + break; + + default: + break; + } + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the TIM Encoder Interface in DMA mode. + * @param htim: pointer to a TIM_HandleTypeDef structure that contains + * the configuration information for TIM module. + * @param Channel: TIM Channels to be enabled. + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_Encoder_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_TIM_DMA_CC_INSTANCE(htim->Instance)); + + /* Disable the Input Capture channels 1 and 2 + (in the EncoderInterface the two possible channels that can be used are TIM_CHANNEL_1 and TIM_CHANNEL_2) */ + if(Channel == TIM_CHANNEL_1) + { + TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_DISABLE); + + /* Disable the capture compare DMA Request 1 */ + __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC1); + } + else if(Channel == TIM_CHANNEL_2) + { + TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_DISABLE); + + /* Disable the capture compare DMA Request 2 */ + __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC2); + } + else + { + TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_1, TIM_CCx_DISABLE); + TIM_CCxChannelCmd(htim->Instance, TIM_CHANNEL_2, TIM_CCx_DISABLE); + + /* Disable the capture compare DMA Request 1 and 2 */ + __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC1); + __HAL_TIM_DISABLE_DMA(htim, TIM_DMA_CC2); + } + + /* Disable the Peripheral */ + __HAL_TIM_DISABLE(htim); + + /* Change the htim state */ + htim->State = HAL_TIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @} + */ +/** @defgroup TIM_Group7 TIM IRQ handler management + * @brief IRQ handler management + * +@verbatim + ============================================================================== + ##### IRQ handler management ##### + ============================================================================== + [..] + This section provides Timer IRQ handler function. + +@endverbatim + * @{ + */ +/** + * @brief This function handles TIM interrupts requests. + * @param htim: TIM handle + * @retval None + */ +void HAL_TIM_IRQHandler(TIM_HandleTypeDef *htim) +{ + /* Capture compare 1 event */ + if(__HAL_TIM_GET_FLAG(htim, TIM_FLAG_CC1) != RESET) + { + if(__HAL_TIM_GET_ITSTATUS(htim, TIM_IT_CC1) !=RESET) + { + { + __HAL_TIM_CLEAR_IT(htim, TIM_IT_CC1); + htim->Channel = HAL_TIM_ACTIVE_CHANNEL_1; + + /* Input capture event */ + if((htim->Instance->CCMR1 & TIM_CCMR1_CC1S) != 0x00) + { + HAL_TIM_IC_CaptureCallback(htim); + } + /* Output compare event */ + else + { + HAL_TIM_OC_DelayElapsedCallback(htim); + HAL_TIM_PWM_PulseFinishedCallback(htim); + } + htim->Channel = HAL_TIM_ACTIVE_CHANNEL_CLEARED; + } + } + } + /* Capture compare 2 event */ + if(__HAL_TIM_GET_FLAG(htim, TIM_FLAG_CC2) != RESET) + { + if(__HAL_TIM_GET_ITSTATUS(htim, TIM_IT_CC2) !=RESET) + { + __HAL_TIM_CLEAR_IT(htim, TIM_IT_CC2); + htim->Channel = HAL_TIM_ACTIVE_CHANNEL_2; + /* Input capture event */ + if((htim->Instance->CCMR1 & TIM_CCMR1_CC2S) != 0x00) + { + HAL_TIM_IC_CaptureCallback(htim); + } + /* Output compare event */ + else + { + HAL_TIM_OC_DelayElapsedCallback(htim); + HAL_TIM_PWM_PulseFinishedCallback(htim); + } + htim->Channel = HAL_TIM_ACTIVE_CHANNEL_CLEARED; + } + } + /* Capture compare 3 event */ + if(__HAL_TIM_GET_FLAG(htim, TIM_FLAG_CC3) != RESET) + { + if(__HAL_TIM_GET_ITSTATUS(htim, TIM_IT_CC3) !=RESET) + { + __HAL_TIM_CLEAR_IT(htim, TIM_IT_CC3); + htim->Channel = HAL_TIM_ACTIVE_CHANNEL_3; + /* Input capture event */ + if((htim->Instance->CCMR2 & TIM_CCMR2_CC3S) != 0x00) + { + HAL_TIM_IC_CaptureCallback(htim); + } + /* Output compare event */ + else + { + HAL_TIM_OC_DelayElapsedCallback(htim); + HAL_TIM_PWM_PulseFinishedCallback(htim); + } + htim->Channel = HAL_TIM_ACTIVE_CHANNEL_CLEARED; + } + } + /* Capture compare 4 event */ + if(__HAL_TIM_GET_FLAG(htim, TIM_FLAG_CC4) != RESET) + { + if(__HAL_TIM_GET_ITSTATUS(htim, TIM_IT_CC4) !=RESET) + { + __HAL_TIM_CLEAR_IT(htim, TIM_IT_CC4); + htim->Channel = HAL_TIM_ACTIVE_CHANNEL_4; + /* Input capture event */ + if((htim->Instance->CCMR2 & TIM_CCMR2_CC4S) != 0x00) + { + HAL_TIM_IC_CaptureCallback(htim); + } + /* Output compare event */ + else + { + HAL_TIM_OC_DelayElapsedCallback(htim); + HAL_TIM_PWM_PulseFinishedCallback(htim); + } + htim->Channel = HAL_TIM_ACTIVE_CHANNEL_CLEARED; + } + } + /* TIM Update event */ + if(__HAL_TIM_GET_FLAG(htim, TIM_FLAG_UPDATE) != RESET) + { + if(__HAL_TIM_GET_ITSTATUS(htim, TIM_IT_UPDATE) !=RESET) + { + __HAL_TIM_CLEAR_IT(htim, TIM_IT_UPDATE); + HAL_TIM_PeriodElapsedCallback(htim); + } + } + /* TIM Trigger detection event */ + if(__HAL_TIM_GET_FLAG(htim, TIM_FLAG_TRIGGER) != RESET) + { + if(__HAL_TIM_GET_ITSTATUS(htim, TIM_IT_TRIGGER) !=RESET) + { + __HAL_TIM_CLEAR_IT(htim, TIM_IT_TRIGGER); + HAL_TIM_TriggerCallback(htim); + } + } +} + +/** + * @} + */ +/** @defgroup TIM_Group3 Peripheral Control functions + * @brief Peripheral Control functions + * +@verbatim + ============================================================================== + ##### Peripheral Control functions ##### + ============================================================================== + [..] + This section provides functions allowing to: + (+) Configure The Input Output channels for OC, PWM, IC or One Pulse mode. + (+) Configure External Clock source. + (+) Configure Master and the Slave synchronization. + (+) Configure the DMA Burst Mode. + +@endverbatim + * @{ + */ +/** + * @brief Initializes the TIM Output Compare Channels according to the specified + * parameters in the TIM_OC_InitTypeDef. + * @param htim: pointer to a TIM_HandleTypeDef structure that contains + * the configuration information for TIM module. + * @param sConfig: TIM Output Compare configuration structure + * @param Channel: TIM Channels to be enabled. + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @arg TIM_CHANNEL_3: TIM Channel 3 selected + * @arg TIM_CHANNEL_4: TIM Channel 4 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_OC_ConfigChannel(TIM_HandleTypeDef *htim, TIM_OC_InitTypeDef* sConfig, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_TIM_CHANNELS(Channel)); + assert_param(IS_TIM_OC_MODE(sConfig->OCMode)); + assert_param(IS_TIM_OC_POLARITY(sConfig->OCPolarity)); + assert_param(IS_TIM_FAST_STATE(sConfig->OCFastMode)); + + /* Check input state */ + __HAL_LOCK(htim); + + htim->State = HAL_TIM_STATE_BUSY; + + switch (Channel) + { + case TIM_CHANNEL_1: + { + assert_param(IS_TIM_CC1_INSTANCE(htim->Instance)); + /* Configure the TIM Channel 1 in Output Compare */ + TIM_OC1_SetConfig(htim->Instance, sConfig); + } + break; + + case TIM_CHANNEL_2: + { + assert_param(IS_TIM_CC2_INSTANCE(htim->Instance)); + /* Configure the TIM Channel 2 in Output Compare */ + TIM_OC2_SetConfig(htim->Instance, sConfig); + } + break; + + case TIM_CHANNEL_3: + { + assert_param(IS_TIM_CC3_INSTANCE(htim->Instance)); + /* Configure the TIM Channel 3 in Output Compare */ + TIM_OC3_SetConfig(htim->Instance, sConfig); + } + break; + + case TIM_CHANNEL_4: + { + assert_param(IS_TIM_CC4_INSTANCE(htim->Instance)); + /* Configure the TIM Channel 4 in Output Compare */ + TIM_OC4_SetConfig(htim->Instance, sConfig); + } + break; + + default: + break; + } + htim->State = HAL_TIM_STATE_READY; + + __HAL_UNLOCK(htim); + + return HAL_OK; +} + +/** + * @brief Initializes the TIM Input Capture Channels according to the specified + * parameters in the TIM_IC_InitTypeDef. + * @param htim: pointer to a TIM_HandleTypeDef structure that contains + * the configuration information for TIM module. + * @param sConfig: TIM Input Capture configuration structure + * @param Channel: TIM Channels to be enabled. + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @arg TIM_CHANNEL_3: TIM Channel 3 selected + * @arg TIM_CHANNEL_4: TIM Channel 4 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_IC_ConfigChannel(TIM_HandleTypeDef *htim, TIM_IC_InitTypeDef* sConfig, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_TIM_CC1_INSTANCE(htim->Instance)); + assert_param(IS_TIM_IC_POLARITY(sConfig->ICPolarity)); + assert_param(IS_TIM_IC_SELECTION(sConfig->ICSelection)); + assert_param(IS_TIM_IC_PRESCALER(sConfig->ICPrescaler)); + assert_param(IS_TIM_IC_FILTER(sConfig->ICFilter)); + + __HAL_LOCK(htim); + + htim->State = HAL_TIM_STATE_BUSY; + + if (Channel == TIM_CHANNEL_1) + { + /* TI1 Configuration */ + TIM_TI1_SetConfig(htim->Instance, + sConfig->ICPolarity, + sConfig->ICSelection, + sConfig->ICFilter); + + /* Reset the IC1PSC Bits */ + htim->Instance->CCMR1 &= ~TIM_CCMR1_IC1PSC; + + /* Set the IC1PSC value */ + htim->Instance->CCMR1 |= sConfig->ICPrescaler; + } + else if (Channel == TIM_CHANNEL_2) + { + /* TI2 Configuration */ + assert_param(IS_TIM_CC2_INSTANCE(htim->Instance)); + + TIM_TI2_SetConfig(htim->Instance, + sConfig->ICPolarity, + sConfig->ICSelection, + sConfig->ICFilter); + + /* Reset the IC2PSC Bits */ + htim->Instance->CCMR1 &= ~TIM_CCMR1_IC2PSC; + + /* Set the IC2PSC value */ + htim->Instance->CCMR1 |= (sConfig->ICPrescaler << 8); + } + else if (Channel == TIM_CHANNEL_3) + { + /* TI3 Configuration */ + assert_param(IS_TIM_CC3_INSTANCE(htim->Instance)); + + TIM_TI3_SetConfig(htim->Instance, + sConfig->ICPolarity, + sConfig->ICSelection, + sConfig->ICFilter); + + /* Reset the IC3PSC Bits */ + htim->Instance->CCMR2 &= ~TIM_CCMR2_IC3PSC; + + /* Set the IC3PSC value */ + htim->Instance->CCMR2 |= sConfig->ICPrescaler; + } + else + { + /* TI4 Configuration */ + assert_param(IS_TIM_CC4_INSTANCE(htim->Instance)); + + TIM_TI4_SetConfig(htim->Instance, + sConfig->ICPolarity, + sConfig->ICSelection, + sConfig->ICFilter); + + /* Reset the IC4PSC Bits */ + htim->Instance->CCMR2 &= ~TIM_CCMR2_IC4PSC; + + /* Set the IC4PSC value */ + htim->Instance->CCMR2 |= (sConfig->ICPrescaler << 8); + } + + htim->State = HAL_TIM_STATE_READY; + + __HAL_UNLOCK(htim); + + return HAL_OK; +} + +/** + * @brief Initializes the TIM PWM channels according to the specified + * parameters in the TIM_OC_InitTypeDef. + * @param htim: pointer to a TIM_HandleTypeDef structure that contains + * the configuration information for TIM module. + * @param sConfig: TIM PWM configuration structure + * @param Channel: TIM Channels to be enabled. + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @arg TIM_CHANNEL_3: TIM Channel 3 selected + * @arg TIM_CHANNEL_4: TIM Channel 4 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_PWM_ConfigChannel(TIM_HandleTypeDef *htim, TIM_OC_InitTypeDef* sConfig, uint32_t Channel) +{ + __HAL_LOCK(htim); + + /* Check the parameters */ + assert_param(IS_TIM_CHANNELS(Channel)); + assert_param(IS_TIM_PWM_MODE(sConfig->OCMode)); + assert_param(IS_TIM_OC_POLARITY(sConfig->OCPolarity)); + + htim->State = HAL_TIM_STATE_BUSY; + + switch (Channel) + { + case TIM_CHANNEL_1: + { + assert_param(IS_TIM_CC1_INSTANCE(htim->Instance)); + /* Configure the Channel 1 in PWM mode */ + TIM_OC1_SetConfig(htim->Instance, sConfig); + + /* Set the Preload enable bit for channel1 */ + htim->Instance->CCMR1 |= TIM_CCMR1_OC1PE; + + /* Configure the Output Fast mode */ + htim->Instance->CCMR1 &= ~TIM_CCMR1_OC1FE; + htim->Instance->CCMR1 |= sConfig->OCFastMode; + } + break; + + case TIM_CHANNEL_2: + { + assert_param(IS_TIM_CC2_INSTANCE(htim->Instance)); + /* Configure the Channel 2 in PWM mode */ + TIM_OC2_SetConfig(htim->Instance, sConfig); + + /* Set the Preload enable bit for channel2 */ + htim->Instance->CCMR1 |= TIM_CCMR1_OC2PE; + + /* Configure the Output Fast mode */ + htim->Instance->CCMR1 &= ~TIM_CCMR1_OC2FE; + htim->Instance->CCMR1 |= sConfig->OCFastMode << 8; + } + break; + + case TIM_CHANNEL_3: + { + assert_param(IS_TIM_CC3_INSTANCE(htim->Instance)); + /* Configure the Channel 3 in PWM mode */ + TIM_OC3_SetConfig(htim->Instance, sConfig); + + /* Set the Preload enable bit for channel3 */ + htim->Instance->CCMR2 |= TIM_CCMR2_OC3PE; + + /* Configure the Output Fast mode */ + htim->Instance->CCMR2 &= ~TIM_CCMR2_OC3FE; + htim->Instance->CCMR2 |= sConfig->OCFastMode; + } + break; + + case TIM_CHANNEL_4: + { + assert_param(IS_TIM_CC4_INSTANCE(htim->Instance)); + /* Configure the Channel 4 in PWM mode */ + TIM_OC4_SetConfig(htim->Instance, sConfig); + + /* Set the Preload enable bit for channel4 */ + htim->Instance->CCMR2 |= TIM_CCMR2_OC4PE; + + /* Configure the Output Fast mode */ + htim->Instance->CCMR2 &= ~TIM_CCMR2_OC4FE; + htim->Instance->CCMR2 |= sConfig->OCFastMode << 8; + } + break; + + default: + break; + } + + htim->State = HAL_TIM_STATE_READY; + + __HAL_UNLOCK(htim); + + return HAL_OK; +} + +/** + * @brief Initializes the TIM One Pulse Channels according to the specified + * parameters in the TIM_OnePulse_InitTypeDef. + * @param htim: pointer to a TIM_HandleTypeDef structure that contains + * the configuration information for TIM module. + * @param sConfig: TIM One Pulse configuration structure + * @param OutputChannel : TIM Channels to be enabled + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @param InputChannel: TIM Channels to be enabled. + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_OnePulse_ConfigChannel(TIM_HandleTypeDef *htim, TIM_OnePulse_InitTypeDef* sConfig, uint32_t OutputChannel, uint32_t InputChannel) +{ + TIM_OC_InitTypeDef temp1; + + /* Check the parameters */ + assert_param(IS_TIM_OPM_CHANNELS(OutputChannel)); + assert_param(IS_TIM_OPM_CHANNELS(InputChannel)); + + if(OutputChannel != InputChannel) + { + __HAL_LOCK(htim); + + htim->State = HAL_TIM_STATE_BUSY; + + /* Extract the Ouput compare configuration from sConfig structure */ + temp1.OCMode = sConfig->OCMode; + temp1.Pulse = sConfig->Pulse; + temp1.OCPolarity = sConfig->OCPolarity; + + switch (OutputChannel) + { + case TIM_CHANNEL_1: + { + assert_param(IS_TIM_CC1_INSTANCE(htim->Instance)); + + TIM_OC1_SetConfig(htim->Instance, &temp1); + } + break; + case TIM_CHANNEL_2: + { + assert_param(IS_TIM_CC2_INSTANCE(htim->Instance)); + + TIM_OC2_SetConfig(htim->Instance, &temp1); + } + break; + default: + break; + } + switch (InputChannel) + { + case TIM_CHANNEL_1: + { + assert_param(IS_TIM_CC1_INSTANCE(htim->Instance)); + + TIM_TI1_SetConfig(htim->Instance, sConfig->ICPolarity, + sConfig->ICSelection, sConfig->ICFilter); + + /* Reset the IC1PSC Bits */ + htim->Instance->CCMR1 &= ~TIM_CCMR1_IC1PSC; + + /* Select the Trigger source */ + htim->Instance->SMCR &= ~TIM_SMCR_TS; + htim->Instance->SMCR |= TIM_TS_TI1FP1; + + /* Select the Slave Mode */ + htim->Instance->SMCR &= ~TIM_SMCR_SMS; + htim->Instance->SMCR |= TIM_SLAVEMODE_TRIGGER; + } + break; + case TIM_CHANNEL_2: + { + assert_param(IS_TIM_CC2_INSTANCE(htim->Instance)); + + TIM_TI2_SetConfig(htim->Instance, sConfig->ICPolarity, + sConfig->ICSelection, sConfig->ICFilter); + + /* Reset the IC2PSC Bits */ + htim->Instance->CCMR1 &= ~TIM_CCMR1_IC2PSC; + + /* Select the Trigger source */ + htim->Instance->SMCR &= ~TIM_SMCR_TS; + htim->Instance->SMCR |= TIM_TS_TI2FP2; + + /* Select the Slave Mode */ + htim->Instance->SMCR &= ~TIM_SMCR_SMS; + htim->Instance->SMCR |= TIM_SLAVEMODE_TRIGGER; + } + break; + + default: + break; + } + + htim->State = HAL_TIM_STATE_READY; + + __HAL_UNLOCK(htim); + + return HAL_OK; + } + else + { + return HAL_ERROR; + } +} + +/** + * @brief Configure the DMA Burst to transfer Data from the memory to the TIM peripheral + * @param htim: pointer to a TIM_HandleTypeDef structure that contains + * the configuration information for TIM module. + * @param BurstBaseAddress: TIM Base address from when the DMA will starts the Data write. + * This parameters can be on of the following values: + * @arg TIM_DMABase_CR1 + * @arg TIM_DMABase_CR2 + * @arg TIM_DMABase_SMCR + * @arg TIM_DMABase_DIER + * @arg TIM_DMABase_SR + * @arg TIM_DMABase_EGR + * @arg TIM_DMABase_CCMR1 + * @arg TIM_DMABase_CCMR2 + * @arg TIM_DMABase_CCER + * @arg TIM_DMABase_CNT + * @arg TIM_DMABase_PSC + * @arg TIM_DMABase_ARR + * @arg TIM_DMABase_CCR1 + * @arg TIM_DMABase_CCR2 + * @arg TIM_DMABase_CCR3 + * @arg TIM_DMABase_CCR4 + * @arg TIM_DMABase_DCR + * @param BurstRequestSrc: TIM DMA Request sources. + * This parameters can be on of the following values: + * @arg TIM_DMA_UPDATE: TIM update Interrupt source + * @arg TIM_DMA_CC1: TIM Capture Compare 1 DMA source + * @arg TIM_DMA_CC2: TIM Capture Compare 2 DMA source + * @arg TIM_DMA_CC3: TIM Capture Compare 3 DMA source + * @arg TIM_DMA_CC4: TIM Capture Compare 4 DMA source + * @arg TIM_DMA_TRIGGER: TIM Trigger DMA source + * @param BurstBuffer: The Buffer address. + * @param BurstLength: DMA Burst length. This parameter can be one value + * between TIM_DMABurstLength_1Transfer and TIM_DMABurstLength_18Transfers. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_DMABurst_WriteStart(TIM_HandleTypeDef *htim, uint32_t BurstBaseAddress, uint32_t BurstRequestSrc, + uint32_t* BurstBuffer, uint32_t BurstLength) +{ + /* Check the parameters */ + assert_param(IS_TIM_DMABURST_INSTANCE(htim->Instance)); + assert_param(IS_TIM_DMA_BASE(BurstBaseAddress)); + assert_param(IS_TIM_DMA_SOURCE(BurstRequestSrc)); + assert_param(IS_TIM_DMA_LENGTH(BurstLength)); + + if((htim->State == HAL_TIM_STATE_BUSY)) + { + return HAL_BUSY; + } + else if((htim->State == HAL_TIM_STATE_READY)) + { + if((BurstBuffer == 0 ) && (BurstLength > 0)) + { + return HAL_ERROR; + } + else + { + htim->State = HAL_TIM_STATE_BUSY; + } + } + switch(BurstRequestSrc) + { + case TIM_DMA_UPDATE: + { + /* Set the DMA Period elapsed callback */ + htim->hdma[TIM_DMA_ID_UPDATE]->XferCpltCallback = TIM_DMAPeriodElapsedCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_UPDATE]->XferErrorCallback = HAL_TIM_DMAError ; + + /* Enable the DMA Stream */ + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_UPDATE], (uint32_t)BurstBuffer, (uint32_t)&htim->Instance->DMAR, ((BurstLength) >> 8) + 1); + } + break; + case TIM_DMA_CC1: + { + /* Set the DMA Period elapsed callback */ + htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = HAL_TIM_DMADelayPulseCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = HAL_TIM_DMAError ; + + /* Enable the DMA Stream */ + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)BurstBuffer, (uint32_t)&htim->Instance->DMAR, ((BurstLength) >> 8) + 1); + } + break; + case TIM_DMA_CC2: + { + /* Set the DMA Period elapsed callback */ + htim->hdma[TIM_DMA_ID_CC2]->XferCpltCallback = HAL_TIM_DMADelayPulseCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC2]->XferErrorCallback = HAL_TIM_DMAError ; + + /* Enable the DMA Stream */ + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)BurstBuffer, (uint32_t)&htim->Instance->DMAR, ((BurstLength) >> 8) + 1); + } + break; + case TIM_DMA_CC3: + { + /* Set the DMA Period elapsed callback */ + htim->hdma[TIM_DMA_ID_CC3]->XferCpltCallback = HAL_TIM_DMADelayPulseCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC3]->XferErrorCallback = HAL_TIM_DMAError ; + + /* Enable the DMA Stream */ + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC3], (uint32_t)BurstBuffer, (uint32_t)&htim->Instance->DMAR, ((BurstLength) >> 8) + 1); + } + break; + case TIM_DMA_CC4: + { + /* Set the DMA Period elapsed callback */ + htim->hdma[TIM_DMA_ID_CC4]->XferCpltCallback = HAL_TIM_DMADelayPulseCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC4]->XferErrorCallback = HAL_TIM_DMAError ; + + /* Enable the DMA Stream */ + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC4], (uint32_t)BurstBuffer, (uint32_t)&htim->Instance->DMAR, ((BurstLength) >> 8) + 1); + } + break; + case TIM_DMA_TRIGGER: + { + /* Set the DMA Period elapsed callback */ + htim->hdma[TIM_DMA_ID_TRIGGER]->XferCpltCallback = TIM_DMATriggerCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_TRIGGER]->XferErrorCallback = HAL_TIM_DMAError ; + + /* Enable the DMA Stream */ + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_TRIGGER], (uint32_t)BurstBuffer, (uint32_t)&htim->Instance->DMAR, ((BurstLength) >> 8) + 1); + } + break; + default: + break; + } + /* configure the DMA Burst Mode */ + htim->Instance->DCR = BurstBaseAddress | BurstLength; + + /* Enable the TIM DMA Request */ + __HAL_TIM_ENABLE_DMA(htim, BurstRequestSrc); + + htim->State = HAL_TIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the TIM DMA Burst mode + * @param htim: pointer to a TIM_HandleTypeDef structure that contains + * the configuration information for TIM module. + * @param BurstRequestSrc: TIM DMA Request sources to disable + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_DMABurst_WriteStop(TIM_HandleTypeDef *htim, uint32_t BurstRequestSrc) +{ + /* Check the parameters */ + assert_param(IS_TIM_DMA_SOURCE(BurstRequestSrc)); + + /* Disable the TIM Update DMA request */ + __HAL_TIM_DISABLE_DMA(htim, BurstRequestSrc); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Configure the DMA Burst to transfer Data from the TIM peripheral to the memory + * @param htim: pointer to a TIM_HandleTypeDef structure that contains + * the configuration information for TIM module. + * @param BurstBaseAddress: TIM Base address from when the DMA will starts the Data read. + * This parameters can be on of the following values: + * @arg TIM_DMABase_CR1 + * @arg TIM_DMABase_CR2 + * @arg TIM_DMABase_SMCR + * @arg TIM_DMABase_DIER + * @arg TIM_DMABase_SR + * @arg TIM_DMABase_EGR + * @arg TIM_DMABase_CCMR1 + * @arg TIM_DMABase_CCMR2 + * @arg TIM_DMABase_CCER + * @arg TIM_DMABase_CNT + * @arg TIM_DMABase_PSC + * @arg TIM_DMABase_ARR + * @arg TIM_DMABase_CCR1 + * @arg TIM_DMABase_CCR2 + * @arg TIM_DMABase_CCR3 + * @arg TIM_DMABase_CCR4 + * @arg TIM_DMABase_DCR + * @param BurstRequestSrc: TIM DMA Request sources. + * This parameters can be on of the following values: + * @arg TIM_DMA_UPDATE: TIM update Interrupt source + * @arg TIM_DMA_CC1: TIM Capture Compare 1 DMA source + * @arg TIM_DMA_CC2: TIM Capture Compare 2 DMA source + * @arg TIM_DMA_CC3: TIM Capture Compare 3 DMA source + * @arg TIM_DMA_CC4: TIM Capture Compare 4 DMA source + * @arg TIM_DMA_TRIGGER: TIM Trigger DMA source + * @param BurstBuffer: The Buffer address. + * @param BurstLength: DMA Burst length. This parameter can be one value + * between TIM_DMABurstLength_1Transfer and TIM_DMABurstLength_18Transfers. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_DMABurst_ReadStart(TIM_HandleTypeDef *htim, uint32_t BurstBaseAddress, uint32_t BurstRequestSrc, + uint32_t *BurstBuffer, uint32_t BurstLength) +{ + /* Check the parameters */ + assert_param(IS_TIM_DMABURST_INSTANCE(htim->Instance)); + assert_param(IS_TIM_DMA_BASE(BurstBaseAddress)); + assert_param(IS_TIM_DMA_SOURCE(BurstRequestSrc)); + assert_param(IS_TIM_DMA_LENGTH(BurstLength)); + + if((htim->State == HAL_TIM_STATE_BUSY)) + { + return HAL_BUSY; + } + else if((htim->State == HAL_TIM_STATE_READY)) + { + if((BurstBuffer == 0 ) && (BurstLength > 0)) + { + return HAL_ERROR; + } + else + { + htim->State = HAL_TIM_STATE_BUSY; + } + } + switch(BurstRequestSrc) + { + case TIM_DMA_UPDATE: + { + /* Set the DMA Period elapsed callback */ + htim->hdma[TIM_DMA_ID_UPDATE]->XferCpltCallback = TIM_DMAPeriodElapsedCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_UPDATE]->XferErrorCallback = HAL_TIM_DMAError ; + + /* Enable the DMA Stream */ + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_UPDATE], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, ((BurstLength) >> 8) + 1); + } + break; + case TIM_DMA_CC1: + { + /* Set the DMA Period elapsed callback */ + htim->hdma[TIM_DMA_ID_CC1]->XferCpltCallback = HAL_TIM_DMACaptureCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC1]->XferErrorCallback = HAL_TIM_DMAError ; + + /* Enable the DMA Stream */ + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC1], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, ((BurstLength) >> 8) + 1); + } + break; + case TIM_DMA_CC2: + { + /* Set the DMA Period elapsed callback */ + htim->hdma[TIM_DMA_ID_CC2]->XferCpltCallback = HAL_TIM_DMACaptureCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC2]->XferErrorCallback = HAL_TIM_DMAError ; + + /* Enable the DMA Stream */ + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC2], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, ((BurstLength) >> 8) + 1); + } + break; + case TIM_DMA_CC3: + { + /* Set the DMA Period elapsed callback */ + htim->hdma[TIM_DMA_ID_CC3]->XferCpltCallback = HAL_TIM_DMACaptureCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC3]->XferErrorCallback = HAL_TIM_DMAError ; + + /* Enable the DMA Stream */ + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC3], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, ((BurstLength) >> 8) + 1); + } + break; + case TIM_DMA_CC4: + { + /* Set the DMA Period elapsed callback */ + htim->hdma[TIM_DMA_ID_CC4]->XferCpltCallback = HAL_TIM_DMACaptureCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_CC4]->XferErrorCallback = HAL_TIM_DMAError ; + + /* Enable the DMA Stream */ + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_CC4], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, ((BurstLength) >> 8) + 1); + } + break; + case TIM_DMA_TRIGGER: + { + /* Set the DMA Period elapsed callback */ + htim->hdma[TIM_DMA_ID_TRIGGER]->XferCpltCallback = TIM_DMATriggerCplt; + + /* Set the DMA error callback */ + htim->hdma[TIM_DMA_ID_TRIGGER]->XferErrorCallback = HAL_TIM_DMAError ; + + /* Enable the DMA Stream */ + HAL_DMA_Start_IT(htim->hdma[TIM_DMA_ID_TRIGGER], (uint32_t)&htim->Instance->DMAR, (uint32_t)BurstBuffer, ((BurstLength) >> 8) + 1); + } + break; + default: + break; + } + + /* configure the DMA Burst Mode */ + htim->Instance->DCR = BurstBaseAddress | BurstLength; + + /* Enable the TIM DMA Request */ + __HAL_TIM_ENABLE_DMA(htim, BurstRequestSrc); + + htim->State = HAL_TIM_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stop the DMA burst reading + * @param htim: pointer to a TIM_HandleTypeDef structure that contains + * the configuration information for TIM module. + * @param BurstRequestSrc: TIM DMA Request sources to disable. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_DMABurst_ReadStop(TIM_HandleTypeDef *htim, uint32_t BurstRequestSrc) +{ + /* Check the parameters */ + assert_param(IS_TIM_DMA_SOURCE(BurstRequestSrc)); + + /* Disable the TIM Update DMA request */ + __HAL_TIM_DISABLE_DMA(htim, BurstRequestSrc); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Generate a software event + * @param htim: pointer to a TIM_HandleTypeDef structure that contains + * the configuration information for TIM module. + * @param EventSource: specifies the event source. + * This parameter can be one of the following values: + * @arg TIM_EventSource_Update: Timer update Event source + * @arg TIM_EventSource_CC1: Timer Capture Compare 1 Event source + * @arg TIM_EventSource_CC2: Timer Capture Compare 2 Event source + * @arg TIM_EventSource_CC3: Timer Capture Compare 3 Event source + * @arg TIM_EventSource_CC4: Timer Capture Compare 4 Event source + * @arg TIM_EventSource_Trigger: Timer Trigger Event source + * @note TIM6 can only generate an update event. + * @retval HAL status + */ + +HAL_StatusTypeDef HAL_TIM_GenerateEvent(TIM_HandleTypeDef *htim, uint32_t EventSource) +{ + /* Check the parameters */ + assert_param(IS_TIM_INSTANCE(htim->Instance)); + assert_param(IS_TIM_EVENT_SOURCE(EventSource)); + + /* Process Locked */ + __HAL_LOCK(htim); + + /* Change the TIM state */ + htim->State = HAL_TIM_STATE_BUSY; + + /* Set the event sources */ + htim->Instance->EGR = EventSource; + + /* Change the TIM state */ + htim->State = HAL_TIM_STATE_READY; + + __HAL_UNLOCK(htim); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Configures the OCRef clear feature + * @param htim: pointer to a TIM_HandleTypeDef structure that contains + * the configuration information for TIM module. + * @param sClearInputConfig: pointer to a TIM_ClearInputConfigTypeDef structure that + * contains the OCREF clear feature and parameters for the TIM peripheral. + * @param Channel: specifies the TIM Channel. + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @arg TIM_CHANNEL_3: TIM Channel 3 selected + * @arg TIM_CHANNEL_4: TIM Channel 4 selected + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_ConfigOCrefClear(TIM_HandleTypeDef *htim, TIM_ClearInputConfigTypeDef * sClearInputConfig, uint32_t Channel) +{ + /* Check the parameters */ + assert_param(IS_TIM_CC1_INSTANCE(htim->Instance)); + assert_param(IS_TIM_CHANNELS(Channel)); + assert_param(IS_TIM_CLEARINPUT_SOURCE(sClearInputConfig->ClearInputSource)); + assert_param(IS_TIM_CLEARINPUT_POLARITY(sClearInputConfig->ClearInputPolarity)); + assert_param(IS_TIM_CLEARINPUT_PRESCALER(sClearInputConfig->ClearInputPrescaler)); + assert_param(IS_TIM_CLEARINPUT_FILTER(sClearInputConfig->ClearInputFilter)); + + /* Process Locked */ + __HAL_LOCK(htim); + + htim->State = HAL_TIM_STATE_BUSY; + + if(sClearInputConfig->ClearInputSource == TIM_CLEARINPUTSOURCE_ETR) + { + TIM_ETR_SetConfig(htim->Instance, + sClearInputConfig->ClearInputPrescaler, + sClearInputConfig->ClearInputPolarity, + sClearInputConfig->ClearInputFilter); + } + + switch (Channel) + { + case TIM_CHANNEL_1: + { + if(sClearInputConfig->ClearInputState != RESET) + { + /* Enable the Ocref clear feature for Channel 1 */ + htim->Instance->CCMR1 |= TIM_CCMR1_OC1CE; + } + else + { + /* Disable the Ocref clear feature for Channel 1 */ + htim->Instance->CCMR1 &= ~TIM_CCMR1_OC1CE; + } + } + break; + case TIM_CHANNEL_2: + { + assert_param(IS_TIM_CC2_INSTANCE(htim->Instance)); + if(sClearInputConfig->ClearInputState != RESET) + { + /* Enable the Ocref clear feature for Channel 2 */ + htim->Instance->CCMR1 |= TIM_CCMR1_OC2CE; + } + else + { + /* Disable the Ocref clear feature for Channel 2 */ + htim->Instance->CCMR1 &= ~TIM_CCMR1_OC2CE; + } + } + break; + case TIM_CHANNEL_3: + { + assert_param(IS_TIM_CC3_INSTANCE(htim->Instance)); + if(sClearInputConfig->ClearInputState != RESET) + { + /* Enable the Ocref clear feature for Channel 3 */ + htim->Instance->CCMR2 |= TIM_CCMR2_OC3CE; + } + else + { + /* Disable the Ocref clear feature for Channel 3 */ + htim->Instance->CCMR2 &= ~TIM_CCMR2_OC3CE; + } + } + break; + case TIM_CHANNEL_4: + { + assert_param(IS_TIM_CC4_INSTANCE(htim->Instance)); + if(sClearInputConfig->ClearInputState != RESET) + { + /* Enable the Ocref clear feature for Channel 4 */ + htim->Instance->CCMR2 |= TIM_CCMR2_OC4CE; + } + else + { + /* Disable the Ocref clear feature for Channel 4 */ + htim->Instance->CCMR2 &= ~TIM_CCMR2_OC4CE; + } + } + break; + default: + break; + } + + htim->State = HAL_TIM_STATE_READY; + + __HAL_UNLOCK(htim); + + return HAL_OK; +} + +/** + * @brief Configures the clock source to be used + * @param htim: pointer to a TIM_HandleTypeDef structure that contains + * the configuration information for TIM module. + * @param sClockSourceConfig: pointer to a TIM_ClockConfigTypeDef structure that + * contains the clock source information for the TIM peripheral. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_ConfigClockSource(TIM_HandleTypeDef *htim, TIM_ClockConfigTypeDef * sClockSourceConfig) +{ + uint32_t tmpsmcr = 0; + + /* Process Locked */ + __HAL_LOCK(htim); + + htim->State = HAL_TIM_STATE_BUSY; + + /* Check the parameters */ + assert_param(IS_TIM_CLOCKSOURCE(sClockSourceConfig->ClockSource)); + assert_param(IS_TIM_CLOCKPOLARITY(sClockSourceConfig->ClockPolarity)); + assert_param(IS_TIM_CLOCKPRESCALER(sClockSourceConfig->ClockPrescaler)); + assert_param(IS_TIM_CLOCKFILTER(sClockSourceConfig->ClockFilter)); + + /* Reset the SMS, TS, ECE, ETPS and ETRF bits */ + tmpsmcr = htim->Instance->SMCR; + tmpsmcr &= ~(TIM_SMCR_SMS | TIM_SMCR_TS); + tmpsmcr &= ~(TIM_SMCR_ETF | TIM_SMCR_ETPS | TIM_SMCR_ECE | TIM_SMCR_ETP); + htim->Instance->SMCR = tmpsmcr; + + switch (sClockSourceConfig->ClockSource) + { + case TIM_CLOCKSOURCE_INTERNAL: + { + assert_param(IS_TIM_INSTANCE(htim->Instance)); + /* Disable slave mode to clock the prescaler directly with the internal clock */ + htim->Instance->SMCR &= ~TIM_SMCR_SMS; + } + break; + + case TIM_CLOCKSOURCE_ETRMODE1: + { + assert_param(IS_TIM_ETR_INSTANCE(htim->Instance)); + /* Configure the ETR Clock source */ + TIM_ETR_SetConfig(htim->Instance, + sClockSourceConfig->ClockPrescaler, + sClockSourceConfig->ClockPolarity, + sClockSourceConfig->ClockFilter); + /* Get the TIMx SMCR register value */ + tmpsmcr = htim->Instance->SMCR; + /* Reset the SMS and TS Bits */ + tmpsmcr &= ~(TIM_SMCR_SMS | TIM_SMCR_TS); + /* Select the External clock mode1 and the ETRF trigger */ + tmpsmcr |= (TIM_SLAVEMODE_EXTERNAL1 | TIM_CLOCKSOURCE_ETRMODE1); + /* Write to TIMx SMCR */ + htim->Instance->SMCR = tmpsmcr; + } + break; + + case TIM_CLOCKSOURCE_ETRMODE2: + { + assert_param(IS_TIM_ETR_INSTANCE(htim->Instance)); + /* Configure the ETR Clock source */ + TIM_ETR_SetConfig(htim->Instance, + sClockSourceConfig->ClockPrescaler, + sClockSourceConfig->ClockPolarity, + sClockSourceConfig->ClockFilter); + /* Enable the External clock mode2 */ + htim->Instance->SMCR |= TIM_SMCR_ECE; + } + break; + + case TIM_CLOCKSOURCE_TI1: + { + assert_param(IS_TIM_CC1_INSTANCE(htim->Instance)); + TIM_TI1_ConfigInputStage(htim->Instance, + sClockSourceConfig->ClockPolarity, + sClockSourceConfig->ClockFilter); + TIM_ITRx_SetConfig(htim->Instance, TIM_CLOCKSOURCE_TI1); + } + break; + case TIM_CLOCKSOURCE_TI2: + { + assert_param(IS_TIM_CC2_INSTANCE(htim->Instance)); + TIM_TI2_ConfigInputStage(htim->Instance, + sClockSourceConfig->ClockPolarity, + sClockSourceConfig->ClockFilter); + TIM_ITRx_SetConfig(htim->Instance, TIM_CLOCKSOURCE_TI2); + } + break; + case TIM_CLOCKSOURCE_TI1ED: + { + assert_param(IS_TIM_CC1_INSTANCE(htim->Instance)); + TIM_TI1_ConfigInputStage(htim->Instance, + sClockSourceConfig->ClockPolarity, + sClockSourceConfig->ClockFilter); + TIM_ITRx_SetConfig(htim->Instance, TIM_CLOCKSOURCE_TI1ED); + } + break; + case TIM_CLOCKSOURCE_ITR0: + { + assert_param(IS_TIM_CC2_INSTANCE(htim->Instance)); + TIM_ITRx_SetConfig(htim->Instance, TIM_CLOCKSOURCE_ITR0); + } + break; + case TIM_CLOCKSOURCE_ITR1: + { + assert_param(IS_TIM_CC2_INSTANCE(htim->Instance)); + TIM_ITRx_SetConfig(htim->Instance, TIM_CLOCKSOURCE_ITR1); + } + break; + case TIM_CLOCKSOURCE_ITR2: + { + assert_param(IS_TIM_CC2_INSTANCE(htim->Instance)); + TIM_ITRx_SetConfig(htim->Instance, TIM_CLOCKSOURCE_ITR2); + } + break; + case TIM_CLOCKSOURCE_ITR3: + { + assert_param(IS_TIM_CC2_INSTANCE(htim->Instance)); + TIM_ITRx_SetConfig(htim->Instance, TIM_CLOCKSOURCE_ITR3); + } + break; + + default: + break; + } + htim->State = HAL_TIM_STATE_READY; + + __HAL_UNLOCK(htim); + + return HAL_OK; +} + +/** + * @brief Selects the signal connected to the TI1 input: direct from CH1_input + * or a XOR combination between CH1_input, CH2_input & CH3_input + * @param htim: pointer to a TIM_HandleTypeDef structure that contains + * the configuration information for TIM module.. + * @param TI1_Selection: Indicate whether or not channel 1 is connected to the + * output of a XOR gate. + * This parameter can be one of the following values: + * @arg TIM_TI1SELECTION_CH1: The TIMx_CH1 pin is connected to TI1 input + * @arg TIM_TI1SELECTION_XORCOMBINATION: The TIMx_CH1, CH2 and CH3 + * pins are connected to the TI1 input (XOR combination) + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_ConfigTI1Input(TIM_HandleTypeDef *htim, uint32_t TI1_Selection) +{ + uint32_t tmpcr2 = 0; + + /* Check the parameters */ + assert_param(IS_TIM_XOR_INSTANCE(htim->Instance)); + assert_param(IS_TIM_TI1SELECTION(TI1_Selection)); + + /* Get the TIMx CR2 register value */ + tmpcr2 = htim->Instance->CR2; + + /* Reset the TI1 selection */ + tmpcr2 &= ~TIM_CR2_TI1S; + + /* Set the the TI1 selection */ + tmpcr2 |= TI1_Selection; + + /* Write to TIMxCR2 */ + htim->Instance->CR2 = tmpcr2; + + return HAL_OK; +} + +/** + * @brief Configures the TIM in Slave mode + * @param htim: pointer to a TIM_HandleTypeDef structure that contains + * the configuration information for TIM module.. + * @param sSlaveConfig: pointer to a TIM_SlaveConfigTypeDef structure that + * contains the selected trigger (internal trigger input, filtered + * timer input or external trigger input) and the ) and the Slave + * mode (Disable, Reset, Gated, Trigger, External clock mode 1). + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIM_SlaveConfigSynchronization(TIM_HandleTypeDef *htim, TIM_SlaveConfigTypeDef * sSlaveConfig) +{ + uint32_t tmpsmcr = 0; + uint32_t tmpccmr1 = 0; + uint32_t tmpccer = 0; + + /* Check the parameters */ + assert_param(IS_TIM_SLAVE_INSTANCE(htim->Instance)); + assert_param(IS_TIM_SLAVE_MODE(sSlaveConfig->SlaveMode)); + assert_param(IS_TIM_TRIGGER_SELECTION(sSlaveConfig->InputTrigger)); + + __HAL_LOCK(htim); + + htim->State = HAL_TIM_STATE_BUSY; + + /* Get the TIMx SMCR register value */ + tmpsmcr = htim->Instance->SMCR; + + /* Reset the Trigger Selection Bits */ + tmpsmcr &= ~TIM_SMCR_TS; + /* Set the Input Trigger source */ + tmpsmcr |= sSlaveConfig->InputTrigger; + + /* Reset the slave mode Bits */ + tmpsmcr &= ~TIM_SMCR_SMS; + /* Set the slave mode */ + tmpsmcr |= sSlaveConfig->SlaveMode; + + /* Write to TIMx SMCR */ + htim->Instance->SMCR = tmpsmcr; + + /* Configure the trigger prescaler, filter, and polarity */ + switch (sSlaveConfig->InputTrigger) + { + case TIM_TS_ETRF: + { + /* Check the parameters */ + assert_param(IS_TIM_ETR_INSTANCE(htim->Instance)); + assert_param(IS_TIM_TRIGGERPRESCALER(sSlaveConfig->TriggerPrescaler)); + assert_param(IS_TIM_TRIGGERPOLARITY(sSlaveConfig->TriggerPolarity)); + assert_param(IS_TIM_TRIGGERFILTER(sSlaveConfig->TriggerFilter)); + /* Configure the ETR Trigger source */ + TIM_ETR_SetConfig(htim->Instance, + sSlaveConfig->TriggerPrescaler, + sSlaveConfig->TriggerPolarity, + sSlaveConfig->TriggerFilter); + } + break; + + case TIM_TS_TI1F_ED: + { + /* Check the parameters */ + assert_param(IS_TIM_CC1_INSTANCE(htim->Instance)); + assert_param(IS_TIM_TRIGGERFILTER(sSlaveConfig->TriggerFilter)); + + /* Disable the Channel 1: Reset the CC1E Bit */ + tmpccer = htim->Instance->CCER; + htim->Instance->CCER &= ~TIM_CCER_CC1E; + tmpccmr1 = htim->Instance->CCMR1; + + /* Set the filter */ + tmpccmr1 &= ~TIM_CCMR1_IC1F; + tmpccmr1 |= ((sSlaveConfig->TriggerFilter) << 4); + + /* Write to TIMx CCMR1 and CCER registers */ + htim->Instance->CCMR1 = tmpccmr1; + htim->Instance->CCER = tmpccer; + + } + break; + + case TIM_TS_TI1FP1: + { + /* Check the parameters */ + assert_param(IS_TIM_CC1_INSTANCE(htim->Instance)); + assert_param(IS_TIM_TRIGGERPOLARITY(sSlaveConfig->TriggerPolarity)); + assert_param(IS_TIM_TRIGGERFILTER(sSlaveConfig->TriggerFilter)); + + /* Configure TI1 Filter and Polarity */ + TIM_TI1_ConfigInputStage(htim->Instance, + sSlaveConfig->TriggerPolarity, + sSlaveConfig->TriggerFilter); + } + break; + + case TIM_TS_TI2FP2: + { + /* Check the parameters */ + assert_param(IS_TIM_CC2_INSTANCE(htim->Instance)); + assert_param(IS_TIM_TRIGGERPOLARITY(sSlaveConfig->TriggerPolarity)); + assert_param(IS_TIM_TRIGGERFILTER(sSlaveConfig->TriggerFilter)); + + /* Configure TI2 Filter and Polarity */ + TIM_TI2_ConfigInputStage(htim->Instance, + sSlaveConfig->TriggerPolarity, + sSlaveConfig->TriggerFilter); + } + break; + + case TIM_TS_ITR0: + { + /* Check the parameter */ + assert_param(IS_TIM_CC2_INSTANCE(htim->Instance)); + } + break; + + case TIM_TS_ITR1: + { + /* Check the parameter */ + assert_param(IS_TIM_CC2_INSTANCE(htim->Instance)); + } + break; + + case TIM_TS_ITR2: + { + /* Check the parameter */ + assert_param(IS_TIM_CC2_INSTANCE(htim->Instance)); + } + break; + + case TIM_TS_ITR3: + { + /* Check the parameter */ + assert_param(IS_TIM_CC2_INSTANCE(htim->Instance)); + } + break; + + default: + break; + } + + htim->State = HAL_TIM_STATE_READY; + + __HAL_UNLOCK(htim); + + return HAL_OK; +} + +/** + * @brief Read the captured value from Capture Compare unit + * @param htim: pointer to a TIM_HandleTypeDef structure that contains + * the configuration information for TIM module.. + * @param Channel: TIM Channels to be enabled. + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @arg TIM_CHANNEL_3: TIM Channel 3 selected + * @arg TIM_CHANNEL_4: TIM Channel 4 selected + * @retval Captured value + */ +uint32_t HAL_TIM_ReadCapturedValue(TIM_HandleTypeDef *htim, uint32_t Channel) +{ + uint32_t tmpreg = 0; + + __HAL_LOCK(htim); + + switch (Channel) + { + case TIM_CHANNEL_1: + { + /* Check the parameters */ + assert_param(IS_TIM_CC1_INSTANCE(htim->Instance)); + + /* Return the capture 1 value */ + tmpreg = htim->Instance->CCR1; + + break; + } + case TIM_CHANNEL_2: + { + /* Check the parameters */ + assert_param(IS_TIM_CC2_INSTANCE(htim->Instance)); + + /* Return the capture 2 value */ + tmpreg = htim->Instance->CCR2; + + break; + } + + case TIM_CHANNEL_3: + { + /* Check the parameters */ + assert_param(IS_TIM_CC3_INSTANCE(htim->Instance)); + + /* Return the capture 3 value */ + tmpreg = htim->Instance->CCR3; + + break; + } + + case TIM_CHANNEL_4: + { + /* Check the parameters */ + assert_param(IS_TIM_CC4_INSTANCE(htim->Instance)); + + /* Return the capture 4 value */ + tmpreg = htim->Instance->CCR4; + + break; + } + + default: + break; + } + + __HAL_UNLOCK(htim); + return tmpreg; +} + +/** + * @} + */ + +/** @defgroup TIM_Group4 TIM Callbacks functions + * @brief TIM Callbacks functions + * +@verbatim + ============================================================================== + ##### TIM Callbacks functions ##### + ============================================================================== + [..] + This section provides TIM callback functions: + (+) Timer Period elapsed callback + (+) Timer Output Compare callback + (+) Timer Input capture callback + (+) Timer Trigger callback + (+) Timer Error callback + +@endverbatim + * @{ + */ + +/** + * @brief Period elapsed callback in non blocking mode + * @param htim: pointer to a TIM_HandleTypeDef structure that contains + * the configuration information for TIM module. + * @retval None + */ +__weak void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the __HAL_TIM_PeriodElapsedCallback could be implemented in the user file + */ + +} +/** + * @brief Output Compare callback in non blocking mode + * @param htim: pointer to a TIM_HandleTypeDef structure that contains + * the configuration information for TIM module. + * @retval None + */ +__weak void HAL_TIM_OC_DelayElapsedCallback(TIM_HandleTypeDef *htim) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the __HAL_TIM_OC_DelayElapsedCallback could be implemented in the user file + */ +} +/** + * @brief Input Capture callback in non blocking mode + * @param htim : TIM IC handle + * @retval None + */ +__weak void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef *htim) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the __HAL_TIM_IC_CaptureCallback could be implemented in the user file + */ +} + +/** + * @brief PWM Pulse finished callback in non blocking mode + * @param htim: pointer to a TIM_HandleTypeDef structure that contains + * the configuration information for TIM module. + * @retval None + */ +__weak void HAL_TIM_PWM_PulseFinishedCallback(TIM_HandleTypeDef *htim) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the __HAL_TIM_PWM_PulseFinishedCallback could be implemented in the user file + */ +} + +/** + * @brief Hall Trigger detection callback in non blocking mode + * @param htim: pointer to a TIM_HandleTypeDef structure that contains + * the configuration information for TIM module. + * @retval None + */ +__weak void HAL_TIM_TriggerCallback(TIM_HandleTypeDef *htim) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_TIM_TriggerCallback could be implemented in the user file + */ +} + +/** + * @brief Timer error callback in non blocking mode + * @param htim: pointer to a TIM_HandleTypeDef structure that contains + * the configuration information for TIM module. + * @retval None + */ +__weak void HAL_TIM_ErrorCallback(TIM_HandleTypeDef *htim) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_TIM_ErrorCallback could be implemented in the user file + */ +} + +/** + * @brief TIM DMA Period Elapse complete callback. + * @param hdma : pointer to DMA handle. + * @retval None + */ +static void TIM_DMAPeriodElapsedCplt(DMA_HandleTypeDef *hdma) +{ + TIM_HandleTypeDef* htim = ( TIM_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + + htim->State= HAL_TIM_STATE_READY; + + HAL_TIM_PeriodElapsedCallback(htim); +} + + +/** + * @brief TIM DMA Trigger callback. + * @param hdma : pointer to DMA handle. + * @retval None + */ +static void TIM_DMATriggerCplt(DMA_HandleTypeDef *hdma) +{ + TIM_HandleTypeDef* htim = ( TIM_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + + htim->State= HAL_TIM_STATE_READY; + + HAL_TIM_TriggerCallback(htim); +} + +/** + * @} + */ + +/** @defgroup TIM_Group5 Peripheral State functions + * @brief Peripheral State functions + * +@verbatim + ============================================================================== + ##### Peripheral State functions ##### + ============================================================================== + [..] + This subsection permit to get in run-time the status of the peripheral + and the data flow. + +@endverbatim + * @{ + */ + +/** + * @brief Return the TIM Base state + * @param htim: pointer to a TIM_HandleTypeDef structure that contains + * the configuration information for TIM module. + * @retval HAL state + */ +HAL_TIM_StateTypeDef HAL_TIM_Base_GetState(TIM_HandleTypeDef *htim) +{ + return htim->State; +} + +/** + * @brief Return the TIM OC state + * @param htim: TIM Ouput Compare handle + * @retval HAL state + */ +HAL_TIM_StateTypeDef HAL_TIM_OC_GetState(TIM_HandleTypeDef *htim) +{ + return htim->State; +} + +/** + * @brief Return the TIM PWM state + * @param htim: pointer to a TIM_HandleTypeDef structure that contains + * the configuration information for TIM module. + * @retval HAL state + */ +HAL_TIM_StateTypeDef HAL_TIM_PWM_GetState(TIM_HandleTypeDef *htim) +{ + return htim->State; +} + +/** + * @brief Return the TIM Input Capture state + * @param htim: pointer to a TIM_HandleTypeDef structure that contains + * the configuration information for TIM module. + * @retval HAL state + */ +HAL_TIM_StateTypeDef HAL_TIM_IC_GetState(TIM_HandleTypeDef *htim) +{ + return htim->State; +} + +/** + * @brief Return the TIM One Pulse Mode state + * @param htim: TIM OPM handle + * @retval HAL state + */ +HAL_TIM_StateTypeDef HAL_TIM_OnePulse_GetState(TIM_HandleTypeDef *htim) +{ + return htim->State; +} + +/** + * @brief Return the TIM Encoder Mode state + * @param htim: pointer to a TIM_HandleTypeDef structure that contains + * the configuration information for TIM module. + * @retval HAL state + */ +HAL_TIM_StateTypeDef HAL_TIM_Encoder_GetState(TIM_HandleTypeDef *htim) +{ + return htim->State; +} + +/** + * @} + */ + +/** + * @brief TIM DMA error callback + * @param hdma: pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +void HAL_TIM_DMAError(DMA_HandleTypeDef *hdma) +{ + TIM_HandleTypeDef* htim = ( TIM_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + + htim->State= HAL_TIM_STATE_READY; + + HAL_TIM_ErrorCallback(htim); +} + +/** + * @brief TIM DMA Delay Pulse complete callback. + * @param hdma: pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +void HAL_TIM_DMADelayPulseCplt(DMA_HandleTypeDef *hdma) +{ + TIM_HandleTypeDef* htim = ( TIM_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + + htim->State= HAL_TIM_STATE_READY; + + HAL_TIM_PWM_PulseFinishedCallback(htim); +} +/** + * @brief TIM DMA Capture complete callback. + * @param hdma: pointer to a DMA_HandleTypeDef structure that contains + * the configuration information for the specified DMA module. + * @retval None + */ +void HAL_TIM_DMACaptureCplt(DMA_HandleTypeDef *hdma) +{ + TIM_HandleTypeDef* htim = ( TIM_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + + htim->State= HAL_TIM_STATE_READY; + + HAL_TIM_IC_CaptureCallback(htim); + +} + +/** + * @brief Time Base configuration + * @param TIMx: TIM periheral + * @retval None + */ +static void TIM_Base_SetConfig(TIM_TypeDef *TIMx, TIM_Base_InitTypeDef *Structure) +{ + uint32_t tmpcr1 = 0; + tmpcr1 = TIMx->CR1; + + /* Set TIM Time Base Unit parameters ---------------------------------------*/ + if(IS_TIM_CC3_INSTANCE(TIMx) != RESET) + { + /* Select the Counter Mode */ + tmpcr1 &= ~(TIM_CR1_DIR | TIM_CR1_CMS); + tmpcr1 |= Structure->CounterMode; + } + + if(IS_TIM_CC1_INSTANCE(TIMx) != RESET) + { + /* Set the clock division */ + tmpcr1 &= ~TIM_CR1_CKD; + tmpcr1 |= (uint32_t)Structure->ClockDivision; + } + + TIMx->CR1 = tmpcr1; + + /* Set the Autoreload value */ + TIMx->ARR = (uint32_t)Structure->Period ; + + /* Set the Prescaler value */ + TIMx->PSC = (uint32_t)Structure->Prescaler; + + /* Generate an update event to reload the Prescaler value immediatly */ + TIMx->EGR = TIM_EGR_UG; +} + +/** + * @brief Time Ouput Compare 1 configuration + * @param TIMx to select the TIM peripheral + * @param OC_Config: The ouput configuration structure + * @retval None + */ +static void TIM_OC1_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config) +{ + uint32_t tmpccmrx = 0; + uint32_t tmpccer = 0; + uint32_t tmpcr2 = 0; + + /* Disable the Channel 1: Reset the CC1E Bit */ + TIMx->CCER &= ~TIM_CCER_CC1E; + + /* Get the TIMx CCER register value */ + tmpccer = TIMx->CCER; + /* Get the TIMx CR2 register value */ + tmpcr2 = TIMx->CR2; + + /* Get the TIMx CCMR1 register value */ + tmpccmrx = TIMx->CCMR1; + + /* Reset the Output Compare Mode Bits */ + tmpccmrx &= ~TIM_CCMR1_OC1M; + tmpccmrx &= ~TIM_CCMR1_CC1S; + /* Select the Output Compare Mode */ + tmpccmrx |= OC_Config->OCMode; + + /* Reset the Output Polarity level */ + tmpccer &= ~TIM_CCER_CC1P; + /* Set the Output Compare Polarity */ + tmpccer |= OC_Config->OCPolarity; + + /* Write to TIMx CR2 */ + TIMx->CR2 = tmpcr2; + + /* Write to TIMx CCMR1 */ + TIMx->CCMR1 = tmpccmrx; + + /* Set the Capture Compare Register value */ + TIMx->CCR1 = OC_Config->Pulse; + + /* Write to TIMx CCER */ + TIMx->CCER = tmpccer; +} + +/** + * @brief Time Ouput Compare 2 configuration + * @param TIMx to select the TIM peripheral + * @param OC_Config: The ouput configuration structure + * @retval None + */ +static void TIM_OC2_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config) +{ + uint32_t tmpccmrx = 0; + uint32_t tmpccer = 0; + uint32_t tmpcr2 = 0; + + /* Disable the Channel 2: Reset the CC2E Bit */ + TIMx->CCER &= ~TIM_CCER_CC2E; + + /* Get the TIMx CCER register value */ + tmpccer = TIMx->CCER; + /* Get the TIMx CR2 register value */ + tmpcr2 = TIMx->CR2; + + /* Get the TIMx CCMR1 register value */ + tmpccmrx = TIMx->CCMR1; + + /* Reset the Output Compare mode and Capture/Compare selection Bits */ + tmpccmrx &= ~TIM_CCMR1_OC2M; + tmpccmrx &= ~TIM_CCMR1_CC2S; + + /* Select the Output Compare Mode */ + tmpccmrx |= (OC_Config->OCMode << 8); + + /* Reset the Output Polarity level */ + tmpccer &= ~TIM_CCER_CC2P; + /* Set the Output Compare Polarity */ + tmpccer |= (OC_Config->OCPolarity << 4); + + /* Write to TIMx CR2 */ + TIMx->CR2 = tmpcr2; + + /* Write to TIMx CCMR1 */ + TIMx->CCMR1 = tmpccmrx; + + /* Set the Capture Compare Register value */ + TIMx->CCR2 = OC_Config->Pulse; + + /* Write to TIMx CCER */ + TIMx->CCER = tmpccer; +} + +/** + * @brief Time Ouput Compare 3 configuration + * @param TIMx to select the TIM peripheral + * @param OC_Config: The ouput configuration structure + * @retval None + */ +static void TIM_OC3_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config) +{ + uint32_t tmpccmrx = 0; + uint32_t tmpccer = 0; + uint32_t tmpcr2 = 0; + + /* Disable the Channel 3: Reset the CC2E Bit */ + TIMx->CCER &= ~TIM_CCER_CC3E; + + /* Get the TIMx CCER register value */ + tmpccer = TIMx->CCER; + /* Get the TIMx CR2 register value */ + tmpcr2 = TIMx->CR2; + + /* Get the TIMx CCMR2 register value */ + tmpccmrx = TIMx->CCMR2; + + /* Reset the Output Compare mode and Capture/Compare selection Bits */ + tmpccmrx &= ~TIM_CCMR2_OC3M; + tmpccmrx &= ~TIM_CCMR2_CC3S; + /* Select the Output Compare Mode */ + tmpccmrx |= OC_Config->OCMode; + + /* Reset the Output Polarity level */ + tmpccer &= ~TIM_CCER_CC3P; + /* Set the Output Compare Polarity */ + tmpccer |= (OC_Config->OCPolarity << 8); + + /* Write to TIMx CR2 */ + TIMx->CR2 = tmpcr2; + + /* Write to TIMx CCMR2 */ + TIMx->CCMR2 = tmpccmrx; + + /* Set the Capture Compare Register value */ + TIMx->CCR3 = OC_Config->Pulse; + + /* Write to TIMx CCER */ + TIMx->CCER = tmpccer; +} + +/** + * @brief Time Ouput Compare 4 configuration + * @param TIMx to select the TIM peripheral + * @param OC_Config: The ouput configuration structure + * @retval None + */ +static void TIM_OC4_SetConfig(TIM_TypeDef *TIMx, TIM_OC_InitTypeDef *OC_Config) +{ + uint32_t tmpccmrx = 0; + uint32_t tmpccer = 0; + uint32_t tmpcr2 = 0; + + /* Disable the Channel 4: Reset the CC4E Bit */ + TIMx->CCER &= ~TIM_CCER_CC4E; + + /* Get the TIMx CCER register value */ + tmpccer = TIMx->CCER; + /* Get the TIMx CR2 register value */ + tmpcr2 = TIMx->CR2; + + /* Get the TIMx CCMR2 register value */ + tmpccmrx = TIMx->CCMR2; + + /* Reset the Output Compare mode and Capture/Compare selection Bits */ + tmpccmrx &= ~TIM_CCMR2_OC4M; + tmpccmrx &= ~TIM_CCMR2_CC4S; + + /* Select the Output Compare Mode */ + tmpccmrx |= (OC_Config->OCMode << 8); + + /* Reset the Output Polarity level */ + tmpccer &= ~TIM_CCER_CC4P; + /* Set the Output Compare Polarity */ + tmpccer |= (OC_Config->OCPolarity << 12); + + /* Write to TIMx CR2 */ + TIMx->CR2 = tmpcr2; + + /* Write to TIMx CCMR2 */ + TIMx->CCMR2 = tmpccmrx; + + /* Set the Capture Compare Register value */ + TIMx->CCR4 = OC_Config->Pulse; + + /* Write to TIMx CCER */ + TIMx->CCER = tmpccer; +} + +/** + * @brief Configure the TI1 as Input. + * @param TIMx to select the TIM peripheral. + * @param TIM_ICPolarity : The Input Polarity. + * This parameter can be one of the following values: + * @arg TIM_ICPolarity_Rising + * @arg TIM_ICPolarity_Falling + * @arg TIM_ICPolarity_BothEdge + * @param TIM_ICSelection: specifies the input to be used. + * This parameter can be one of the following values: + * @arg TIM_ICSelection_DirectTI: TIM Input 1 is selected to be connected to IC1. + * @arg TIM_ICSelection_IndirectTI: TIM Input 1 is selected to be connected to IC2. + * @arg TIM_ICSelection_TRC: TIM Input 1 is selected to be connected to TRC. + * @param TIM_ICFilter: Specifies the Input Capture Filter. + * This parameter must be a value between 0x00 and 0x0F. + * @retval None + */ +static void TIM_TI1_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICSelection, + uint32_t TIM_ICFilter) +{ + uint32_t tmpccmr1 = 0; + uint32_t tmpccer = 0; + + /* Disable the Channel 1: Reset the CC1E Bit */ + TIMx->CCER &= ~TIM_CCER_CC1E; + tmpccmr1 = TIMx->CCMR1; + tmpccer = TIMx->CCER; + + /* Select the Input */ + if(IS_TIM_CC2_INSTANCE(TIMx) != RESET) + { + tmpccmr1 &= ~TIM_CCMR1_CC1S; + tmpccmr1 |= TIM_ICSelection; + } + else + { + tmpccmr1 &= ~TIM_CCMR1_CC1S; + tmpccmr1 |= TIM_CCMR1_CC1S_0; + } + + /* Set the filter */ + tmpccmr1 &= ~TIM_CCMR1_IC1F; + tmpccmr1 |= (TIM_ICFilter << 4); + + /* Select the Polarity and set the CC1E Bit */ + tmpccer &= ~(TIM_CCER_CC1P | TIM_CCER_CC1NP); + tmpccer |= TIM_ICPolarity; + + /* Write to TIMx CCMR1 and CCER registers */ + TIMx->CCMR1 = tmpccmr1; + TIMx->CCER = tmpccer; +} + +/** + * @brief Configure the Polarity and Filter for TI1. + * @param TIMx to select the TIM peripheral. + * @param TIM_ICPolarity : The Input Polarity. + * This parameter can be one of the following values: + * @arg TIM_ICPolarity_Rising + * @arg TIM_ICPolarity_Falling + * @arg TIM_ICPolarity_BothEdge + * @param TIM_ICFilter: Specifies the Input Capture Filter. + * This parameter must be a value between 0x00 and 0x0F. + * @retval None + */ +static void TIM_TI1_ConfigInputStage(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICFilter) +{ + uint32_t tmpccmr1 = 0; + uint32_t tmpccer = 0; + + /* Disable the Channel 1: Reset the CC1E Bit */ + tmpccer = TIMx->CCER; + TIMx->CCER &= ~TIM_CCER_CC1E; + tmpccmr1 = TIMx->CCMR1; + + /* Set the filter */ + tmpccmr1 &= ~TIM_CCMR1_IC1F; + tmpccmr1 |= (TIM_ICFilter << 4); + + /* Select the Polarity and set the CC1E Bit */ + tmpccer &= ~(TIM_CCER_CC1P | TIM_CCER_CC1NP); + tmpccer |= TIM_ICPolarity; + + /* Write to TIMx CCMR1 and CCER registers */ + TIMx->CCMR1 = tmpccmr1; + TIMx->CCER = tmpccer; +} + +/** + * @brief Configure the TI2 as Input. + * @param TIMx to select the TIM peripheral + * @param TIM_ICPolarity : The Input Polarity. + * This parameter can be one of the following values: + * @arg TIM_ICPolarity_Rising + * @arg TIM_ICPolarity_Falling + * @arg TIM_ICPolarity_BothEdge + * @param TIM_ICSelection: specifies the input to be used. + * This parameter can be one of the following values: + * @arg TIM_ICSelection_DirectTI: TIM Input 2 is selected to be connected to IC2. + * @arg TIM_ICSelection_IndirectTI: TIM Input 2 is selected to be connected to IC1. + * @arg TIM_ICSelection_TRC: TIM Input 2 is selected to be connected to TRC. + * @param TIM_ICFilter: Specifies the Input Capture Filter. + * This parameter must be a value between 0x00 and 0x0F. + * @retval None + */ +static void TIM_TI2_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICSelection, + uint32_t TIM_ICFilter) +{ + uint32_t tmpccmr1 = 0; + uint32_t tmpccer = 0; + + /* Disable the Channel 2: Reset the CC2E Bit */ + TIMx->CCER &= ~TIM_CCER_CC2E; + tmpccmr1 = TIMx->CCMR1; + tmpccer = TIMx->CCER; + + /* Select the Input */ + tmpccmr1 &= ~TIM_CCMR1_CC2S; + tmpccmr1 |= (TIM_ICSelection << 8); + + /* Set the filter */ + tmpccmr1 &= ~TIM_CCMR1_IC2F; + tmpccmr1 |= (TIM_ICFilter << 12); + + /* Select the Polarity and set the CC2E Bit */ + tmpccer &= ~(TIM_CCER_CC2P | TIM_CCER_CC2NP); + tmpccer |= (TIM_ICPolarity << 4); + + /* Write to TIMx CCMR1 and CCER registers */ + TIMx->CCMR1 = tmpccmr1 ; + TIMx->CCER = tmpccer; +} + +/** + * @brief Configure the Polarity and Filter for TI2. + * @param TIMx to select the TIM peripheral. + * @param TIM_ICPolarity : The Input Polarity. + * This parameter can be one of the following values: + * @arg TIM_ICPolarity_Rising + * @arg TIM_ICPolarity_Falling + * @arg TIM_ICPolarity_BothEdge + * @param TIM_ICFilter: Specifies the Input Capture Filter. + * This parameter must be a value between 0x00 and 0x0F. + * @retval None + */ +static void TIM_TI2_ConfigInputStage(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICFilter) +{ + uint32_t tmpccmr1 = 0; + uint32_t tmpccer = 0; + + /* Disable the Channel 2: Reset the CC2E Bit */ + TIMx->CCER &= ~TIM_CCER_CC2E; + tmpccmr1 = TIMx->CCMR1; + tmpccer = TIMx->CCER; + + /* Set the filter */ + tmpccmr1 &= ~TIM_CCMR1_IC2F; + tmpccmr1 |= (TIM_ICFilter << 12); + + /* Select the Polarity and set the CC2E Bit */ + tmpccer &= ~(TIM_CCER_CC2P | TIM_CCER_CC2NP); + tmpccer |= (TIM_ICPolarity << 4); + + /* Write to TIMx CCMR1 and CCER registers */ + TIMx->CCMR1 = tmpccmr1 ; + TIMx->CCER = tmpccer; +} + +/** + * @brief Configure the TI3 as Input. + * @param TIMx to select the TIM peripheral + * @param TIM_ICPolarity : The Input Polarity. + * This parameter can be one of the following values: + * @arg TIM_ICPolarity_Rising + * @arg TIM_ICPolarity_Falling + * @arg TIM_ICPolarity_BothEdge + * @param TIM_ICSelection: specifies the input to be used. + * This parameter can be one of the following values: + * @arg TIM_ICSelection_DirectTI: TIM Input 3 is selected to be connected to IC3. + * @arg TIM_ICSelection_IndirectTI: TIM Input 3 is selected to be connected to IC4. + * @arg TIM_ICSelection_TRC: TIM Input 3 is selected to be connected to TRC. + * @param TIM_ICFilter: Specifies the Input Capture Filter. + * This parameter must be a value between 0x00 and 0x0F. + * @retval None + */ +static void TIM_TI3_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICSelection, + uint32_t TIM_ICFilter) +{ + uint32_t tmpccmr2 = 0; + uint32_t tmpccer = 0; + + /* Disable the Channel 3: Reset the CC3E Bit */ + TIMx->CCER &= ~TIM_CCER_CC3E; + tmpccmr2 = TIMx->CCMR2; + tmpccer = TIMx->CCER; + + /* Select the Input */ + tmpccmr2 &= ~TIM_CCMR2_CC3S; + tmpccmr2 |= TIM_ICSelection; + + /* Set the filter */ + tmpccmr2 &= ~TIM_CCMR2_IC3F; + tmpccmr2 |= (TIM_ICFilter << 4); + + /* Select the Polarity and set the CC3E Bit */ + tmpccer &= ~(TIM_CCER_CC3P | TIM_CCER_CC3NP); + tmpccer |= (TIM_ICPolarity << 8); + + /* Write to TIMx CCMR2 and CCER registers */ + TIMx->CCMR2 = tmpccmr2; + TIMx->CCER = tmpccer; +} + +/** + * @brief Configure the TI4 as Input. + * @param TIMx to select the TIM peripheral + * @param TIM_ICPolarity : The Input Polarity. + * This parameter can be one of the following values: + * @arg TIM_ICPolarity_Rising + * @arg TIM_ICPolarity_Falling + * @arg TIM_ICPolarity_BothEdge + * @param TIM_ICSelection: specifies the input to be used. + * This parameter can be one of the following values: + * @arg TIM_ICSelection_DirectTI: TIM Input 4 is selected to be connected to IC4. + * @arg TIM_ICSelection_IndirectTI: TIM Input 4 is selected to be connected to IC3. + * @arg TIM_ICSelection_TRC: TIM Input 4 is selected to be connected to TRC. + * @param TIM_ICFilter: Specifies the Input Capture Filter. + * This parameter must be a value between 0x00 and 0x0F. + * @retval None + */ +static void TIM_TI4_SetConfig(TIM_TypeDef *TIMx, uint32_t TIM_ICPolarity, uint32_t TIM_ICSelection, + uint32_t TIM_ICFilter) +{ + uint32_t tmpccmr2 = 0; + uint32_t tmpccer = 0; + + /* Disable the Channel 4: Reset the CC4E Bit */ + TIMx->CCER &= ~TIM_CCER_CC4E; + tmpccmr2 = TIMx->CCMR2; + tmpccer = TIMx->CCER; + + /* Select the Input */ + tmpccmr2 &= ~TIM_CCMR2_CC4S; + tmpccmr2 |= (TIM_ICSelection << 8); + + /* Set the filter */ + tmpccmr2 &= ~TIM_CCMR2_IC4F; + tmpccmr2 |= (TIM_ICFilter << 12); + + /* Select the Polarity and set the CC4E Bit */ + tmpccer &= ~(TIM_CCER_CC4P | TIM_CCER_CC4NP); + tmpccer |= (TIM_ICPolarity << 12); + + /* Write to TIMx CCMR2 and CCER registers */ + TIMx->CCMR2 = tmpccmr2; + TIMx->CCER = tmpccer ; +} + +/** + * @brief Selects the Input Trigger source + * @param TIMx to select the TIM peripheral + * @param InputTriggerSource: The Input Trigger source. + * This parameter can be one of the following values: + * @arg TIM_TS_ITR0: Internal Trigger 0 + * @arg TIM_TS_ITR1: Internal Trigger 1 + * @arg TIM_TS_ITR2: Internal Trigger 2 + * @arg TIM_TS_ITR3: Internal Trigger 3 + * @arg TIM_TS_TI1F_ED: TI1 Edge Detector + * @arg TIM_TS_TI1FP1: Filtered Timer Input 1 + * @arg TIM_TS_TI2FP2: Filtered Timer Input 2 + * @arg TIM_TS_ETRF: External Trigger input + * @retval None + */ +static void TIM_ITRx_SetConfig(TIM_TypeDef *TIMx, uint16_t TIM_ITRx) +{ + uint32_t tmpsmcr = 0; + + /* Get the TIMx SMCR register value */ + tmpsmcr = TIMx->SMCR; + /* Reset the TS Bits */ + tmpsmcr &= ~TIM_SMCR_TS; + /* Set the Input Trigger source and the slave mode*/ + tmpsmcr |= TIM_ITRx | TIM_SLAVEMODE_EXTERNAL1; + /* Write to TIMx SMCR */ + TIMx->SMCR = tmpsmcr; +} +/** + * @brief Configures the TIMx External Trigger (ETR). + * @param TIMx to select the TIM peripheral + * @param TIM_ExtTRGPrescaler: The external Trigger Prescaler. + * This parameter can be one of the following values: + * @arg TIM_ExtTRGPSC_DIV1: ETRP Prescaler OFF. + * @arg TIM_ExtTRGPSC_DIV2: ETRP frequency divided by 2. + * @arg TIM_ExtTRGPSC_DIV4: ETRP frequency divided by 4. + * @arg TIM_ExtTRGPSC_DIV8: ETRP frequency divided by 8. + * @param TIM_ExtTRGPolarity: The external Trigger Polarity. + * This parameter can be one of the following values: + * @arg TIM_ExtTRGPolarity_Inverted: active low or falling edge active. + * @arg TIM_ExtTRGPolarity_NonInverted: active high or rising edge active. + * @param ExtTRGFilter: External Trigger Filter. + * This parameter must be a value between 0x00 and 0x0F + * @retval None + */ +static void TIM_ETR_SetConfig(TIM_TypeDef* TIMx, uint32_t TIM_ExtTRGPrescaler, + uint32_t TIM_ExtTRGPolarity, uint32_t ExtTRGFilter) +{ + uint32_t tmpsmcr = 0; + + tmpsmcr = TIMx->SMCR; + + /* Reset the ETR Bits */ + tmpsmcr &= ~(TIM_SMCR_ETF | TIM_SMCR_ETPS | TIM_SMCR_ECE | TIM_SMCR_ETP); + + /* Set the Prescaler, the Filter value and the Polarity */ + tmpsmcr |= (uint32_t)(TIM_ExtTRGPrescaler | (TIM_ExtTRGPolarity | (ExtTRGFilter << 8))); + + /* Write to TIMx SMCR */ + TIMx->SMCR = tmpsmcr; +} + +/** + * @brief Enables or disables the TIM Capture Compare Channel x. + * @param TIMx to select the TIM peripheral + * @param Channel: specifies the TIM Channel + * This parameter can be one of the following values: + * @arg TIM_Channel_1: TIM Channel 1 + * @arg TIM_Channel_2: TIM Channel 2 + * @arg TIM_Channel_3: TIM Channel 3 + * @arg TIM_Channel_4: TIM Channel 4 + * @param ChannelState: specifies the TIM Channel CCxE bit new state. + * This parameter can be: TIM_CCx_ENABLE or TIM_CCx_Disable. + * @retval None + */ +static void TIM_CCxChannelCmd(TIM_TypeDef* TIMx, uint32_t Channel, uint32_t ChannelState) +{ + uint32_t tmp = 0; + + /* Check the parameters */ + assert_param(IS_TIM_CC1_INSTANCE(TIMx)); + assert_param(IS_TIM_CHANNELS(Channel)); + + tmp = TIM_CCER_CC1E << Channel; + + /* Reset the CCxE Bit */ + TIMx->CCER &= ~tmp; + + /* Set or reset the CCxE Bit */ + TIMx->CCER |= (uint32_t)(ChannelState << Channel); +} + + +/** + * @} + */ + +#endif /* HAL_TIM_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_tim.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_tim.h new file mode 100644 index 0000000000..9603e18c33 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_tim.h @@ -0,0 +1,1284 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_tim.h + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief Header file of TIM HAL module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32L0xx_HAL_TIM_H +#define __STM32L0xx_HAL_TIM_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal_def.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @addtogroup TIM + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ + +/** + * @brief TIM Time base Configuration Structure definition + */ +typedef struct +{ + uint32_t Prescaler; /*!< Specifies the prescaler value used to divide the TIM clock. + This parameter can be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF */ + + uint32_t CounterMode; /*!< Specifies the counter mode. + This parameter can be a value of @ref TIM_Counter_Mode */ + + uint32_t Period; /*!< Specifies the period value to be loaded into the active + Auto-Reload Register at the next update event. + This parameter can be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF. */ + + uint32_t ClockDivision; /*!< Specifies the clock division. + This parameter can be a value of @ref TIM_ClockDivision */ +} TIM_Base_InitTypeDef; + +/** + * @brief TIM Output Compare Configuration Structure definition + */ + +typedef struct +{ + uint32_t OCMode; /*!< Specifies the TIM mode. + This parameter can be a value of @ref TIM_Output_Compare_and_PWM_modes */ + + uint32_t Pulse; /*!< Specifies the pulse value to be loaded into the Capture Compare Register. + This parameter can be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF */ + + uint32_t OCPolarity; /*!< Specifies the output polarity. + This parameter can be a value of @ref TIM_Output_Compare_Polarity */ + + uint32_t OCFastMode; /*!< Specifies the Fast mode state. + This parameter can be a value of @ref TIM_Output_Fast_State + @note This parameter is valid only in PWM1 and PWM2 mode. */ + +} TIM_OC_InitTypeDef; + +/** + * @brief TIM One Pulse Mode Configuration Structure definition + */ +typedef struct +{ + uint32_t OCMode; /*!< Specifies the TIM mode. + This parameter can be a value of @ref TIM_Output_Compare_and_PWM_modes */ + + uint32_t Pulse; /*!< Specifies the pulse value to be loaded into the Capture Compare Register. + This parameter can be a number between Min_Data = 0x0000 and Max_Data = 0xFFFF */ + + uint32_t OCPolarity; /*!< Specifies the output polarity. + This parameter can be a value of @ref TIM_Output_Compare_Polarity */ + + + uint32_t ICPolarity; /*!< Specifies the active edge of the input signal. + This parameter can be a value of @ref TIM_Input_Capture_Polarity */ + + uint32_t ICSelection; /*!< Specifies the input. + This parameter can be a value of @ref TIM_Input_Capture_Selection */ + + uint32_t ICFilter; /*!< Specifies the input capture filter. + This parameter can be a number between Min_Data = 0x0 and Max_Data = 0xF */ +} TIM_OnePulse_InitTypeDef; + + +/** + * @brief TIM Input Capture Configuration Structure definition + */ + +typedef struct +{ + uint32_t ICPolarity; /*!< Specifies the active edge of the input signal. + This parameter can be a value of @ref TIM_Input_Capture_Polarity */ + + uint32_t ICSelection; /*!< Specifies the input. + This parameter can be a value of @ref TIM_Input_Capture_Selection */ + + uint32_t ICPrescaler; /*!< Specifies the Input Capture Prescaler. + This parameter can be a value of @ref TIM_Input_Capture_Prescaler */ + + uint32_t ICFilter; /*!< Specifies the input capture filter. + This parameter can be a number between Min_Data = 0x0 and Max_Data = 0xF */ +} TIM_IC_InitTypeDef; + +/** + * @brief TIM Encoder Configuration Structure definition + */ + +typedef struct +{ + uint32_t EncoderMode; /*!< Specifies the active edge of the input signal. + This parameter can be a value of @ref TIM_Encoder_Mode */ + + uint32_t IC1Polarity; /*!< Specifies the active edge of the input signal. + This parameter can be a value of @ref TIM_Input_Capture_Polarity */ + + uint32_t IC1Selection; /*!< Specifies the input. + This parameter can be a value of @ref TIM_Input_Capture_Selection */ + + uint32_t IC1Prescaler; /*!< Specifies the Input Capture Prescaler. + This parameter can be a value of @ref TIM_Input_Capture_Prescaler */ + + uint32_t IC1Filter; /*!< Specifies the input capture filter. + This parameter can be a number between Min_Data = 0x0 and Max_Data = 0xF */ + + uint32_t IC2Polarity; /*!< Specifies the active edge of the input signal. + This parameter can be a value of @ref TIM_Input_Capture_Polarity */ + + uint32_t IC2Selection; /*!< Specifies the input. + This parameter can be a value of @ref TIM_Input_Capture_Selection */ + + uint32_t IC2Prescaler; /*!< Specifies the Input Capture Prescaler. + This parameter can be a value of @ref TIM_Input_Capture_Prescaler */ + + uint32_t IC2Filter; /*!< Specifies the input capture filter. + This parameter can be a number between Min_Data = 0x0 and Max_Data = 0xF */ +} TIM_Encoder_InitTypeDef; + +/** + * @brief Clock Configuration Handle Structure definition + */ +typedef struct +{ + uint32_t ClockSource; /*!< TIM clock sources + This parameter can be a value of @ref TIM_Clock_Source */ + uint32_t ClockPolarity; /*!< TIM clock polarity + This parameter can be a value of @ref TIM_Clock_Polarity */ + uint32_t ClockPrescaler; /*!< TIM clock prescaler + This parameter can be a value of @ref TIM_Clock_Prescaler */ + uint32_t ClockFilter; /*!< TIM clock filter + This parameter can be a value of @ref TIM_Clock_Filter */ +}TIM_ClockConfigTypeDef; + +/** + * @brief Clear Input Configuration Handle Structure definition + */ +typedef struct +{ + uint32_t ClearInputState; /*!< TIM clear Input state + This parameter can be ENABLE or DISABLE */ + uint32_t ClearInputSource; /*!< TIM clear Input sources + This parameter can be a value of @ref TIM_ClearInput_Source */ + uint32_t ClearInputPolarity; /*!< TIM Clear Input polarity + This parameter can be a value of @ref TIM_ClearInput_Polarity */ + uint32_t ClearInputPrescaler; /*!< TIM Clear Input prescaler + This parameter can be a value of @ref TIM_ClearInput_Prescaler */ + uint32_t ClearInputFilter; /*!< TIM Clear Input filter + This parameter can be a value of @ref TIM_ClearInput_Filter */ +}TIM_ClearInputConfigTypeDef; + +/** + * @brief TIM Slave configuration Structure definition + */ +typedef struct { + uint32_t SlaveMode; /*!< Slave mode selection + This parameter can be a value of @ref TIM_Slave_Mode */ + uint32_t InputTrigger; /*!< Input Trigger source + This parameter can be a value of @ref TIM_Trigger_Selection */ + uint32_t TriggerPolarity; /*!< Input Trigger polarity + This parameter can be a value of @ref TIM_Trigger_Polarity */ + uint32_t TriggerPrescaler; /*!< Input trigger prescaler + This parameter can be a value of @ref TIM_Trigger_Prescaler */ + uint32_t TriggerFilter; /*!< Input trigger filter + This parameter can be a value of @ref TIM_Trigger_Filter */ + +}TIM_SlaveConfigTypeDef; + +/** + * @brief HAL State structures definition + */ +typedef enum +{ + HAL_TIM_STATE_RESET = 0x00, /*!< Peripheral not yet initialized or disabled */ + HAL_TIM_STATE_READY = 0x01, /*!< Peripheral Initialized and ready for use */ + HAL_TIM_STATE_BUSY = 0x02, /*!< An internal process is ongoing */ + HAL_TIM_STATE_TIMEOUT = 0x03, /*!< Timeout state */ + HAL_TIM_STATE_ERROR = 0x04 /*!< Reception process is ongoing */ +}HAL_TIM_StateTypeDef; + +/** + * @brief HAL Active channel structures definition + */ +typedef enum +{ + HAL_TIM_ACTIVE_CHANNEL_1 = 0x01, /*!< The active channel is 1 */ + HAL_TIM_ACTIVE_CHANNEL_2 = 0x02, /*!< The active channel is 2 */ + HAL_TIM_ACTIVE_CHANNEL_3 = 0x04, /*!< The active channel is 3 */ + HAL_TIM_ACTIVE_CHANNEL_4 = 0x08, /*!< The active channel is 4 */ + HAL_TIM_ACTIVE_CHANNEL_CLEARED = 0x00 /*!< All active channels cleared */ +}HAL_TIM_ActiveChannel; + +/** + * @brief TIM Time Base Handle Structure definition + */ +typedef struct +{ + TIM_TypeDef *Instance; /*!< Register base address */ + TIM_Base_InitTypeDef Init; /*!< TIM Time Base required parameters */ + HAL_TIM_ActiveChannel Channel; /*!< Active channel */ + DMA_HandleTypeDef *hdma[7]; /*!< DMA Handlers array + This array is accessed by a @ref DMA_Handle_index */ + HAL_LockTypeDef Lock; /*!< Locking object */ +__IO HAL_TIM_StateTypeDef State; /*!< TIM operation state */ +}TIM_HandleTypeDef; + +/* Exported constants --------------------------------------------------------*/ +/** @defgroup TIM_Exported_Constants + * @{ + */ + +/** @defgroup TIM_Input_Channel_Polarity + * @{ + */ +#define TIM_INPUTCHANNELPOLARITY_RISING ((uint32_t)0x00000000) /*!< Polarity for TIx source */ +#define TIM_INPUTCHANNELPOLARITY_FALLING (TIM_CCER_CC1P) /*!< Polarity for TIx source */ +#define TIM_INPUTCHANNELPOLARITY_BOTHEDGE (TIM_CCER_CC1P | TIM_CCER_CC1NP) /*!< Polarity for TIx source */ +/** + * @} + */ + +/** @defgroup TIM_ETR_Polarity + * @{ + */ +#define TIM_ETRPOLARITY_INVERTED (TIM_SMCR_ETP) /*!< Polarity for ETR source */ +#define TIM_ETRPOLARITY_NONINVERTED ((uint32_t)0x0000) /*!< Polarity for ETR source */ +/** + * @} + */ + +/** @defgroup TIM_ETR_Prescaler + * @{ + */ +#define TIM_ETRPRESCALER_DIV1 ((uint32_t)0x0000) /*!< No prescaler is used */ +#define TIM_ETRPRESCALER_DIV2 (TIM_SMCR_ETPS_0) /*!< ETR input source is divided by 2 */ +#define TIM_ETRPRESCALER_DIV4 (TIM_SMCR_ETPS_1) /*!< ETR input source is divided by 4 */ +#define TIM_ETRPRESCALER_DIV8 (TIM_SMCR_ETPS) /*!< ETR input source is divided by 8 */ +/** + * @} + */ + +/** @defgroup TIM_Counter_Mode + * @{ + */ +#define TIM_COUNTERMODE_UP ((uint32_t)0x0000) +#define TIM_COUNTERMODE_DOWN TIM_CR1_DIR +#define TIM_COUNTERMODE_CENTERALIGNED1 TIM_CR1_CMS_0 +#define TIM_COUNTERMODE_CENTERALIGNED2 TIM_CR1_CMS_1 +#define TIM_COUNTERMODE_CENTERALIGNED3 TIM_CR1_CMS + +#define IS_TIM_COUNTER_MODE(MODE) (((MODE) == TIM_COUNTERMODE_UP) || \ + ((MODE) == TIM_COUNTERMODE_DOWN) || \ + ((MODE) == TIM_COUNTERMODE_CENTERALIGNED1) || \ + ((MODE) == TIM_COUNTERMODE_CENTERALIGNED2) || \ + ((MODE) == TIM_COUNTERMODE_CENTERALIGNED3)) +/** + * @} + */ + +/** @defgroup TIM_ClockDivision + * @{ + */ +#define TIM_CLOCKDIVISION_DIV1 ((uint32_t)0x0000) +#define TIM_CLOCKDIVISION_DIV2 (TIM_CR1_CKD_0) +#define TIM_CLOCKDIVISION_DIV4 (TIM_CR1_CKD_1) + +#define IS_TIM_CLOCKDIVISION_DIV(DIV) (((DIV) == TIM_CLOCKDIVISION_DIV1) || \ + ((DIV) == TIM_CLOCKDIVISION_DIV2) || \ + ((DIV) == TIM_CLOCKDIVISION_DIV4)) +/** + * @} + */ + +/** @defgroup TIM_Output_Compare_and_PWM_modes + * @{ + */ +#define TIM_OCMODE_TIMING ((uint32_t)0x0000) +#define TIM_OCMODE_ACTIVE (TIM_CCMR1_OC1M_0) +#define TIM_OCMODE_INACTIVE (TIM_CCMR1_OC1M_1) +#define TIM_OCMODE_TOGGLE (TIM_CCMR1_OC1M_0 | TIM_CCMR1_OC1M_1) +#define TIM_OCMODE_PWM1 (TIM_CCMR1_OC1M_1 | TIM_CCMR1_OC1M_2) +#define TIM_OCMODE_PWM2 (TIM_CCMR1_OC1M) +#define TIM_OCMODE_FORCED_ACTIVE (TIM_CCMR1_OC1M_0 | TIM_CCMR1_OC1M_2) +#define TIM_OCMODE_FORCED_INACTIVE (TIM_CCMR1_OC1M_2) + +#define IS_TIM_PWM_MODE(MODE) (((MODE) == TIM_OCMODE_PWM1) || \ + ((MODE) == TIM_OCMODE_PWM2)) + +#define IS_TIM_OC_MODE(MODE) (((MODE) == TIM_OCMODE_TIMING) || \ + ((MODE) == TIM_OCMODE_ACTIVE) || \ + ((MODE) == TIM_OCMODE_INACTIVE) || \ + ((MODE) == TIM_OCMODE_TOGGLE) || \ + ((MODE) == TIM_OCMODE_FORCED_ACTIVE) || \ + ((MODE) == TIM_OCMODE_FORCED_INACTIVE)) +/** + * @} + */ + +/** @defgroup TIM_Output_Compare_State + * @{ + */ +#define TIM_OUTPUTSTATE_DISABLE ((uint32_t)0x0000) +#define TIM_OUTPUTSTATE_ENABLE (TIM_CCER_CC1E) + +#define IS_TIM_OUTPUT_STATE(STATE) (((STATE) == TIM_OUTPUTSTATE_DISABLE) || \ + ((STATE) == TIM_OUTPUTSTATE_ENABLE)) +/** + * @} + */ +/** @defgroup TIM_Output_Fast_State + * @{ + */ +#define TIM_OCFAST_DISABLE ((uint32_t)0x0000) +#define TIM_OCFAST_ENABLE (TIM_CCMR1_OC1FE) + +#define IS_TIM_FAST_STATE(STATE) (((STATE) == TIM_OCFAST_DISABLE) || \ + ((STATE) == TIM_OCFAST_ENABLE)) +/** + * @} + */ +/** @defgroup TIM_Output_Compare_N_State + * @{ + */ +#define TIM_OUTPUTNSTATE_DISABLE ((uint32_t)0x0000) +#define TIM_OUTPUTNSTATE_ENABLE (TIM_CCER_CC1NE) + +#define IS_TIM_OUTPUTN_STATE(STATE) (((STATE) == TIM_OUTPUTNSTATE_DISABLE) || \ + ((STATE) == TIM_OUTPUTNSTATE_ENABLE)) +/** + * @} + */ + +/** @defgroup TIM_Output_Compare_Polarity + * @{ + */ +#define TIM_OCPOLARITY_HIGH ((uint32_t)0x0000) +#define TIM_OCPOLARITY_LOW (TIM_CCER_CC1P) + +#define IS_TIM_OC_POLARITY(POLARITY) (((POLARITY) == TIM_OCPOLARITY_HIGH) || \ + ((POLARITY) == TIM_OCPOLARITY_LOW)) +/** + * @} + */ + +/** @defgroup TIM_Channel + * @{ + */ + +#define TIM_CHANNEL_1 ((uint32_t)0x0000) +#define TIM_CHANNEL_2 ((uint32_t)0x0004) +#define TIM_CHANNEL_3 ((uint32_t)0x0008) +#define TIM_CHANNEL_4 ((uint32_t)0x000C) +#define TIM_CHANNEL_ALL ((uint32_t)0x0018) + +#define IS_TIM_CHANNELS(CHANNEL) (((CHANNEL) == TIM_CHANNEL_1) || \ + ((CHANNEL) == TIM_CHANNEL_2) || \ + ((CHANNEL) == TIM_CHANNEL_3) || \ + ((CHANNEL) == TIM_CHANNEL_4) || \ + ((CHANNEL) == TIM_CHANNEL_ALL)) + +#define IS_TIM_PWMI_CHANNELS(CHANNEL) (((CHANNEL) == TIM_CHANNEL_1) || \ + ((CHANNEL) == TIM_CHANNEL_2)) + +#define IS_TIM_OPM_CHANNELS(CHANNEL) (((CHANNEL) == TIM_CHANNEL_1) || \ + ((CHANNEL) == TIM_CHANNEL_2)) +/** + * @} + */ + +/** @defgroup TIM_Input_Capture_Polarity + * @{ + */ +#define TIM_ICPOLARITY_RISING TIM_INPUTCHANNELPOLARITY_RISING +#define TIM_ICPOLARITY_FALLING TIM_INPUTCHANNELPOLARITY_FALLING +#define TIM_ICPOLARITY_BOTHEDGE TIM_INPUTCHANNELPOLARITY_BOTHEDGE + +#define IS_TIM_IC_POLARITY(POLARITY) (((POLARITY) == TIM_ICPOLARITY_RISING) || \ + ((POLARITY) == TIM_ICPOLARITY_FALLING) || \ + ((POLARITY) == TIM_ICPOLARITY_BOTHEDGE)) +/** + * @} + */ + +/** @defgroup TIM_Input_Capture_Selection + * @{ + */ +#define TIM_ICSELECTION_DIRECTTI (TIM_CCMR1_CC1S_0) /*!< TIM Input 1, 2, 3 or 4 is selected to be + connected to IC1, IC2, IC3 or IC4, respectively */ +#define TIM_ICSELECTION_INDIRECTTI (TIM_CCMR1_CC1S_1) /*!< TIM Input 1, 2, 3 or 4 is selected to be + connected to IC2, IC1, IC4 or IC3, respectively */ +#define TIM_ICSELECTION_TRC (TIM_CCMR1_CC1S) /*!< TIM Input 1, 2, 3 or 4 is selected to be connected to TRC */ + +#define IS_TIM_IC_SELECTION(SELECTION) (((SELECTION) == TIM_ICSELECTION_DIRECTTI) || \ + ((SELECTION) == TIM_ICSELECTION_INDIRECTTI) || \ + ((SELECTION) == TIM_ICSELECTION_TRC)) +/** + * @} + */ + +/** @defgroup TIM_Input_Capture_Prescaler + * @{ + */ +#define TIM_ICPSC_DIV1 ((uint32_t)0x0000) /*!< Capture performed each time an edge is detected on the capture input */ +#define TIM_ICPSC_DIV2 (TIM_CCMR1_IC1PSC_0) /*!< Capture performed once every 2 events */ +#define TIM_ICPSC_DIV4 (TIM_CCMR1_IC1PSC_1) /*!< Capture performed once every 4 events */ +#define TIM_ICPSC_DIV8 (TIM_CCMR1_IC1PSC) /*!< Capture performed once every 8 events */ + +#define IS_TIM_IC_PRESCALER(PRESCALER) (((PRESCALER) == TIM_ICPSC_DIV1) || \ + ((PRESCALER) == TIM_ICPSC_DIV2) || \ + ((PRESCALER) == TIM_ICPSC_DIV4) || \ + ((PRESCALER) == TIM_ICPSC_DIV8)) +/** + * @} + */ + +/** @defgroup TIM_One_Pulse_Mode + * @{ + */ +#define TIM_OPMODE_SINGLE (TIM_CR1_OPM) +#define TIM_OPMODE_REPETITIVE ((uint32_t)0x0000) +#define IS_TIM_OPM_MODE(MODE) (((MODE) == TIM_OPMODE_SINGLE) || \ + ((MODE) == TIM_OPMODE_REPETITIVE)) +/** + * @} + */ +/** @defgroup TIM_Encoder_Mode + * @{ + */ +#define TIM_ENCODERMODE_TI1 (TIM_SMCR_SMS_0) +#define TIM_ENCODERMODE_TI2 (TIM_SMCR_SMS_1) +#define TIM_ENCODERMODE_TI12 (TIM_SMCR_SMS_1 | TIM_SMCR_SMS_0) +#define IS_TIM_ENCODER_MODE(MODE) (((MODE) == TIM_ENCODERMODE_TI1) || \ + ((MODE) == TIM_ENCODERMODE_TI2) || \ + ((MODE) == TIM_ENCODERMODE_TI12)) +/** + * @} + */ +/** @defgroup TIM_Interrupt_definition + * @{ + */ +#define TIM_IT_UPDATE (TIM_DIER_UIE) +#define TIM_IT_CC1 (TIM_DIER_CC1IE) +#define TIM_IT_CC2 (TIM_DIER_CC2IE) +#define TIM_IT_CC3 (TIM_DIER_CC3IE) +#define TIM_IT_CC4 (TIM_DIER_CC4IE) +#define TIM_IT_TRIGGER (TIM_DIER_TIE) + +#define IS_TIM_IT(IT) ((((IT) & 0xFFFFFFA0) == 0x00000000) && ((IT) != 0x00000000)) + +#define IS_TIM_GET_IT(IT) (((IT) == TIM_IT_UPDATE) || \ + ((IT) == TIM_IT_CC1) || \ + ((IT) == TIM_IT_CC2) || \ + ((IT) == TIM_IT_CC3) || \ + ((IT) == TIM_IT_CC4) || \ + ((IT) == TIM_IT_TRIGGER)) +/** + * @} + */ + +/** @defgroup TIM_DMA_sources + * @{ + */ +#define TIM_DMA_UPDATE (TIM_DIER_UDE) +#define TIM_DMA_CC1 (TIM_DIER_CC1DE) +#define TIM_DMA_CC2 (TIM_DIER_CC2DE) +#define TIM_DMA_CC3 (TIM_DIER_CC3DE) +#define TIM_DMA_CC4 (TIM_DIER_CC4DE) +#define TIM_DMA_TRIGGER (TIM_DIER_TDE) +#define IS_TIM_DMA_SOURCE(SOURCE) ((((SOURCE) & 0xFFFFA0FF) == 0x00000000) && ((SOURCE) != 0x00000000)) + +/** + * @} + */ + +/** @defgroup TIM_Event_Source + * @{ + */ +#define TIM_EventSource_Update TIM_EGR_UG +#define TIM_EventSource_CC1 TIM_EGR_CC1G +#define TIM_EventSource_CC2 TIM_EGR_CC2G +#define TIM_EventSource_CC3 TIM_EGR_CC3G +#define TIM_EventSource_CC4 TIM_EGR_CC4G +#define TIM_EventSource_Trigger TIM_EGR_TG +#define IS_TIM_EVENT_SOURCE(SOURCE) ((((SOURCE) & 0xFFFFFFA0) == 0x00000000) && ((SOURCE) != 0x00000000)) + +/** + * @} + */ + +/** @defgroup TIM_Flag_definition + * @{ + */ +#define TIM_FLAG_UPDATE (TIM_SR_UIF) +#define TIM_FLAG_CC1 (TIM_SR_CC1IF) +#define TIM_FLAG_CC2 (TIM_SR_CC2IF) +#define TIM_FLAG_CC3 (TIM_SR_CC3IF) +#define TIM_FLAG_CC4 (TIM_SR_CC4IF) +#define TIM_FLAG_TRIGGER (TIM_SR_TIF) +#define TIM_FLAG_CC1OF (TIM_SR_CC1OF) +#define TIM_FLAG_CC2OF (TIM_SR_CC2OF) +#define TIM_FLAG_CC3OF (TIM_SR_CC3OF) +#define TIM_FLAG_CC4OF (TIM_SR_CC4OF) + +#define IS_TIM_FLAG(FLAG) (((FLAG) == TIM_FLAG_UPDATE) || \ + ((FLAG) == TIM_FLAG_CC1) || \ + ((FLAG) == TIM_FLAG_CC2) || \ + ((FLAG) == TIM_FLAG_CC3) || \ + ((FLAG) == TIM_FLAG_CC4) || \ + ((FLAG) == TIM_FLAG_TRIGGER) || \ + ((FLAG) == TIM_FLAG_CC1OF) || \ + ((FLAG) == TIM_FLAG_CC2OF) || \ + ((FLAG) == TIM_FLAG_CC3OF) || \ + ((FLAG) == TIM_FLAG_CC4OF)) +/** + * @} + */ + +/** @defgroup TIM_Clock_Source + * @{ + */ +#define TIM_CLOCKSOURCE_ETRMODE2 (TIM_SMCR_ETPS_1) +#define TIM_CLOCKSOURCE_INTERNAL (TIM_SMCR_ETPS_0) +#define TIM_CLOCKSOURCE_ITR0 ((uint32_t)0x0000) +#define TIM_CLOCKSOURCE_ITR1 (TIM_SMCR_TS_0) +#define TIM_CLOCKSOURCE_ITR2 (TIM_SMCR_TS_1) +#define TIM_CLOCKSOURCE_ITR3 (TIM_SMCR_TS_0 | TIM_SMCR_TS_1) +#define TIM_CLOCKSOURCE_TI1ED (TIM_SMCR_TS_2) +#define TIM_CLOCKSOURCE_TI1 (TIM_SMCR_TS_0 | TIM_SMCR_TS_2) +#define TIM_CLOCKSOURCE_TI2 (TIM_SMCR_TS_1 | TIM_SMCR_TS_2) +#define TIM_CLOCKSOURCE_ETRMODE1 (TIM_SMCR_TS) + +#define IS_TIM_CLOCKSOURCE(CLOCK) (((CLOCK) == TIM_CLOCKSOURCE_INTERNAL) || \ + ((CLOCK) == TIM_CLOCKSOURCE_ETRMODE2) || \ + ((CLOCK) == TIM_CLOCKSOURCE_ITR0) || \ + ((CLOCK) == TIM_CLOCKSOURCE_ITR1) || \ + ((CLOCK) == TIM_CLOCKSOURCE_ITR2) || \ + ((CLOCK) == TIM_CLOCKSOURCE_ITR3) || \ + ((CLOCK) == TIM_CLOCKSOURCE_TI1ED) || \ + ((CLOCK) == TIM_CLOCKSOURCE_TI1) || \ + ((CLOCK) == TIM_CLOCKSOURCE_TI2) || \ + ((CLOCK) == TIM_CLOCKSOURCE_ETRMODE1)) +/** + * @} + */ + +/** @defgroup TIM_Clock_Polarity + * @{ + */ +#define TIM_CLOCKPOLARITY_INVERTED TIM_ETRPOLARITY_INVERTED /*!< Polarity for ETRx clock sources */ +#define TIM_CLOCKPOLARITY_NONINVERTED TIM_ETRPOLARITY_NONINVERTED /*!< Polarity for ETRx clock sources */ +#define TIM_CLOCKPOLARITY_RISING TIM_INPUTCHANNELPOLARITY_RISING /*!< Polarity for TIx clock sources */ +#define TIM_CLOCKPOLARITY_FALLING TIM_INPUTCHANNELPOLARITY_FALLING /*!< Polarity for TIx clock sources */ +#define TIM_CLOCKPOLARITY_BOTHEDGE TIM_INPUTCHANNELPOLARITY_BOTHEDGE /*!< Polarity for TIx clock sources */ + +#define IS_TIM_CLOCKPOLARITY(POLARITY) (((POLARITY) == TIM_CLOCKPOLARITY_INVERTED) || \ + ((POLARITY) == TIM_CLOCKPOLARITY_NONINVERTED) || \ + ((POLARITY) == TIM_CLOCKPOLARITY_RISING) || \ + ((POLARITY) == TIM_CLOCKPOLARITY_FALLING) || \ + ((POLARITY) == TIM_CLOCKPOLARITY_BOTHEDGE)) +/** + * @} + */ +/** @defgroup TIM_Clock_Prescaler + * @{ + */ +#define TIM_CLOCKPRESCALER_DIV1 TIM_ETRPRESCALER_DIV1 /*!< No prescaler is used */ +#define TIM_CLOCKPRESCALER_DIV2 TIM_ETRPRESCALER_DIV2 /*!< Prescaler for External ETR Clock: Capture performed once every 2 events. */ +#define TIM_CLOCKPRESCALER_DIV4 TIM_ETRPRESCALER_DIV4 /*!< Prescaler for External ETR Clock: Capture performed once every 4 events. */ +#define TIM_CLOCKPRESCALER_DIV8 TIM_ETRPRESCALER_DIV8 /*!< Prescaler for External ETR Clock: Capture performed once every 8 events. */ + +#define IS_TIM_CLOCKPRESCALER(PRESCALER) (((PRESCALER) == TIM_CLOCKPRESCALER_DIV1) || \ + ((PRESCALER) == TIM_CLOCKPRESCALER_DIV2) || \ + ((PRESCALER) == TIM_CLOCKPRESCALER_DIV4) || \ + ((PRESCALER) == TIM_CLOCKPRESCALER_DIV8)) +/** + * @} + */ +/** @defgroup TIM_Clock_Filter + * @{ + */ +#define IS_TIM_CLOCKFILTER(ICFILTER) ((ICFILTER) <= 0xF) +/** + * @} + */ + +/** @defgroup TIM_ClearInput_Source + * @{ + */ +#define TIM_CLEARINPUTSOURCE_ETR ((uint32_t)0x0001) +#define TIM_CLEARINPUTSOURCE_NONE ((uint32_t)0x0000) + +#define IS_TIM_CLEARINPUT_SOURCE(SOURCE) (((SOURCE) == TIM_CLEARINPUTSOURCE_NONE) || \ + ((SOURCE) == TIM_CLEARINPUTSOURCE_ETR)) +/** + * @} + */ + +/** @defgroup TIM_ClearInput_Polarity + * @{ + */ +#define TIM_CLEARINPUTPOLARITY_INVERTED TIM_ETRPOLARITY_INVERTED /*!< Polarity for ETRx pin */ +#define TIM_CLEARINPUTPOLARITY_NONINVERTED TIM_ETRPOLARITY_NONINVERTED /*!< Polarity for ETRx pin */ +#define IS_TIM_CLEARINPUT_POLARITY(POLARITY) (((POLARITY) == TIM_CLEARINPUTPOLARITY_INVERTED) || \ + ((POLARITY) == TIM_CLEARINPUTPOLARITY_NONINVERTED)) +/** + * @} + */ + +/** @defgroup TIM_ClearInput_Prescaler + * @{ + */ +#define TIM_CLEARINPUTPRESCALER_DIV1 TIM_ETRPRESCALER_DIV1 /*!< No prescaler is used */ +#define TIM_CLEARINPUTPRESCALER_DIV2 TIM_ETRPRESCALER_DIV2 /*!< Prescaler for External ETR pin: Capture performed once every 2 events. */ +#define TIM_CLEARINPUTPRESCALER_DIV4 TIM_ETRPRESCALER_DIV4 /*!< Prescaler for External ETR pin: Capture performed once every 4 events. */ +#define TIM_CLEARINPUTPRESCALER_DIV8 TIM_ETRPRESCALER_DIV8 /*!< Prescaler for External ETR pin: Capture performed once every 8 events. */ +#define IS_TIM_CLEARINPUT_PRESCALER(PRESCALER) (((PRESCALER) == TIM_CLEARINPUTPRESCALER_DIV1) || \ + ((PRESCALER) == TIM_CLEARINPUTPRESCALER_DIV2) || \ + ((PRESCALER) == TIM_CLEARINPUTPRESCALER_DIV4) || \ + ((PRESCALER) == TIM_CLEARINPUTPRESCALER_DIV8)) +/** + * @} + */ + +/** @defgroup TIM_ClearInput_Filter + * @{ + */ +#define IS_TIM_CLEARINPUT_FILTER(ICFILTER) ((ICFILTER) <= 0xF) +/** + * @} + */ + + +/** @defgroup TIM_Master_Mode_Selection + * @{ + */ +#define TIM_TRGO_RESET ((uint32_t)0x0000) +#define TIM_TRGO_ENABLE (TIM_CR2_MMS_0) +#define TIM_TRGO_UPDATE (TIM_CR2_MMS_1) +#define TIM_TRGO_OC1 ((TIM_CR2_MMS_1 | TIM_CR2_MMS_0)) +#define TIM_TRGO_OC1REF (TIM_CR2_MMS_2) +#define TIM_TRGO_OC2REF ((TIM_CR2_MMS_2 | TIM_CR2_MMS_0)) +#define TIM_TRGO_OC3REF ((TIM_CR2_MMS_2 | TIM_CR2_MMS_1)) +#define TIM_TRGO_OC4REF ((TIM_CR2_MMS_2 | TIM_CR2_MMS_1 | TIM_CR2_MMS_0)) + +#define IS_TIM_TRGO_SOURCE(SOURCE) (((SOURCE) == TIM_TRGO_RESET) || \ + ((SOURCE) == TIM_TRGO_ENABLE) || \ + ((SOURCE) == TIM_TRGO_UPDATE) || \ + ((SOURCE) == TIM_TRGO_OC1) || \ + ((SOURCE) == TIM_TRGO_OC1REF) || \ + ((SOURCE) == TIM_TRGO_OC2REF) || \ + ((SOURCE) == TIM_TRGO_OC3REF) || \ + ((SOURCE) == TIM_TRGO_OC4REF)) + + +/** + * @} + */ +/** @defgroup TIM_Slave_Mode + * @{ + */ +#define TIM_SLAVEMODE_DISABLE ((uint32_t)0x0000) +#define TIM_SLAVEMODE_RESET ((uint32_t)0x0004) +#define TIM_SLAVEMODE_GATED ((uint32_t)0x0005) +#define TIM_SLAVEMODE_TRIGGER ((uint32_t)0x0006) +#define TIM_SLAVEMODE_EXTERNAL1 ((uint32_t)0x0007) + +#define IS_TIM_SLAVE_MODE(MODE) (((MODE) == TIM_SLAVEMODE_DISABLE) || \ + ((MODE) == TIM_SLAVEMODE_GATED) || \ + ((MODE) == TIM_SLAVEMODE_RESET) || \ + ((MODE) == TIM_SLAVEMODE_TRIGGER) || \ + ((MODE) == TIM_SLAVEMODE_EXTERNAL1)) +/** + * @} + */ + +/** @defgroup TIM_Master_Slave_Mode + * @{ + */ + +#define TIM_MASTERSLAVEMODE_ENABLE ((uint32_t)0x0080) +#define TIM_MASTERSLAVEMODE_DISABLE ((uint32_t)0x0000) +#define IS_TIM_MSM_STATE(STATE) (((STATE) == TIM_MASTERSLAVEMODE_ENABLE) || \ + ((STATE) == TIM_MASTERSLAVEMODE_DISABLE)) +/** + * @} + */ +/** @defgroup TIM_Trigger_Selection + * @{ + */ +#define TIM_TS_ITR0 ((uint32_t)0x0000) +#define TIM_TS_ITR1 ((uint32_t)0x0010) +#define TIM_TS_ITR2 ((uint32_t)0x0020) +#define TIM_TS_ITR3 ((uint32_t)0x0030) +#define TIM_TS_TI1F_ED ((uint32_t)0x0040) +#define TIM_TS_TI1FP1 ((uint32_t)0x0050) +#define TIM_TS_TI2FP2 ((uint32_t)0x0060) +#define TIM_TS_ETRF ((uint32_t)0x0070) +#define TIM_TS_NONE ((uint32_t)0xFFFF) +#define IS_TIM_TRIGGER_SELECTION(SELECTION) (((SELECTION) == TIM_TS_ITR0) || \ + ((SELECTION) == TIM_TS_ITR1) || \ + ((SELECTION) == TIM_TS_ITR2) || \ + ((SELECTION) == TIM_TS_ITR3) || \ + ((SELECTION) == TIM_TS_TI1F_ED) || \ + ((SELECTION) == TIM_TS_TI1FP1) || \ + ((SELECTION) == TIM_TS_TI2FP2) || \ + ((SELECTION) == TIM_TS_ETRF)) +#define IS_TIM_INTERNAL_TRIGGER_SELECTION(SELECTION) (((SELECTION) == TIM_TS_ITR0) || \ + ((SELECTION) == TIM_TS_ITR1) || \ + ((SELECTION) == TIM_TS_ITR2) || \ + ((SELECTION) == TIM_TS_ITR3)) +#define IS_TIM_INTERNAL_TRIGGEREVENT_SELECTION(SELECTION) (((SELECTION) == TIM_TS_ITR0) || \ + ((SELECTION) == TIM_TS_ITR1) || \ + ((SELECTION) == TIM_TS_ITR2) || \ + ((SELECTION) == TIM_TS_ITR3) || \ + ((SELECTION) == TIM_TS_NONE)) +/** + * @} + */ + +/** @defgroup TIM_Trigger_Polarity + * @{ + */ +#define TIM_TRIGGERPOLARITY_INVERTED TIM_ETRPOLARITY_INVERTED /*!< Polarity for ETRx trigger sources */ +#define TIM_TRIGGERPOLARITY_NONINVERTED TIM_ETRPOLARITY_NONINVERTED /*!< Polarity for ETRx trigger sources */ +#define TIM_TRIGGERPOLARITY_RISING TIM_INPUTCHANNELPOLARITY_RISING /*!< Polarity for TIxFPx or TI1_ED trigger sources */ +#define TIM_TRIGGERPOLARITY_FALLING TIM_INPUTCHANNELPOLARITY_FALLING /*!< Polarity for TIxFPx or TI1_ED trigger sources */ +#define TIM_TRIGGERPOLARITY_BOTHEDGE TIM_INPUTCHANNELPOLARITY_BOTHEDGE /*!< Polarity for TIxFPx or TI1_ED trigger sources */ + +#define IS_TIM_TRIGGERPOLARITY(POLARITY) (((POLARITY) == TIM_TRIGGERPOLARITY_INVERTED ) || \ + ((POLARITY) == TIM_TRIGGERPOLARITY_NONINVERTED) || \ + ((POLARITY) == TIM_TRIGGERPOLARITY_RISING ) || \ + ((POLARITY) == TIM_TRIGGERPOLARITY_FALLING ) || \ + ((POLARITY) == TIM_TRIGGERPOLARITY_BOTHEDGE )) +/** + * @} + */ + +/** @defgroup TIM_Trigger_Prescaler + * @{ + */ +#define TIM_TRIGGERPRESCALER_DIV1 TIM_ETRPRESCALER_DIV1 /*!< No prescaler is used */ +#define TIM_TRIGGERPRESCALER_DIV2 TIM_ETRPRESCALER_DIV2 /*!< Prescaler for External ETR Trigger: Capture performed once every 2 events. */ +#define TIM_TRIGGERPRESCALER_DIV4 TIM_ETRPRESCALER_DIV4 /*!< Prescaler for External ETR Trigger: Capture performed once every 4 events. */ +#define TIM_TRIGGERPRESCALER_DIV8 TIM_ETRPRESCALER_DIV8 /*!< Prescaler for External ETR Trigger: Capture performed once every 8 events. */ + +#define IS_TIM_TRIGGERPRESCALER(PRESCALER) (((PRESCALER) == TIM_TRIGGERPRESCALER_DIV1) || \ + ((PRESCALER) == TIM_TRIGGERPRESCALER_DIV2) || \ + ((PRESCALER) == TIM_TRIGGERPRESCALER_DIV4) || \ + ((PRESCALER) == TIM_TRIGGERPRESCALER_DIV8)) +/** + * @} + */ + +/** @defgroup TIM_Trigger_Filter + * @{ + */ +#define IS_TIM_TRIGGERFILTER(ICFILTER) ((ICFILTER) <= 0xF) +/** + * @} + */ + + /** @defgroup TIM_TI1_Selection + * @{ + */ +#define TIM_TI1SELECTION_CH1 ((uint32_t)0x0000) +#define TIM_TI1SELECTION_XORCOMBINATION (TIM_CR2_TI1S) + +#define IS_TIM_TI1SELECTION(TI1SELECTION) (((TI1SELECTION) == TIM_TI1SELECTION_CH1) || \ + ((TI1SELECTION) == TIM_TI1SELECTION_XORCOMBINATION)) +/** + * @} + */ + +/** @defgroup TIM_DMA_Base_address + * @{ + */ +#define TIM_DMABase_CR1 (0x00000000) +#define TIM_DMABase_CR2 (0x00000001) +#define TIM_DMABase_SMCR (0x00000002) +#define TIM_DMABase_DIER (0x00000003) +#define TIM_DMABase_SR (0x00000004) +#define TIM_DMABase_EGR (0x00000005) +#define TIM_DMABase_CCMR1 (0x00000006) +#define TIM_DMABase_CCMR2 (0x00000007) +#define TIM_DMABase_CCER (0x00000008) +#define TIM_DMABase_CNT (0x00000009) +#define TIM_DMABase_PSC (0x0000000A) +#define TIM_DMABase_ARR (0x0000000B) +#define TIM_DMABase_CCR1 (0x0000000D) +#define TIM_DMABase_CCR2 (0x0000000E) +#define TIM_DMABase_CCR3 (0x0000000F) +#define TIM_DMABase_CCR4 (0x00000010) +#define TIM_DMABase_DCR (0x00000012) +#define TIM_DMABase_OR (0x00000013) +#define IS_TIM_DMA_BASE(BASE) (((BASE) == TIM_DMABase_CR1) || \ + ((BASE) == TIM_DMABase_CR2) || \ + ((BASE) == TIM_DMABase_SMCR) || \ + ((BASE) == TIM_DMABase_DIER) || \ + ((BASE) == TIM_DMABase_SR) || \ + ((BASE) == TIM_DMABase_EGR) || \ + ((BASE) == TIM_DMABase_CCMR1) || \ + ((BASE) == TIM_DMABase_CCMR2) || \ + ((BASE) == TIM_DMABase_CCER) || \ + ((BASE) == TIM_DMABase_CNT) || \ + ((BASE) == TIM_DMABase_PSC) || \ + ((BASE) == TIM_DMABase_ARR) || \ + ((BASE) == TIM_DMABase_CCR1) || \ + ((BASE) == TIM_DMABase_CCR2) || \ + ((BASE) == TIM_DMABase_CCR3) || \ + ((BASE) == TIM_DMABase_CCR4) || \ + ((BASE) == TIM_DMABase_DCR) || \ + ((BASE) == TIM_DMABase_OR)) +/** + * @} + */ + +/** @defgroup TIM_DMA_Burst_Length + * @{ + */ +#define TIM_DMABurstLength_1Transfer (0x00000000) +#define TIM_DMABurstLength_2Transfers (0x00000100) +#define TIM_DMABurstLength_3Transfers (0x00000200) +#define TIM_DMABurstLength_4Transfers (0x00000300) +#define TIM_DMABurstLength_5Transfers (0x00000400) +#define TIM_DMABurstLength_6Transfers (0x00000500) +#define TIM_DMABurstLength_7Transfers (0x00000600) +#define TIM_DMABurstLength_8Transfers (0x00000700) +#define TIM_DMABurstLength_9Transfers (0x00000800) +#define TIM_DMABurstLength_10Transfers (0x00000900) +#define TIM_DMABurstLength_11Transfers (0x00000A00) +#define TIM_DMABurstLength_12Transfers (0x00000B00) +#define TIM_DMABurstLength_13Transfers (0x00000C00) +#define TIM_DMABurstLength_14Transfers (0x00000D00) +#define TIM_DMABurstLength_15Transfers (0x00000E00) +#define TIM_DMABurstLength_16Transfers (0x00000F00) +#define TIM_DMABurstLength_17Transfers (0x00001000) +#define TIM_DMABurstLength_18Transfers (0x00001100) +#define IS_TIM_DMA_LENGTH(LENGTH) (((LENGTH) == TIM_DMABurstLength_1Transfer) || \ + ((LENGTH) == TIM_DMABurstLength_2Transfers) || \ + ((LENGTH) == TIM_DMABurstLength_3Transfers) || \ + ((LENGTH) == TIM_DMABurstLength_4Transfers) || \ + ((LENGTH) == TIM_DMABurstLength_5Transfers) || \ + ((LENGTH) == TIM_DMABurstLength_6Transfers) || \ + ((LENGTH) == TIM_DMABurstLength_7Transfers) || \ + ((LENGTH) == TIM_DMABurstLength_8Transfers) || \ + ((LENGTH) == TIM_DMABurstLength_9Transfers) || \ + ((LENGTH) == TIM_DMABurstLength_10Transfers) || \ + ((LENGTH) == TIM_DMABurstLength_11Transfers) || \ + ((LENGTH) == TIM_DMABurstLength_12Transfers) || \ + ((LENGTH) == TIM_DMABurstLength_13Transfers) || \ + ((LENGTH) == TIM_DMABurstLength_14Transfers) || \ + ((LENGTH) == TIM_DMABurstLength_15Transfers) || \ + ((LENGTH) == TIM_DMABurstLength_16Transfers) || \ + ((LENGTH) == TIM_DMABurstLength_17Transfers) || \ + ((LENGTH) == TIM_DMABurstLength_18Transfers)) +/** + * @} + */ + +/** @defgroup TIM_Input_Capture_Filer_Value + * @{ + */ +#define IS_TIM_IC_FILTER(ICFILTER) ((ICFILTER) <= 0xF) +/** + * @} + */ + +/** @defgroup DMA_Handle_index + * @{ + */ +#define TIM_DMA_ID_UPDATE ((uint16_t) 0x0) /*!< Index of the DMA handle used for Update DMA requests */ +#define TIM_DMA_ID_CC1 ((uint16_t) 0x1) /*!< Index of the DMA handle used for Capture/Compare 1 DMA requests */ +#define TIM_DMA_ID_CC2 ((uint16_t) 0x2) /*!< Index of the DMA handle used for Capture/Compare 2 DMA requests */ +#define TIM_DMA_ID_CC3 ((uint16_t) 0x3) /*!< Index of the DMA handle used for Capture/Compare 3 DMA requests */ +#define TIM_DMA_ID_CC4 ((uint16_t) 0x4) /*!< Index of the DMA handle used for Capture/Compare 4 DMA requests */ +#define TIM_DMA_ID_TRIGGER ((uint16_t) 0x5) /*!< Index of the DMA handle used for Trigger DMA requests */ +/** + * @} + */ + +/** @defgroup Channel_CC_State + * @{ + */ +#define TIM_CCx_ENABLE ((uint32_t)0x0001) +#define TIM_CCx_DISABLE ((uint32_t)0x0000) +/** + * @} + */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ + +/** @brief Reset UART handle state + * @param __HANDLE__: TIM handle + * @retval None + */ +#define __HAL_TIM_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_TIM_STATE_RESET) + +/** + * @brief Enable the TIM peripheral. + * @param __HANDLE__: TIM handle + * @retval None + */ +#define __HAL_TIM_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1|=(TIM_CR1_CEN)) + +/* The counter of a timer instance is disabled only if all the CCx channels have + been disabled */ +#define CCER_CCxE_MASK ((uint32_t)(TIM_CCER_CC1E | TIM_CCER_CC2E | TIM_CCER_CC3E | TIM_CCER_CC4E)) + +/** + * @brief Disable the TIM peripheral. + * @param __HANDLE__: TIM handle + * @retval None + */ +#define __HAL_TIM_DISABLE(__HANDLE__) \ + do { \ + if (((__HANDLE__)->Instance->CCER & CCER_CCxE_MASK) == 0) \ + { \ + (__HANDLE__)->Instance->CR1 &= ~(TIM_CR1_CEN); \ + } \ + } while(0) + +#define __HAL_TIM_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->DIER |= (__INTERRUPT__)) +#define __HAL_TIM_ENABLE_DMA(__HANDLE__, __DMA__) ((__HANDLE__)->Instance->DIER |= (__DMA__)) +#define __HAL_TIM_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->DIER &= ~(__INTERRUPT__)) +#define __HAL_TIM_DISABLE_DMA(__HANDLE__, __DMA__) ((__HANDLE__)->Instance->DIER &= ~(__DMA__)) +#define __HAL_TIM_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->SR &(__FLAG__)) == (__FLAG__)) +#define __HAL_TIM_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->SR &= ~(__FLAG__)) + +#define __HAL_TIM_GET_ITSTATUS(__HANDLE__, __INTERRUPT__) ((((__HANDLE__)->Instance->DIER & (__INTERRUPT__)) == (__INTERRUPT__)) ? SET : RESET) +#define __HAL_TIM_CLEAR_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->SR &= ~(__INTERRUPT__)) + +#define __HAL_TIM_DIRECTION_STATUS(__HANDLE__) (((__HANDLE__)->Instance->CR1 &(TIM_CR1_DIR)) == (TIM_CR1_DIR)) +#define __HAL_TIM_PRESCALER (__HANDLE__, __PRESC__) ((__HANDLE__)->Instance->PSC |= (__PRESC__)) + +#define __HAL_TIM_SetICPrescalerValue(__HANDLE__, __CHANNEL__, __ICPSC__) \ +(((__CHANNEL__) == TIM_CHANNEL_1) ? ((__HANDLE__)->Instance->CCMR1 |= (__ICPSC__)) :\ + ((__CHANNEL__) == TIM_CHANNEL_2) ? ((__HANDLE__)->Instance->CCMR1 |= ((__ICPSC__) << 8)) :\ + ((__CHANNEL__) == TIM_CHANNEL_3) ? ((__HANDLE__)->Instance->CCMR2 |= (__ICPSC__)) :\ + ((__HANDLE__)->Instance->CCMR2 |= ((__ICPSC__) << 8))) + +#define __HAL_TIM_ResetICPrescalerValue(__HANDLE__, __CHANNEL__) \ +(((__CHANNEL__) == TIM_CHANNEL_1) ? ((__HANDLE__)->Instance->CCMR1 &= (uint16_t)~TIM_CCMR1_IC1PSC) :\ + ((__CHANNEL__) == TIM_CHANNEL_2) ? ((__HANDLE__)->Instance->CCMR1 &= (uint16_t)~TIM_CCMR1_IC2PSC) :\ + ((__CHANNEL__) == TIM_CHANNEL_3) ? ((__HANDLE__)->Instance->CCMR2 &= (uint16_t)~TIM_CCMR2_IC3PSC) :\ + ((__HANDLE__)->Instance->CCMR2 &= (uint16_t)~TIM_CCMR2_IC4PSC)) + +/** + * @brief Sets the TIM Capture Compare Register value on runtime without + * calling another time ConfigChannel function. + * @param __HANDLE__: TIM handle. + * @param __CHANNEL__ : TIM Channels to be configured. + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @arg TIM_CHANNEL_3: TIM Channel 3 selected + * @arg TIM_CHANNEL_4: TIM Channel 4 selected + * @param __COMPARE__: specifies the Capture Compare register new value. + * @retval None + */ +#define __HAL_TIM_SetCompare(__HANDLE__, __CHANNEL__, __COMPARE__) \ +(*(__IO uint32_t *)(&((__HANDLE__)->Instance->CCR1) + ((__CHANNEL__) >> 2)) = (__COMPARE__)) + +/** + * @brief Gets the TIM Capture Compare Register value on runtime + * @param __HANDLE__: TIM handle. + * @param __CHANNEL__ : TIM Channel associated with the capture compare register + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: get capture/compare 1 register value + * @arg TIM_CHANNEL_2: get capture/compare 2 register value + * @arg TIM_CHANNEL_3: get capture/compare 3 register value + * @arg TIM_CHANNEL_4: get capture/compare 4 register value + * @retval None + */ +#define __HAL_TIM_GetCompare(__HANDLE__, __CHANNEL__) \ + (*(__IO uint32_t *)(&((__HANDLE__)->Instance->CCR1) + ((__CHANNEL__) >> 2))) + +/** + * @brief Sets the TIM Counter Register value on runtime. + * @param __HANDLE__: TIM handle. + * @param __COUNTER__: specifies the Counter register new value. + * @retval None + */ +#define __HAL_TIM_SetCounter(__HANDLE__, __COUNTER__) ((__HANDLE__)->Instance->CNT = (__COUNTER__)) + +/** + * @brief Gets the TIM Counter Register value on runtime. + * @param __HANDLE__: TIM handle. + * @retval None + */ +#define __HAL_TIM_GetCounter(__HANDLE__) ((__HANDLE__)->Instance->CNT) + +/** + * @brief Sets the TIM Autoreload Register value on runtime without calling + * another time any Init function. + * @param __HANDLE__: TIM handle. + * @param __AUTORELOAD__: specifies the Counter register new value. + * @retval None + */ +#define __HAL_TIM_SetAutoreload(__HANDLE__, __AUTORELOAD__) \ + do{ \ + (__HANDLE__)->Instance->ARR = (__AUTORELOAD__); \ + (__HANDLE__)->Init.Period = (__AUTORELOAD__); \ + } while(0) +/** + * @brief Gets the TIM Autoreload Register value on runtime + * @param __HANDLE__: TIM handle. + * @retval None + */ +#define __HAL_TIM_GetAutoreload(__HANDLE__) ((__HANDLE__)->Instance->ARR) + +/** + * @brief Sets the TIM Clock Division value on runtime without calling + * another time any Init function. + * @param __HANDLE__: TIM handle. + * @param __CKD__: specifies the clock division value. + * This parameter can be one of the following value: + * @arg TIM_CLOCKDIVISION_DIV1 + * @arg TIM_CLOCKDIVISION_DIV2 + * @arg TIM_CLOCKDIVISION_DIV4 + * @retval None + */ +#define __HAL_TIM_SetClockDivision(__HANDLE__, __CKD__) \ + do{ \ + (__HANDLE__)->Instance->CR1 &= (uint16_t)(~TIM_CR1_CKD); \ + (__HANDLE__)->Instance->CR1 |= (__CKD__); \ + (__HANDLE__)->Init.ClockDivision = (__CKD__); \ + } while(0) +/** + * @brief Gets the TIM Clock Division value on runtime + * @param __HANDLE__: TIM handle. + * @retval None + */ +#define __HAL_TIM_GetClockDivision(__HANDLE__) ((__HANDLE__)->Instance->CR1 & TIM_CR1_CKD) + +/** + * @brief Sets the TIM Input Capture prescaler on runtime without calling + * another time HAL_TIM_IC_ConfigChannel() function. + * @param __HANDLE__: TIM handle. + * @param __CHANNEL__ : TIM Channels to be configured. + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: TIM Channel 1 selected + * @arg TIM_CHANNEL_2: TIM Channel 2 selected + * @arg TIM_CHANNEL_3: TIM Channel 3 selected + * @arg TIM_CHANNEL_4: TIM Channel 4 selected + * @param __ICPSC__: specifies the Input Capture4 prescaler new value. + * This parameter can be one of the following values: + * @arg TIM_ICPSC_DIV1: no prescaler + * @arg TIM_ICPSC_DIV2: capture is done once every 2 events + * @arg TIM_ICPSC_DIV4: capture is done once every 4 events + * @arg TIM_ICPSC_DIV8: capture is done once every 8 events + * @retval None + */ +#define __HAL_TIM_SetICPrescaler(__HANDLE__, __CHANNEL__, __ICPSC__) \ + do{ \ + __HAL_TIM_ResetICPrescalerValue((__HANDLE__), (__CHANNEL__)); \ + __HAL_TIM_SetICPrescalerValue((__HANDLE__), (__CHANNEL__), (__ICPSC__)); \ + } while(0) + +/** + * @brief Gets the TIM Input Capture prescaler on runtime + * @param __HANDLE__: TIM handle. + * @param __CHANNEL__ : TIM Channels to be configured. + * This parameter can be one of the following values: + * @arg TIM_CHANNEL_1: get input capture 1 prescaler value + * @arg TIM_CHANNEL_2: get input capture 2 prescaler value + * @arg TIM_CHANNEL_3: get input capture 3 prescaler value + * @arg TIM_CHANNEL_4: get input capture 4 prescaler value + * @retval None + */ +#define __HAL_TIM_GetICPrescaler(__HANDLE__, __CHANNEL__) \ + (((__CHANNEL__) == TIM_CHANNEL_1) ? ((__HANDLE__)->Instance->CCMR1 & TIM_CCMR1_IC1PSC) :\ + ((__CHANNEL__) == TIM_CHANNEL_2) ? (((__HANDLE__)->Instance->CCMR1 & TIM_CCMR1_IC2PSC) >> 8) :\ + ((__CHANNEL__) == TIM_CHANNEL_3) ? ((__HANDLE__)->Instance->CCMR2 & TIM_CCMR2_IC3PSC) :\ + (((__HANDLE__)->Instance->CCMR2 & TIM_CCMR2_IC4PSC)) >> 8) +/* Include TIM HAL Extension module */ +#include "stm32l0xx_hal_tim_ex.h" + +/* Exported functions --------------------------------------------------------*/ + +/* Time Base functions ********************************************************/ +HAL_StatusTypeDef HAL_TIM_Base_Init(TIM_HandleTypeDef *htim); +HAL_StatusTypeDef HAL_TIM_Base_DeInit(TIM_HandleTypeDef *htim); +void HAL_TIM_Base_MspInit(TIM_HandleTypeDef *htim); +void HAL_TIM_Base_MspDeInit(TIM_HandleTypeDef *htim); +/* Blocking mode: Polling */ +HAL_StatusTypeDef HAL_TIM_Base_Start(TIM_HandleTypeDef *htim); +HAL_StatusTypeDef HAL_TIM_Base_Stop(TIM_HandleTypeDef *htim); +/* Non-Blocking mode: Interrupt */ +HAL_StatusTypeDef HAL_TIM_Base_Start_IT(TIM_HandleTypeDef *htim); +HAL_StatusTypeDef HAL_TIM_Base_Stop_IT(TIM_HandleTypeDef *htim); +/* Non-Blocking mode: DMA */ +HAL_StatusTypeDef HAL_TIM_Base_Start_DMA(TIM_HandleTypeDef *htim, uint32_t *pData, uint16_t Length); +HAL_StatusTypeDef HAL_TIM_Base_Stop_DMA(TIM_HandleTypeDef *htim); + +/* Timer Output Compare functions **********************************************/ +HAL_StatusTypeDef HAL_TIM_OC_Init(TIM_HandleTypeDef *htim); +HAL_StatusTypeDef HAL_TIM_OC_DeInit(TIM_HandleTypeDef *htim); +void HAL_TIM_OC_MspInit(TIM_HandleTypeDef *htim); +void HAL_TIM_OC_MspDeInit(TIM_HandleTypeDef *htim); +/* Blocking mode: Polling */ +HAL_StatusTypeDef HAL_TIM_OC_Start(TIM_HandleTypeDef *htim, uint32_t Channel); +HAL_StatusTypeDef HAL_TIM_OC_Stop(TIM_HandleTypeDef *htim, uint32_t Channel); +/* Non-Blocking mode: Interrupt */ +HAL_StatusTypeDef HAL_TIM_OC_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel); +HAL_StatusTypeDef HAL_TIM_OC_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channel); +/* Non-Blocking mode: DMA */ +HAL_StatusTypeDef HAL_TIM_OC_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel, uint32_t *pData, uint16_t Length); +HAL_StatusTypeDef HAL_TIM_OC_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel); + +/* Timer PWM functions *********************************************************/ +HAL_StatusTypeDef HAL_TIM_PWM_Init(TIM_HandleTypeDef *htim); +HAL_StatusTypeDef HAL_TIM_PWM_DeInit(TIM_HandleTypeDef *htim); +void HAL_TIM_PWM_MspInit(TIM_HandleTypeDef *htim); +void HAL_TIM_PWM_MspDeInit(TIM_HandleTypeDef *htim); +/* Blocking mode: Polling */ +HAL_StatusTypeDef HAL_TIM_PWM_Start(TIM_HandleTypeDef *htim, uint32_t Channel); +HAL_StatusTypeDef HAL_TIM_PWM_Stop(TIM_HandleTypeDef *htim, uint32_t Channel); +/* Non-Blocking mode: Interrupt */ +HAL_StatusTypeDef HAL_TIM_PWM_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel); +HAL_StatusTypeDef HAL_TIM_PWM_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channel); +/* Non-Blocking mode: DMA */ +HAL_StatusTypeDef HAL_TIM_PWM_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel, uint32_t *pData, uint16_t Length); +HAL_StatusTypeDef HAL_TIM_PWM_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel); + +/* Timer Input Capture functions ***********************************************/ +HAL_StatusTypeDef HAL_TIM_IC_Init(TIM_HandleTypeDef *htim); +HAL_StatusTypeDef HAL_TIM_IC_DeInit(TIM_HandleTypeDef *htim); +void HAL_TIM_IC_MspInit(TIM_HandleTypeDef *htim); +void HAL_TIM_IC_MspDeInit(TIM_HandleTypeDef *htim); +/* Blocking mode: Polling */ +HAL_StatusTypeDef HAL_TIM_IC_Start(TIM_HandleTypeDef *htim, uint32_t Channel); +HAL_StatusTypeDef HAL_TIM_IC_Stop(TIM_HandleTypeDef *htim, uint32_t Channel); +/* Non-Blocking mode: Interrupt */ +HAL_StatusTypeDef HAL_TIM_IC_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel); +HAL_StatusTypeDef HAL_TIM_IC_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channel); +/* Non-Blocking mode: DMA */ +HAL_StatusTypeDef HAL_TIM_IC_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel, uint32_t *pData, uint16_t Length); +HAL_StatusTypeDef HAL_TIM_IC_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel); + +/* Timer One Pulse functions ***************************************************/ +HAL_StatusTypeDef HAL_TIM_OnePulse_Init(TIM_HandleTypeDef *htim, uint32_t OnePulseMode); +HAL_StatusTypeDef HAL_TIM_OnePulse_DeInit(TIM_HandleTypeDef *htim); +void HAL_TIM_OnePulse_MspInit(TIM_HandleTypeDef *htim); +void HAL_TIM_OnePulse_MspDeInit(TIM_HandleTypeDef *htim); +/* Blocking mode: Polling */ +HAL_StatusTypeDef HAL_TIM_OnePulse_Start(TIM_HandleTypeDef *htim, uint32_t OutputChannel); +HAL_StatusTypeDef HAL_TIM_OnePulse_Stop(TIM_HandleTypeDef *htim, uint32_t OutputChannel); + +/* Non-Blocking mode: Interrupt */ +HAL_StatusTypeDef HAL_TIM_OnePulse_Start_IT(TIM_HandleTypeDef *htim, uint32_t OutputChannel); +HAL_StatusTypeDef HAL_TIM_OnePulse_Stop_IT(TIM_HandleTypeDef *htim, uint32_t OutputChannel); + +/* Timer Encoder functions *****************************************************/ +HAL_StatusTypeDef HAL_TIM_Encoder_Init(TIM_HandleTypeDef *htim, TIM_Encoder_InitTypeDef* sConfig); +HAL_StatusTypeDef HAL_TIM_Encoder_DeInit(TIM_HandleTypeDef *htim); +void HAL_TIM_Encoder_MspInit(TIM_HandleTypeDef *htim); +void HAL_TIM_Encoder_MspDeInit(TIM_HandleTypeDef *htim); +/* Blocking mode: Polling */ +HAL_StatusTypeDef HAL_TIM_Encoder_Start(TIM_HandleTypeDef *htim, uint32_t Channel); +HAL_StatusTypeDef HAL_TIM_Encoder_Stop(TIM_HandleTypeDef *htim, uint32_t Channel); +/* Non-Blocking mode: Interrupt */ +HAL_StatusTypeDef HAL_TIM_Encoder_Start_IT(TIM_HandleTypeDef *htim, uint32_t Channel); +HAL_StatusTypeDef HAL_TIM_Encoder_Stop_IT(TIM_HandleTypeDef *htim, uint32_t Channel); +/* Non-Blocking mode: DMA */ +HAL_StatusTypeDef HAL_TIM_Encoder_Start_DMA(TIM_HandleTypeDef *htim, uint32_t Channel, uint32_t *pData1, uint32_t *pData2, uint16_t Length); +HAL_StatusTypeDef HAL_TIM_Encoder_Stop_DMA(TIM_HandleTypeDef *htim, uint32_t Channel); + +/* Interrupt Handler functions **********************************************/ +void HAL_TIM_IRQHandler(TIM_HandleTypeDef *htim); + +/* Control functions *********************************************************/ +HAL_StatusTypeDef HAL_TIM_OC_ConfigChannel(TIM_HandleTypeDef *htim, TIM_OC_InitTypeDef* sConfig, uint32_t Channel); +HAL_StatusTypeDef HAL_TIM_PWM_ConfigChannel(TIM_HandleTypeDef *htim, TIM_OC_InitTypeDef* sConfig, uint32_t Channel); +HAL_StatusTypeDef HAL_TIM_IC_ConfigChannel(TIM_HandleTypeDef *htim, TIM_IC_InitTypeDef* sConfig, uint32_t Channel); +HAL_StatusTypeDef HAL_TIM_OnePulse_ConfigChannel(TIM_HandleTypeDef *htim, TIM_OnePulse_InitTypeDef* sConfig, uint32_t OutputChannel, uint32_t InputChannel); +HAL_StatusTypeDef HAL_TIM_ConfigOCrefClear(TIM_HandleTypeDef *htim, TIM_ClearInputConfigTypeDef * sClearInputConfig, uint32_t Channel); +HAL_StatusTypeDef HAL_TIM_ConfigClockSource(TIM_HandleTypeDef *htim, TIM_ClockConfigTypeDef * sClockSourceConfig); +HAL_StatusTypeDef HAL_TIM_ConfigTI1Input(TIM_HandleTypeDef *htim, uint32_t TI1_Selection); +HAL_StatusTypeDef HAL_TIM_SlaveConfigSynchronization(TIM_HandleTypeDef *htim, TIM_SlaveConfigTypeDef * sSlaveConfig); +HAL_StatusTypeDef HAL_TIM_DMABurst_WriteStart(TIM_HandleTypeDef *htim, uint32_t BurstBaseAddress, uint32_t BurstRequestSrc, \ + uint32_t *BurstBuffer, uint32_t BurstLength); +HAL_StatusTypeDef HAL_TIM_DMABurst_WriteStop(TIM_HandleTypeDef *htim, uint32_t BurstRequestSrc); +HAL_StatusTypeDef HAL_TIM_DMABurst_ReadStart(TIM_HandleTypeDef *htim, uint32_t BurstBaseAddress, uint32_t BurstRequestSrc, \ + uint32_t *BurstBuffer, uint32_t BurstLength); +HAL_StatusTypeDef HAL_TIM_DMABurst_ReadStop(TIM_HandleTypeDef *htim, uint32_t BurstRequestSrc); +HAL_StatusTypeDef HAL_TIM_GenerateEvent(TIM_HandleTypeDef *htim, uint32_t EventSource); +uint32_t HAL_TIM_ReadCapturedValue(TIM_HandleTypeDef *htim, uint32_t Channel); + +/* Callback in non blocking modes (Interrupt and DMA) *************************/ +void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim); +void HAL_TIM_OC_DelayElapsedCallback(TIM_HandleTypeDef *htim); +void HAL_TIM_IC_CaptureCallback(TIM_HandleTypeDef *htim); +void HAL_TIM_PWM_PulseFinishedCallback(TIM_HandleTypeDef *htim); +void HAL_TIM_TriggerCallback(TIM_HandleTypeDef *htim); +void HAL_TIM_ErrorCallback(TIM_HandleTypeDef *htim); + +/* Peripheral State functions **************************************************/ +HAL_TIM_StateTypeDef HAL_TIM_Base_GetState(TIM_HandleTypeDef *htim); +HAL_TIM_StateTypeDef HAL_TIM_OC_GetState(TIM_HandleTypeDef *htim); +HAL_TIM_StateTypeDef HAL_TIM_PWM_GetState(TIM_HandleTypeDef *htim); +HAL_TIM_StateTypeDef HAL_TIM_IC_GetState(TIM_HandleTypeDef *htim); +HAL_TIM_StateTypeDef HAL_TIM_OnePulse_GetState(TIM_HandleTypeDef *htim); +HAL_TIM_StateTypeDef HAL_TIM_Encoder_GetState(TIM_HandleTypeDef *htim); +void HAL_TIM_DMADelayPulseCplt(DMA_HandleTypeDef *hdma); +void HAL_TIM_DMAError(DMA_HandleTypeDef *hdma); +void HAL_TIM_DMACaptureCplt(DMA_HandleTypeDef *hdma); + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __STM32L0xx_HAL_TIM_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_tim_ex.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_tim_ex.c new file mode 100644 index 0000000000..ae04574134 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_tim_ex.c @@ -0,0 +1,240 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_tim_ex.c + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief TIM HAL module driver. + * @brief This file provides firmware functions to manage the following + * functionalities of the Timer (TIM) peripheral: + * + Time Hall Sensor Interface Initialization + * + Time Hall Sensor Interface Start + * + Time Master and Slave synchronization configuration + @verbatim +================================================================================ + ##### ##### +================================================================================ + + [..] The Timer features include: + (#) 16-bit up, down, up/down auto-reload counter. + (#) 16-bit programmable prescaler allowing dividing (also “on the fly”) the counter clock + frequency either by any factor between 1 and 65536. + (#) Up to 4 independent channels for: + Input Capture + Output Compare + PWM generation (Edge and Center-aligned Mode) + One-pulse mode output + (#) Synchronization circuit to control the timer with external signals and to interconnect + several timers together. + (#) Supports incremental (quadrature) encoder and hall-sensor circuitry for positioning + purposes + + ##### How to use this driver ##### +================================================================================ + [..] + (#) Enable the TIM interface clock using + __TIMx_CLK_ENABLE(); + + (#) TIM pins configuration + (++) Enable the clock for the TIM GPIOs using the following function: + __GPIOx_CLK_ENABLE(); + (++) Configure these TIM pins in Alternate function mode using HAL_GPIO_Init(); + + (#) The external Clock can be configured, if needed (the default clock is the internal clock from the APBx), + using the following function: + HAL_TIM_ConfigClockSource, the clock configuration should be done before any start function. + + (#) Configure the TIM in the desired operating mode using one of the + configuration function of this driver: + (++) HAL_TIMEx_MasterConfigSynchronization() to configure the peripheral in master mode. + + (#) Remap the Timer I/O using HAL_TIMEx_RemapConfig() API. + + + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @defgroup TIMEx + * @brief TIM HAL module driver + * @{ + */ + +#ifdef HAL_TIM_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup TIMEx_Private_Functions + * @{ + */ + + +/** @defgroup TIMEx_Group3 Peripheral Control functions + * @brief Peripheral Control functions + * +@verbatim + =============================================================================== + ##### Peripheral Control functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Configure Master and the Slave synchronization. + +@endverbatim + * @{ + */ + +/** + * @brief Configures the TIM in master mode. + * @param htim: TIM handle. + * @param sMasterConfig: pointer to a TIM_MasterConfigTypeDef structure that + * contains the selected trigger output (TRGO) and the Master/Slave + * mode. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIMEx_MasterConfigSynchronization(TIM_HandleTypeDef *htim, TIM_MasterConfigTypeDef * sMasterConfig) +{ + /* Check the parameters */ + assert_param(IS_TIM_MASTER_INSTANCE(htim->Instance)); + assert_param(IS_TIM_TRGO_SOURCE(sMasterConfig->MasterOutputTrigger)); + assert_param(IS_TIM_MSM_STATE(sMasterConfig->MasterSlaveMode)); + + __HAL_LOCK(htim); + + /* Change the handler state */ + htim->State = HAL_TIM_STATE_BUSY; + + /* Reset the MMS Bits */ + htim->Instance->CR2 &= ~TIM_CR2_MMS; + /* Select the TRGO source */ + htim->Instance->CR2 |= sMasterConfig->MasterOutputTrigger; + + /* Reset the MSM Bit */ + htim->Instance->SMCR &= ~TIM_SMCR_MSM; + /* Set or Reset the MSM Bit */ + htim->Instance->SMCR |= sMasterConfig->MasterSlaveMode; + + htim->State = HAL_TIM_STATE_READY; + + __HAL_UNLOCK(htim); + + return HAL_OK; +} + +/** + * @brief Configures the TIM2, TIM5 and TIM11 Remapping input capabilities. + * @param htim: pointer to a TIM_HandleTypeDef structure that contains + * the configuration information for TIM module. + * @param TIM_Remap: specifies the TIM input remapping source. + * This parameter can be one of the following values: + * @arg TIM2_ETR_GPIO : TIM2 ETR is connected to GPIO (default). + * @arg TIM2_ETR_HSI48 : TIM2 ETR is connected to HSI48. + * @arg TIM2_ETR_LSE : TIM2 ETR is connected to LSE. + * @arg TIM2_ETR_COMP2_OUT : TIM2 ETR is connected to COMP2 output. + * @arg TIM2_ETR_COMP1_OUT : TIM2 ETR is connected to COMP1 output. + * @arg TIM2_TI4_GPIO1 : TIM2 TI4 is connected to GPIO1(default). + * @arg TIM2_TI4_COMP1 : TIM2 TI4 is connected to COMP1. + * @arg TIM2_TI4_COMP2 : TIM2 TI4 is connected to COMP2. + * @arg TIM2_TI4_GPIO2 : TIM2 TI4 is connected to GPIO2. + * @arg TIM21_ETR_GPIO : TIM21 ETR is connected to GPIO(default). + * @arg TIM21_ETR_COMP2_OUT : TIM21 ETR is connected to COMP2 output. + * @arg TIM21_ETR_COMP1_OUT : TIM21 ETR is connected to COMP1 output. + * @arg TIM21_ETR_LSE : TIM21 ETR is connected to LSE. + * @arg TIM21_TI1_MCO : TIM21 TI1 is connected to MCO.. + * @arg TIM21_TI1_RTC_WKUT_IT : TIM21 TI1 is connected to RTC WAKEUP interrupt. + * @arg TIM21_TI1_HSE_RTC : TIM21 TI1 is connected to HSE_RTC. + * @arg TIM21_TI1_MSI : TIM21 TI1 is connected to MSI clock. + * @arg TIM21_TI1_LSE : TIM21 TI1 is connected to LSE. + * @arg TIM21_TI1_LSI : TIM21 TI1 is connected to LSI. + * @arg TIM21_TI1_COMP1_OUT : TIM21 TI1 is connected to COMP1_OUT. + * @arg TIM21_TI1_GPIO : TIM21 TI1 is connected to GPIO(default). + * @arg TIM21_TI2_GPIO : TIM21 TI2 is connected to GPIO(default). + * @arg TIM21_TI2_COMP2_OUT : TIM21 TI2 is connected to COMP2 output. + * @arg TIM22_ETR_LSE : TIM22 ETR is connected to LSE. + * @arg TIM22_ETR_COMP2_OUT : TIM22 ETR is connected to COMP2 output. + * @arg TIM22_ETR_COMP1_OUT : TIM22 ETR is connected to COMP1 output. + * @arg TIM22_ETR_GPIO : TIM22 ETR is connected to GPIO(default). + * @arg TIM22_TI1_GPIO1 : TIM22 TI1 is connected to GPIO(default). + * @arg TIM22_TI1_COMP2_OUT : TIM22 TI1 is connected to COMP2 output. + * @arg TIM22_TI1_COMP1_OUT : TIM22 TI1 is connected to COMP1 output. + * @arg TIM22_TI1_GPIO2 : TIM22 TI1 is connected to GPIO. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TIMEx_RemapConfig(TIM_HandleTypeDef *htim, uint32_t Remap) +{ + __HAL_LOCK(htim); + + /* Check parameters */ + assert_param(IS_TIM_REMAP_INSTANCE(htim->Instance)); + assert_param(IS_TIM_REMAP(Remap)); + + /* Change the handler state */ + htim->State = HAL_TIM_STATE_BUSY; + + /* Set the Timer remapping configuration */ + htim->Instance->OR &= (uint32_t)(Remap >> 16); + htim->Instance->OR |= Remap; + + /* Change the handler state */ + htim->State = HAL_TIM_STATE_READY; + + __HAL_UNLOCK(htim); + + return HAL_OK; +} + +/** + * @} + */ + +/** + * @} + */ + +#endif /* HAL_TIM_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_tim_ex.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_tim_ex.h new file mode 100644 index 0000000000..000419bb64 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_tim_ex.h @@ -0,0 +1,197 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_tim_ex.h + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief Header file of TIM HAL module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32L0xx_HAL_TIM_EX_H +#define __STM32L0xx_HAL_TIM_EX_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal_def.h" + +/** @addtogroup STM32L0xx_HAL + * @{ + */ + +/** @addtogroup TIMEx + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ + +/** + * @brief TIM Master configuration Structure definition + */ +typedef struct { + uint32_t MasterOutputTrigger; /*!< Trigger output (TRGO) selection + This parameter can be a value of @ref TIMEx_Master_Mode_Selection */ + uint32_t MasterSlaveMode; /*!< Master/slave mode selection + This parameter can be a value of @ref TIMEx_Master_Slave_Mode */ +}TIM_MasterConfigTypeDef; + + +/* Exported constants --------------------------------------------------------*/ +/** @defgroup TIMEx_Exported_Constants + * @{ + */ + +/** @defgroup TIMEx_Master_Mode_Selection + * @{ + */ +#define TIM_TRGO_RESET ((uint32_t)0x0000) +#define TIM_TRGO_ENABLE (TIM_CR2_MMS_0) +#define TIM_TRGO_UPDATE (TIM_CR2_MMS_1) +#define TIM_TRGO_OC1 ((TIM_CR2_MMS_1 | TIM_CR2_MMS_0)) +#define TIM_TRGO_OC1REF (TIM_CR2_MMS_2) +#define TIM_TRGO_OC2REF ((TIM_CR2_MMS_2 | TIM_CR2_MMS_0)) +#define TIM_TRGO_OC3REF ((TIM_CR2_MMS_2 | TIM_CR2_MMS_1)) +#define TIM_TRGO_OC4REF ((TIM_CR2_MMS_2 | TIM_CR2_MMS_1 | TIM_CR2_MMS_0)) + +#define IS_TIM_TRGO_SOURCE(SOURCE) (((SOURCE) == TIM_TRGO_RESET) || \ + ((SOURCE) == TIM_TRGO_ENABLE) || \ + ((SOURCE) == TIM_TRGO_UPDATE) || \ + ((SOURCE) == TIM_TRGO_OC1) || \ + ((SOURCE) == TIM_TRGO_OC1REF) || \ + ((SOURCE) == TIM_TRGO_OC2REF) || \ + ((SOURCE) == TIM_TRGO_OC3REF) || \ + ((SOURCE) == TIM_TRGO_OC4REF)) + +/** + * @} + */ + +/** @defgroup TIMEx_Remap + * @{ + */ + +#define TIM2_ETR_GPIO ((uint32_t)0xFFF80000) +#define TIM2_ETR_HSI48 ((uint32_t)0xFFF80004) +#define TIM2_ETR_LSE ((uint32_t)0xFFF80005) +#define TIM2_ETR_COMP2_OUT ((uint32_t)0xFFF80006) +#define TIM2_ETR_COMP1_OUT ((uint32_t)0xFFF80007) +#define TIM2_TI4_GPIO1 ((uint32_t)0xFFE70000) +#define TIM2_TI4_COMP2 ((uint32_t)0xFFE70008) +#define TIM2_TI4_COMP1 ((uint32_t)0xFFE70010) +#define TIM2_TI4_GPIO2 ((uint32_t)0xFFE70018) +#define TIM21_ETR_GPIO ((uint32_t)0xFFF40000) +#define TIM21_ETR_COMP2_OUT ((uint32_t)0xFFF40001) +#define TIM21_ETR_COMP1_OUT ((uint32_t)0xFFF40002) +#define TIM21_ETR_LSE ((uint32_t)0xFFF40003) +#define TIM21_TI1_MCO ((uint32_t)0xFFE3001C) +#define TIM21_TI1_RTC_WKUT_IT ((uint32_t)0xFFE30004) +#define TIM21_TI1_HSE_RTC ((uint32_t)0xFFE30008) +#define TIM21_TI1_MSI ((uint32_t)0xFFE3000C) +#define TIM21_TI1_LSE ((uint32_t)0xFFE30010) +#define TIM21_TI1_LSI ((uint32_t)0xFFE30014) +#define TIM21_TI1_COMP1_OUT ((uint32_t)0xFFE30018) +#define TIM21_TI1_GPIO ((uint32_t)0xFFE30000) +#define TIM21_TI2_GPIO ((uint32_t)0xFFDF0000) +#define TIM21_TI2_COMP2_OUT ((uint32_t)0xFFDF0020) +#define TIM22_ETR_LSE ((uint32_t)0xFFFC0000) +#define TIM22_ETR_COMP2_OUT ((uint32_t)0xFFFC0001) +#define TIM22_ETR_COMP1_OUT ((uint32_t)0xFFFC0002) +#define TIM22_ETR_GPIO ((uint32_t)0xFFFC0003) +#define TIM22_TI1_GPIO1 ((uint32_t)0xFFF70000) +#define TIM22_TI1_COMP2_OUT ((uint32_t)0xFFF70004) +#define TIM22_TI1_COMP1_OUT ((uint32_t)0xFFF70008) +#define TIM22_TI1_GPIO2 ((uint32_t)0xFFF7000C) + + +#define IS_TIM_REMAP(TIM_REMAP) (((TIM_REMAP) == TIM2_ETR_GPIO )|| \ + ((TIM_REMAP) == TIM2_ETR_HSI48 )|| \ + ((TIM_REMAP) == TIM2_ETR_LSE )|| \ + ((TIM_REMAP) == TIM2_ETR_COMP2_OUT )|| \ + ((TIM_REMAP) == TIM2_ETR_COMP1_OUT )|| \ + ((TIM_REMAP) == TIM2_TI4_GPIO1 )|| \ + ((TIM_REMAP) == TIM2_TI4_COMP1 )|| \ + ((TIM_REMAP) == TIM2_TI4_COMP2 )|| \ + ((TIM_REMAP) == TIM2_TI4_GPIO2 )|| \ + ((TIM_REMAP) == TIM21_ETR_GPIO )|| \ + ((TIM_REMAP) == TIM21_ETR_COMP2_OUT )|| \ + ((TIM_REMAP) == TIM21_ETR_COMP1_OUT )|| \ + ((TIM_REMAP) == TIM21_ETR_LSE )|| \ + ((TIM_REMAP) == TIM21_TI1_MCO )|| \ + ((TIM_REMAP) == TIM21_TI1_RTC_WKUT_IT )|| \ + ((TIM_REMAP) == TIM21_TI1_HSE_RTC )|| \ + ((TIM_REMAP) == TIM21_TI1_MSI )|| \ + ((TIM_REMAP) == TIM21_TI1_LSE )|| \ + ((TIM_REMAP) == TIM21_TI1_LSI )|| \ + ((TIM_REMAP) == TIM21_TI1_COMP1_OUT )|| \ + ((TIM_REMAP) == TIM21_TI1_GPIO )|| \ + ((TIM_REMAP) == TIM21_TI2_GPIO )|| \ + ((TIM_REMAP) == TIM21_TI2_COMP2_OUT )|| \ + ((TIM_REMAP) == TIM22_ETR_LSE )|| \ + ((TIM_REMAP) == TIM22_ETR_COMP2_OUT )|| \ + ((TIM_REMAP) == TIM22_ETR_COMP1_OUT )|| \ + ((TIM_REMAP) == TIM22_ETR_GPIO )|| \ + ((TIM_REMAP) == TIM22_TI1_GPIO1 )|| \ + ((TIM_REMAP) == TIM22_TI1_COMP2_OUT )|| \ + ((TIM_REMAP) == TIM22_TI1_COMP1_OUT )|| \ + ((TIM_REMAP) == TIM22_TI1_GPIO2 )) + + +/** + * @} + */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ +/* Exported functions --------------------------------------------------------*/ +/* Control functions ***********************************************************/ +HAL_StatusTypeDef HAL_TIMEx_RemapConfig(TIM_HandleTypeDef *htim, uint32_t Remap); +HAL_StatusTypeDef HAL_TIMEx_MasterConfigSynchronization(TIM_HandleTypeDef *htim, TIM_MasterConfigTypeDef * sMasterConfig); +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __STM32L0xx_HAL_TIM_EX_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_tsc.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_tsc.c new file mode 100644 index 0000000000..b820ec827b --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_tsc.c @@ -0,0 +1,766 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_tsc.c + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief This file provides firmware functions to manage the following + * functionalities of the Touch Sensing Controller (TSC) peripheral: + * + Initialization and DeInitialization + * + Channel IOs, Shield IOs and Sampling IOs configuration + * + Start and Stop an acquisition + * + Read acquisition result + * + Interrupts and flags management + * + @verbatim +================================================================================ + ##### TSC specific features ##### +================================================================================ + [..] + (#) Proven and robust surface charge transfer acquisition principle + + (#) Supports up to 3 capacitive sensing channels per group + + (#) Capacitive sensing channels can be acquired in parallel offering a very good + response time + + (#) Spread spectrum feature to improve system robustness in noisy environments + + (#) Full hardware management of the charge transfer acquisition sequence + + (#) Programmable charge transfer frequency + + (#) Programmable sampling capacitor I/O pin + + (#) Programmable channel I/O pin + + (#) Programmable max count value to avoid long acquisition when a channel is faulty + + (#) Dedicated end of acquisition and max count error flags with interrupt capability + + (#) One sampling capacitor for up to 3 capacitive sensing channels to reduce the system + components + + (#) Compatible with proximity, touchkey, linear and rotary touch sensor implementation + + + ##### How to use this driver ##### +================================================================================ + [..] + (#) Enable the TSC interface clock using __TSC_CLK_ENABLE() macro. + + (#) GPIO pins configuration + (++) Enable the clock for the TSC GPIOs using __GPIOx_CLK_ENABLE() macro. + (++) Configure the TSC pins used as sampling IOs in alternate function output Open-Drain mode, + and TSC pins used as channel/shield IOs in alternate function output Push-Pull mode + using HAL_GPIO_Init() function. + (++) Configure the alternate function on all the TSC pins using HAL_xxxx() function. + + (#) Interrupts configuration + (++) Configure the NVIC (if the interrupt model is used) using HAL_xxx() function. + + (#) TSC configuration + (++) Configure all TSC parameters and used TSC IOs using HAL_TSC_Init() function. + + *** Acquisition sequence *** + =================================== + [..] + (+) Discharge all IOs using HAL_TSC_IODischarge() function. + (+) Wait a certain time allowing a good discharge of all capacitors. This delay depends + of the sampling capacitor and electrodes design. + (+) Select the channel IOs to be acquired using HAL_TSC_IOConfig() function. + (+) Launch the acquisition using either HAL_TSC_Start() or HAL_TSC_Start_IT() function. + If the synchronized mode is selected, the acquisition will start as soon as the signal + is received on the synchro pin. + (+) Wait the end of acquisition using either HAL_TSC_PollForAcquisition() or + HAL_TSC_GetState() function or using WFI instruction for example. + (+) Check the group acquisition status using HAL_TSC_GroupGetStatus() function. + (+) Read the acquisition value using HAL_TSC_GroupGetValue() function. + + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @defgroup TSC + * @brief HAL TSC module driver + * @{ + */ + +#ifdef HAL_TSC_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +static uint32_t TSC_extract_groups(uint32_t iomask); +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup TSC_Private_Functions + * @{ + */ + +/** @defgroup TSC_Group1 Initialization/de-initialization functions + * @brief Initialization and Configuration functions + * +@verbatim + =============================================================================== + ##### Initialization and de-initialization functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Initialize and configure the TSC. + (+) De-initialize the TSC. +@endverbatim + * @{ + */ + +/** + * @brief Initializes the TSC peripheral according to the specified parameters + * in the TSC_InitTypeDef structure. + * @param htsc: TSC handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TSC_Init(TSC_HandleTypeDef* htsc) +{ + /* Check TSC handle allocation */ + if (htsc == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_TSC_ALL_INSTANCE(htsc->Instance)); + assert_param(IS_TSC_CTPH(htsc->Init.CTPulseHighLength)); + assert_param(IS_TSC_CTPL(htsc->Init.CTPulseLowLength)); + assert_param(IS_TSC_SS(htsc->Init.SpreadSpectrum)); + assert_param(IS_TSC_SSD(htsc->Init.SpreadSpectrumDeviation)); + assert_param(IS_TSC_SS_PRESC(htsc->Init.SpreadSpectrumPrescaler)); + assert_param(IS_TSC_PG_PRESC(htsc->Init.PulseGeneratorPrescaler)); + assert_param(IS_TSC_MCV(htsc->Init.MaxCountValue)); + assert_param(IS_TSC_IODEF(htsc->Init.IODefaultMode)); + assert_param(IS_TSC_SYNC_POL(htsc->Init.SynchroPinPolarity)); + assert_param(IS_TSC_ACQ_MODE(htsc->Init.AcquisitionMode)); + assert_param(IS_TSC_MCE_IT(htsc->Init.MaxCountInterrupt)); + + /* Initialize the TSC state */ + htsc->State = HAL_TSC_STATE_BUSY; + + /* Init the low level hardware : GPIO, CLOCK, CORTEX */ + HAL_TSC_MspInit(htsc); + + /*--------------------------------------------------------------------------*/ + /* Set TSC parameters */ + + /* Enable TSC */ + htsc->Instance->CR = TSC_CR_TSCE; + + /* Set all functions */ + htsc->Instance->CR |= (htsc->Init.CTPulseHighLength | + htsc->Init.CTPulseLowLength | + (uint32_t)(htsc->Init.SpreadSpectrumDeviation << 17) | + htsc->Init.SpreadSpectrumPrescaler | + htsc->Init.PulseGeneratorPrescaler | + htsc->Init.MaxCountValue | + htsc->Init.IODefaultMode | + htsc->Init.SynchroPinPolarity | + htsc->Init.AcquisitionMode); + + /* Spread spectrum */ + if (htsc->Init.SpreadSpectrum == ENABLE) + { + htsc->Instance->CR |= TSC_CR_SSE; + } + + /* Disable Schmitt trigger hysteresis on all used TSC IOs */ + htsc->Instance->IOHCR = (uint32_t)(~(htsc->Init.ChannelIOs | htsc->Init.ShieldIOs | htsc->Init.SamplingIOs)); + + /* Set channel and shield IOs */ + htsc->Instance->IOCCR = (htsc->Init.ChannelIOs | htsc->Init.ShieldIOs); + + /* Set sampling IOs */ + htsc->Instance->IOSCR = htsc->Init.SamplingIOs; + + /* Set the groups to be acquired */ + htsc->Instance->IOGCSR = TSC_extract_groups(htsc->Init.ChannelIOs); + + /* Clear interrupts */ + htsc->Instance->IER &= (uint32_t)(~(TSC_IT_EOA | TSC_IT_MCE)); + + /* Clear flags */ + htsc->Instance->ICR |= (TSC_FLAG_EOA | TSC_FLAG_MCE); + + /*--------------------------------------------------------------------------*/ + + /* Initialize the TSC state */ + htsc->State = HAL_TSC_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Deinitializes the TSC peripheral registers to their default reset values. + * @param htsc: TSC handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TSC_DeInit(TSC_HandleTypeDef* htsc) +{ + /* Check TSC handle allocation */ + if (htsc == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_TSC_ALL_INSTANCE(htsc->Instance)); + + /* Change TSC state */ + htsc->State = HAL_TSC_STATE_BUSY; + + /* DeInit the low level hardware */ + HAL_TSC_MspDeInit(htsc); + + /* Change TSC state */ + htsc->State = HAL_TSC_STATE_RESET; + + /* Process unlocked */ + __HAL_UNLOCK(htsc); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Initializes the TSC MSP. + * @param htsc: pointer to a TSC_HandleTypeDef structure that contains + * the configuration information for the specified TSC. + * @retval None + */ +__weak void HAL_TSC_MspInit(TSC_HandleTypeDef* htsc) +{ + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_TSC_MspInit could be implemented in the user file. + */ +} + +/** + * @brief DeInitializes the TSC MSP. + * @param htsc: pointer to a TSC_HandleTypeDef structure that contains + * the configuration information for the specified TSC. + * @retval None + */ +__weak void HAL_TSC_MspDeInit(TSC_HandleTypeDef* htsc) +{ + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_TSC_MspDeInit could be implemented in the user file. + */ +} + +/** + * @} + */ + +/** @defgroup HAL_TSC_Group2 IO operation functions + * @brief IO operation functions + * +@verbatim + =============================================================================== + ##### I/O Operation functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Start acquisition in polling mode. + (+) Start acquisition in interrupt mode. + (+) Stop conversion in polling mode. + (+) Stop conversion in interrupt mode. + (+) Get group acquisition status. + (+) Get group acquisition value. +@endverbatim + * @{ + */ + +/** + * @brief Starts the acquisition. + * @param htsc: pointer to a TSC_HandleTypeDef structure that contains + * the configuration information for the specified TSC. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TSC_Start(TSC_HandleTypeDef* htsc) +{ + /* Check the parameters */ + assert_param(IS_TSC_ALL_INSTANCE(htsc->Instance)); + + /* Process locked */ + __HAL_LOCK(htsc); + + /* Change TSC state */ + htsc->State = HAL_TSC_STATE_BUSY; + + /* Clear interrupts */ + __HAL_TSC_DISABLE_IT(htsc, (TSC_IT_EOA | TSC_IT_MCE)); + + /* Clear flags */ + __HAL_TSC_CLEAR_FLAG(htsc, (TSC_FLAG_EOA | TSC_FLAG_MCE)); + + /* Stop discharging the IOs */ + __HAL_TSC_SET_IODEF_INFLOAT(htsc); + + /* Launch the acquisition */ + __HAL_TSC_START_ACQ(htsc); + + /* Process unlocked */ + __HAL_UNLOCK(htsc); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Enables the interrupt and starts the acquisition + * @param htsc: pointer to a TSC_HandleTypeDef structure that contains + * the configuration information for the specified TSC. + * @retval HAL status. + */ +HAL_StatusTypeDef HAL_TSC_Start_IT(TSC_HandleTypeDef* htsc) +{ + /* Check the parameters */ + assert_param(IS_TSC_ALL_INSTANCE(htsc->Instance)); + assert_param(IS_TSC_MCE_IT(htsc->Init.MaxCountInterrupt)); + + /* Process locked */ + __HAL_LOCK(htsc); + + /* Change TSC state */ + htsc->State = HAL_TSC_STATE_BUSY; + + /* Enable end of acquisition interrupt */ + __HAL_TSC_ENABLE_IT(htsc, TSC_IT_EOA); + + /* Enable max count error interrupt (optional) */ + if (htsc->Init.MaxCountInterrupt == ENABLE) + { + __HAL_TSC_ENABLE_IT(htsc, TSC_IT_MCE); + } + else + { + __HAL_TSC_DISABLE_IT(htsc, TSC_IT_MCE); + } + + /* Clear flags */ + __HAL_TSC_CLEAR_FLAG(htsc, (TSC_FLAG_EOA | TSC_FLAG_MCE)); + + /* Stop discharging the IOs */ + __HAL_TSC_SET_IODEF_INFLOAT(htsc); + + /* Launch the acquisition */ + __HAL_TSC_START_ACQ(htsc); + + /* Process unlocked */ + __HAL_UNLOCK(htsc); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the acquisition previously launched in polling mode + * @param htsc: pointer to a TSC_HandleTypeDef structure that contains + * the configuration information for the specified TSC. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TSC_Stop(TSC_HandleTypeDef* htsc) +{ + /* Check the parameters */ + assert_param(IS_TSC_ALL_INSTANCE(htsc->Instance)); + + /* Process locked */ + __HAL_LOCK(htsc); + + /* Stop the acquisition */ + __HAL_TSC_STOP_ACQ(htsc); + + /* Clear flags */ + __HAL_TSC_CLEAR_FLAG(htsc, (TSC_FLAG_EOA | TSC_FLAG_MCE)); + + /* Change TSC state */ + htsc->State = HAL_TSC_STATE_READY; + + /* Process unlocked */ + __HAL_UNLOCK(htsc); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Stops the acquisition previously launched in interrupt mode + * @param htsc: pointer to a TSC_HandleTypeDef structure that contains + * the configuration information for the specified TSC. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TSC_Stop_IT(TSC_HandleTypeDef* htsc) +{ + /* Check the parameters */ + assert_param(IS_TSC_ALL_INSTANCE(htsc->Instance)); + + /* Process locked */ + __HAL_LOCK(htsc); + + /* Stop the acquisition */ + __HAL_TSC_STOP_ACQ(htsc); + + /* Disable interrupts */ + __HAL_TSC_DISABLE_IT(htsc, (TSC_IT_EOA | TSC_IT_MCE)); + + /* Clear flags */ + __HAL_TSC_CLEAR_FLAG(htsc, (TSC_FLAG_EOA | TSC_FLAG_MCE)); + + /* Change TSC state */ + htsc->State = HAL_TSC_STATE_READY; + + /* Process unlocked */ + __HAL_UNLOCK(htsc); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Gets the acquisition status for a group + * @param htsc: pointer to a TSC_HandleTypeDef structure that contains + * the configuration information for the specified TSC. + * @param gx_index: Index of the group + * @retval Group status + */ +TSC_GroupStatusTypeDef HAL_TSC_GroupGetStatus(TSC_HandleTypeDef* htsc, uint32_t gx_index) +{ + /* Check the parameters */ + assert_param(IS_TSC_ALL_INSTANCE(htsc->Instance)); + assert_param(IS_GROUP_INDEX(gx_index)); + + /* Return the group status */ + return(__HAL_TSC_GET_GROUP_STATUS(htsc, gx_index)); +} + +/** + * @brief Gets the acquisition measure for a group + * @param htsc: pointer to a TSC_HandleTypeDef structure that contains + * the configuration information for the specified TSC. + * @param gx_index: Index of the group + * @retval Acquisition measure + */ +uint32_t HAL_TSC_GroupGetValue(TSC_HandleTypeDef* htsc, uint32_t gx_index) +{ + /* Check the parameters */ + assert_param(IS_TSC_ALL_INSTANCE(htsc->Instance)); + assert_param(IS_GROUP_INDEX(gx_index)); + + /* Return the group acquisition counter */ + return htsc->Instance->IOGXCR[gx_index]; +} + +/** + * @} + */ + +/** @defgroup HAL_TSC_Group3 Peripheral Control functions + * @brief Peripheral Control functions + * +@verbatim + =============================================================================== + ##### Peripheral Control functions ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) Configure TSC IOs + (+) Discharge TSC IOs +@endverbatim + * @{ + */ + +/** + * @brief Configures TSC IOs + * @param htsc: pointer to a TSC_HandleTypeDef structure that contains + * the configuration information for the specified TSC. + * @param config: pointer to the configuration structure. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TSC_IOConfig(TSC_HandleTypeDef* htsc, TSC_IOConfigTypeDef* config) +{ + /* Check the parameters */ + assert_param(IS_TSC_ALL_INSTANCE(htsc->Instance)); + + /* Process locked */ + __HAL_LOCK(htsc); + + /* Stop acquisition */ + __HAL_TSC_STOP_ACQ(htsc); + + /* Disable Schmitt trigger hysteresis on all used TSC IOs */ + htsc->Instance->IOHCR = (uint32_t)(~(config->ChannelIOs | config->ShieldIOs | config->SamplingIOs)); + + /* Set channel and shield IOs */ + htsc->Instance->IOCCR = (config->ChannelIOs | config->ShieldIOs); + + /* Set sampling IOs */ + htsc->Instance->IOSCR = config->SamplingIOs; + + /* Set groups to be acquired */ + htsc->Instance->IOGCSR = TSC_extract_groups(config->ChannelIOs); + + /* Process unlocked */ + __HAL_UNLOCK(htsc); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Discharge TSC IOs + * @param htsc: pointer to a TSC_HandleTypeDef structure that contains + * the configuration information for the specified TSC. + * @param choice: enable or disable + * @retval HAL status + */ +HAL_StatusTypeDef HAL_TSC_IODischarge(TSC_HandleTypeDef* htsc, uint32_t choice) +{ + /* Check the parameters */ + assert_param(IS_TSC_ALL_INSTANCE(htsc->Instance)); + + /* Process locked */ + __HAL_LOCK(htsc); + + if (choice == ENABLE) + { + __HAL_TSC_SET_IODEF_OUTPPLOW(htsc); + } + else + { + __HAL_TSC_SET_IODEF_INFLOAT(htsc); + } + + /* Process unlocked */ + __HAL_UNLOCK(htsc); + + /* Return the group acquisition counter */ + return HAL_OK; +} + +/** + * @} + */ + +/** @defgroup HAL_TSC_Group4 State functions + * @brief State functions + * +@verbatim + =============================================================================== + ##### State functions ##### + =============================================================================== + [..] + This subsection provides functions allowing to + (+) Get TSC state. + (+) Poll for acquisition completed. + (+) Handles TSC interrupt request. + +@endverbatim + * @{ + */ + +/** + * @brief Return the TSC state + * @param htsc: pointer to a TSC_HandleTypeDef structure that contains + * the configuration information for the specified TSC. + * @retval HAL state + */ +HAL_TSC_StateTypeDef HAL_TSC_GetState(TSC_HandleTypeDef* htsc) +{ + /* Check the parameters */ + assert_param(IS_TSC_ALL_INSTANCE(htsc->Instance)); + + if (htsc->State == HAL_TSC_STATE_BUSY) + { + /* Check end of acquisition flag */ + if (__HAL_TSC_GET_FLAG(htsc, TSC_FLAG_EOA) != RESET) + { + /* Check max count error flag */ + if (__HAL_TSC_GET_FLAG(htsc, TSC_FLAG_MCE) != RESET) + { + /* Change TSC state */ + htsc->State = HAL_TSC_STATE_ERROR; + } + else + { + /* Change TSC state */ + htsc->State = HAL_TSC_STATE_READY; + } + } + } + + /* Return TSC state */ + return htsc->State; +} + +/** + * @brief Start acquisition and wait until completion + * @note There is no need of a timeout parameter as the max count error is already + * managed by the TSC peripheral. + * @param htsc: pointer to a TSC_HandleTypeDef structure that contains + * the configuration information for the specified TSC. + * @retval HAL state + */ +HAL_StatusTypeDef HAL_TSC_PollForAcquisition(TSC_HandleTypeDef* htsc) +{ + /* Check the parameters */ + assert_param(IS_TSC_ALL_INSTANCE(htsc->Instance)); + + /* Process locked */ + __HAL_LOCK(htsc); + + /* Check end of acquisition */ + while (HAL_TSC_GetState(htsc) == HAL_TSC_STATE_BUSY) + { + /* The timeout (max count error) is managed by the TSC peripheral itself. */ + } + + /* Process unlocked */ + __HAL_UNLOCK(htsc); + + return HAL_OK; +} + +/** + * @brief Handles TSC interrupt request + * @param htsc: pointer to a TSC_HandleTypeDef structure that contains + * the configuration information for the specified TSC. + * @retval None + */ +void HAL_TSC_IRQHandler(TSC_HandleTypeDef* htsc) +{ + /* Check the parameters */ + assert_param(IS_TSC_ALL_INSTANCE(htsc->Instance)); + + /* Check if the end of acquisition occured */ + if (__HAL_TSC_GET_FLAG(htsc, TSC_FLAG_EOA) != RESET) + { + /* Clear EOA flag */ + __HAL_TSC_CLEAR_FLAG(htsc, TSC_FLAG_EOA); + } + + /* Check if max count error occured */ + if (__HAL_TSC_GET_FLAG(htsc, TSC_FLAG_MCE) != RESET) + { + /* Clear MCE flag */ + __HAL_TSC_CLEAR_FLAG(htsc, TSC_FLAG_MCE); + /* Change TSC state */ + htsc->State = HAL_TSC_STATE_ERROR; + /* Conversion completed callback */ + HAL_TSC_ErrorCallback(htsc); + } + else + { + /* Change TSC state */ + htsc->State = HAL_TSC_STATE_READY; + /* Conversion completed callback */ + HAL_TSC_ConvCpltCallback(htsc); + } +} + +/** + * @} + */ + +/** + * @brief Acquisition completed callback in non blocking mode + * @param htsc: pointer to a TSC_HandleTypeDef structure that contains + * the configuration information for the specified TSC. + * @retval None + */ +__weak void HAL_TSC_ConvCpltCallback(TSC_HandleTypeDef* htsc) +{ + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_TSC_ConvCpltCallback could be implemented in the user file. + */ +} + +/** + * @brief Error callback in non blocking mode + * @param htsc: pointer to a TSC_HandleTypeDef structure that contains + * the configuration information for the specified TSC. + * @retval None + */ +__weak void HAL_TSC_ErrorCallback(TSC_HandleTypeDef* htsc) +{ + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_TSC_ErrorCallback could be implemented in the user file. + */ +} + +/** + * @brief Utility function used to set the acquired groups mask + * @param iomask: Channels IOs mask + * @retval Acquired groups mask + */ +static uint32_t TSC_extract_groups(uint32_t iomask) +{ + uint32_t groups = 0; + uint32_t idx; + + for (idx = 0; idx < TSC_NB_OF_GROUPS; idx++) + { + if ((iomask & ((uint32_t)0x0F << (idx * 4))) != RESET) + { + groups |= ((uint32_t)1 << idx); + } + } + + return groups; +} + +/** + * @} + */ + +#endif /* HAL_TSC_MODULE_ENABLED */ + +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_tsc.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_tsc.h new file mode 100644 index 0000000000..a8579bea67 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_tsc.h @@ -0,0 +1,586 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_tsc.h + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief This file contains all the functions prototypes for the TSC firmware + * library. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32L0xx_TSC_H +#define __STM32L0xx_TSC_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal_def.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @addtogroup TSC + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ + +/** + * @brief TSC state structure definition + */ +typedef enum +{ + HAL_TSC_STATE_RESET = 0x00, /*!< TSC registers have their reset value */ + HAL_TSC_STATE_READY = 0x01, /*!< TSC registers are initialized or acquisition is completed with success */ + HAL_TSC_STATE_BUSY = 0x02, /*!< TSC initialization or acquisition is on-going */ + HAL_TSC_STATE_ERROR = 0x03 /*!< Acquisition is completed with max count error */ +} HAL_TSC_StateTypeDef; + +/** + * @brief TSC group status structure definition + */ +typedef enum +{ + TSC_GROUP_ONGOING = 0x00, /*!< Acquisition on group is on-going or not started */ + TSC_GROUP_COMPLETED = 0x01 /*!< Acquisition on group is completed with success (no max count error) */ +} TSC_GroupStatusTypeDef; + +/** + * @brief TSC init structure definition + */ +typedef struct +{ + uint32_t CTPulseHighLength; /*!< Charge-transfer high pulse length */ + uint32_t CTPulseLowLength; /*!< Charge-transfer low pulse length */ + uint32_t SpreadSpectrum; /*!< Spread spectrum activation */ + uint32_t SpreadSpectrumDeviation; /*!< Spread spectrum deviation */ + uint32_t SpreadSpectrumPrescaler; /*!< Spread spectrum prescaler */ + uint32_t PulseGeneratorPrescaler; /*!< Pulse generator prescaler */ + uint32_t MaxCountValue; /*!< Max count value */ + uint32_t IODefaultMode; /*!< IO default mode */ + uint32_t SynchroPinPolarity; /*!< Synchro pin polarity */ + uint32_t AcquisitionMode; /*!< Acquisition mode */ + uint32_t MaxCountInterrupt; /*!< Max count interrupt activation */ + uint32_t ChannelIOs; /*!< Channel IOs mask */ + uint32_t ShieldIOs; /*!< Shield IOs mask */ + uint32_t SamplingIOs; /*!< Sampling IOs mask */ +} TSC_InitTypeDef; + +/** + * @brief TSC IOs configuration structure definition + */ +typedef struct +{ + uint32_t ChannelIOs; /*!< Channel IOs mask */ + uint32_t ShieldIOs; /*!< Shield IOs mask */ + uint32_t SamplingIOs; /*!< Sampling IOs mask */ +} TSC_IOConfigTypeDef; + +/** + * @brief TSC handle Structure definition + */ +typedef struct +{ + TSC_TypeDef *Instance; /*!< Register base address */ + TSC_InitTypeDef Init; /*!< Initialization parameters */ + __IO HAL_TSC_StateTypeDef State; /*!< Peripheral state */ + HAL_LockTypeDef Lock; /*!< Lock feature */ +} TSC_HandleTypeDef; + +/* Exported constants --------------------------------------------------------*/ + +/** @defgroup TSC_Exported_Constants + * @{ + */ + +#define IS_TSC_ALL_INSTANCE(PERIPH) ((PERIPH) == TSC) + +#define TSC_CTPH_1CYCLE ((uint32_t)((uint32_t) 0 << 28)) +#define TSC_CTPH_2CYCLES ((uint32_t)((uint32_t) 1 << 28)) +#define TSC_CTPH_3CYCLES ((uint32_t)((uint32_t) 2 << 28)) +#define TSC_CTPH_4CYCLES ((uint32_t)((uint32_t) 3 << 28)) +#define TSC_CTPH_5CYCLES ((uint32_t)((uint32_t) 4 << 28)) +#define TSC_CTPH_6CYCLES ((uint32_t)((uint32_t) 5 << 28)) +#define TSC_CTPH_7CYCLES ((uint32_t)((uint32_t) 6 << 28)) +#define TSC_CTPH_8CYCLES ((uint32_t)((uint32_t) 7 << 28)) +#define TSC_CTPH_9CYCLES ((uint32_t)((uint32_t) 8 << 28)) +#define TSC_CTPH_10CYCLES ((uint32_t)((uint32_t) 9 << 28)) +#define TSC_CTPH_11CYCLES ((uint32_t)((uint32_t)10 << 28)) +#define TSC_CTPH_12CYCLES ((uint32_t)((uint32_t)11 << 28)) +#define TSC_CTPH_13CYCLES ((uint32_t)((uint32_t)12 << 28)) +#define TSC_CTPH_14CYCLES ((uint32_t)((uint32_t)13 << 28)) +#define TSC_CTPH_15CYCLES ((uint32_t)((uint32_t)14 << 28)) +#define TSC_CTPH_16CYCLES ((uint32_t)((uint32_t)15 << 28)) +#define IS_TSC_CTPH(VAL) (((VAL) == TSC_CTPH_1CYCLE) || \ + ((VAL) == TSC_CTPH_2CYCLES) || \ + ((VAL) == TSC_CTPH_3CYCLES) || \ + ((VAL) == TSC_CTPH_4CYCLES) || \ + ((VAL) == TSC_CTPH_5CYCLES) || \ + ((VAL) == TSC_CTPH_6CYCLES) || \ + ((VAL) == TSC_CTPH_7CYCLES) || \ + ((VAL) == TSC_CTPH_8CYCLES) || \ + ((VAL) == TSC_CTPH_9CYCLES) || \ + ((VAL) == TSC_CTPH_10CYCLES) || \ + ((VAL) == TSC_CTPH_11CYCLES) || \ + ((VAL) == TSC_CTPH_12CYCLES) || \ + ((VAL) == TSC_CTPH_13CYCLES) || \ + ((VAL) == TSC_CTPH_14CYCLES) || \ + ((VAL) == TSC_CTPH_15CYCLES) || \ + ((VAL) == TSC_CTPH_16CYCLES)) + +#define TSC_CTPL_1CYCLE ((uint32_t)((uint32_t) 0 << 24)) +#define TSC_CTPL_2CYCLES ((uint32_t)((uint32_t) 1 << 24)) +#define TSC_CTPL_3CYCLES ((uint32_t)((uint32_t) 2 << 24)) +#define TSC_CTPL_4CYCLES ((uint32_t)((uint32_t) 3 << 24)) +#define TSC_CTPL_5CYCLES ((uint32_t)((uint32_t) 4 << 24)) +#define TSC_CTPL_6CYCLES ((uint32_t)((uint32_t) 5 << 24)) +#define TSC_CTPL_7CYCLES ((uint32_t)((uint32_t) 6 << 24)) +#define TSC_CTPL_8CYCLES ((uint32_t)((uint32_t) 7 << 24)) +#define TSC_CTPL_9CYCLES ((uint32_t)((uint32_t) 8 << 24)) +#define TSC_CTPL_10CYCLES ((uint32_t)((uint32_t) 9 << 24)) +#define TSC_CTPL_11CYCLES ((uint32_t)((uint32_t)10 << 24)) +#define TSC_CTPL_12CYCLES ((uint32_t)((uint32_t)11 << 24)) +#define TSC_CTPL_13CYCLES ((uint32_t)((uint32_t)12 << 24)) +#define TSC_CTPL_14CYCLES ((uint32_t)((uint32_t)13 << 24)) +#define TSC_CTPL_15CYCLES ((uint32_t)((uint32_t)14 << 24)) +#define TSC_CTPL_16CYCLES ((uint32_t)((uint32_t)15 << 24)) +#define IS_TSC_CTPL(VAL) (((VAL) == TSC_CTPL_1CYCLE) || \ + ((VAL) == TSC_CTPL_2CYCLES) || \ + ((VAL) == TSC_CTPL_3CYCLES) || \ + ((VAL) == TSC_CTPL_4CYCLES) || \ + ((VAL) == TSC_CTPL_5CYCLES) || \ + ((VAL) == TSC_CTPL_6CYCLES) || \ + ((VAL) == TSC_CTPL_7CYCLES) || \ + ((VAL) == TSC_CTPL_8CYCLES) || \ + ((VAL) == TSC_CTPL_9CYCLES) || \ + ((VAL) == TSC_CTPL_10CYCLES) || \ + ((VAL) == TSC_CTPL_11CYCLES) || \ + ((VAL) == TSC_CTPL_12CYCLES) || \ + ((VAL) == TSC_CTPL_13CYCLES) || \ + ((VAL) == TSC_CTPL_14CYCLES) || \ + ((VAL) == TSC_CTPL_15CYCLES) || \ + ((VAL) == TSC_CTPL_16CYCLES)) + +#define IS_TSC_SS(VAL) (((VAL) == DISABLE) || ((VAL) == ENABLE)) + +#define IS_TSC_SSD(VAL) (((VAL) == 0) || (((VAL) > 0) && ((VAL) < 128))) + +#define TSC_SS_PRESC_DIV1 ((uint32_t)0) +#define TSC_SS_PRESC_DIV2 (TSC_CR_SSPSC) +#define IS_TSC_SS_PRESC(VAL) (((VAL) == TSC_SS_PRESC_DIV1) || ((VAL) == TSC_SS_PRESC_DIV2)) + +#define TSC_PG_PRESC_DIV1 ((uint32_t)(0 << 12)) +#define TSC_PG_PRESC_DIV2 ((uint32_t)(1 << 12)) +#define TSC_PG_PRESC_DIV4 ((uint32_t)(2 << 12)) +#define TSC_PG_PRESC_DIV8 ((uint32_t)(3 << 12)) +#define TSC_PG_PRESC_DIV16 ((uint32_t)(4 << 12)) +#define TSC_PG_PRESC_DIV32 ((uint32_t)(5 << 12)) +#define TSC_PG_PRESC_DIV64 ((uint32_t)(6 << 12)) +#define TSC_PG_PRESC_DIV128 ((uint32_t)(7 << 12)) +#define IS_TSC_PG_PRESC(VAL) (((VAL) == TSC_PG_PRESC_DIV1) || \ + ((VAL) == TSC_PG_PRESC_DIV2) || \ + ((VAL) == TSC_PG_PRESC_DIV4) || \ + ((VAL) == TSC_PG_PRESC_DIV8) || \ + ((VAL) == TSC_PG_PRESC_DIV16) || \ + ((VAL) == TSC_PG_PRESC_DIV32) || \ + ((VAL) == TSC_PG_PRESC_DIV64) || \ + ((VAL) == TSC_PG_PRESC_DIV128)) + +#define TSC_MCV_255 ((uint32_t)(0 << 5)) +#define TSC_MCV_511 ((uint32_t)(1 << 5)) +#define TSC_MCV_1023 ((uint32_t)(2 << 5)) +#define TSC_MCV_2047 ((uint32_t)(3 << 5)) +#define TSC_MCV_4095 ((uint32_t)(4 << 5)) +#define TSC_MCV_8191 ((uint32_t)(5 << 5)) +#define TSC_MCV_16383 ((uint32_t)(6 << 5)) +#define IS_TSC_MCV(VAL) (((VAL) == TSC_MCV_255) || \ + ((VAL) == TSC_MCV_511) || \ + ((VAL) == TSC_MCV_1023) || \ + ((VAL) == TSC_MCV_2047) || \ + ((VAL) == TSC_MCV_4095) || \ + ((VAL) == TSC_MCV_8191) || \ + ((VAL) == TSC_MCV_16383)) + +#define TSC_IODEF_OUT_PP_LOW ((uint32_t)0) +#define TSC_IODEF_IN_FLOAT (TSC_CR_IODEF) +#define IS_TSC_IODEF(VAL) (((VAL) == TSC_IODEF_OUT_PP_LOW) || ((VAL) == TSC_IODEF_IN_FLOAT)) + +#define TSC_SYNC_POL_FALL ((uint32_t)0) +#define TSC_SYNC_POL_RISE_HIGH (TSC_CR_SYNCPOL) +#define IS_TSC_SYNC_POL(VAL) (((VAL) == TSC_SYNC_POL_FALL) || ((VAL) == TSC_SYNC_POL_RISE_HIGH)) + +#define TSC_ACQ_MODE_NORMAL ((uint32_t)0) +#define TSC_ACQ_MODE_SYNCHRO (TSC_CR_SYNCPOL) +#define IS_TSC_ACQ_MODE(VAL) (((VAL) == TSC_ACQ_MODE_NORMAL) || ((VAL) == TSC_ACQ_MODE_SYNCHRO)) + +#define TSC_IOMODE_UNUSED ((uint32_t)0) +#define TSC_IOMODE_CHANNEL ((uint32_t)1) +#define TSC_IOMODE_SHIELD ((uint32_t)2) +#define TSC_IOMODE_SAMPLING ((uint32_t)3) +#define IS_TSC_IOMODE(VAL) (((VAL) == TSC_IOMODE_UNUSED) || \ + ((VAL) == TSC_IOMODE_CHANNEL) || \ + ((VAL) == TSC_IOMODE_SHIELD) || \ + ((VAL) == TSC_IOMODE_SAMPLING)) + +/** @defgroup TSC_interrupts_definition + * @{ + */ +#define TSC_IT_EOA ((uint32_t)TSC_IER_EOAIE) +#define TSC_IT_MCE ((uint32_t)TSC_IER_MCEIE) +#define IS_TSC_MCE_IT(VAL) (((VAL) == DISABLE) || ((VAL) == ENABLE)) +/** + * @} + */ + +/** @defgroup TSC_flags_definition + * @{ + */ +#define TSC_FLAG_EOA ((uint32_t)TSC_ISR_EOAF) +#define TSC_FLAG_MCE ((uint32_t)TSC_ISR_MCEF) +/** + * @} + */ + +#define TSC_NB_OF_GROUPS (8) + +#define TSC_GROUP1 ((uint32_t)0x00000001) +#define TSC_GROUP2 ((uint32_t)0x00000002) +#define TSC_GROUP3 ((uint32_t)0x00000004) +#define TSC_GROUP4 ((uint32_t)0x00000008) +#define TSC_GROUP5 ((uint32_t)0x00000010) +#define TSC_GROUP6 ((uint32_t)0x00000020) +#define TSC_GROUP7 ((uint32_t)0x00000040) +#define TSC_GROUP8 ((uint32_t)0x00000080) +#define TSC_ALL_GROUPS ((uint32_t)0x000000FF) + +#define TSC_GROUP1_IDX ((uint32_t)0) +#define TSC_GROUP2_IDX ((uint32_t)1) +#define TSC_GROUP3_IDX ((uint32_t)2) +#define TSC_GROUP4_IDX ((uint32_t)3) +#define TSC_GROUP5_IDX ((uint32_t)4) +#define TSC_GROUP6_IDX ((uint32_t)5) +#define TSC_GROUP7_IDX ((uint32_t)6) +#define TSC_GROUP8_IDX ((uint32_t)7) +#define IS_GROUP_INDEX(VAL) (((VAL) == 0) || (((VAL) > 0) && ((VAL) < TSC_NB_OF_GROUPS))) + +#define TSC_GROUP1_IO1 ((uint32_t)0x00000001) +#define TSC_GROUP1_IO2 ((uint32_t)0x00000002) +#define TSC_GROUP1_IO3 ((uint32_t)0x00000004) +#define TSC_GROUP1_IO4 ((uint32_t)0x00000008) +#define TSC_GROUP1_ALL_IOS ((uint32_t)0x0000000F) + +#define TSC_GROUP2_IO1 ((uint32_t)0x00000010) +#define TSC_GROUP2_IO2 ((uint32_t)0x00000020) +#define TSC_GROUP2_IO3 ((uint32_t)0x00000040) +#define TSC_GROUP2_IO4 ((uint32_t)0x00000080) +#define TSC_GROUP2_ALL_IOS ((uint32_t)0x000000F0) + +#define TSC_GROUP3_IO1 ((uint32_t)0x00000100) +#define TSC_GROUP3_IO2 ((uint32_t)0x00000200) +#define TSC_GROUP3_IO3 ((uint32_t)0x00000400) +#define TSC_GROUP3_IO4 ((uint32_t)0x00000800) +#define TSC_GROUP3_ALL_IOS ((uint32_t)0x00000F00) + +#define TSC_GROUP4_IO1 ((uint32_t)0x00001000) +#define TSC_GROUP4_IO2 ((uint32_t)0x00002000) +#define TSC_GROUP4_IO3 ((uint32_t)0x00004000) +#define TSC_GROUP4_IO4 ((uint32_t)0x00008000) +#define TSC_GROUP4_ALL_IOS ((uint32_t)0x0000F000) + +#define TSC_GROUP5_IO1 ((uint32_t)0x00010000) +#define TSC_GROUP5_IO2 ((uint32_t)0x00020000) +#define TSC_GROUP5_IO3 ((uint32_t)0x00040000) +#define TSC_GROUP5_IO4 ((uint32_t)0x00080000) +#define TSC_GROUP5_ALL_IOS ((uint32_t)0x000F0000) + +#define TSC_GROUP6_IO1 ((uint32_t)0x00100000) +#define TSC_GROUP6_IO2 ((uint32_t)0x00200000) +#define TSC_GROUP6_IO3 ((uint32_t)0x00400000) +#define TSC_GROUP6_IO4 ((uint32_t)0x00800000) +#define TSC_GROUP6_ALL_IOS ((uint32_t)0x00F00000) + +#define TSC_GROUP7_IO1 ((uint32_t)0x01000000) +#define TSC_GROUP7_IO2 ((uint32_t)0x02000000) +#define TSC_GROUP7_IO3 ((uint32_t)0x04000000) +#define TSC_GROUP7_IO4 ((uint32_t)0x08000000) +#define TSC_GROUP7_ALL_IOS ((uint32_t)0x0F000000) + +#define TSC_GROUP8_IO1 ((uint32_t)0x10000000) +#define TSC_GROUP8_IO2 ((uint32_t)0x20000000) +#define TSC_GROUP8_IO3 ((uint32_t)0x40000000) +#define TSC_GROUP8_IO4 ((uint32_t)0x80000000) +#define TSC_GROUP8_ALL_IOS ((uint32_t)0xF0000000) + +#define TSC_ALL_GROUPS_ALL_IOS ((uint32_t)0xFFFFFFFF) + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ + +/** @brief Reset TSC handle state + * @param __HANDLE__: TSC handle + * @retval None + */ +#define __HAL_TSC_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_TSC_STATE_RESET) + +/** + * @brief Enable the TSC peripheral. + * @param __HANDLE__: TSC handle + * @retval None + */ +#define __HAL_TSC_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= TSC_CR_TSCE) + +/** + * @brief Disable the TSC peripheral. + * @param __HANDLE__: TSC handle + * @retval None + */ +#define __HAL_TSC_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR &= (uint32_t)(~TSC_CR_TSCE)) + +/** + * @brief Start acquisition + * @param __HANDLE__: TSC handle + * @retval None + */ +#define __HAL_TSC_START_ACQ(__HANDLE__) ((__HANDLE__)->Instance->CR |= TSC_CR_START) + +/** + * @brief Stop acquisition + * @param __HANDLE__: TSC handle + * @retval None + */ +#define __HAL_TSC_STOP_ACQ(__HANDLE__) ((__HANDLE__)->Instance->CR &= (uint32_t)(~TSC_CR_START)) + +/** + * @brief Set IO default mode to output push-pull low + * @param __HANDLE__: TSC handle + * @retval None + */ +#define __HAL_TSC_SET_IODEF_OUTPPLOW(__HANDLE__) ((__HANDLE__)->Instance->CR &= (uint32_t)(~TSC_CR_IODEF)) + +/** + * @brief Set IO default mode to input floating + * @param __HANDLE__: TSC handle + * @retval None + */ +#define __HAL_TSC_SET_IODEF_INFLOAT(__HANDLE__) ((__HANDLE__)->Instance->CR |= TSC_CR_IODEF) + +/** + * @brief Set synchronization polarity to falling edge + * @param __HANDLE__: TSC handle + * @retval None + */ +#define __HAL_TSC_SET_SYNC_POL_FALL(__HANDLE__) ((__HANDLE__)->Instance->CR &= (uint32_t)(~TSC_CR_SYNCPOL)) + +/** + * @brief Set synchronization polarity to rising edge and high level + * @param __HANDLE__: TSC handle + * @retval None + */ +#define __HAL_TSC_SET_SYNC_POL_RISE_HIGH(__HANDLE__) ((__HANDLE__)->Instance->CR |= TSC_CR_SYNCPOL) + +/** + * @brief Enable TSC interrupt. + * @param __HANDLE__: TSC handle + * @param __INTERRUPT__: TSC interrupt + * @retval None + */ +#define __HAL_TSC_ENABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->IER |= (__INTERRUPT__)) + +/** + * @brief Disable TSC interrupt. + * @param __HANDLE__: TSC handle + * @param __INTERRUPT__: TSC interrupt + * @retval None + */ +#define __HAL_TSC_DISABLE_IT(__HANDLE__, __INTERRUPT__) ((__HANDLE__)->Instance->IER &= (uint32_t)(~(__INTERRUPT__))) + +/** @brief Check if the specified TSC interrupt source is enabled or disabled. + * @param __HANDLE__: TSC Handle + * @param __INTERRUPT__: TSC interrupt + * @retval SET or RESET + */ +#define __HAL_TSC_GET_IT_SOURCE(__HANDLE__, __INTERRUPT__) ((((__HANDLE__)->Instance->IER & (__INTERRUPT__)) == (__INTERRUPT__)) ? SET : RESET) + +/** + * @brief Get the selected TSC's flag status. + * @param __HANDLE__: TSC handle + * @param __FLAG__: TSC flag + * @retval SET or RESET + */ +#define __HAL_TSC_GET_FLAG(__HANDLE__, __FLAG__) ((((__HANDLE__)->Instance->ISR & (__FLAG__)) == (__FLAG__)) ? SET : RESET) + +/** + * @brief Clear the TSC's pending flag. + * @param __HANDLE__: TSC handle + * @param __FLAG__: TSC flag + * @retval None + */ +#define __HAL_TSC_CLEAR_FLAG(__HANDLE__, __FLAG__) ((__HANDLE__)->Instance->ICR |= (__FLAG__)) + +/** + * @brief Enable schmitt trigger hysteresis on a group of IOs + * @param __HANDLE__: TSC handle + * @param __GX_IOY_MASK__: IOs mask + * @retval None + */ +#define __HAL_TSC_ENABLE_HYSTERESIS(__HANDLE__, __GX_IOY_MASK__) ((__HANDLE__)->Instance->IOHCR |= (__GX_IOY_MASK__)) + +/** + * @brief Disable schmitt trigger hysteresis on a group of IOs + * @param __HANDLE__: TSC handle + * @param __GX_IOY_MASK__: IOs mask + * @retval None + */ +#define __HAL_TSC_DISABLE_HYSTERESIS(__HANDLE__, __GX_IOY_MASK__) ((__HANDLE__)->Instance->IOHCR &= (uint32_t)(~(__GX_IOY_MASK__))) + +/** + * @brief Open analog switch on a group of IOs + * @param __HANDLE__: TSC handle + * @param __GX_IOY_MASK__: IOs mask + * @retval None + */ +#define __HAL_TSC_OPEN_ANALOG_SWITCH(__HANDLE__, __GX_IOY_MASK__) ((__HANDLE__)->Instance->IOASCR &= (uint32_t)(~(__GX_IOY_MASK__))) + +/** + * @brief Close analog switch on a group of IOs + * @param __HANDLE__: TSC handle + * @param __GX_IOY_MASK__: IOs mask + * @retval None + */ +#define __HAL_TSC_CLOSE_ANALOG_SWITCH(__HANDLE__, __GX_IOY_MASK__) ((__HANDLE__)->Instance->IOASCR |= (__GX_IOY_MASK__)) + +/** + * @brief Enable a group of IOs in channel mode + * @param __HANDLE__: TSC handle + * @param __GX_IOY_MASK__: IOs mask + * @retval None + */ +#define __HAL_TSC_ENABLE_CHANNEL(__HANDLE__, __GX_IOY_MASK__) ((__HANDLE__)->Instance->IOCCR |= (__GX_IOY_MASK__)) + +/** + * @brief Disable a group of channel IOs + * @param __HANDLE__: TSC handle + * @param __GX_IOY_MASK__: IOs mask + * @retval None + */ +#define __HAL_TSC_DISABLE_CHANNEL(__HANDLE__, __GX_IOY_MASK__) ((__HANDLE__)->Instance->IOCCR &= (uint32_t)(~(__GX_IOY_MASK__))) + +/** + * @brief Enable a group of IOs in sampling mode + * @param __HANDLE__: TSC handle + * @param __GX_IOY_MASK__: IOs mask + * @retval None + */ +#define __HAL_TSC_ENABLE_SAMPLING(__HANDLE__, __GX_IOY_MASK__) ((__HANDLE__)->Instance->IOSCR |= (__GX_IOY_MASK__)) + +/** + * @brief Disable a group of sampling IOs + * @param __HANDLE__: TSC handle + * @param __GX_IOY_MASK__: IOs mask + * @retval None + */ +#define __HAL_TSC_DISABLE_SAMPLING(__HANDLE__, __GX_IOY_MASK__) ((__HANDLE__)->Instance->IOSCR &= (uint32_t)(~(__GX_IOY_MASK__))) + +/** + * @brief Enable acquisition groups + * @param __HANDLE__: TSC handle + * @param __GX_MASK__: Groups mask + * @retval None + */ +#define __HAL_TSC_ENABLE_GROUP(__HANDLE__, __GX_MASK__) ((__HANDLE__)->Instance->IOGCSR |= (__GX_MASK__)) + +/** + * @brief Disable acquisition groups + * @param __HANDLE__: TSC handle + * @param __GX_MASK__: Groups mask + * @retval None + */ +#define __HAL_TSC_DISABLE_GROUP(__HANDLE__, __GX_MASK__) ((__HANDLE__)->Instance->IOGCSR &= (uint32_t)(~(__GX_MASK__))) + +/** @brief Gets acquisition group status + * @param __HANDLE__: TSC Handle + * @param __GX_INDEX__: Group index + * @retval SET or RESET + */ +#define __HAL_TSC_GET_GROUP_STATUS(__HANDLE__, __GX_INDEX__) \ +((((__HANDLE__)->Instance->IOGCSR & (uint32_t)((uint32_t)1 << ((__GX_INDEX__) + (uint32_t)16))) == (uint32_t)((uint32_t)1 << ((__GX_INDEX__) + (uint32_t)16))) ? TSC_GROUP_COMPLETED : TSC_GROUP_ONGOING) + +/* Exported functions --------------------------------------------------------*/ + +/* Initialization and de-initialization functions *****************************/ +HAL_StatusTypeDef HAL_TSC_Init(TSC_HandleTypeDef* htsc); +HAL_StatusTypeDef HAL_TSC_DeInit(TSC_HandleTypeDef *htsc); +void HAL_TSC_MspInit(TSC_HandleTypeDef* htsc); +void HAL_TSC_MspDeInit(TSC_HandleTypeDef* htsc); + +/* IO operation functions *****************************************************/ +HAL_StatusTypeDef HAL_TSC_Start(TSC_HandleTypeDef* htsc); +HAL_StatusTypeDef HAL_TSC_Start_IT(TSC_HandleTypeDef* htsc); +HAL_StatusTypeDef HAL_TSC_Stop(TSC_HandleTypeDef* htsc); +HAL_StatusTypeDef HAL_TSC_Stop_IT(TSC_HandleTypeDef* htsc); +TSC_GroupStatusTypeDef HAL_TSC_GroupGetStatus(TSC_HandleTypeDef* htsc, uint32_t gx_index); +uint32_t HAL_TSC_GroupGetValue(TSC_HandleTypeDef* htsc, uint32_t gx_index); + +/* Peripheral Control functions ***********************************************/ +HAL_StatusTypeDef HAL_TSC_IOConfig(TSC_HandleTypeDef* htsc, TSC_IOConfigTypeDef* config); +HAL_StatusTypeDef HAL_TSC_IODischarge(TSC_HandleTypeDef* htsc, uint32_t choice); + +/* Peripheral State and Error functions ***************************************/ +HAL_TSC_StateTypeDef HAL_TSC_GetState(TSC_HandleTypeDef* htsc); +HAL_StatusTypeDef HAL_TSC_PollForAcquisition(TSC_HandleTypeDef* htsc); +void HAL_TSC_IRQHandler(TSC_HandleTypeDef* htsc); + +/* Callback functions *********************************************************/ +void HAL_TSC_ConvCpltCallback(TSC_HandleTypeDef* htsc); +void HAL_TSC_ErrorCallback(TSC_HandleTypeDef* htsc); + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /*__STM32L0xx_TSC_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_uart.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_uart.c new file mode 100644 index 0000000000..65ad6b4811 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_uart.c @@ -0,0 +1,1984 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_uart.c + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief UART HAL module driver. + * + * This file provides firmware functions to manage the following + * functionalities of the Universal Asynchronous Receiver Transmitter Peripheral (UART). + * + Initialization and de-initialization methods + * + IO operation methods + * + Peripheral Control methods + * + @verbatim + =============================================================================== + ##### How to use this driver ##### + =============================================================================== + [..] + The UART HAL driver can be used as follows: + + (#) Declare a UART_HandleTypeDef handle structure. + + (#) Initialize the UART low level resources by implementing the HAL_UART_MspInit() API: + (##) Enable the USARTx interface clock. + (##) UART pins configuration: + (+++) Enable the clock for the UART GPIOs. + (+++) Configure these UART pins as alternate function pull-up. + (##) NVIC configuration if you need to use interrupt process (HAL_UART_Transmit_IT() + and HAL_UART_Receive_IT() APIs): + (+++) Configure the USARTx interrupt priority. + (+++) Enable the NVIC USART IRQ handle. + + (##) DMA Configuration if you need to use DMA process (HAL_UART_Transmit_DMA() + and HAL_UART_Receive_DMA() APIs): + (+++) Declare a DMA handle structure for the Tx/Rx stream. + (+++) Enable the DMAx interface clock. + (+++) Configure the declared DMA handle structure with the required + Tx/Rx parameters. + (+++) Configure the DMA Tx/Rx Stream. + (+++) Associate the initialized DMA handle to the UART DMA Tx/Rx handle. + (+++) Configure the priority and enable the NVIC for the transfer complete + interrupt on the DMA Tx/Rx Stream. + + (#) Program the Baud Rate, Word Length, Stop Bit, Parity, Hardware + flow control and Mode(Receiver/Transmitter) in the Init structure. + + (#) For the UART asynchronous mode, initialize the UART registers by calling + the HAL_UART_Init() API. + + (#) For the UART Half duplex mode, initialize the UART registers by calling + the HAL_HalfDuplex_Init() API. + + (#) For the LIN mode, initialize the UART registers by calling the HAL_LIN_Init() API. + + (#) For the Multi-Processor mode, initialize the UART registers by calling + the HAL_MultiProcessor_Init() API. + + [..] + (@) The specific UART interrupts (Transmission complete interrupt, + RXNE interrupt and Error Interrupts) will be managed using the macros + __HAL_UART_ENABLE_IT() and __HAL_UART_DISABLE_IT() inside the transmit + and receive process. + + [..] + (@) These APIs (HAL_UART_Init() and HAL_HalfDuplex_Init()) configure also the + low level Hardware GPIO, CLOCK, CORTEX...etc) by calling the customed + HAL_UART_MspInit() API. + + [..] + Three operation modes are available within this driver : + + *** Polling mode IO operation *** + ================================= + [..] + (+) Send an amount of data in blocking mode using HAL_UART_Transmit() + (+) Receive an amount of data in blocking mode using HAL_UART_Receive() + + *** Interrupt mode IO operation *** + =================================== + [..] + (+) Send an amount of data in non blocking mode using HAL_UART_Transmit_IT() + (+) At transmission end of half transfer HAL_UART_TxHalfCpltCallback is executed and user can + add his own code by customization of function pointer HAL_UART_TxHalfCpltCallback + (+) At transmission end of transfer HAL_UART_TxCpltCallback is executed and user can + add his own code by customization of function pointer HAL_UART_TxCpltCallback + (+) Receive an amount of data in non blocking mode using HAL_UART_Receive_IT() + (+) At reception end of half transfer HAL_UART_RxHalfCpltCallback is executed and user can + add his own code by customization of function pointer HAL_UART_RxHalfCpltCallback + (+) At reception end of transfer HAL_UART_RxCpltCallback is executed and user can + add his own code by customization of function pointer HAL_UART_RxCpltCallback + (+) In case of transfer Error, HAL_UART_ErrorCallback() function is executed and user can + add his own code by customization of function pointer HAL_UART_ErrorCallback + + *** DMA mode IO operation *** + ============================== + [..] + (+) Send an amount of data in non blocking mode (DMA) using HAL_UART_Transmit_DMA() + (+) At transmission end of half transfer HAL_UART_TxHalfCpltCallback is executed and user can + add his own code by customization of function pointer HAL_UART_TxHalfCpltCallback + (+) At transmission end of transfer HAL_UART_TxCpltCallback is executed and user can + add his own code by customization of function pointer HAL_UART_TxCpltCallback + (+) Receive an amount of data in non blocking mode (DMA) using HAL_UART_Receive_DMA() + (+) At reception end of half transfer HAL_UART_RxHalfCpltCallback is executed and user can + add his own code by customization of function pointer HAL_UART_RxHalfCpltCallback + (+) At reception end of transfer HAL_UART_RxCpltCallback is executed and user can + add his own code by customization of function pointer HAL_UART_RxCpltCallback + (+) In case of transfer Error, HAL_UART_ErrorCallback() function is executed and user can + add his own code by customization of function pointer HAL_UART_ErrorCallback + (+) Pause the DMA Transfer using HAL_UART_DMAPause() + (+) Resume the DMA Transfer using HAL_UART_DMAResume() + (+) Stop the DMA Transfer using HAL_UART_DMAStop() + + *** UART HAL driver macros list *** + ============================================= + [..] + Below the list of most used macros in UART HAL driver. + + (+) __HAL_UART_ENABLE: Enable the UART peripheral + (+) __HAL_UART_DISABLE: Disable the UART peripheral + (+) __HAL_UART_GET_FLAG : Check whether the specified UART flag is set or not + (+) __HAL_UART_CLEAR_FLAG : Clear the specified UART pending flag + (+) __HAL_UART_ENABLE_IT: Enable the specified UART interrupt + (+) __HAL_UART_DISABLE_IT: Disable the specified UART interrupt + + [..] + (@) You can refer to the UART HAL driver header file for more useful macros + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @defgroup UART + * @brief HAL UART module driver + * @{ + */ +#ifdef HAL_UART_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +#define UART_TIMEOUT_VALUE ((uint32_t) 22000) +#define UART_CR1_FIELDS ((uint32_t)(USART_CR1_M | USART_CR1_PCE | USART_CR1_PS | \ + USART_CR1_TE | USART_CR1_RE | USART_CR1_OVER8)) +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +static void UART_DMATransmitCplt(DMA_HandleTypeDef *hdma); +static void UART_DMATxHalfCplt(DMA_HandleTypeDef *hdma); +static void UART_DMAReceiveCplt(DMA_HandleTypeDef *hdma); +static void UART_DMARxHalfCplt(DMA_HandleTypeDef *hdma); +static void UART_DMAError(DMA_HandleTypeDef *hdma); +static HAL_StatusTypeDef UART_Transmit_IT(UART_HandleTypeDef *huart); +static HAL_StatusTypeDef UART_Receive_IT(UART_HandleTypeDef *huart); + +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup UART_Private_Functions + * @{ + */ + +/** @defgroup HAL_UART_Group1 Initialization/de-initialization methods + * @brief Initialization and Configuration functions + * +@verbatim +=============================================================================== + ##### Initialization and Configuration functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to initialize the USARTx or the UARTy + in asynchronous mode. + (+) For the asynchronous mode only these parameters can be configured: + (++) Baud Rate + (++) Word Length + (++) Stop Bit + (++) Parity: If the parity is enabled, then the MSB bit of the data written + in the data register is transmitted but is changed by the parity bit. + Depending on the frame length defined by the M bit (8-bits or 9-bits), + the possible UART frame formats are as listed in the following table: + +-----------------------------------------------------------------------+ + | M1 bit | M0 bit | PCE bit | USART frame | + |---------|---------|-----------|---------------------------------------| + | 0 | 0 | 0 | | SB | 8 bit data | STB | | + |---------|---------|-----------|---------------------------------------| + | 0 | 0 | 1 | | SB | 7 bit data | PB | STB | | + |---------|---------|-----------|---------------------------------------| + | 0 | 1 | 0 | | SB | 9 bit data | STB | | + |---------|---------|-----------|---------------------------------------| + | 0 | 1 | 1 | | SB | 8 bit data | PB | STB | | + |---------|---------|-----------|---------------------------------------| + | 1 | 0 | 0 | | SB | 7 bit data | STB | | + |---------|---------|-----------|---------------------------------------| + | 1 | 0 | 1 | | SB | 6 bit data | PB | STB | | + +-----------------------------------------------------------------------+ + (++) Hardware flow control + (++) Receiver/transmitter modes + (++) Over Sampling Method + (++) One-Bit Sampling Method + (+) For the asynchronous mode, the following advanced features can be configured as well: + (++) TX and/or RX pin level inversion + (++) data logical level inversion + (++) RX and TX pins swap + (++) RX overrun detection disabling + (++) DMA disabling on RX error + (++) MSB first on communication line + (++) auto Baud rate detection + [..] + The HAL_UART_Init(), HAL_HalfDuplex_Init(), HAL_LIN_Init()and HAL_MultiProcessorEx_Init()API + follow respectively the UART asynchronous, UART Half duplex, UART LIN mode + and UART multiprocessor mode mode configuration procedures (details for the procedures + are available in reference manual). + +@endverbatim + * @{ + */ + +/** + * @brief Initializes the UART mode according to the specified + * parameters in the UART_InitTypeDef and creates the associated handle . + * @param huart: uart handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_UART_Init(UART_HandleTypeDef *huart) +{ + /* Check the UART handle allocation */ + if(huart == NULL) + { + return HAL_ERROR; + } + + if(huart->Init.HwFlowCtl != UART_HWCONTROL_NONE) + { + /* Check the parameters */ + assert_param(IS_UART_HWFLOW_INSTANCE(huart->Instance)); + } + else + { + /* Check the parameters */ + assert_param(IS_UART_INSTANCE(huart->Instance)); + } + + if(huart->State == HAL_UART_STATE_RESET) + { + /* Init the low level hardware : GPIO, CLOCK, CORTEX */ + HAL_UART_MspInit(huart); + } + + huart->State = HAL_UART_STATE_BUSY; + + /* Disable the Peripheral */ + __HAL_UART_DISABLE(huart); + + /* Set the UART Communication parameters */ + UART_SetConfig(huart); + + if (huart->AdvancedInit.AdvFeatureInit != UART_ADVFEATURE_NO_INIT) + { + UART_AdvFeatureConfig(huart); + } + + /* In asynchronous mode, the following bits must be kept cleared: + - LINEN and CLKEN bits in the USART_CR2 register, + - SCEN, HDSEL and IREN bits in the USART_CR3 register.*/ + huart->Instance->CR2 &= ~(USART_CR2_LINEN | USART_CR2_CLKEN); + huart->Instance->CR3 &= ~(USART_CR3_SCEN | USART_CR3_HDSEL | USART_CR3_IREN); + + /* Enable the Peripheral */ + __HAL_UART_ENABLE(huart); + + /* TEACK and/or REACK to check before moving huart->State to Ready */ + return (UART_CheckIdleState(huart)); +} + +/** + * @brief Initializes the half-duplex mode according to the specified + * parameters in the UART_InitTypeDef and creates the associated handle . + * @param huart: uart handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_HalfDuplex_Init(UART_HandleTypeDef *huart) +{ + /* Check the UART handle allocation */ + if(huart == NULL) + { + return HAL_ERROR; + } + + if(huart->State == HAL_UART_STATE_RESET) + { + /* Init the low level hardware : GPIO, CLOCK, CORTEX */ + HAL_UART_MspInit(huart); + } + + /* Disable the Peripheral */ + __HAL_UART_DISABLE(huart); + + /* Set the UART Communication parameters */ + UART_SetConfig(huart); + + if (huart->AdvancedInit.AdvFeatureInit != UART_ADVFEATURE_NO_INIT) + { + UART_AdvFeatureConfig(huart); + } + + /* In half-duplex mode, the following bits must be kept cleared: + - LINEN and CLKEN bits in the USART_CR2 register, + - SCEN and IREN bits in the USART_CR3 register.*/ + huart->Instance->CR2 &= ~(USART_CR2_LINEN | USART_CR2_CLKEN); + huart->Instance->CR3 &= ~(USART_CR3_IREN | USART_CR3_SCEN); + + /* Enable the Half-Duplex mode by setting the HDSEL bit in the CR3 register */ + huart->Instance->CR3 |= USART_CR3_HDSEL; + + /* Enable the Peripheral */ + __HAL_UART_ENABLE(huart); + + /* TEACK and/or REACK to check before moving huart->State to Ready */ + return (UART_CheckIdleState(huart)); +} + +/** + * @brief Initializes the LIN mode according to the specified + * parameters in the UART_InitTypeDef and creates the associated handle . + * @param huart: uart handle + * @param BreakDetectLength: specifies the LIN break detection length. + * This parameter can be one of the following values: + * @arg UART_LINBREAKDETECTLENGTH_10B: 10-bit break detection + * @arg UART_LINBREAKDETECTLENGTH_11B: 11-bit break detection + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LIN_Init(UART_HandleTypeDef *huart, uint32_t BreakDetectLength) +{ + /* Check the UART handle allocation */ + if(huart == NULL) + { + return HAL_ERROR; + } + /* Check the Break detection length parameter */ + assert_param(IS_UART_LIN_BREAK_DETECT_LENGTH(BreakDetectLength)); + + /* LIN mode limited to 16-bit oversampling only */ + if(huart->Init.OverSampling == UART_OVERSAMPLING_8) + { + return HAL_ERROR; + } + + if(huart->State == HAL_UART_STATE_RESET) + { + /* Init the low level hardware : GPIO, CLOCK, CORTEX */ + HAL_UART_MspInit(huart); + } + + /* Disable the Peripheral */ + __HAL_UART_DISABLE(huart); + + /* Set the UART Communication parameters */ + UART_SetConfig(huart); + + if (huart->AdvancedInit.AdvFeatureInit != UART_ADVFEATURE_NO_INIT) + { + UART_AdvFeatureConfig(huart); + } + + /* In LIN mode, the following bits must be kept cleared: + - LINEN and CLKEN bits in the USART_CR2 register, + - SCEN and IREN bits in the USART_CR3 register.*/ + huart->Instance->CR2 &= ~(USART_CR2_CLKEN); + huart->Instance->CR3 &= ~(USART_CR3_HDSEL | USART_CR3_IREN | USART_CR3_SCEN); + + /* Enable the LIN mode by setting the LINEN bit in the CR2 register */ + huart->Instance->CR2 |= USART_CR2_LINEN; + + /* Set the USART LIN Break detection length. */ + MODIFY_REG(huart->Instance->CR2, USART_CR2_LBDL, BreakDetectLength); + + /* Enable the Peripheral */ + __HAL_UART_ENABLE(huart); + + /* TEACK and/or REACK to check before moving huart->State to Ready */ + return (UART_CheckIdleState(huart)); +} + +/** + * @brief Initializes the multiprocessor mode according to the specified + * parameters in the UART_InitTypeDef and creates the associated handle. + * @param huart: UART handle + * @param Address: UART node address (4-, 6-, 7- or 8-bit long) + * @param WakeUpMethod: specifies the UART wakeup method. + * This parameter can be one of the following values: + * @arg UART_WAKEUPMETHOD_IDLELINE: WakeUp by an idle line detection + * @arg UART_WAKEUPMETHOD_ADDRESSMARK: WakeUp by an address mark + * @note If the user resorts to idle line detection wake up, the Address parameter + * is useless and ignored by the initialization function. + * @note If the user resorts to address mark wake up, the address length detection + * is configured by default to 4 bits only. For the UART to be able to + * manage 6-, 7- or 8-bit long addresses detection, the API + * HAL_MultiProcessorEx_AddressLength_Set() must be called after + * HAL_MultiProcessor_Init(). + * @retval HAL status + */ +HAL_StatusTypeDef HAL_MultiProcessor_Init(UART_HandleTypeDef *huart, uint8_t Address, uint32_t WakeUpMethod) +{ + /* Check the UART handle allocation */ + if(huart == NULL) + { + return HAL_ERROR; + } + + /* Check the wake up method parameter */ + assert_param(IS_UART_WAKEUPMETHOD(WakeUpMethod)); + + if(huart->State == HAL_UART_STATE_RESET) + { + /* Init the low level hardware : GPIO, CLOCK */ + HAL_UART_MspInit(huart); + } + + huart->State = HAL_UART_STATE_BUSY; + + /* Disable the Peripheral */ + __HAL_UART_DISABLE(huart); + + /* Set the UART Communication parameters */ + UART_SetConfig(huart); + + if (huart->AdvancedInit.AdvFeatureInit != UART_ADVFEATURE_NO_INIT) + { + UART_AdvFeatureConfig(huart); + } + + /* In multiprocessor mode, the following bits must be kept cleared: + - LINEN and CLKEN bits in the USART_CR2 register, + - SCEN, HDSEL and IREN bits in the USART_CR3 register. */ + huart->Instance->CR2 &= ~(USART_CR2_LINEN | USART_CR2_CLKEN); + huart->Instance->CR3 &= ~(USART_CR3_SCEN | USART_CR3_HDSEL | USART_CR3_IREN); + + if (WakeUpMethod == UART_WAKEUPMETHOD_ADDRESSMARK) + { + /* If address mark wake up method is chosen, set the USART address node */ + MODIFY_REG(huart->Instance->CR2, USART_CR2_ADD, ((uint32_t)Address << UART_CR2_ADDRESS_LSB_POS)); + } + + /* Set the wake up method by setting the WAKE bit in the CR1 register */ + MODIFY_REG(huart->Instance->CR1, USART_CR1_WAKE, WakeUpMethod); + + /* Enable the Peripheral */ + __HAL_UART_ENABLE(huart); + + /* TEACK and/or REACK to check before moving huart->State to Ready */ + return (UART_CheckIdleState(huart)); +} + +/** + * @brief DeInitializes the UART peripheral + * @param huart: uart handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_UART_DeInit(UART_HandleTypeDef *huart) +{ + /* Check the UART handle allocation */ + if(huart == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_UART_INSTANCE(huart->Instance)); + + huart->State = HAL_UART_STATE_BUSY; + + /* Disable the Peripheral */ + __HAL_UART_DISABLE(huart); + + huart->Instance->CR1 = 0x0; + huart->Instance->CR2 = 0x0; + huart->Instance->CR3 = 0x0; + + /* DeInit the low level hardware */ + HAL_UART_MspDeInit(huart); + + huart->ErrorCode = HAL_UART_ERROR_NONE; + huart->State = HAL_UART_STATE_RESET; + + /* Release Lock */ + __HAL_UNLOCK(huart); + + return HAL_OK; +} + +/** + * @brief UART MSP Init + * @param huart: uart handle + * @retval None + */ + __weak void HAL_UART_MspInit(UART_HandleTypeDef *huart) +{ + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_UART_MspInit can be implemented in the user file + */ +} + +/** + * @brief UART MSP DeInit + * @param huart: uart handle + * @retval None + */ + __weak void HAL_UART_MspDeInit(UART_HandleTypeDef *huart) +{ + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_UART_MspDeInit can be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup HAL_UART_Group2 IO operation methods + * @brief UART Transmit/Receive functions + * +@verbatim + =============================================================================== + ##### I/O operation methods ##### + =============================================================================== + This subsection provides a set of functions allowing to manage the UART asynchronous + and Half duplex data transfers. + + (#) There are two mode of transfer: + (+) Blocking mode: The communication is performed in polling mode. + The HAL status of all data processing is returned by the same function + after finishing transfer. + (+) No-Blocking mode: The communication is performed using Interrupts + or DMA, These API's return the HAL status. + The end of the data processing will be indicated through the + dedicated UART IRQ when using Interrupt mode or the DMA IRQ when + using DMA mode. + The HAL_UART_TxCpltCallback(), HAL_UART_RxCpltCallback() user callbacks + will be executed respectivelly at the end of the transmit or Receive process + The HAL_UART_ErrorCallback()user callback will be executed when a communication error is detected + + (#) Blocking mode API's are : + (+) HAL_UART_Transmit() + (+) HAL_UART_Receive() + + (#) Non-Blocking mode API's with Interrupt are : + (+) HAL_UART_Transmit_IT() + (+) HAL_UART_Receive_IT() + (+) HAL_UART_IRQHandler() + (+) UART_Transmit_IT() + (+) UART_Receive_IT() + + (#) No-Blocking mode API's with DMA are : + (+) HAL_UART_Transmit_DMA() + (+) HAL_UART_Receive_DMA() + (+) HAL_UART_DMAPause() + (+) HAL_UART_DMAResume() + (+) HAL_UART_DMAStop() + + (#) A set of Transfer Complete Callbacks are provided in No_Blocking mode: + (+) HAL_UART_TxHalfCpltCallback() + (+) HAL_UART_TxCpltCallback() + (+) HAL_UART_RxHalfCpltCallback() + (+) HAL_UART_RxCpltCallback() + (+) HAL_UART_ErrorCallback() + + -@- In the Half duplex communication, it is forbidden to run the transmit + and receive process in parallel, the UART state HAL_UART_STATE_BUSY_TX_RX can't be useful. + +@endverbatim + * @{ + */ + +/** + * @brief Send an amount of data in blocking mode + * @param huart: uart handle + * @param pData: pointer to data buffer + * @param Size: amount of data to be sent + * @param Timeout : Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_UART_Transmit(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size, uint32_t Timeout) +{ + uint16_t* tmp; + + if((huart->State == HAL_UART_STATE_READY) || (huart->State == HAL_UART_STATE_BUSY_RX)) + { + if((pData == NULL ) || (Size == 0)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(huart); + + huart->ErrorCode = HAL_UART_ERROR_NONE; + /* Check if a non-blocking receive process is ongoing or not */ + if(huart->State == HAL_UART_STATE_BUSY_RX) + { + huart->State = HAL_UART_STATE_BUSY_TX_RX; + } + else + { + huart->State = HAL_UART_STATE_BUSY_TX; + } + + huart->TxXferSize = Size; + huart->TxXferCount = Size; + while(huart->TxXferCount > 0) + { + huart->TxXferCount--; + if(UART_WaitOnFlagUntilTimeout(huart, UART_FLAG_TXE, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + if ((huart->Init.WordLength == UART_WORDLENGTH_9B) && (huart->Init.Parity == UART_PARITY_NONE)) + { + tmp = (uint16_t*) pData; + huart->Instance->TDR = (*tmp & (uint16_t)0x01FF); + pData += 2; + } + else + { + huart->Instance->TDR = (*pData++ & (uint8_t)0xFF); + } + } + if(UART_WaitOnFlagUntilTimeout(huart, UART_FLAG_TC, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + /* Check if a non-blocking receive Process is ongoing or not */ + if(huart->State == HAL_UART_STATE_BUSY_TX_RX) + { + huart->State = HAL_UART_STATE_BUSY_RX; + } + else + { + huart->State = HAL_UART_STATE_READY; + } + + /* Process Unlocked */ + __HAL_UNLOCK(huart); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive an amount of data in blocking mode + * @param huart: uart handle + * @param pData: pointer to data buffer + * @param Size: amount of data to be received + * @param Timeout : Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_UART_Receive(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size, uint32_t Timeout) +{ + uint16_t* tmp; + uint16_t uhMask; + + if((huart->State == HAL_UART_STATE_READY) || (huart->State == HAL_UART_STATE_BUSY_TX)) + { + if((pData == NULL ) || (Size == 0)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(huart); + + huart->ErrorCode = HAL_UART_ERROR_NONE; + /* Check if a non-blocking transmit process is ongoing or not */ + if(huart->State == HAL_UART_STATE_BUSY_TX) + { + huart->State = HAL_UART_STATE_BUSY_TX_RX; + } + else + { + huart->State = HAL_UART_STATE_BUSY_RX; + } + + huart->RxXferSize = Size; + huart->RxXferCount = Size; + + /* Computation of UART mask to apply to RDR register */ + __HAL_UART_MASK_COMPUTATION(huart); + uhMask = huart->Mask; + + /* as long as data have to be received */ + while(huart->RxXferCount > 0) + { + huart->RxXferCount--; + if(UART_WaitOnFlagUntilTimeout(huart, UART_FLAG_RXNE, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + if ((huart->Init.WordLength == UART_WORDLENGTH_9B) && (huart->Init.Parity == UART_PARITY_NONE)) + { + tmp = (uint16_t*) pData ; + *tmp = (uint16_t)(huart->Instance->RDR & uhMask); + pData +=2; + } + else + { + *pData++ = (uint8_t)(huart->Instance->RDR & (uint8_t)uhMask); + } + } + + /* Check if a non-blocking transmit Process is ongoing or not */ + if(huart->State == HAL_UART_STATE_BUSY_TX_RX) + { + huart->State = HAL_UART_STATE_BUSY_TX; + } + else + { + huart->State = HAL_UART_STATE_READY; + } + /* Process Unlocked */ + __HAL_UNLOCK(huart); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Send an amount of data in interrupt mode + * @param huart: uart handle + * @param pData: pointer to data buffer + * @param Size: amount of data to be sent + * @retval HAL status + */ +HAL_StatusTypeDef HAL_UART_Transmit_IT(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size) +{ + if((huart->State == HAL_UART_STATE_READY) || (huart->State == HAL_UART_STATE_BUSY_RX)) + { + if((pData == NULL ) || (Size == 0)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(huart); + + huart->pTxBuffPtr = pData; + huart->TxXferSize = Size; + huart->TxXferCount = Size; + + huart->ErrorCode = HAL_UART_ERROR_NONE; + /* Check if a receive process is ongoing or not */ + if(huart->State == HAL_UART_STATE_BUSY_RX) + { + huart->State = HAL_UART_STATE_BUSY_TX_RX; + } + else + { + huart->State = HAL_UART_STATE_BUSY_TX; + } + + /* Enable the UART Parity Error Interrupt */ + __HAL_UART_ENABLE_IT(huart, UART_IT_PE); + + /* Enable the UART Error Interrupt: (Frame error, noise error, overrun error) */ + __HAL_UART_ENABLE_IT(huart, UART_IT_ERR); + + /* Process Unlocked */ + __HAL_UNLOCK(huart); + + /* Enable the UART Transmit Complete Interrupt */ + __HAL_UART_ENABLE_IT(huart, UART_IT_TC); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive an amount of data in interrupt mode + * @param huart: uart handle + * @param pData: pointer to data buffer + * @param Size: amount of data to be received + * @retval HAL status + */ +HAL_StatusTypeDef HAL_UART_Receive_IT(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size) +{ + if((huart->State == HAL_UART_STATE_READY) || (huart->State == HAL_UART_STATE_BUSY_TX)) + { + if((pData == NULL ) || (Size == 0)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(huart); + + huart->pRxBuffPtr = pData; + huart->RxXferSize = Size; + huart->RxXferCount = Size; + + /* Computation of UART mask to apply to RDR register */ + __HAL_UART_MASK_COMPUTATION(huart); + + huart->ErrorCode = HAL_UART_ERROR_NONE; + /* Check if a transmit process is ongoing or not */ + if(huart->State == HAL_UART_STATE_BUSY_TX) + { + huart->State = HAL_UART_STATE_BUSY_TX_RX; + } + else + { + huart->State = HAL_UART_STATE_BUSY_RX; + } + + /* Enable the UART Parity Error Interrupt */ + __HAL_UART_ENABLE_IT(huart, UART_IT_PE); + + /* Enable the UART Error Interrupt: (Frame error, noise error, overrun error) */ + __HAL_UART_ENABLE_IT(huart, UART_IT_ERR); + + /* Process Unlocked */ + __HAL_UNLOCK(huart); + + /* Enable the UART Data Register not empty Interrupt */ + __HAL_UART_ENABLE_IT(huart, UART_IT_RXNE); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Send an amount of data in DMA mode + * @param huart: uart handle + * @param pData: pointer to data buffer + * @param Size: amount of data to be sent + * @retval HAL status + */ +HAL_StatusTypeDef HAL_UART_Transmit_DMA(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size) +{ + uint32_t *tmp; + + if((huart->State == HAL_UART_STATE_READY) || (huart->State == HAL_UART_STATE_BUSY_RX)) + { + if((pData == NULL ) || (Size == 0)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(huart); + + huart->pTxBuffPtr = pData; + huart->TxXferSize = Size; + huart->TxXferCount = Size; + + huart->ErrorCode = HAL_UART_ERROR_NONE; + /* Check if a receive process is ongoing or not */ + if(huart->State == HAL_UART_STATE_BUSY_RX) + { + huart->State = HAL_UART_STATE_BUSY_TX_RX; + } + else + { + huart->State = HAL_UART_STATE_BUSY_TX; + } + + /* Set the UART DMA transfert complete callback */ + huart->hdmatx->XferCpltCallback = UART_DMATransmitCplt; + + /* Set the UART DMA Half transfer complete callback */ + huart->hdmatx->XferHalfCpltCallback = UART_DMATxHalfCplt; + + /* Set the DMA error callback */ + huart->hdmatx->XferErrorCallback = UART_DMAError; + + /* Enable the UART transmit DMA Stream */ + tmp = (uint32_t*)&pData; + HAL_DMA_Start_IT(huart->hdmatx, *(uint32_t*)tmp, (uint32_t)&huart->Instance->TDR, Size); + + /* Enable the DMA transfer for transmit request by setting the DMAT bit + in the UART CR3 register */ + huart->Instance->CR3 |= USART_CR3_DMAT; + + /* Process Unlocked */ + __HAL_UNLOCK(huart); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive an amount of data in DMA mode + * @param huart: uart handle + * @param pData: pointer to data buffer + * @param Size: amount of data to be received + * @note When the UART parity is enabled (PCE = 1) the data received contain the parity bit. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_UART_Receive_DMA(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size) +{ + uint32_t *tmp; + + if((huart->State == HAL_UART_STATE_READY) || (huart->State == HAL_UART_STATE_BUSY_TX)) + { + if((pData == NULL ) || (Size == 0)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(huart); + + huart->pRxBuffPtr = pData; + huart->RxXferSize = Size; + + huart->ErrorCode = HAL_UART_ERROR_NONE; + /* Check if a transmit process is ongoing or not */ + if(huart->State == HAL_UART_STATE_BUSY_TX) + { + huart->State = HAL_UART_STATE_BUSY_TX_RX; + } + else + { + huart->State = HAL_UART_STATE_BUSY_RX; + } + + /* Set the UART DMA transfert complete callback */ + huart->hdmarx->XferCpltCallback = UART_DMAReceiveCplt; + + /* Set the UART DMA Half transfer complete callback */ + huart->hdmarx->XferHalfCpltCallback = UART_DMARxHalfCplt; + + /* Set the DMA error callback */ + huart->hdmarx->XferErrorCallback = UART_DMAError; + + /* Enable the DMA Stream */ + tmp = (uint32_t*)&pData; + HAL_DMA_Start_IT(huart->hdmarx, (uint32_t)&huart->Instance->RDR, *(uint32_t*)tmp, Size); + + /* Enable the DMA transfer for the receiver request by setting the DMAR bit + in the UART CR3 register */ + huart->Instance->CR3 |= USART_CR3_DMAR; + + /* Process Unlocked */ + __HAL_UNLOCK(huart); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Pauses the DMA Transfer. + * @param huart: UART handle + * @retval None + */ +HAL_StatusTypeDef HAL_UART_DMAPause(UART_HandleTypeDef *huart) +{ + /* Process Locked */ + __HAL_LOCK(huart); + + if(huart->State == HAL_UART_STATE_BUSY_TX) + { + /* Disable the UART DMA Tx request */ + huart->Instance->CR3 &= (uint32_t)(~USART_CR3_DMAT); + } + else if(huart->State == HAL_UART_STATE_BUSY_RX) + { + /* Disable the UART DMA Rx request */ + huart->Instance->CR3 &= (uint32_t)(~USART_CR3_DMAR); + } + else if(huart->State == HAL_UART_STATE_BUSY_TX_RX) + { + /* Disable the UART DMA Tx request */ + huart->Instance->CR3 &= (uint32_t)(~USART_CR3_DMAT); + /* Disable the UART DMA Rx request */ + huart->Instance->CR3 &= (uint32_t)(~USART_CR3_DMAR); + } + /* Process Unlocked */ + __HAL_UNLOCK(huart); + + return HAL_OK; +} + +/** + * @brief Resumes the DMA Transfer. + * @param huart: UART handle + * @retval None + */ +HAL_StatusTypeDef HAL_UART_DMAResume(UART_HandleTypeDef *huart) +{ + /* Process Locked */ + __HAL_LOCK(huart); + + if(huart->State == HAL_UART_STATE_BUSY_TX) + { + /* Enable the UART DMA Tx request */ + huart->Instance->CR3 |= USART_CR3_DMAT; + } + else if(huart->State == HAL_UART_STATE_BUSY_RX) + { + /* Enable the UART DMA Rx request */ + huart->Instance->CR3 |= USART_CR3_DMAR; + } + else if(huart->State == HAL_UART_STATE_BUSY_TX_RX) + { + /* Enable the UART DMA Rx request before the DMA Tx request */ + huart->Instance->CR3 |= USART_CR3_DMAR; + /* Enable the UART DMA Tx request */ + huart->Instance->CR3 |= USART_CR3_DMAT; + } + + /* If the UART peripheral is still not enabled, enable it */ + if ((huart->Instance->CR1 & USART_CR1_UE) == 0) + { + /* Enable UART peripheral */ + __HAL_UART_ENABLE(huart); + } + + /* Process Unlocked */ + __HAL_UNLOCK(huart); + + return HAL_OK; +} + +/** + * @brief Stops the DMA Transfer. + * @param huart: UART handle + * @retval None + */ +HAL_StatusTypeDef HAL_UART_DMAStop(UART_HandleTypeDef *huart) +{ + /* Process Locked */ + __HAL_LOCK(huart); + + /* Disable the UART Tx/Rx DMA requests */ + huart->Instance->CR3 &= ~USART_CR3_DMAT; + huart->Instance->CR3 &= ~USART_CR3_DMAR; + + /* Abort the UART DMA tx channel */ + if(huart->hdmatx != NULL) + { + HAL_DMA_Abort(huart->hdmatx); + } + /* Abort the UART DMA rx channel */ + if(huart->hdmarx != NULL) + { + HAL_DMA_Abort(huart->hdmarx); + } + + /* Disable UART peripheral */ + __HAL_UART_DISABLE(huart); + + huart->State = HAL_UART_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(huart); + + return HAL_OK; +} + +/** + * @brief This function handles UART interrupt request. + * @param huart: uart handle + * @retval None + */ +void HAL_UART_IRQHandler(UART_HandleTypeDef *huart) +{ + /* UART parity error interrupt occurred ------------------------------------*/ + if((__HAL_UART_GET_IT(huart, UART_IT_PE) != RESET) && (__HAL_UART_GET_IT_SOURCE(huart, UART_IT_PE) != RESET)) + { + __HAL_UART_CLEAR_IT(huart, UART_CLEAR_PEF); + + huart->ErrorCode |= HAL_UART_ERROR_PE; + /* Set the UART state ready to be able to start again the process */ + huart->State = HAL_UART_STATE_READY; + } + + /* UART frame error interrupt occured --------------------------------------*/ + if((__HAL_UART_GET_IT(huart, UART_IT_FE) != RESET) && (__HAL_UART_GET_IT_SOURCE(huart, UART_IT_ERR) != RESET)) + { + __HAL_UART_CLEAR_IT(huart, UART_CLEAR_FEF); + + huart->ErrorCode |= HAL_UART_ERROR_FE; + /* Set the UART state ready to be able to start again the process */ + huart->State = HAL_UART_STATE_READY; + } + + /* UART noise error interrupt occured --------------------------------------*/ + if((__HAL_UART_GET_IT(huart, UART_IT_NE) != RESET) && (__HAL_UART_GET_IT_SOURCE(huart, UART_IT_ERR) != RESET)) + { + __HAL_UART_CLEAR_IT(huart, UART_CLEAR_NEF); + + huart->ErrorCode |= HAL_UART_ERROR_NE; + /* Set the UART state ready to be able to start again the process */ + huart->State = HAL_UART_STATE_READY; + } + + /* UART Over-Run interrupt occured -----------------------------------------*/ + if((__HAL_UART_GET_IT(huart, UART_IT_ORE) != RESET) && (__HAL_UART_GET_IT_SOURCE(huart, UART_IT_ERR) != RESET)) + { + __HAL_UART_CLEAR_IT(huart, UART_CLEAR_OREF); + + huart->ErrorCode |= HAL_UART_ERROR_ORE; + /* Set the UART state ready to be able to start again the process */ + huart->State = HAL_UART_STATE_READY; + } + + /* Call UART Error Call back function if need be --------------------------*/ + if(huart->ErrorCode != HAL_UART_ERROR_NONE) + { + HAL_UART_ErrorCallback(huart); + } + + /* UART Wake Up interrupt occured ------------------------------------------*/ + if((__HAL_UART_GET_IT(huart, UART_IT_WUF) != RESET) && (__HAL_UART_GET_IT_SOURCE(huart, UART_IT_WUF) != RESET)) + { + __HAL_UART_CLEAR_IT(huart, UART_CLEAR_WUF); + /* Set the UART state ready to be able to start again the process */ + huart->State = HAL_UART_STATE_READY; + HAL_UART_WakeupCallback(huart); + } + + /* UART in mode Receiver ---------------------------------------------------*/ + if((__HAL_UART_GET_IT(huart, UART_IT_RXNE) != RESET) && (__HAL_UART_GET_IT_SOURCE(huart, UART_IT_RXNE) != RESET)) + { + UART_Receive_IT(huart); + /* Clear RXNE interrupt flag */ + __HAL_UART_SEND_REQ(huart, UART_RXDATA_FLUSH_REQUEST); + } + + /* UART in mode Transmitter ------------------------------------------------*/ + if((__HAL_UART_GET_IT(huart, UART_IT_TC) != RESET) &&(__HAL_UART_GET_IT_SOURCE(huart, UART_IT_TC) != RESET)) + { + UART_Transmit_IT(huart); + } + + if(huart->ErrorCode != HAL_UART_ERROR_NONE) + { + HAL_UART_ErrorCallback(huart); + } +} + +/** + * @brief DMA UART transmit process complete callback + * @param hdma: DMA handle + * @retval None + */ +static void UART_DMATransmitCplt(DMA_HandleTypeDef *hdma) +{ + UART_HandleTypeDef* huart = ( UART_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + huart->TxXferCount = 0; + + /* Disable the DMA transfer for transmit request by setting the DMAT bit + in the UART CR3 register */ + huart->Instance->CR3 &= (uint32_t)~((uint32_t)USART_CR3_DMAT); + + /* Wait for UART TC Flag */ + if(UART_WaitOnFlagUntilTimeout(huart, UART_FLAG_TC, RESET, UART_TIMEOUT_VALUE) != HAL_OK) + { + /* Timeout Occured */ + huart->State = HAL_UART_STATE_TIMEOUT; + HAL_UART_ErrorCallback(huart); + } + else + { + /* No Timeout */ + /* Check if a receive process is ongoing or not */ + if(huart->State == HAL_UART_STATE_BUSY_TX_RX) + { + huart->State = HAL_UART_STATE_BUSY_RX; + } + else + { + huart->State = HAL_UART_STATE_READY; + } + HAL_UART_TxCpltCallback(huart); + } +} + +/** + * @brief DMA UART transmit process half complete callback + * @param hdma : DMA handle + * @retval None + */ +static void UART_DMATxHalfCplt(DMA_HandleTypeDef *hdma) +{ + UART_HandleTypeDef* huart = (UART_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent; + + HAL_UART_TxHalfCpltCallback(huart); +} + +/** + * @brief DMA UART receive process complete callback + * @param hdma: DMA handle + * @retval None + */ +static void UART_DMAReceiveCplt(DMA_HandleTypeDef *hdma) +{ + UART_HandleTypeDef* huart = ( UART_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + huart->RxXferCount = 0; + + /* Disable the DMA transfer for the receiver request by setting the DMAR bit + in the UART CR3 register */ + huart->Instance->CR3 &= (uint32_t)~((uint32_t)USART_CR3_DMAR); + + /* Check if a transmit Process is ongoing or not */ + if(huart->State == HAL_UART_STATE_BUSY_TX_RX) + { + huart->State = HAL_UART_STATE_BUSY_TX; + } + else + { + huart->State = HAL_UART_STATE_READY; + } + HAL_UART_RxCpltCallback(huart); +} + +/** + * @brief DMA UART receive process half complete callback + * @param hdma : DMA handle + * @retval None + */ +static void UART_DMARxHalfCplt(DMA_HandleTypeDef *hdma) +{ + UART_HandleTypeDef* huart = (UART_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent; + + HAL_UART_RxHalfCpltCallback(huart); +} + +/** + * @brief DMA UART communication error callback + * @param hdma: DMA handle + * @retval None + */ +static void UART_DMAError(DMA_HandleTypeDef *hdma) +{ + UART_HandleTypeDef* huart = ( UART_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + huart->RxXferCount = 0; + huart->TxXferCount = 0; + huart->State= HAL_UART_STATE_READY; + huart->ErrorCode |= HAL_UART_ERROR_DMA; + HAL_UART_ErrorCallback(huart); +} + +/** + * @brief Tx Transfer completed callbacks + * @param huart: uart handle + * @retval None + */ + __weak void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_UART_TxCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Tx Half Transfer completed callbacks. + * @param huart: UART handle + * @retval None + */ + __weak void HAL_UART_TxHalfCpltCallback(UART_HandleTypeDef *huart) +{ + /* NOTE: This function Should not be modified, when the callback is needed, + the HAL_UART_TxCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Rx Transfer completed callbacks + * @param huart: uart handle + * @retval None + */ +__weak void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart) +{ + /* NOTE : This function Should not be modified, when the callback is needed, + the HAL_UART_TxCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Rx Half Transfer completed callbacks. + * @param huart: UART handle + * @retval None + */ +__weak void HAL_UART_RxHalfCpltCallback(UART_HandleTypeDef *huart) +{ + /* NOTE: This function Should not be modified, when the callback is needed, + the HAL_UART_TxCpltCallback could be implemented in the user file + */ +} + +/** + * @brief UART error callbacks + * @param huart: uart handle + * @retval None + */ + __weak void HAL_UART_ErrorCallback(UART_HandleTypeDef *huart) +{ + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_UART_ErrorCallback can be implemented in the user file + */ +} + +/** + * @brief UART wakeup from Stop mode callback + * @param huart: uart handle + * @retval None + */ + __weak void HAL_UART_WakeupCallback(UART_HandleTypeDef *huart) +{ + /* NOTE : This function should not be modified, when the callback is needed, + the HAL_UART_WakeupCallback can be implemented in the user file + */ +} + +/** + * @brief Send an amount of data in interrupt mode + * Function called under interruption only, once + * interruptions have been enabled by HAL_UART_Transmit_IT() + * @param huart: UART handle + * @retval HAL status + */ +static HAL_StatusTypeDef UART_Transmit_IT(UART_HandleTypeDef *huart) +{ + uint16_t* tmp; + + if ((huart->State == HAL_UART_STATE_BUSY_TX) || (huart->State == HAL_UART_STATE_BUSY_TX_RX)) + { + __HAL_LOCK(huart); + + if(huart->TxXferCount == 0) + { + /* Disable the UART Transmit Complete Interrupt */ + __HAL_UART_DISABLE_IT(huart, UART_IT_TC); + + /* Check if a receive Process is ongoing or not */ + if(huart->State == HAL_UART_STATE_BUSY_TX_RX) + { + huart->State = HAL_UART_STATE_BUSY_RX; + } + else + { + /* Disable the UART Parity Error Interrupt */ + __HAL_UART_DISABLE_IT(huart, UART_IT_PE); + + /* Disable the UART Error Interrupt: (Frame error, noise error, overrun error) */ + __HAL_UART_DISABLE_IT(huart, UART_IT_ERR); + + huart->State = HAL_UART_STATE_READY; + } + /* Call the Process Unlocked before calling the Tx call back API to give the possibiity to + start again the Transmission under the Tx call back API */ + __HAL_UNLOCK(huart); + + HAL_UART_TxCpltCallback(huart); + + return HAL_OK; + } + else + { + if ((huart->Init.WordLength == UART_WORDLENGTH_9B) && (huart->Init.Parity == UART_PARITY_NONE)) + { + tmp = (uint16_t*) huart->pTxBuffPtr; + huart->Instance->TDR = (*tmp & (uint16_t)0x01FF); + huart->pTxBuffPtr += 2; + } + else + { + huart->Instance->TDR = (uint8_t)(*huart->pTxBuffPtr++ & (uint8_t)0xFF); + } + + huart->TxXferCount--; + + /* Process Unlocked */ + __HAL_UNLOCK(huart); + + return HAL_OK; + } + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive an amount of data in interrupt mode + * Function called under interruption only, once + * interruptions have been enabled by HAL_UART_Receive_IT() + * @param huart: UART handle + * @retval HAL status + */ +static HAL_StatusTypeDef UART_Receive_IT(UART_HandleTypeDef *huart) +{ + uint16_t* tmp; + uint16_t uhMask = huart->Mask; + + if((huart->State == HAL_UART_STATE_BUSY_RX) || (huart->State == HAL_UART_STATE_BUSY_TX_RX)) + { + if ((huart->Init.WordLength == UART_WORDLENGTH_9B) && (huart->Init.Parity == UART_PARITY_NONE)) + { + tmp = (uint16_t*) huart->pRxBuffPtr ; + *tmp = (uint16_t)(huart->Instance->RDR & uhMask); + huart->pRxBuffPtr +=2; + } + else + { + *huart->pRxBuffPtr++ = (uint8_t)(huart->Instance->RDR & (uint8_t)uhMask); + } + + if(--huart->RxXferCount == 0) + { + while(HAL_IS_BIT_SET(huart->Instance->ISR, UART_FLAG_RXNE)) + { + } + __HAL_UART_DISABLE_IT(huart, UART_IT_RXNE); + + /* Check if a transmit Process is ongoing or not */ + if(huart->State == HAL_UART_STATE_BUSY_TX_RX) + { + huart->State = HAL_UART_STATE_BUSY_TX; + } + else + { + /* Disable the UART Parity Error Interrupt */ + __HAL_UART_DISABLE_IT(huart, UART_IT_PE); + + /* Disable the UART Error Interrupt: (Frame error, noise error, overrun error) */ + __HAL_UART_DISABLE_IT(huart, UART_IT_ERR); + + huart->State = HAL_UART_STATE_READY; + } + HAL_UART_RxCpltCallback(huart); + return HAL_OK; + } + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Configure the UART peripheral + * @param huart: uart handle + * @retval None + */ +void UART_SetConfig(UART_HandleTypeDef *huart) +{ + uint32_t tmpreg = 0x00000000; + uint32_t clocksource = 0x00000000; + uint16_t brrtemp = 0x0000; + uint16_t usartdiv = 0x0000; + + /* Check the parameters */ + assert_param(IS_UART_BAUDRATE(huart->Init.BaudRate)); + assert_param(IS_UART_WORD_LENGTH(huart->Init.WordLength)); + assert_param(IS_UART_STOPBITS(huart->Init.StopBits)); + assert_param(IS_UART_PARITY(huart->Init.Parity)); + assert_param(IS_UART_MODE(huart->Init.Mode)); + assert_param(IS_UART_HARDWARE_FLOW_CONTROL(huart->Init.HwFlowCtl)); + assert_param(IS_UART_ONEBIT_SAMPLING(huart->Init.OneBitSampling)); + + /*-------------------------- USART CR1 Configuration -----------------------*/ + /* Clear M, PCE, PS, TE, RE and OVER8 bits and configure + * the UART Word Length, Parity, Mode and oversampling: + * set the M bits according to huart->Init.WordLength value + * set PCE and PS bits according to huart->Init.Parity value + * set TE and RE bits according to huart->Init.Mode value + * set OVER8 bit according to huart->Init.OverSampling value */ + tmpreg = (uint32_t)huart->Init.WordLength | huart->Init.Parity | huart->Init.Mode | huart->Init.OverSampling ; + MODIFY_REG(huart->Instance->CR1, UART_CR1_FIELDS, tmpreg); + + /*-------------------------- USART CR2 Configuration -----------------------*/ + /* Configure the UART Stop Bits: Set STOP[13:12] bits according + * to huart->Init.StopBits value */ + MODIFY_REG(huart->Instance->CR2, USART_CR2_STOP, huart->Init.StopBits); + + /*-------------------------- USART CR3 Configuration -----------------------*/ + /* Configure + * - UART HardWare Flow Control: set CTSE and RTSE bits according + * to huart->Init.HwFlowCtl value + * - one-bit sampling method versus three samples' majority rule according + * to huart->Init.OneBitSampling */ + tmpreg = (uint32_t)huart->Init.HwFlowCtl | huart->Init.OneBitSampling ; + MODIFY_REG(huart->Instance->CR3, (USART_CR3_RTSE | USART_CR3_CTSE | USART_CR3_ONEBIT), tmpreg); + + /*-------------------------- USART BRR Configuration -----------------------*/ + __HAL_UART_GETCLOCKSOURCE(huart, clocksource); + + /* Check LPUART instace */ + if(huart->Instance == LPUART1) + { + switch (clocksource) + { + case UART_CLOCKSOURCE_PCLK1: + huart->Instance->BRR = (uint32_t)(__DIV_LPUART(HAL_RCC_GetPCLK1Freq(), huart->Init.BaudRate)); + break; + case UART_CLOCKSOURCE_HSI: + huart->Instance->BRR = (uint32_t)(__DIV_LPUART(HSI_VALUE, huart->Init.BaudRate)); + break; + case UART_CLOCKSOURCE_SYSCLK: + huart->Instance->BRR = (uint32_t)(__DIV_LPUART(HAL_RCC_GetSysClockFreq(), huart->Init.BaudRate)); + break; + case UART_CLOCKSOURCE_LSE: + huart->Instance->BRR = (uint32_t)(__DIV_LPUART(LSE_VALUE, huart->Init.BaudRate)); + break; + default: + break; + } + } + /* Check the UART Over Sampling 8 to set Baud Rate Register */ + else if (huart->Init.OverSampling == UART_OVERSAMPLING_8) + { + switch (clocksource) + { + case UART_CLOCKSOURCE_PCLK1: + usartdiv = (uint32_t)(__DIV_SAMPLING8(HAL_RCC_GetPCLK1Freq(), huart->Init.BaudRate)); + break; + case UART_CLOCKSOURCE_PCLK2: + usartdiv = (uint32_t)(__DIV_SAMPLING8(HAL_RCC_GetPCLK2Freq(), huart->Init.BaudRate)); + break; + case UART_CLOCKSOURCE_HSI: + usartdiv = (uint32_t)(__DIV_SAMPLING8(HSI_VALUE, huart->Init.BaudRate)); + break; + case UART_CLOCKSOURCE_SYSCLK: + huart->Instance->BRR = (uint32_t)(__DIV_SAMPLING8(HAL_RCC_GetSysClockFreq(), huart->Init.BaudRate)); + break; + case UART_CLOCKSOURCE_LSE: + usartdiv = (uint32_t)(__DIV_SAMPLING8(LSE_VALUE, huart->Init.BaudRate)); + break; + default: + break; + } + + brrtemp = usartdiv & 0xFFF0; + brrtemp |= (uint16_t)((uint16_t)(usartdiv & (uint16_t)0x000F) >> (uint16_t)1); + huart->Instance->BRR = brrtemp; + } + else + { + switch (clocksource) + { + case UART_CLOCKSOURCE_PCLK1: + huart->Instance->BRR = (uint32_t)(__DIV_SAMPLING16(HAL_RCC_GetPCLK1Freq(), huart->Init.BaudRate)); + break; + case UART_CLOCKSOURCE_PCLK2: + huart->Instance->BRR = (uint32_t)(__DIV_SAMPLING16(HAL_RCC_GetPCLK2Freq(), huart->Init.BaudRate)); + break; + case UART_CLOCKSOURCE_HSI: + huart->Instance->BRR = (uint32_t)(__DIV_SAMPLING16(HSI_VALUE, huart->Init.BaudRate)); + break; + case UART_CLOCKSOURCE_SYSCLK: + huart->Instance->BRR = (uint32_t)(__DIV_SAMPLING16(HAL_RCC_GetSysClockFreq(), huart->Init.BaudRate)); + break; + case UART_CLOCKSOURCE_LSE: + huart->Instance->BRR = (uint32_t)(__DIV_SAMPLING16(LSE_VALUE, huart->Init.BaudRate)); + break; + default: + break; + } + } +} + +/** + * @brief Check the UART Idle State + * @param huart: uart handle + * @retval HAL status + */ +HAL_StatusTypeDef UART_CheckIdleState(UART_HandleTypeDef *huart) +{ + /* Check if the Transmitter is enabled */ + if((huart->Instance->CR1 & USART_CR1_TE) == USART_CR1_TE) + { + /* Wait until TEACK flag is set */ + if(UART_WaitOnFlagUntilTimeout(huart, USART_ISR_TEACK, RESET, UART_TIMEOUT_VALUE) != HAL_OK) + { + return HAL_TIMEOUT; + } + } + /* Check if the Receiver is enabled */ + if((huart->Instance->CR1 & USART_CR1_RE) == USART_CR1_RE) + { + /* Wait until REACK flag is set */ + if(UART_WaitOnFlagUntilTimeout(huart, USART_ISR_REACK, RESET, UART_TIMEOUT_VALUE) != HAL_OK) + { + return HAL_TIMEOUT; + } + } + + /* Process Unlocked */ + __HAL_UNLOCK(huart); + + /* Initialize the UART state*/ + huart->ErrorCode = HAL_UART_ERROR_NONE; + huart->State= HAL_UART_STATE_READY; + + return HAL_OK; +} + +/** + * @brief Configure the UART peripheral advanced feautures + * @param huart: uart handle + * @retval None + */ +void UART_AdvFeatureConfig(UART_HandleTypeDef *huart) +{ + /* Check whether the set of advanced features to configure is properly set */ + assert_param(IS_UART_ADVFEATURE_INIT(huart->AdvancedInit.AdvFeatureInit)); + + /* if required, configure TX pin active level inversion */ + if(HAL_IS_BIT_SET(huart->AdvancedInit.AdvFeatureInit, UART_ADVFEATURE_TXINVERT_INIT)) + { + assert_param(IS_UART_ADVFEATURE_TXINV(huart->AdvancedInit.TxPinLevelInvert)); + MODIFY_REG(huart->Instance->CR2, USART_CR2_TXINV, huart->AdvancedInit.TxPinLevelInvert); + } + + /* if required, configure RX pin active level inversion */ + if(HAL_IS_BIT_SET(huart->AdvancedInit.AdvFeatureInit, UART_ADVFEATURE_RXINVERT_INIT)) + { + assert_param(IS_UART_ADVFEATURE_RXINV(huart->AdvancedInit.RxPinLevelInvert)); + MODIFY_REG(huart->Instance->CR2, USART_CR2_RXINV, huart->AdvancedInit.RxPinLevelInvert); + } + + /* if required, configure data inversion */ + if(HAL_IS_BIT_SET(huart->AdvancedInit.AdvFeatureInit, UART_ADVFEATURE_DATAINVERT_INIT)) + { + assert_param(IS_UART_ADVFEATURE_DATAINV(huart->AdvancedInit.DataInvert)); + MODIFY_REG(huart->Instance->CR2, USART_CR2_DATAINV, huart->AdvancedInit.DataInvert); + } + + /* if required, configure RX/TX pins swap */ + if(HAL_IS_BIT_SET(huart->AdvancedInit.AdvFeatureInit, UART_ADVFEATURE_SWAP_INIT)) + { + assert_param(IS_UART_ADVFEATURE_SWAP(huart->AdvancedInit.Swap)); + MODIFY_REG(huart->Instance->CR2, USART_CR2_SWAP, huart->AdvancedInit.Swap); + } + + /* if required, configure RX overrun detection disabling */ + if(HAL_IS_BIT_SET(huart->AdvancedInit.AdvFeatureInit, UART_ADVFEATURE_RXOVERRUNDISABLE_INIT)) + { + assert_param(IS_UART_OVERRUN(huart->AdvancedInit.OverrunDisable)); + MODIFY_REG(huart->Instance->CR3, USART_CR3_OVRDIS, huart->AdvancedInit.OverrunDisable); + } + + /* if required, configure DMA disabling on reception error */ + if(HAL_IS_BIT_SET(huart->AdvancedInit.AdvFeatureInit, UART_ADVFEATURE_DMADISABLEONERROR_INIT)) + { + assert_param(IS_UART_ADVFEATURE_DMAONRXERROR(huart->AdvancedInit.DMADisableonRxError)); + MODIFY_REG(huart->Instance->CR3, USART_CR3_DDRE, huart->AdvancedInit.DMADisableonRxError); + } + + /* if required, configure auto Baud rate detection scheme */ + if(HAL_IS_BIT_SET(huart->AdvancedInit.AdvFeatureInit, UART_ADVFEATURE_AUTOBAUDRATE_INIT)) + { + assert_param(IS_UART_ADVFEATURE_AUTOBAUDRATE(huart->AdvancedInit.AutoBaudRateEnable)); + MODIFY_REG(huart->Instance->CR2, USART_CR2_ABREN, huart->AdvancedInit.AutoBaudRateEnable); + /* set auto Baudrate detection parameters if detection is enabled */ + if(huart->AdvancedInit.AutoBaudRateEnable == UART_ADVFEATURE_AUTOBAUDRATE_ENABLE) + { + assert_param(IS_UART_ADVFEATURE_AUTOBAUDRATEMODE(huart->AdvancedInit.AutoBaudRateMode)); + MODIFY_REG(huart->Instance->CR2, USART_CR2_ABRMODE, huart->AdvancedInit.AutoBaudRateMode); + } + } + + /* if required, configure MSB first on communication line */ + if(HAL_IS_BIT_SET(huart->AdvancedInit.AdvFeatureInit, UART_ADVFEATURE_MSBFIRST_INIT)) + { + assert_param(IS_UART_ADVFEATURE_MSBFIRST(huart->AdvancedInit.MSBFirst)); + MODIFY_REG(huart->Instance->CR2, USART_CR2_MSBFIRST, huart->AdvancedInit.MSBFirst); + } +} + +/** + * @brief This function handles UART Communication Timeout. + * @param huart: UART handle + * @param Flag: specifies the UART flag to check. + * @param Status: The new Flag status (SET or RESET). + * @param Timeout: Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef UART_WaitOnFlagUntilTimeout(UART_HandleTypeDef *huart, uint32_t Flag, FlagStatus Status, uint32_t Timeout) +{ + uint32_t tickstart = 0x00; + tickstart = HAL_GetTick(); + + /* Wait until flag is set */ + if(Status == RESET) + { + while(__HAL_UART_GET_FLAG(huart, Flag) == RESET) + { + /* Check for the Timeout */ + if(Timeout != HAL_MAX_DELAY) + { + if((HAL_GetTick() - tickstart ) > Timeout) + { + /* Disable TXE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts for the interrupt process */ + __HAL_UART_DISABLE_IT(huart, UART_IT_TXE); + __HAL_UART_DISABLE_IT(huart, UART_IT_RXNE); + __HAL_UART_DISABLE_IT(huart, UART_IT_PE); + __HAL_UART_DISABLE_IT(huart, UART_IT_ERR); + + huart->State= HAL_UART_STATE_TIMEOUT; + + /* Process Unlocked */ + __HAL_UNLOCK(huart); + + return HAL_TIMEOUT; + } + } + } + } + else + { + while(__HAL_UART_GET_FLAG(huart, Flag) != RESET) + { + /* Check for the Timeout */ + if(Timeout != HAL_MAX_DELAY) + { + if((HAL_GetTick() - tickstart ) > Timeout) + { + /* Disable TXE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts for the interrupt process */ + __HAL_UART_DISABLE_IT(huart, UART_IT_TXE); + __HAL_UART_DISABLE_IT(huart, UART_IT_RXNE); + __HAL_UART_DISABLE_IT(huart, UART_IT_PE); + __HAL_UART_DISABLE_IT(huart, UART_IT_ERR); + + huart->State= HAL_UART_STATE_TIMEOUT; + + /* Process Unlocked */ + __HAL_UNLOCK(huart); + + return HAL_TIMEOUT; + } + } + } + } + return HAL_OK; +} + +/** + * @} + */ + +/** @defgroup HAL_UART_Group3 Peripheral Control methods + * @brief UART control functions + * +@verbatim + =============================================================================== + ##### Peripheral Control methods ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to control the UART. + (+) HAL_MultiProcessor_EnableMuteMode() API enables mute mode + (+) HAL_MultiProcessor_DisableMuteMode() API disables mute mode + (+) HAL_MultiProcessor_EnterMuteMode() API enters mute mode + (+) HAL_HalfDuplex_EnableTransmitter() API enables the transmitter + (+) HAL_HalfDuplex_EnableReceiver() API enables the receiver + (+) HAL_UART_GetState() API is helpful to check in run-time the state of the UART peripheral + (+) HAL_UART_GetError()API is helpful to check in run-time the error state of the UART peripheral +@endverbatim + * @{ + */ + +/** + * @brief Enable UART in mute mode (doesn't mean UART enters mute mode; + * to enter mute mode, HAL_MultiProcessor_EnterMuteMode() API must be called) + * @param huart: uart handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_MultiProcessor_EnableMuteMode(UART_HandleTypeDef *huart) +{ + /* Process Locked */ + __HAL_LOCK(huart); + + huart->State = HAL_UART_STATE_BUSY; + + /* Enable USART mute mode by setting the MME bit in the CR1 register */ + huart->Instance->CR1 |= USART_CR1_MME; + + huart->State = HAL_UART_STATE_READY; + + return (UART_CheckIdleState(huart)); +} + +/** + * @brief Disable UART mute mode (doesn't mean it actually wakes up the software, + * as it may not have been in mute mode at this very moment). + * @param huart: uart handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_MultiProcessor_DisableMuteMode(UART_HandleTypeDef *huart) +{ + /* Process Locked */ + __HAL_LOCK(huart); + + huart->State = HAL_UART_STATE_BUSY; + + /* Disable USART mute mode by clearing the MME bit in the CR1 register */ + huart->Instance->CR1 &= ~(USART_CR1_MME); + + huart->State = HAL_UART_STATE_READY; + + return (UART_CheckIdleState(huart)); +} + +/** + * @brief Enter UART mute mode (means UART actually enters mute mode). + * To exit from mute mode, HAL_MultiProcessor_DisableMuteMode() API must be called. + * @param huart: uart handle + * @retval HAL status + */ +void HAL_MultiProcessor_EnterMuteMode(UART_HandleTypeDef *huart) +{ + __HAL_UART_SEND_REQ(huart, UART_MUTE_MODE_REQUEST); +} + +/** + * @brief Enables the UART transmitter and disables the UART receiver. + * @param huart: UART handle + * @retval HAL status + * @retval None + */ +HAL_StatusTypeDef HAL_HalfDuplex_EnableTransmitter(UART_HandleTypeDef *huart) +{ + /* Process Locked */ + __HAL_LOCK(huart); + huart->State = HAL_UART_STATE_BUSY; + + /* Clear TE and RE bits */ + CLEAR_BIT(huart->Instance->CR1, (USART_CR1_TE | USART_CR1_RE)); + /* Enable the USART's transmit interface by setting the TE bit in the USART CR1 register */ + SET_BIT(huart->Instance->CR1, USART_CR1_TE); + + huart->State = HAL_UART_STATE_READY; + /* Process Unlocked */ + __HAL_UNLOCK(huart); + + return HAL_OK; +} + +/** + * @brief Enables the UART receiver and disables the UART transmitter. + * @param huart: UART handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_HalfDuplex_EnableReceiver(UART_HandleTypeDef *huart) +{ + /* Process Locked */ + __HAL_LOCK(huart); + huart->State = HAL_UART_STATE_BUSY; + + /* Clear TE and RE bits */ + CLEAR_BIT(huart->Instance->CR1, (USART_CR1_TE | USART_CR1_RE)); + /* Enable the USART's receive interface by setting the RE bit in the USART CR1 register */ + SET_BIT(huart->Instance->CR1, USART_CR1_RE); + + huart->State = HAL_UART_STATE_READY; + /* Process Unlocked */ + __HAL_UNLOCK(huart); + + return HAL_OK; +} + +/** + * @brief Transmits break characters. + * @param huart: pointer to a UART_HandleTypeDef structure that contains + * the configuration information for the specified UART module. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_LIN_SendBreak(UART_HandleTypeDef *huart) +{ + /* Check the parameters */ + assert_param(IS_UART_INSTANCE(huart->Instance)); + + /* Process Locked */ + __HAL_LOCK(huart); + + huart->State = HAL_UART_STATE_BUSY; + + /* Send break characters */ + huart->Instance->RQR |= USART_RQR_SBKRQ; + + huart->State = HAL_UART_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(huart); + + return HAL_OK; +} + +/** + * @brief return the UART state + * @param huart: uart handle + * @retval HAL state + */ +HAL_UART_StateTypeDef HAL_UART_GetState(UART_HandleTypeDef *huart) +{ + return huart->State; +} + +/** +* @brief Return the UART error code +* @param huart : pointer to a UART_HandleTypeDef structure that contains + * the configuration information for the specified UART. +* @retval UART Error Code +*/ +uint32_t HAL_UART_GetError(UART_HandleTypeDef *huart) +{ + return huart->ErrorCode; +} + +/** + * @} + */ + +/** + * @} + */ + +#endif /* HAL_UART_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_uart.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_uart.h new file mode 100644 index 0000000000..c6a7025c66 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_uart.h @@ -0,0 +1,978 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_uart.h + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief Header file of UART HAL module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32L0xx_HAL_UART_H +#define __STM32L0xx_HAL_UART_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal_def.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @addtogroup UART + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ + +/** + * @brief UART Init Structure definition + */ +typedef struct +{ + uint32_t BaudRate; /*!< This member configures the UART communication baud rate. + The baud rate register is computed using the following formula: + - If oversampling is 16 or in LIN mode, + Baud Rate Register = ((PCLKx) / ((huart->Init.BaudRate))) + - If oversampling is 8, + Baud Rate Register[15:4] = ((2 * PCLKx) / ((huart->Init.BaudRate)))[15:4] + Baud Rate Register[3] = 0 + Baud Rate Register[2:0] = (((2 * PCLKx) / ((huart->Init.BaudRate)))[3:0]) >> 1 */ + + uint32_t WordLength; /*!< Specifies the number of data bits transmitted or received in a frame. + This parameter can be a value of @ref UART_Word_Length */ + + uint32_t StopBits; /*!< Specifies the number of stop bits transmitted. + This parameter can be a value of @ref UART_Stop_Bits */ + + uint32_t Parity; /*!< Specifies the parity mode. + This parameter can be a value of @ref UART_Parity + @note When parity is enabled, the computed parity is inserted + at the MSB position of the transmitted data (9th bit when + the word length is set to 9 data bits; 8th bit when the + word length is set to 8 data bits). */ + + uint32_t Mode; /*!< Specifies wether the Receive or Transmit mode is enabled or disabled. + This parameter can be a value of @ref UART_Mode */ + + uint32_t HwFlowCtl; /*!< Specifies wether the hardware flow control mode is enabled + or disabled. + This parameter can be a value of @ref UART_Hardware_Flow_Control */ + + uint32_t OverSampling; /*!< Specifies wether the Over sampling 8 is enabled or disabled, to achieve higher speed (up to fPCLK/8). + This parameter can be a value of @ref UART_Over_Sampling */ + + uint32_t OneBitSampling; /*!< Specifies wether a single sample or three samples' majority vote is selected. + Selecting the single sample method increases the receiver tolerance to clock + deviations. This parameter can be a value of @ref UART_OneBit_Sampling. */ +}UART_InitTypeDef; + +/** + * @brief UART Advanced Features initalization structure definition + */ +typedef struct +{ + uint32_t AdvFeatureInit; /*!< Specifies which advanced UART features is initialized. Several + Advanced Features may be initialized at the same time . + This parameter can be a value of @ref UART_Advanced_Features_Initialization_Type */ + + uint32_t TxPinLevelInvert; /*!< Specifies whether the TX pin active level is inverted. + This parameter can be a value of @ref UART_Tx_Inv */ + + uint32_t RxPinLevelInvert; /*!< Specifies whether the RX pin active level is inverted. + This parameter can be a value of @ref UART_Rx_Inv */ + + uint32_t DataInvert; /*!< Specifies whether data are inverted (positive/direct logic + vs negative/inverted logic). + This parameter can be a value of @ref UART_Data_Inv */ + + uint32_t Swap; /*!< Specifies whether TX and RX pins are swapped. + This parameter can be a value of @ref UART_Rx_Tx_Swap */ + + uint32_t OverrunDisable; /*!< Specifies whether the reception overrun detection is disabled. + This parameter can be a value of @ref UART_Overrun_Disable */ + + uint32_t DMADisableonRxError; /*!< Specifies whether the DMA is disabled in case of reception error. + This parameter can be a value of @ref UART_DMA_Disable_on_Rx_Error */ + + uint32_t AutoBaudRateEnable; /*!< Specifies whether auto Baud rate detection is enabled. + This parameter can be a value of @ref UART_AutoBaudRate_Enable */ + + uint32_t AutoBaudRateMode; /*!< If auto Baud rate detection is enabled, specifies how the rate + detection is carried out. + This parameter can be a value of @ref UART_AutoBaud_Rate_Mode */ + + uint32_t MSBFirst; /*!< Specifies whether MSB is sent first on UART line. + This parameter can be a value of @ref UART_MSB_First */ +} UART_AdvFeatureInitTypeDef; + +/** + * @brief HAL UART State structures definition + */ +typedef enum +{ + HAL_UART_STATE_RESET = 0x00, /*!< Peripheral Reset state */ + HAL_UART_STATE_READY = 0x01, /*!< Peripheral Initialized and ready for use */ + HAL_UART_STATE_BUSY = 0x02, /*!< an internal process is ongoing */ + HAL_UART_STATE_BUSY_TX = 0x12, /*!< Data Transmission process is ongoing */ + HAL_UART_STATE_BUSY_RX = 0x22, /*!< Data Reception process is ongoing */ + HAL_UART_STATE_BUSY_TX_RX = 0x32, /*!< Data Transmission and Reception process is ongoing */ + HAL_UART_STATE_TIMEOUT = 0x03, /*!< Timeout state */ + HAL_UART_STATE_ERROR = 0x04 /*!< Error */ +}HAL_UART_StateTypeDef; + +/** + * @brief HAL UART Error Code structure definition + */ +typedef enum +{ + HAL_UART_ERROR_NONE = 0x00, /*!< No error */ + HAL_UART_ERROR_PE = 0x01, /*!< Parity error */ + HAL_UART_ERROR_NE = 0x02, /*!< Noise error */ + HAL_UART_ERROR_FE = 0x04, /*!< frame error */ + HAL_UART_ERROR_ORE = 0x08, /*!< Overrun error */ + HAL_UART_ERROR_DMA = 0x10 /*!< DMA transfer error */ +}HAL_UART_ErrorTypeDef; + +/** + * @brief UART clock sources definition + */ +typedef enum +{ + UART_CLOCKSOURCE_PCLK1 = 0x00, /*!< PCLK1 clock source */ + UART_CLOCKSOURCE_PCLK2 = 0x01, /*!< PCLK2 clock source */ + UART_CLOCKSOURCE_HSI = 0x02, /*!< HSI clock source */ + UART_CLOCKSOURCE_SYSCLK = 0x04, /*!< SYSCLK clock source */ + UART_CLOCKSOURCE_LSE = 0x08 /*!< LSE clock source */ +}UART_ClockSourceTypeDef; + +/** + * @brief UART handle Structure definition + */ +typedef struct +{ + USART_TypeDef *Instance; /* UART registers base address */ + + UART_InitTypeDef Init; /* UART communication parameters */ + + UART_AdvFeatureInitTypeDef AdvancedInit; /* UART Advanced Features initialization parameters */ + + uint8_t *pTxBuffPtr; /* Pointer to UART Tx transfer Buffer */ + + uint16_t TxXferSize; /* UART Tx Transfer size */ + + uint16_t TxXferCount; /* UART Tx Transfer Counter */ + + uint8_t *pRxBuffPtr; /* Pointer to UART Rx transfer Buffer */ + + uint16_t RxXferSize; /* UART Rx Transfer size */ + + uint16_t RxXferCount; /* UART Rx Transfer Counter */ + + uint16_t Mask; /* UART Rx RDR register mask */ + + DMA_HandleTypeDef *hdmatx; /* UART Tx DMA Handle parameters */ + + DMA_HandleTypeDef *hdmarx; /* UART Rx DMA Handle parameters */ + + HAL_LockTypeDef Lock; /* Locking object */ + + __IO HAL_UART_StateTypeDef State; /* UART communication state */ + + __IO HAL_UART_ErrorTypeDef ErrorCode; /* UART Error code */ + +}UART_HandleTypeDef; + + +/* Exported constants --------------------------------------------------------*/ +/** @defgroup UART_Exported_Constants + * @{ + */ + +/** @defgroup UART_Stop_Bits UART Number of Stop Bits + * @{ + */ +#define UART_STOPBITS_1 ((uint32_t)0x0000) +#define UART_STOPBITS_2 ((uint32_t)USART_CR2_STOP_1) +#define IS_UART_STOPBITS(STOPBITS) (((STOPBITS) == UART_STOPBITS_1) || \ + ((STOPBITS) == UART_STOPBITS_2)) +/** + * @} + */ + +/** @defgroup UART_Parity UART Parity + * @{ + */ +#define UART_PARITY_NONE ((uint32_t)0x0000) +#define UART_PARITY_EVEN ((uint32_t)USART_CR1_PCE) +#define UART_PARITY_ODD ((uint32_t)(USART_CR1_PCE | USART_CR1_PS)) +#define IS_UART_PARITY(PARITY) (((PARITY) == UART_PARITY_NONE) || \ + ((PARITY) == UART_PARITY_EVEN) || \ + ((PARITY) == UART_PARITY_ODD)) +/** + * @} + */ + +/** @defgroup UART_Hardware_Flow_Control UART Hardware Flow Control + * @{ + */ +#define UART_HWCONTROL_NONE ((uint32_t)0x0000) +#define UART_HWCONTROL_RTS ((uint32_t)USART_CR3_RTSE) +#define UART_HWCONTROL_CTS ((uint32_t)USART_CR3_CTSE) +#define UART_HWCONTROL_RTS_CTS ((uint32_t)(USART_CR3_RTSE | USART_CR3_CTSE)) +#define IS_UART_HARDWARE_FLOW_CONTROL(CONTROL)\ + (((CONTROL) == UART_HWCONTROL_NONE) || \ + ((CONTROL) == UART_HWCONTROL_RTS) || \ + ((CONTROL) == UART_HWCONTROL_CTS) || \ + ((CONTROL) == UART_HWCONTROL_RTS_CTS)) +/** + * @} + */ + +/** @defgroup UART_Mode UART Transfer Mode + * @{ + */ +#define UART_MODE_RX ((uint32_t)USART_CR1_RE) +#define UART_MODE_TX ((uint32_t)USART_CR1_TE) +#define UART_MODE_TX_RX ((uint32_t)(USART_CR1_TE |USART_CR1_RE)) +#define IS_UART_MODE(MODE) ((((MODE) & (~((uint32_t)(UART_MODE_TX_RX)))) == (uint32_t)0x00) && ((MODE) != (uint32_t)0x00)) +/** + * @} + */ + + /** @defgroup UART_State UART State + * @{ + */ +#define UART_STATE_DISABLE ((uint32_t)0x0000) +#define UART_STATE_ENABLE ((uint32_t)USART_CR1_UE) +#define IS_UART_STATE(STATE) (((STATE) == UART_STATE_DISABLE) || \ + ((STATE) == UART_STATE_ENABLE)) +/** + * @} + */ + +/** @defgroup UART_Over_Sampling UART Over Sampling + * @{ + */ +#define UART_OVERSAMPLING_16 ((uint32_t)0x0000) +#define UART_OVERSAMPLING_8 ((uint32_t)USART_CR1_OVER8) +#define IS_UART_OVERSAMPLING(SAMPLING) (((SAMPLING) == UART_OVERSAMPLING_16) || \ + ((SAMPLING) == UART_OVERSAMPLING_8)) +/** + * @} + */ + +/** @defgroup UART_OneBit_Sampling UART One Bit Sampling Method + * @{ + */ +#define UART_ONEBIT_SAMPLING_DISABLED ((uint32_t)0x0000) +#define UART_ONEBIT_SAMPLING_ENABLED ((uint32_t)USART_CR3_ONEBIT) +#define IS_UART_ONEBIT_SAMPLING(ONEBIT) (((ONEBIT) == UART_ONEBIT_SAMPLING_DISABLED) || \ + ((ONEBIT) == UART_ONEBIT_SAMPLING_ENABLED)) +/** + * @} + */ + + +/** @defgroup UART_Receiver_TimeOut UART Receiver TimeOut + * @{ + */ +#define UART_RECEIVER_TIMEOUT_DISABLE ((uint32_t)0x00000000) +#define UART_RECEIVER_TIMEOUT_ENABLE ((uint32_t)USART_CR2_RTOEN) +#define IS_UART_RECEIVER_TIMEOUT(TIMEOUT) (((TIMEOUT) == UART_RECEIVER_TIMEOUT_DISABLE) || \ + ((TIMEOUT) == UART_RECEIVER_TIMEOUT_ENABLE)) +/** + * @} + */ + +/** @defgroup UART_LIN UART Local Interconnection Network mode + * @{ + */ +#define UART_LIN_DISABLE ((uint32_t)0x00000000) +#define UART_LIN_ENABLE ((uint32_t)USART_CR2_LINEN) +#define IS_UART_LIN(LIN) (((LIN) == UART_LIN_DISABLE) || \ + ((LIN) == UART_LIN_ENABLE)) +/** + * @} + */ + +/** @defgroup UART_LIN_Break_Detection UART LIN Break Detection + * @{ + */ +#define UART_LINBREAKDETECTLENGTH_10B ((uint32_t)0x00000000) +#define UART_LINBREAKDETECTLENGTH_11B ((uint32_t)USART_CR2_LBDL) +#define IS_UART_LIN_BREAK_DETECT_LENGTH(LENGTH) (((LENGTH) == UART_LINBREAKDETECTLENGTH_10B) || \ + ((LENGTH) == UART_LINBREAKDETECTLENGTH_11B)) +/** + * @} + */ + + + +/** @defgroup UART_One_Bit UART One Bit sampling + * @{ + */ +#define UART_ONE_BIT_SAMPLE_DISABLED ((uint32_t)0x00000000) +#define UART_ONE_BIT_SAMPLE_ENABLED ((uint32_t)USART_CR3_ONEBIT) +#define IS_UART_ONEBIT_SAMPLE(ONEBIT) (((ONEBIT) == UART_ONE_BIT_SAMPLE_DISABLED) || \ + ((ONEBIT) == UART_ONE_BIT_SAMPLE_ENABLED)) +/** + * @} + */ + +/** @defgroup UART_DMA_Tx UART DMA Tx + * @{ + */ +#define UART_DMA_TX_DISABLE ((uint32_t)0x00000000) +#define UART_DMA_TX_ENABLE ((uint32_t)USART_CR3_DMAT) +#define IS_UART_DMA_TX(DMATX) (((DMATX) == UART_DMA_TX_DISABLE) || \ + ((DMATX) == UART_DMA_TX_ENABLE)) +/** + * @} + */ + +/** @defgroup UART_DMA_Rx UART DMA Rx + * @{ + */ +#define UART_DMA_RX_DISABLE ((uint32_t)0x0000) +#define UART_DMA_RX_ENABLE ((uint32_t)USART_CR3_DMAR) +#define IS_UART_DMA_RX(DMARX) (((DMARX) == UART_DMA_RX_DISABLE) || \ + ((DMARX) == UART_DMA_RX_ENABLE)) +/** + * @} + */ + +/** @defgroup UART_Half_Duplex_Selection UART Half Duplex Selection + * @{ + */ +#define UART_HALF_DUPLEX_DISABLE ((uint32_t)0x0000) +#define UART_HALF_DUPLEX_ENABLE ((uint32_t)USART_CR3_HDSEL) +#define IS_UART_HALF_DUPLEX(HDSEL) (((HDSEL) == UART_HALF_DUPLEX_DISABLE) || \ + ((HDSEL) == UART_HALF_DUPLEX_ENABLE)) +/** + * @} + */ + +/** @defgroup UART_Flags UART Status Flags + * Elements values convention: 0xXXXX + * - 0xXXXX : Flag mask in the ISR register + * @{ + */ +#define UART_FLAG_REACK ((uint32_t)0x00400000) +#define UART_FLAG_TEACK ((uint32_t)0x00200000) +#define UART_FLAG_WUF ((uint32_t)0x00100000) +#define UART_FLAG_RWU ((uint32_t)0x00080000) +#define UART_FLAG_SBKF ((uint32_t)0x00040000 +#define UART_FLAG_CMF ((uint32_t)0x00020000) +#define UART_FLAG_BUSY ((uint32_t)0x00010000) +#define UART_FLAG_ABRF ((uint32_t)0x00008000) +#define UART_FLAG_ABRE ((uint32_t)0x00004000) +#define UART_FLAG_EOBF ((uint32_t)0x00001000) +#define UART_FLAG_RTOF ((uint32_t)0x00000800) +#define UART_FLAG_CTS ((uint32_t)0x00000400) +#define UART_FLAG_CTSIF ((uint32_t)0x00000200) +#define UART_FLAG_LBDF ((uint32_t)0x00000100) +#define UART_FLAG_TXE ((uint32_t)0x00000080) +#define UART_FLAG_TC ((uint32_t)0x00000040) +#define UART_FLAG_RXNE ((uint32_t)0x00000020) +#define UART_FLAG_IDLE ((uint32_t)0x00000010) +#define UART_FLAG_ORE ((uint32_t)0x00000008) +#define UART_FLAG_NE ((uint32_t)0x00000004) +#define UART_FLAG_FE ((uint32_t)0x00000002) +#define UART_FLAG_PE ((uint32_t)0x00000001) +/** + * @} + */ + +/** @defgroup UART_Interrupt_definition UART Interrupts Definition + * Elements values convention: 0000ZZZZ0XXYYYYYb + * - YYYYY : Interrupt source position in the XX register (5bits) + * - XX : Interrupt source register (2bits) + * - 01: CR1 register + * - 10: CR2 register + * - 11: CR3 register + * - ZZZZ : Flag position in the ISR register(4bits) + * @{ + */ +#define UART_IT_PE ((uint32_t)0x0028) +#define UART_IT_TXE ((uint32_t)0x0727) +#define UART_IT_TC ((uint32_t)0x0626) +#define UART_IT_RXNE ((uint32_t)0x0525) +#define UART_IT_IDLE ((uint32_t)0x0424) +#define UART_IT_LBD ((uint32_t)0x0846) +#define UART_IT_CTS ((uint32_t)0x096A) +#define UART_IT_CM ((uint32_t)0x142E) +#define UART_IT_WUF ((uint32_t)0x1476) + +/** Elements values convention: 000000000XXYYYYYb + * - YYYYY : Interrupt source position in the XX register (5bits) + * - XX : Interrupt source register (2bits) + * - 01: CR1 register + * - 10: CR2 register + * - 11: CR3 register + */ +#define UART_IT_ERR ((uint32_t)0x0060) + +/** Elements values convention: 0000ZZZZ00000000b + * - ZZZZ : Flag position in the ISR register(4bits) + */ +#define UART_IT_ORE ((uint32_t)0x0300) +#define UART_IT_NE ((uint32_t)0x0200) +#define UART_IT_FE ((uint32_t)0x0100) +/** + * @} + */ + +/** @defgroup UART_IT_CLEAR_Flags UART Interruption Clear Flags + * @{ + */ +#define UART_CLEAR_PEF USART_ICR_PECF /*!< Parity Error Clear Flag */ +#define UART_CLEAR_FEF USART_ICR_FECF /*!< Framing Error Clear Flag */ +#define UART_CLEAR_NEF USART_ICR_NCF /*!< Noise detected Clear Flag */ +#define UART_CLEAR_OREF USART_ICR_ORECF /*!< OverRun Error Clear Flag */ +#define UART_CLEAR_IDLEF USART_ICR_IDLECF /*!< IDLE line detected Clear Flag */ +#define UART_CLEAR_TCF USART_ICR_TCCF /*!< Transmission Complete Clear Flag */ +#define UART_CLEAR_LBDF USART_ICR_LBDCF /*!< LIN Break Detection Clear Flag */ +#define UART_CLEAR_CTSF USART_ICR_CTSCF /*!< CTS Interrupt Clear Flag */ +#define UART_CLEAR_RTOF USART_ICR_RTOCF /*!< Receiver Time Out Clear Flag */ +#define UART_CLEAR_EOBF USART_ICR_EOBCF /*!< End Of Block Clear Flag */ +#define UART_CLEAR_CMF USART_ICR_CMCF /*!< Character Match Clear Flag */ +#define UART_CLEAR_WUF USART_ICR_WUCF /*!< Wake Up from stop mode Clear Flag */ +/** + * @} + */ + +/** @defgroup UART_Request_Parameters UART Request Parameters + * @{ + */ +#define UART_AUTOBAUD_REQUEST ((uint32_t)USART_RQR_ABRRQ) /*!< Auto-Baud Rate Request */ +#define UART_SENDBREAK_REQUEST ((uint32_t)USART_RQR_SBKRQ) /*!< Send Break Request */ +#define UART_MUTE_MODE_REQUEST ((uint32_t)USART_RQR_MMRQ) /*!< Mute Mode Request */ +#define UART_RXDATA_FLUSH_REQUEST ((uint32_t)USART_RQR_RXFRQ) /*!< Receive Data flush Request */ +#define UART_TXDATA_FLUSH_REQUEST ((uint32_t)USART_RQR_TXFRQ) /*!< Transmit data flush Request */ +#define IS_UART_REQUEST_PARAMETER(PARAM) (((PARAM) == UART_AUTOBAUD_REQUEST) || \ + ((PARAM) == UART_SENDBREAK_REQUEST) || \ + ((PARAM) == UART_MUTE_MODE_REQUEST) || \ + ((PARAM) == UART_RXDATA_FLUSH_REQUEST) || \ + ((PARAM) == UART_TXDATA_FLUSH_REQUEST)) +/** + * @} + */ + +/** @defgroup UART_Advanced_Features_Initialization_Type UART Advanced Feature Initialization Type + * @{ + */ +#define UART_ADVFEATURE_NO_INIT ((uint32_t)0x00000000) +#define UART_ADVFEATURE_TXINVERT_INIT ((uint32_t)0x00000001) +#define UART_ADVFEATURE_RXINVERT_INIT ((uint32_t)0x00000002) +#define UART_ADVFEATURE_DATAINVERT_INIT ((uint32_t)0x00000004) +#define UART_ADVFEATURE_SWAP_INIT ((uint32_t)0x00000008) +#define UART_ADVFEATURE_RXOVERRUNDISABLE_INIT ((uint32_t)0x00000010) +#define UART_ADVFEATURE_DMADISABLEONERROR_INIT ((uint32_t)0x00000020) +#define UART_ADVFEATURE_AUTOBAUDRATE_INIT ((uint32_t)0x00000040) +#define UART_ADVFEATURE_MSBFIRST_INIT ((uint32_t)0x00000080) +#define IS_UART_ADVFEATURE_INIT(INIT) ((INIT) <= (UART_ADVFEATURE_NO_INIT | \ + UART_ADVFEATURE_TXINVERT_INIT | \ + UART_ADVFEATURE_RXINVERT_INIT | \ + UART_ADVFEATURE_DATAINVERT_INIT | \ + UART_ADVFEATURE_SWAP_INIT | \ + UART_ADVFEATURE_RXOVERRUNDISABLE_INIT | \ + UART_ADVFEATURE_DMADISABLEONERROR_INIT | \ + UART_ADVFEATURE_AUTOBAUDRATE_INIT | \ + UART_ADVFEATURE_MSBFIRST_INIT)) +/** + * @} + */ + +/** @defgroup UART_Tx_Inv UART Advanced Feature TX Pin Active Level Inversion + * @{ + */ +#define UART_ADVFEATURE_TXINV_DISABLE ((uint32_t)0x00000000) +#define UART_ADVFEATURE_TXINV_ENABLE ((uint32_t)USART_CR2_TXINV) +#define IS_UART_ADVFEATURE_TXINV(TXINV) (((TXINV) == UART_ADVFEATURE_TXINV_DISABLE) || \ + ((TXINV) == UART_ADVFEATURE_TXINV_ENABLE)) +/** + * @} + */ + +/** @defgroup UART_Rx_Inv UART Advanced Feature RX Pin Active Level Inversion + * @{ + */ +#define UART_ADVFEATURE_RXINV_DISABLE ((uint32_t)0x00000000) +#define UART_ADVFEATURE_RXINV_ENABLE ((uint32_t)USART_CR2_RXINV) +#define IS_UART_ADVFEATURE_RXINV(RXINV) (((RXINV) == UART_ADVFEATURE_RXINV_DISABLE) || \ + ((RXINV) == UART_ADVFEATURE_RXINV_ENABLE)) +/** + * @} + */ + +/** @defgroup UART_Data_Inv UART Advanced Feature Binary Data Inversion + * @{ + */ +#define UART_ADVFEATURE_DATAINV_DISABLE ((uint32_t)0x00000000) +#define UART_ADVFEATURE_DATAINV_ENABLE ((uint32_t)USART_CR2_DATAINV) +#define IS_UART_ADVFEATURE_DATAINV(DATAINV) (((DATAINV) == UART_ADVFEATURE_DATAINV_DISABLE) || \ + ((DATAINV) == UART_ADVFEATURE_DATAINV_ENABLE)) +/** + * @} + */ + +/** @defgroup UART_Rx_Tx_Swap UART Advanced Feature RX TX Pins Swap + * @{ + */ +#define UART_ADVFEATURE_SWAP_DISABLE ((uint32_t)0x00000000) +#define UART_ADVFEATURE_SWAP_ENABLE ((uint32_t)USART_CR2_SWAP) +#define IS_UART_ADVFEATURE_SWAP(SWAP) (((SWAP) == UART_ADVFEATURE_SWAP_DISABLE) || \ + ((SWAP) == UART_ADVFEATURE_SWAP_ENABLE)) +/** + * @} + */ + +/** @defgroup UART_Overrun_Disable UART Advanced Feature Overrun Disable + * @{ + */ +#define UART_ADVFEATURE_OVERRUN_ENABLE ((uint32_t)0x00000000) +#define UART_ADVFEATURE_OVERRUN_DISABLE ((uint32_t)USART_CR3_OVRDIS) +#define IS_UART_OVERRUN(OVERRUN) (((OVERRUN) == UART_ADVFEATURE_OVERRUN_ENABLE) || \ + ((OVERRUN) == UART_ADVFEATURE_OVERRUN_DISABLE)) +/** + * @} + */ + +/** @defgroup UART_AutoBaudRate_Enable UART Advanced Feature Auto BaudRate Enable + * @{ + */ +#define UART_ADVFEATURE_AUTOBAUDRATE_DISABLE ((uint32_t)0x00000000) +#define UART_ADVFEATURE_AUTOBAUDRATE_ENABLE ((uint32_t)USART_CR2_ABREN) +#define IS_UART_ADVFEATURE_AUTOBAUDRATE(AUTOBAUDRATE) (((AUTOBAUDRATE) == UART_ADVFEATURE_AUTOBAUDRATE_DISABLE) || \ + ((AUTOBAUDRATE) == UART_ADVFEATURE_AUTOBAUDRATE_ENABLE)) +/** + * @} + */ + +/** @defgroup UART_DMA_Disable_on_Rx_Error UART Advanced Feature DMA Disable On Rx Error + * @{ + */ +#define UART_ADVFEATURE_DMA_ENABLEONRXERROR ((uint32_t)0x00000000) +#define UART_ADVFEATURE_DMA_DISABLEONRXERROR ((uint32_t)USART_CR3_DDRE) +#define IS_UART_ADVFEATURE_DMAONRXERROR(DMA) (((DMA) == UART_ADVFEATURE_DMA_ENABLEONRXERROR) || \ + ((DMA) == UART_ADVFEATURE_DMA_DISABLEONRXERROR)) +/** + * @} + */ + +/** @defgroup UART_MSB_First UART Advanced Feature MSB First + * @{ + */ +#define UART_ADVFEATURE_MSBFIRST_DISABLE ((uint32_t)0x00000000) +#define UART_ADVFEATURE_MSBFIRST_ENABLE ((uint32_t)USART_CR2_MSBFIRST) +#define IS_UART_ADVFEATURE_MSBFIRST(MSBFIRST) (((MSBFIRST) == UART_ADVFEATURE_MSBFIRST_DISABLE) || \ + ((MSBFIRST) == UART_ADVFEATURE_MSBFIRST_ENABLE)) +/** + * @} + */ + +/** @defgroup UART_Stop_Mode_Enable UART Advanced Feature Stop Mode Enable + * @{ + */ +#define UART_ADVFEATURE_STOPMODE_DISABLE ((uint32_t)0x00000000) +#define UART_ADVFEATURE_STOPMODE_ENABLE ((uint32_t)USART_CR1_UESM) +#define IS_UART_ADVFEATURE_STOPMODE(STOPMODE) (((STOPMODE) == UART_ADVFEATURE_STOPMODE_DISABLE) || \ + ((STOPMODE) == UART_ADVFEATURE_STOPMODE_ENABLE)) +/** + * @} + */ + +/** @defgroup UART_Mute_Mode UART Advanced Feature Mute Mode Enable + * @{ + */ +#define UART_ADVFEATURE_MUTEMODE_DISABLE ((uint32_t)0x00000000) +#define UART_ADVFEATURE_MUTEMODE_ENABLE ((uint32_t)USART_CR1_MME) +#define IS_UART_MUTE_MODE(MUTE) (((MUTE) == UART_ADVFEATURE_MUTEMODE_DISABLE) || \ + ((MUTE) == UART_ADVFEATURE_MUTEMODE_ENABLE)) +/** + * @} + */ + +/** @defgroup UART_CR2_ADDRESS_LSB_POS UART Address-matching LSB Position In CR2 Register + * @{ + */ +#define UART_CR2_ADDRESS_LSB_POS ((uint32_t) 24) +/** + * @} + */ + +/** @defgroup UART_WakeUp_from_Stop_Selection UART WakeUp From Stop Selection + * @{ + */ +#define UART_WAKEUP_ON_ADDRESS ((uint32_t)0x0000) +#define UART_WAKEUP_ON_STARTBIT ((uint32_t)USART_CR3_WUS_1) +#define UART_WAKEUP_ON_READDATA_NONEMPTY ((uint32_t)USART_CR3_WUS) +#define IS_UART_WAKEUP_SELECTION(WAKE) (((WAKE) == UART_WAKEUP_ON_ADDRESS) || \ + ((WAKE) == UART_WAKEUP_ON_STARTBIT) || \ + ((WAKE) == UART_WAKEUP_ON_READDATA_NONEMPTY)) +/** + * @} + */ + +/** @defgroup UART_DriverEnable_Polarity UART DriverEnable Polarity + * @{ + */ +#define UART_DE_POLARITY_HIGH ((uint32_t)0x00000000) +#define UART_DE_POLARITY_LOW ((uint32_t)USART_CR3_DEP) +#define IS_UART_DE_POLARITY(POLARITY) (((POLARITY) == UART_DE_POLARITY_HIGH) || \ + ((POLARITY) == UART_DE_POLARITY_LOW)) +/** + * @} + */ + +/** @defgroup UART_CR1_DEAT_ADDRESS_LSB_POS UART Driver Enable Assertion Time LSB Position In CR1 Register + * @{ + */ +#define UART_CR1_DEAT_ADDRESS_LSB_POS ((uint32_t) 21) +/** + * @} + */ + +/** @defgroup UART_CR1_DEDT_ADDRESS_LSB_POS UART Driver Enable DeAssertion Time LSB Position In CR1 Register + * @{ + */ +#define UART_CR1_DEDT_ADDRESS_LSB_POS ((uint32_t) 16) +/** + * @} + */ + +/** @defgroup UART_Interruption_Mask UART Interruptions Flag Mask + * @{ + */ +#define UART_IT_MASK ((uint32_t)0x001F) +/** + * @} + */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ +/** @defgroup UART_Exported_Macros + * @{ + */ + +/** @brief Reset UART handle state + * @param __HANDLE__: specifies the UART Handle. + * The Handle Instance which can be USART1, USART2 or LPUART. + * @retval None + */ +#define __HAL_UART_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_UART_STATE_RESET) + +/** @brief Checks whether the specified UART flag is set or not. + * @param __HANDLE__: specifies the UART Handle. + * This parameter can be USART1, USART2 or LPUART. + * @param __FLAG__: specifies the flag to check. + * This parameter can be one of the following values: + * @arg UART_FLAG_REACK: Receive enable ackowledge flag + * @arg UART_FLAG_TEACK: Transmit enable ackowledge flag + * @arg UART_FLAG_WUF: Wake up from stop mode flag + * @arg UART_FLAG_RWU: Receiver wake up flag (is the UART in mute mode) + * @arg UART_FLAG_SBKF: Send Break flag + * @arg UART_FLAG_CMF: Character match flag + * @arg UART_FLAG_BUSY: Busy flag + * @arg UART_FLAG_ABRF: Auto Baud rate detection flag + * @arg UART_FLAG_ABRE: Auto Baud rate detection error flag + * @arg UART_FLAG_EOBF: End of block flag + * @arg UART_FLAG_RTOF: Receiver timeout flag + * @arg UART_FLAG_CTS: CTS Change flag (not available for UART4 and UART5) + * @arg UART_FLAG_LBD: LIN Break detection flag + * @arg UART_FLAG_TXE: Transmit data register empty flag + * @arg UART_FLAG_TC: Transmission Complete flag + * @arg UART_FLAG_RXNE: Receive data register not empty flag + * @arg UART_FLAG_IDLE: Idle Line detection flag + * @arg UART_FLAG_ORE: OverRun Error flag + * @arg UART_FLAG_NE: Noise Error flag + * @arg UART_FLAG_FE: Framing Error flag + * @arg UART_FLAG_PE: Parity Error flag + * @retval The new state of __FLAG__ (TRUE or FALSE). + */ +#define __HAL_UART_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->ISR & (__FLAG__)) == (__FLAG__)) + +/** @brief Enables the specified UART interrupt. + * @param __HANDLE__: specifies the UART Handle. + * This parameter can be USART1, USART2 or LPUART. + * @param __INTERRUPT__: specifies the UART interrupt source to enable. + * This parameter can be one of the following values: + * @arg UART_IT_WUF: Wakeup from stop mode interrupt + * @arg UART_IT_CM: Character match interrupt + * @arg UART_IT_CTS: CTS change interrupt + * @arg UART_IT_LBD: LIN Break detection interrupt + * @arg UART_IT_TXE: Transmit Data Register empty interrupt + * @arg UART_IT_TC: Transmission complete interrupt + * @arg UART_IT_RXNE: Receive Data register not empty interrupt + * @arg UART_IT_IDLE: Idle line detection interrupt + * @arg UART_IT_PE: Parity Error interrupt + * @arg UART_IT_ERR: Error interrupt(Frame error, noise error, overrun error) + * @retval None + */ +#define __HAL_UART_ENABLE_IT(__HANDLE__, __INTERRUPT__) (((((uint8_t)(__INTERRUPT__)) >> 5) == 1)? ((__HANDLE__)->Instance->CR1 |= (1 << ((__INTERRUPT__) & UART_IT_MASK))): \ + ((((uint8_t)(__INTERRUPT__)) >> 5) == 2)? ((__HANDLE__)->Instance->CR2 |= (1 << ((__INTERRUPT__) & UART_IT_MASK))): \ + ((__HANDLE__)->Instance->CR3 |= (1 << ((__INTERRUPT__) & UART_IT_MASK)))) + +/** @brief Disables the specified UART interrupt. + * @param __HANDLE__: specifies the UART Handle. + * This parameter can be USART1, USART2 or LPUART. + * @param __INTERRUPT__: specifies the UART interrupt source to disable. + * This parameter can be one of the following values: + * @arg UART_IT_WUF: Wakeup from stop mode interrupt + * @arg UART_IT_CM: Character match interrupt + * @arg UART_IT_CTS: CTS change interrupt + * @arg UART_IT_LBD: LIN Break detection interrupt + * @arg UART_IT_TXE: Transmit Data Register empty interrupt + * @arg UART_IT_TC: Transmission complete interrupt + * @arg UART_IT_RXNE: Receive Data register not empty interrupt + * @arg UART_IT_IDLE: Idle line detection interrupt + * @arg UART_IT_PE: Parity Error interrupt + * @arg UART_IT_ERR: Error interrupt(Frame error, noise error, overrun error) + * @retval None + */ +#define __HAL_UART_DISABLE_IT(__HANDLE__, __INTERRUPT__) (((((uint8_t)(__INTERRUPT__)) >> 5) == 1)? ((__HANDLE__)->Instance->CR1 &= ~ ((uint32_t)1 << ((__INTERRUPT__) & UART_IT_MASK))): \ + ((((uint8_t)(__INTERRUPT__)) >> 5) == 2)? ((__HANDLE__)->Instance->CR2 &= ~ ((uint32_t)1 << ((__INTERRUPT__) & UART_IT_MASK))): \ + ((__HANDLE__)->Instance->CR3 &= ~ ((uint32_t)1 << ((__INTERRUPT__) & UART_IT_MASK)))) + +/** @brief Checks whether the specified UART interrupt has occurred or not. + * @param __HANDLE__: specifies the UART Handle. + * This parameter can be USART1, USART2 or LPUART. + * @param __IT__: specifies the UART interrupt to check. + * This parameter can be one of the following values: + * @arg UART_IT_WUF: Wakeup from stop mode interrupt + * @arg UART_IT_CM: Character match interrupt + * @arg UART_IT_CTS: CTS change interrupt (not available for UART4 and UART5) + * @arg UART_IT_LBD: LIN Break detection interrupt + * @arg UART_IT_TXE: Transmit Data Register empty interrupt + * @arg UART_IT_TC: Transmission complete interrupt + * @arg UART_IT_RXNE: Receive Data register not empty interrupt + * @arg UART_IT_IDLE: Idle line detection interrupt + * @arg UART_IT_ORE: OverRun Error interrupt + * @arg UART_IT_NE: Noise Error interrupt + * @arg UART_IT_FE: Framing Error interrupt + * @arg UART_IT_PE: Parity Error interrupt + * @retval The new state of __IT__ (TRUE or FALSE). + */ +#define __HAL_UART_GET_IT(__HANDLE__, __IT__) ((__HANDLE__)->Instance->ISR & ((uint32_t)1 << ((__IT__)>> 0x08))) + +/** @brief Checks whether the specified UART interrupt source is enabled. + * @param __HANDLE__: specifies the UART Handle. + * This parameter can be USART1, USART2 or LPUART. + * @param __IT__: specifies the UART interrupt source to check. + * This parameter can be one of the following values: + * @arg UART_IT_CTS: CTS change interrupt (not available for UART4 and UART5) + * @arg UART_IT_LBD: LIN Break detection interrupt + * @arg UART_IT_TXE: Transmit Data Register empty interrupt + * @arg UART_IT_TC: Transmission complete interrupt + * @arg UART_IT_RXNE: Receive Data register not empty interrupt + * @arg UART_IT_IDLE: Idle line detection interrupt + * @arg UART_IT_ORE: OverRun Error interrupt + * @arg UART_IT_NE: Noise Error interrupt + * @arg UART_IT_FE: Framing Error interrupt + * @arg UART_IT_PE: Parity Error interrupt + * @retval The new state of __IT__ (TRUE or FALSE). + */ +#define __HAL_UART_GET_IT_SOURCE(__HANDLE__, __IT__) ((((((uint8_t)(__IT__)) >> 5) == 1)? (__HANDLE__)->Instance->CR1:(((((uint8_t)(__IT__)) >> 5) == 2)? \ + (__HANDLE__)->Instance->CR2 : (__HANDLE__)->Instance->CR3)) & ((uint32_t)1 << (((uint16_t)(__IT__)) & UART_IT_MASK))) + +/** @brief Clears the specified UART ISR flag, in setting the proper ICR register flag. + * @param __HANDLE__: specifies the UART Handle. + * This parameter can be USART1, USART2 or LPUART. + * @param __IT_CLEAR__: specifies the interrupt clear register flag that needs to be set + * to clear the corresponding interrupt + * This parameter can be one of the following values: + * @arg UART_CLEAR_PEF: Parity Error Clear Flag + * @arg UART_CLEAR_FEF: Framing Error Clear Flag + * @arg UART_CLEAR_NEF: Noise detected Clear Flag + * @arg UART_CLEAR_OREF: OverRun Error Clear Flag + * @arg UART_CLEAR_IDLEF: IDLE line detected Clear Flag + * @arg UART_CLEAR_TCF: Transmission Complete Clear Flag + * @arg UART_CLEAR_LBDF: LIN Break Detection Clear Flag + * @arg UART_CLEAR_CTSF: CTS Interrupt Clear Flag + * @arg UART_CLEAR_RTOF: Receiver Time Out Clear Flag + * @arg UART_CLEAR_EOBF: End Of Block Clear Flag + * @arg UART_CLEAR_CMF: Character Match Clear Flag + * @arg UART_CLEAR_WUF: Wake Up from stop mode Clear Flag + * @retval None + */ +#define __HAL_UART_CLEAR_IT(__HANDLE__, __IT_CLEAR__) ((__HANDLE__)->Instance->ICR |= (uint32_t)(__IT_CLEAR__)) + +/** @brief Set a specific UART request flag. + * @param __HANDLE__: specifies the UART Handle. + * This parameter can be USART1, USART2 or LPUART. + * @param __REQ__: specifies the request flag to set + * This parameter can be one of the following values: + * @arg UART_AUTOBAUD_REQUEST: Auto-Baud Rate Request + * @arg UART_SENDBREAK_REQUEST: Send Break Request + * @arg UART_MUTE_MODE_REQUEST: Mute Mode Request + * @arg UART_RXDATA_FLUSH_REQUEST: Receive Data flush Request + * @arg UART_TXDATA_FLUSH_REQUEST: Transmit data flush Request + * @retval None + */ +#define __HAL_UART_SEND_REQ(__HANDLE__, __REQ__) ((__HANDLE__)->Instance->RQR |= (uint16_t)(__REQ__)) + +/** @brief Enable UART + * @param __HANDLE__: specifies the UART Handle. + * The Handle Instance can be USART1, USART2 or LPUART. + * @retval None + */ +#define __HAL_UART_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 |= USART_CR1_UE) + +/** @brief Disable UART + * @param __HANDLE__: specifies the UART Handle. + * The Handle Instance can be USART1, USART2 or LPUART. + * @retval None + */ +#define __HAL_UART_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 &= ~USART_CR1_UE) + +/** @brief BRR division operation to set BRR register with LPUART + * @param _PCLK_: LPUART clock + * @param _BAUD_: Baud rate set by the user + * @retval Division result + */ +#define __DIV_LPUART(_PCLK_, _BAUD_) (((_PCLK_)*256)/((_BAUD_))) + +/** @brief BRR division operation to set BRR register in 8-bit oversampling mode + * @param _PCLK_: UART clock + * @param _BAUD_: Baud rate set by the user + * @retval Division result + */ +#define __DIV_SAMPLING8(_PCLK_, _BAUD_) (((_PCLK_)*2)/((_BAUD_))) + +/** @brief BRR division operation to set BRR register in 16-bit oversampling mode + * @param _PCLK_: UART clock + * @param _BAUD_: Baud rate set by the user + * @retval Division result + */ +#define __DIV_SAMPLING16(_PCLK_, _BAUD_) (((_PCLK_))/((_BAUD_))) + +/** @brief Check UART Baud rate + * @param BAUDRATE: Baudrate specified by the user + * The maximum Baud Rate is derived from the maximum clock on L0 (i.e. 32 MHz) + * divided by the smallest oversampling used on the USART (i.e. 8) + * @retval Test result (TRUE or FALSE). + */ +#define IS_UART_BAUDRATE(BAUDRATE) ((BAUDRATE) < 4000001) + +/** @brief Check UART byte address + * @param ADDRESS: UART 8-bit address for wake-up process scheme + * @retval Test result (TRUE or FALSE). + */ +#define IS_UART_7B_ADDRESS(ADDRESS) ((ADDRESS) <= 0x7F) + +/** @brief Check UART 4-bit address + * @param ADDRESS: UART 4-bit address for wake-up process scheme + * @retval Test result (TRUE or FALSE). + */ +#define IS_UART_4B_ADDRESS(ADDRESS) ((ADDRESS) <= 0xF) + +/** @brief Check UART assertion time + * @param TIME: 5-bit value assertion time + * @retval Test result (TRUE or FALSE). + */ +#define IS_UART_ASSERTIONTIME(TIME) ((TIME) <= 0x1F) + +/** @brief Check UART deassertion time + * @param TIME: 5-bit value deassertion time + * @retval Test result (TRUE or FALSE). + */ +#define IS_UART_DEASSERTIONTIME(TIME) ((TIME) <= 0x1F) + +/** + * @} + */ +/* Include UART HAL Extension module */ +#include "stm32l0xx_hal_uart_ex.h" +/* Exported functions --------------------------------------------------------*/ +/* Initialization/de-initialization functions ********************************/ +HAL_StatusTypeDef HAL_UART_Init(UART_HandleTypeDef *huart); +HAL_StatusTypeDef HAL_HalfDuplex_Init(UART_HandleTypeDef *huart); +HAL_StatusTypeDef HAL_LIN_Init(UART_HandleTypeDef *huart, uint32_t BreakDetectLength); +HAL_StatusTypeDef HAL_MultiProcessor_Init(UART_HandleTypeDef *huart, uint8_t Address, uint32_t WakeUpMethod); +HAL_StatusTypeDef HAL_UART_DeInit (UART_HandleTypeDef *huart); +void HAL_UART_MspInit(UART_HandleTypeDef *huart); +void HAL_UART_MspDeInit(UART_HandleTypeDef *huart); + +/* IO operation functions *****************************************************/ +HAL_StatusTypeDef HAL_UART_Transmit(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size, uint32_t Timeout); +HAL_StatusTypeDef HAL_UART_Receive(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size, uint32_t Timeout); +HAL_StatusTypeDef HAL_UART_Transmit_IT(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size); +HAL_StatusTypeDef HAL_UART_Receive_IT(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size); +HAL_StatusTypeDef HAL_UART_Transmit_DMA(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size); +HAL_StatusTypeDef HAL_UART_Receive_DMA(UART_HandleTypeDef *huart, uint8_t *pData, uint16_t Size); +HAL_StatusTypeDef HAL_UART_DMAPause(UART_HandleTypeDef *huart); +HAL_StatusTypeDef HAL_UART_DMAResume(UART_HandleTypeDef *huart); +HAL_StatusTypeDef HAL_UART_DMAStop(UART_HandleTypeDef *huart); +void HAL_UART_IRQHandler(UART_HandleTypeDef *huart); +void HAL_UART_TxHalfCpltCallback(UART_HandleTypeDef *huart); +void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart); +void HAL_UART_RxHalfCpltCallback(UART_HandleTypeDef *huart); +void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart); +void HAL_UART_ErrorCallback(UART_HandleTypeDef *huart); +void HAL_UART_WakeupCallback(UART_HandleTypeDef *huart); + +/* Peripheral Control and State functions ************************************/ +HAL_StatusTypeDef HAL_MultiProcessor_EnableMuteMode(UART_HandleTypeDef *huart); +HAL_StatusTypeDef HAL_MultiProcessor_DisableMuteMode(UART_HandleTypeDef *huart); +void HAL_MultiProcessor_EnterMuteMode(UART_HandleTypeDef *huart); +HAL_StatusTypeDef HAL_HalfDuplex_EnableTransmitter(UART_HandleTypeDef *huart); +HAL_StatusTypeDef HAL_HalfDuplex_EnableReceiver(UART_HandleTypeDef *huart); +HAL_StatusTypeDef HAL_LIN_SendBreak(UART_HandleTypeDef *huart); +HAL_UART_StateTypeDef HAL_UART_GetState(UART_HandleTypeDef *huart); +uint32_t HAL_UART_GetError(UART_HandleTypeDef *huart); + +/* Non-User functions ********************************************************/ +void UART_SetConfig(UART_HandleTypeDef *huart); +HAL_StatusTypeDef UART_CheckIdleState(UART_HandleTypeDef *huart); +HAL_StatusTypeDef UART_WaitOnFlagUntilTimeout(UART_HandleTypeDef *huart, uint32_t Flag, FlagStatus Status, uint32_t Timeout); +void UART_AdvFeatureConfig(UART_HandleTypeDef *huart); +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __STM32L0xx_HAL_UART_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_uart_ex.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_uart_ex.c new file mode 100644 index 0000000000..fcdd704b60 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_uart_ex.c @@ -0,0 +1,428 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_uart_ex.c + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief Extended UART HAL module driver. + * + * This file provides firmware functions to manage the following + * functionalities of the Inter Integrated Circuit (UART) peripheral: + * + Extended Control methods + * + @verbatim + ============================================================================== + ##### UART peripheral extended features ##### + ============================================================================== + + [..] Comparing to other previous devices, the UART interface for STM32L0XX + devices contains the following additional features + + (+) Possibility to disable or enable Analog Noise Filter + (+) Use of a configured Digital Noise Filter + (+) Disable or enable wakeup from Stop mode + + ##### How to use this driver ##### + ============================================================================== + [..] This driver provides functions to configure Noise Filter + + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @defgroup UARTEx + * @brief UARTEx module driver + * @{ + */ + +#ifdef HAL_UART_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +#define UART_REACK_TIMEOUT ((uint32_t) 1000) +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +static void UART_Wakeup_AddressConfig(UART_HandleTypeDef *huart, UART_WakeUpTypeDef WakeUpSelection); +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup UARTEX_Private_Functions + * @{ + */ + +/** @defgroup UARTEx_Group1 Extended Initialization/de-initialization functions + * @brief Extended Initialization and Configuration Functions + + * +@verbatim +=============================================================================== + ##### Initialization and Configuration functions ##### + =============================================================================== + [..] + The HAL_RS485Ex_Init() API follows respectively the UART RS485 mode + configuration procedures (details for the procedures are available in reference manual). + +@endverbatim + * @{ + */ + +/** + * @brief Initializes the RS485 Driver enable feature according to the specified + * parameters in the UART_InitTypeDef and creates the associated handle . + * @param huart: uart handle + * @param Polarity: select the driver enable polarity + * This parameter can be one of the following values: + * @arg UART_DE_POLARITY_HIGH: DE signal is active high + * @arg UART_DE_POLARITY_LOW: DE signal is active low + * @param AssertionTime: Driver Enable assertion time + * 5-bit value defining the time between the activation of the DE (Driver Enable) + * signal and the beginning of the start bit. It is expressed in sample time + * units (1/8 or 1/16 bit time, depending on the oversampling rate) + * @param DeassertionTime: Driver Enable deassertion time + * 5-bit value defining the time between the end of the last stop bit, in a + * transmitted message, and the de-activation of the DE (Driver Enable) signal. + * It is expressed in sample time units (1/8 or 1/16 bit time, depending on the + * oversampling rate). + * @retval HAL status + */ +HAL_StatusTypeDef HAL_RS485Ex_Init(UART_HandleTypeDef *huart, uint32_t Polarity, uint32_t AssertionTime, uint32_t DeassertionTime) +{ + uint32_t temp = 0x0; + + /* Check the UART handle allocation */ + if(huart == NULL) + { + return HAL_ERROR; + } + + /* Check the Driver Enable polarity */ + assert_param(IS_UART_DE_POLARITY(Polarity)); + + /* Check the Driver Enable assertion time */ + assert_param(IS_UART_ASSERTIONTIME(AssertionTime)); + + /* Check the Driver Enable deassertion time */ + assert_param(IS_UART_DEASSERTIONTIME(DeassertionTime)); + + if(huart->State == HAL_UART_STATE_RESET) + { + /* Init the low level hardware : GPIO, CLOCK, CORTEX */ + HAL_UART_MspInit(huart); + } + + huart->State = HAL_UART_STATE_BUSY; + + /* Disable the Peripheral */ + __HAL_UART_DISABLE(huart); + + /* Set the UART Communication parameters */ + UART_SetConfig(huart); + + if(huart->AdvancedInit.AdvFeatureInit != UART_ADVFEATURE_NO_INIT) + { + UART_AdvFeatureConfig(huart); + } + + /* Enable the Driver Enable mode by setting the DEM bit in the CR3 register */ + huart->Instance->CR3 |= USART_CR3_DEM; + + /* Set the Driver Enable polarity */ + MODIFY_REG(huart->Instance->CR3, USART_CR3_DEP, Polarity); + + /* Set the Driver Enable assertion and deassertion times */ + temp = (AssertionTime << UART_CR1_DEAT_ADDRESS_LSB_POS); + temp |= (DeassertionTime << UART_CR1_DEDT_ADDRESS_LSB_POS); + MODIFY_REG(huart->Instance->CR1, (USART_CR1_DEDT|USART_CR1_DEAT), temp); + + /* Enable the Peripheral */ + __HAL_UART_ENABLE(huart); + + /* TEACK and/or REACK to check before moving huart->State to Ready */ + return (UART_CheckIdleState(huart)); +} + +/** + * @} + */ + +/** @defgroup UARTEX_Group1 Peripheral Control methods + * @brief management functions + * +@verbatim + =============================================================================== + ##### Peripheral Control methods ##### + =============================================================================== + [..] This section provides functions allowing to: + (+) UART_AdvFeatureConfig() API optionally configures the UART advanced features + (+) HAL_MultiProcessorEx_AddressLength_Set() API optionally sets the UART node address + detection length to more than 4 bits for multiprocessor address mark wake up. + (+) HAL_UARTEx_EnableStopMode() API enables the UART to wake up the MCU from stop mode + (+) HAL_UARTEx_DisableStopMode() API disables the above functionality + (+) HAL_UARTEx_EnableClockStopMode() API enables the UART HSI clock during stop mode + (+) HAL_UARTEx_DisableClockStopMode() API disables the above functionality + (+) UART_Wakeup_AddressConfig() API configures the wake-up from stop mode parameters + +@endverbatim + * @{ + */ + +/** + * @brief Enable UART Stop Mode + * The UART is able to wake up the MCU from Stop mode as long as UART clock is HSI or LSE + * @param huart: uart handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_UARTEx_EnableStopMode(UART_HandleTypeDef *huart) +{ + /* Process Locked */ + __HAL_LOCK(huart); + + huart->State = HAL_UART_STATE_BUSY; + + /* Set the USART UESM bit */ + huart->Instance->CR1 |= USART_CR1_UESM; + + huart->State = HAL_UART_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(huart); + + return HAL_OK; +} + +/** + * @brief Enable UART Clock in Stop Mode + * The UART keeps the Clock ON during Stop mode + * @param huart: uart handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_UARTEx_EnableClockStopMode(UART_HandleTypeDef *huart) +{ + /* Process Locked */ + __HAL_LOCK(huart); + + huart->State = HAL_UART_STATE_BUSY; + + /* Set the USART UESM bit */ + huart->Instance->CR3 |= USART_CR3_UCESM; + + huart->State = HAL_UART_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(huart); + + return HAL_OK; +} + +/** + * @brief Disable UART Stop Mode + * @param huart: uart handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_UARTEx_DisableStopMode(UART_HandleTypeDef *huart) +{ + /* Process Locked */ + __HAL_LOCK(huart); + + huart->State = HAL_UART_STATE_BUSY; + + /* Clear USART UESM bit */ + huart->Instance->CR1 &= ~(USART_CR1_UESM); + + huart->State = HAL_UART_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(huart); + + return HAL_OK; +} + +/** + * @brief Disable UART Clock in Stop Mode + * @param huart: uart handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_UARTEx_DisableClockStopMode(UART_HandleTypeDef *huart) +{ + /* Process Locked */ + __HAL_LOCK(huart); + + huart->State = HAL_UART_STATE_BUSY; + + /* Clear USART UESM bit */ + huart->Instance->CR3 &= ~(USART_CR3_UCESM); + + huart->State = HAL_UART_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(huart); + + return HAL_OK; +} + +/** + * @brief Set Wakeup from Stop mode interrupt flag selection + * @param huart: uart handle, + * @param WakeUpSelection: address match, Start Bit detection or RXNE bit status. + * This parameter can be one of the following values: + * @arg UART_WAKEUP_ON_ADDRESS + * @arg UART_WAKEUP_ON_STARTBIT + * @arg UART_WAKEUP_ON_READDATA_NONEMPTY + * @retval HAL status + */ +HAL_StatusTypeDef HAL_UARTEx_StopModeWakeUpSourceConfig(UART_HandleTypeDef *huart, UART_WakeUpTypeDef WakeUpSelection) +{ + /* Check the wake-up selection parameter */ + assert_param(IS_UART_WAKEUP_SELECTION(WakeUpSelection.WakeUpEvent)); + + /* Process Locked */ + __HAL_LOCK(huart); + + huart->State = HAL_UART_STATE_BUSY; + + /* Disable the Peripheral */ + __HAL_UART_DISABLE(huart); + + /* Set the wake-up selection scheme */ + MODIFY_REG(huart->Instance->CR3, USART_CR3_WUS, WakeUpSelection.WakeUpEvent); + + if(WakeUpSelection.WakeUpEvent == UART_WAKEUP_ON_ADDRESS) + { + UART_Wakeup_AddressConfig(huart, WakeUpSelection); + } + + /* Enable the Peripheral */ + __HAL_UART_ENABLE(huart); + + /* Wait until REACK flag is set before moving huart->State to Ready */ + if(UART_WaitOnFlagUntilTimeout(huart, USART_ISR_REACK, RESET, UART_REACK_TIMEOUT) != HAL_OK) + { + return HAL_TIMEOUT; + } + + /* Process Unlocked */ + __HAL_UNLOCK(huart); + + /* Initialize the UART state*/ + huart->ErrorCode = HAL_UART_ERROR_NONE; + huart->State= HAL_UART_STATE_READY; + + return HAL_OK; +} +/** + * @brief By default in multiprocessor mode, when the wake up method is set + * to address mark, the UART handles only 4-bit long addresses detection. + * This API allows to enable longer addresses detection (6-, 7- or 8-bit + * long): + * - 6-bit address detection in 7-bit data mode + * - 7-bit address detection in 8-bit data mode + * - 8-bit address detection in 9-bit data mode + * @param huart: UART handle + * @param AddressLength: this parameter can be one of the following values: + * @arg UART_ADDRESS_DETECT_4B: 4-bit long address + * @arg UART_ADDRESS_DETECT_7B: 6-, 7- or 8-bit long address + * @retval HAL status + */ +HAL_StatusTypeDef HAL_MultiProcessorEx_AddressLength_Set(UART_HandleTypeDef *huart, uint32_t AddressLength) +{ + /* Check the UART handle allocation */ + if(huart == NULL) + { + return HAL_ERROR; + } + + /* Check the address length parameter */ + assert_param(IS_UART_ADDRESSLENGTH_DETECT(AddressLength)); + + huart->State = HAL_UART_STATE_BUSY; + + /* Disable the Peripheral */ + __HAL_UART_DISABLE(huart); + + /* Set the address length */ + MODIFY_REG(huart->Instance->CR2, USART_CR2_ADDM7, AddressLength); + + /* Enable the Peripheral */ + __HAL_UART_ENABLE(huart); + + /* TEACK and/or REACK to check before moving huart->State to Ready */ + return (UART_CheckIdleState(huart)); +} + +/** + * @brief Initializes the UART wake-up from stop mode parameters when triggered by address detection. + * @param huart: uart handle + * @param WakeUpSelection: UART wake up from stop mode parameters + * @retval HAL status + */ +static void UART_Wakeup_AddressConfig(UART_HandleTypeDef *huart, UART_WakeUpTypeDef WakeUpSelection) +{ + assert_param(IS_UART_ADDRESSLENGTH_DETECT(WakeUpSelection.AddressLength)); + if(WakeUpSelection.AddressLength == UART_ADDRESS_DETECT_4B) + { + assert_param(IS_UART_4B_ADDRESS(WakeUpSelection.Address)); + } + else + { + assert_param(IS_UART_7B_ADDRESS(WakeUpSelection.Address)); + } + + /* Set the USART address length */ + MODIFY_REG(huart->Instance->CR2, USART_CR2_ADDM7, WakeUpSelection.AddressLength); + + /* Set the USART address node */ + MODIFY_REG(huart->Instance->CR2, USART_CR2_ADD, ((uint32_t)WakeUpSelection.Address << UART_CR2_ADDRESS_LSB_POS)); +} + +/** + * @} + */ + +/** + * @} + */ + +#endif /* HAL_UART_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_uart_ex.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_uart_ex.h new file mode 100644 index 0000000000..481a3ec172 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_uart_ex.h @@ -0,0 +1,289 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_uart_ex.h + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief Header file of UART HAL Extension module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32L0xx_HAL_UART_EX_H +#define __STM32L0xx_HAL_UART_EX_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal_def.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @addtogroup UARTEx + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/** + * @brief UART wake up from stop mode parameters + */ +typedef struct +{ + uint32_t WakeUpEvent; /*!< Specifies which event will activat the Wakeup from Stop mode flag (WUF). + This parameter can be a value of @ref UARTEx_WakeUp_from_Stop_Selection. + If set to UART_WAKEUP_ON_ADDRESS, the two other fields below must + be filled up. */ + + uint16_t AddressLength; /*!< Specifies whether the address is 4 or 7-bit long. + This parameter can be a value of @ref UARTEx_WakeUp_Address_Length */ + + uint8_t Address; /*!< UART/USART node address (7-bit long max) */ +} UART_WakeUpTypeDef; + +/* Exported constants --------------------------------------------------------*/ +/** @defgroup UARTEx_Extended_Exported_Constants + * @{ + */ + +/** @defgroup UARTEx_Word_Length UART Word Length + * @{ + */ +#define UART_WORDLENGTH_7B ((uint32_t)USART_CR1_M_1) +#define UART_WORDLENGTH_8B ((uint32_t)0x0000) +#define UART_WORDLENGTH_9B ((uint32_t)USART_CR1_M_0) +#define IS_UART_WORD_LENGTH(LENGTH) (((LENGTH) == UART_WORDLENGTH_7B) || \ + ((LENGTH) == UART_WORDLENGTH_8B) || \ + ((LENGTH) == UART_WORDLENGTH_9B)) +/** + * @} + */ + +/** @defgroup UARTEx_AutoBaud_Rate_Mode UART Advanced Feature AutoBaud Rate Mode + * @{ + */ +#define UART_ADVFEATURE_AUTOBAUDRATE_ONSTARTBIT ((uint32_t)0x0000) +#define UART_ADVFEATURE_AUTOBAUDRATE_ONFALLINGEDGE ((uint32_t)USART_CR2_ABRMODE_0) +#define UART_ADVFEATURE_AUTOBAUDRATE_ON0X7FFRAME ((uint32_t)USART_CR2_ABRMODE_1) +#define UART_ADVFEATURE_AUTOBAUDRATE_ON0X55FRAME ((uint32_t)USART_CR2_ABRMODE) +#define IS_UART_ADVFEATURE_AUTOBAUDRATEMODE(MODE) (((MODE) == UART_ADVFEATURE_AUTOBAUDRATE_ONSTARTBIT) || \ + ((MODE) == UART_ADVFEATURE_AUTOBAUDRATE_ONFALLINGEDGE) || \ + ((MODE) == UART_ADVFEATURE_AUTOBAUDRATE_ON0X7FFRAME) || \ + ((MODE) == UART_ADVFEATURE_AUTOBAUDRATE_ON0X55FRAME)) +/** + * @} + */ + +/** @defgroup UARTEx_WakeUp_Address_Length UART WakeUp Address Length + * @{ + */ +#define UART_ADDRESS_DETECT_4B ((uint32_t)0x00000000) +#define UART_ADDRESS_DETECT_7B ((uint32_t)USART_CR2_ADDM7) +#define IS_UART_ADDRESSLENGTH_DETECT(ADDRESS) (((ADDRESS) == UART_ADDRESS_DETECT_4B) || \ + ((ADDRESS) == UART_ADDRESS_DETECT_7B)) +/** + * @} + */ + + + /** @defgroup UARTEx_WakeUp_Methods UART WakeUp Methods + * @{ + */ +#define UART_WAKEUPMETHOD_IDLELINE ((uint32_t)0x00000000) +#define UART_WAKEUPMETHOD_ADDRESSMARK ((uint32_t)USART_CR1_WAKE) +#define IS_UART_WAKEUPMETHOD(WAKEUP) (((WAKEUP) == UART_WAKEUPMETHOD_IDLELINE) || \ + ((WAKEUP) == UART_WAKEUPMETHOD_ADDRESSMARK)) +/** + * @} + */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ + +/** @defgroup UARTEx_Extended_Exported_Macros + * @{ + */ + +/** @brief Reports the UART clock source. + * @param __HANDLE__: specifies the UART Handle + * @param __CLOCKSOURCE__ : output variable + * @retval UART clocking source, written in __CLOCKSOURCE__. + */ +#define __HAL_UART_GETCLOCKSOURCE(__HANDLE__,__CLOCKSOURCE__) \ + do { \ + if((__HANDLE__)->Instance == USART1) \ + { \ + switch(__HAL_RCC_GET_USART1_SOURCE()) \ + { \ + case RCC_USART1CLKSOURCE_PCLK2: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_PCLK2; \ + break; \ + case RCC_USART1CLKSOURCE_HSI: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_HSI; \ + break; \ + case RCC_USART1CLKSOURCE_SYSCLK: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_SYSCLK; \ + break; \ + case RCC_USART1CLKSOURCE_LSE: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_LSE; \ + break; \ + default: \ + break; \ + } \ + } \ + else if((__HANDLE__)->Instance == USART2) \ + { \ + switch(__HAL_RCC_GET_USART2_SOURCE()) \ + { \ + case RCC_USART2CLKSOURCE_PCLK1: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_PCLK1; \ + break; \ + case RCC_USART2CLKSOURCE_HSI: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_HSI; \ + break; \ + case RCC_USART2CLKSOURCE_SYSCLK: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_SYSCLK; \ + break; \ + case RCC_USART2CLKSOURCE_LSE: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_LSE; \ + break; \ + default: \ + break; \ + } \ + } \ + else if((__HANDLE__)->Instance == LPUART1) \ + { \ + switch(__HAL_RCC_GET_LPUART1_SOURCE()) \ + { \ + case RCC_LPUART1CLKSOURCE_PCLK1: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_PCLK1; \ + break; \ + case RCC_LPUART1CLKSOURCE_HSI: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_HSI; \ + break; \ + case RCC_LPUART1CLKSOURCE_SYSCLK: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_SYSCLK; \ + break; \ + case RCC_LPUART1CLKSOURCE_LSE: \ + (__CLOCKSOURCE__) = UART_CLOCKSOURCE_LSE; \ + break; \ + default: \ + break; \ + } \ + } \ + } while(0) + +/** @brief Reports the UART mask to apply to retrieve the received data + * according to the word length and to the parity bits activation. + * If PCE = 1, the parity bit is not included in the data extracted + * by the reception API(). + * This masking operation is not carried out in the case of + * DMA transfers. + * @param __HANDLE__: specifies the UART Handle + * @param __MASK__ : output variable + * @retval mask to apply to UART RDR register value. + */ +#define __HAL_UART_MASK_COMPUTATION(__HANDLE__) \ + do { \ + if ((__HANDLE__)->Init.WordLength == UART_WORDLENGTH_9B) \ + { \ + if ((__HANDLE__)->Init.Parity == UART_PARITY_NONE) \ + { \ + (__HANDLE__)->Mask = 0x01FF ; \ + } \ + else \ + { \ + (__HANDLE__)->Mask = 0x00FF ; \ + } \ + } \ + else if ((__HANDLE__)->Init.WordLength == UART_WORDLENGTH_8B) \ + { \ + if ((__HANDLE__)->Init.Parity == UART_PARITY_NONE) \ + { \ + (__HANDLE__)->Mask = 0x00FF ; \ + } \ + else \ + { \ + (__HANDLE__)->Mask = 0x007F ; \ + } \ + } \ + else if ((__HANDLE__)->Init.WordLength == UART_WORDLENGTH_7B) \ + { \ + if ((__HANDLE__)->Init.Parity == UART_PARITY_NONE) \ + { \ + (__HANDLE__)->Mask = 0x007F ; \ + } \ + else \ + { \ + (__HANDLE__)->Mask = 0x003F ; \ + } \ + } \ +} while(0) + +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/* Initialization/de-initialization functions ********************************/ +HAL_StatusTypeDef HAL_RS485Ex_Init(UART_HandleTypeDef *huart, uint32_t Polarity, uint32_t AssertionTime, uint32_t DeassertionTime); + +/* IO operation functions *****************************************************/ +/* Peripheral Control functions **********************************************/ +HAL_StatusTypeDef HAL_UARTEx_StopModeWakeUpSourceConfig(UART_HandleTypeDef *huart, UART_WakeUpTypeDef WakeUpSelection); +HAL_StatusTypeDef HAL_UARTEx_EnableStopMode(UART_HandleTypeDef *huart); +HAL_StatusTypeDef HAL_UARTEx_EnableClockStopMode(UART_HandleTypeDef *huart); +HAL_StatusTypeDef HAL_UARTEx_DisableStopMode(UART_HandleTypeDef *huart); +HAL_StatusTypeDef HAL_UARTEx_DisableClockStopMode(UART_HandleTypeDef *huart); + +/* Peripheral State functions ************************************************/ +HAL_StatusTypeDef HAL_MultiProcessorEx_AddressLength_Set(UART_HandleTypeDef *huart, uint32_t AddressLength); + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __STM32L0xx_HAL_UART_EX_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_usart.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_usart.c new file mode 100644 index 0000000000..4c59306e46 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_usart.c @@ -0,0 +1,1738 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_usart.c + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief USART HAL module driver. + * + * This file provides firmware functions to manage the following + * functionalities of the Universal Synchronous/Asynchronous Receiver Transmitter + * Peripheral (USART). + * + Initialization and de-initialization functions + * + IO operation functions + * + Peripheral Control functions + * + @verbatim + =============================================================================== + ##### How to use this driver ##### + =============================================================================== + [..] + The USART HAL driver can be used as follows: + + (#) Declare a USART_HandleTypeDef handle structure. + (#) Initialize the USART low level resources by implement the HAL_USART_MspInit ()API: + (##) Enable the USARTx interface clock. + (##) USART pins configuration: + (+) Enable the clock for the USART GPIOs. + (+) Configure these USART pins as alternate function pull-up. + (##) NVIC configuration if you need to use interrupt process (HAL_USART_Transmit_IT(), + HAL_USART_Receive_IT() and HAL_USART_TransmitReceive_IT() APIs): + (+) Configure the USARTx interrupt priority. + (+) Enable the NVIC USART IRQ handle. + (@) The specific USART interrupts (Transmission complete interrupt, + RXNE interrupt and Error Interrupts) will be managed using the macros + __HAL_USART_ENABLE_IT() and __HAL_USART_DISABLE_IT() inside the transmit and receive process. + (##) DMA Configuration if you need to use DMA process (HAL_USART_Transmit_DMA() + HAL_USART_Receive_IT() and HAL_USART_TransmitReceive_IT() APIs): + (+) Declare a DMA handle structure for the Tx/Rx stream. + (+) Enable the DMAx interface clock. + (+) Configure the declared DMA handle structure with the required Tx/Rx parameters. + (+) Configure the DMA Tx/Rx Stream. + (+) Associate the initilalized DMA handle to the USART DMA Tx/Rx handle. + (+) Configure the priority and enable the NVIC for the transfer complete interrupt on the DMA Tx/Rx Stream. + + (#) Program the Baud Rate, Word Length, Stop Bit, Parity, Hardware + flow control and Mode(Receiver/Transmitter) in the husart Init structure. + + (#) Initialize the USART registers by calling the HAL_USART_Init() API: + (+) These API's configures also the low level Hardware GPIO, CLOCK, CORTEX...etc) + by calling the customed HAL_USART_MspInit(&husart) API. + + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @defgroup USART + * @brief HAL USART Synchronous module driver + * @{ + */ +#ifdef HAL_USART_MODULE_ENABLED +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +#define DUMMY_DATA ((uint16_t) 0xFFFF) +#define TEACK_REACK_TIMEOUT ((uint32_t) 1000) +#define HAL_USART_TXDMA_TIMEOUTVALUE ((uint32_t) 22000) + +#define USART_CR1_FIELDS ((uint32_t)(USART_CR1_M | USART_CR1_PCE | \ + USART_CR1_PS | USART_CR1_TE | USART_CR1_RE)) +#define USART_CR2_FIELDS ((uint32_t)(USART_CR2_CPHA | USART_CR2_CPOL | \ + USART_CR2_CLKEN | USART_CR2_LBCL | USART_CR2_STOP)) +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +static void USART_DMATransmitCplt(DMA_HandleTypeDef *hdma); +static void USART_DMATxHalfCplt(DMA_HandleTypeDef *hdma); +static void USART_DMAReceiveCplt(DMA_HandleTypeDef *hdma); +static void USART_DMARxHalfCplt(DMA_HandleTypeDef *hdma); +static void USART_DMAError(DMA_HandleTypeDef *hdma); +static HAL_StatusTypeDef USART_WaitOnFlagUntilTimeout(USART_HandleTypeDef *husart, uint32_t Flag, FlagStatus Status, uint32_t Timeout); +static void USART_SetConfig (USART_HandleTypeDef *husart); +static HAL_StatusTypeDef USART_CheckIdleState(USART_HandleTypeDef *husart); +static HAL_StatusTypeDef USART_Transmit_IT(USART_HandleTypeDef *husart); +static HAL_StatusTypeDef USART_Receive_IT(USART_HandleTypeDef *husart); +static HAL_StatusTypeDef USART_TransmitReceive_IT(USART_HandleTypeDef *husart); +/* Private functions ---------------------------------------------------------*/ + + +/** @defgroup USART_Private_Functions + * @{ + */ + +/** @defgroup USART_Group1 USART Initialization/de-initialization functions + * @brief Initialization and Configuration functions + * +@verbatim + =============================================================================== + ##### Initialization and Configuration functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to initialize the USART + in asynchronous and in synchronous modes. + (+) For the asynchronous mode only these parameters can be configured: + (++) Baud Rate + (++) Word Length + (++) Stop Bit + (++) Parity: If the parity is enabled, then the MSB bit of the data written + in the data register is transmitted but is changed by the parity bit. + Depending on the frame length defined by the M bit (8-bits or 9-bits), + the possible USART frame formats are as listed in the following table: + +-------------------------------------------------------------+ + | M0 bit | PCE bit | USART frame | + |---------------------|---------------------------------------| + | 0 | 0 | | SB | 8 bit data | STB | | + |---------|-----------|---------------------------------------| + | 0 | 1 | | SB | 7 bit data | PB | STB | | + |---------|-----------|---------------------------------------| + | 1 | 0 | | SB | 9 bit data | STB | | + |---------|-----------|---------------------------------------| + | 1 | 1 | | SB | 8 bit data | PB | STB | | + +-------------------------------------------------------------+ + (++) USART polarity + (++) USART phase + (++) USART LastBit + (++) Receiver/transmitter modes + + [..] + The HAL_USART_Init() function follows the USART synchronous configuration + procedure (details for the procedure are available in reference manual (RM0329)). + +@endverbatim + * @{ + */ + +/** + * @brief Initializes the USART mode according to the specified + * parameters in the USART_InitTypeDef and create the associated handle. + * @param husart: USART handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_USART_Init(USART_HandleTypeDef *husart) +{ + /* Check the USART handle allocation */ + if(husart == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_USART_INSTANCE(husart->Instance)); + + if(husart->State == HAL_USART_STATE_RESET) + { + /* Init the low level hardware : GPIO, CLOCK, CORTEX */ + HAL_USART_MspInit(husart); + } + + husart->State = HAL_USART_STATE_BUSY; + + /* Disable the Peripheral */ + __HAL_USART_DISABLE(husart); + + /* Set the Usart Communication parameters */ + USART_SetConfig(husart); + + /* In Synchronous mode, the following bits must be kept cleared: + - LINEN bit in the USART_CR2 register + - HDSEL, SCEN and IREN bits in the USART_CR3 register.*/ + husart->Instance->CR2 &= ~USART_CR2_LINEN; + husart->Instance->CR3 &= ~(USART_CR3_SCEN | USART_CR3_HDSEL | USART_CR3_IREN); + + /* Enable the Peripharal */ + __HAL_USART_ENABLE(husart); + + /* TEACK and/or REACK to check before moving husart->State to Ready */ + return (USART_CheckIdleState(husart)); +} + +/** + * @brief DeInitializes the USART peripheral. + * @param husart: USART handle + * @retval HAL status + */ +HAL_StatusTypeDef HAL_USART_DeInit(USART_HandleTypeDef *husart) +{ + /* Check the USART handle allocation */ + if(husart == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_USART_INSTANCE(husart->Instance)); + + husart->State = HAL_USART_STATE_BUSY; + + husart->Instance->CR1 = 0x0; + husart->Instance->CR2 = 0x0; + husart->Instance->CR3 = 0x0; + + /* DeInit the low level hardware */ + HAL_USART_MspDeInit(husart); + + husart->ErrorCode = HAL_USART_ERROR_NONE; + husart->State = HAL_USART_STATE_RESET; + + /* Release Lock */ + __HAL_UNLOCK(husart); + + return HAL_OK; +} + +/** + * @brief USART MSP Init. + * @param husart: USART handle + * @retval None + */ + __weak void HAL_USART_MspInit(USART_HandleTypeDef *husart) +{ + /* NOTE: This function Should not be modified, when the callback is needed, + the HAL_USART_MspInit could be implenetd in the user file + */ +} + +/** + * @brief USART MSP DeInit. + * @param husart: USART handle + * @retval None + */ + __weak void HAL_USART_MspDeInit(USART_HandleTypeDef *husart) +{ + /* NOTE: This function Should not be modified, when the callback is needed, + the HAL_USART_MspDeInit could be implenetd in the user file + */ +} + +/** + * @} + */ + +/** @defgroup HAL_USART_Group2 IO operation functions + * @brief USART Transmit/Receive functions + * +@verbatim + =============================================================================== + ##### I/O operation functions ##### + =============================================================================== + This subsection provides a set of functions allowing to manage the USART synchronous + data transfers. + + [..] The USART supports master mode only: it cannot receive or send data related to an input + clock (SCLK is always an output). + + (#) There are two mode of transfer: + (+) Blocking mode: The communication is performed in polling mode. + The HAL status of all data processing is returned by the same function + after finishing transfer. + (+) No-Blocking mode: The communication is performed using Interrupts + or DMA, These API's return the HAL status. + The end of the data processing will be indicated through the + dedicated USART IRQ when using Interrupt mode or the DMA IRQ when + using DMA mode. + The HAL_USART_TxCpltCallback(), HAL_USART_RxCpltCallback() and HAL_USART_TxRxCpltCallback() user callbacks + will be executed respectivelly at the end of the transmit or Receive process + The HAL_USART_ErrorCallback()user callback will be executed when a communication error is detected + + (#) Blocking mode API's are : + (+) HAL_USART_Transmit()in simplex mode + (+) HAL_USART_Receive() in full duplex receive only + (+) HAL_USART_TransmitReceive() in full duplex mode + + (#) Non-Blocking mode API's with Interrupt are : + (+) HAL_USART_Transmit_IT()in simplex mode + (+) HAL_USART_Receive_IT() in full duplex receive only + (+) HAL_USART_TransmitReceive_IT()in full duplex mode + (+) HAL_USART_IRQHandler() + + (#) No-Blocking mode functions with DMA are : + (+) HAL_USART_Transmit_DMA()in simplex mode + (+) HAL_USART_Receive_DMA() in full duplex receive only + (+) HAL_USART_TransmitReceive_DMA() in full duplex mode + (+) HAL_USART_DMAPause() + (+) HAL_USART_DMAResume() + (+) HAL_USART_DMAStop() + + (#) A set of Transfer Complete Callbacks are provided in No_Blocking mode: + (+) HAL_USART_TxCpltCallback() + (+) HAL_USART_RxCpltCallback() + (+) HAL_USART_TxHalfCpltCallback() + (+) HAL_USART_RxHalfCpltCallback() + (+) HAL_USART_ErrorCallback() + (+) HAL_USART_TxRxCpltCallback() + +@endverbatim + * @{ + */ + +/** + * @brief Simplex Send an amount of data in blocking mode + * @param husart: USART handle + * @param pTxData: Pointer to data buffer + * @param Size: Amount of data to be sent + * @param Timeout : Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_USART_Transmit(USART_HandleTypeDef *husart, uint8_t *pTxData, uint16_t Size, uint32_t Timeout) +{ + uint16_t* tmp; + + if(husart->State == HAL_USART_STATE_READY) + { + if((pTxData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(husart); + + husart->ErrorCode = HAL_USART_ERROR_NONE; + husart->State = HAL_USART_STATE_BUSY_TX; + + husart->TxXferSize = Size; + husart->TxXferCount = Size; + + /* Check the remaining data to be sent */ + while(husart->TxXferCount > 0) + { + husart->TxXferCount--; + if(USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_TC, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + if((husart->Init.WordLength == USART_WORDLENGTH_9B) && (husart->Init.Parity == USART_PARITY_NONE)) + { + tmp = (uint16_t*) pTxData; + husart->Instance->TDR = (*tmp & (uint16_t)0x01FF); + pTxData += 2; + } + else + { + husart->Instance->TDR = (*pTxData++ & (uint8_t)0xFF); + } + } + + if(USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_TC, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + husart->State = HAL_USART_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(husart); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive an amount of data in blocking mode + * To receive synchronous data, dummy data are simultaneously transmitted + * @param husart: USART handle + * @param pRxData: pointer to data buffer + * @param Size: amount of data to be received + * @param Timeout : Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_USART_Receive(USART_HandleTypeDef *husart, uint8_t *pRxData, uint16_t Size, uint32_t Timeout) +{ + uint16_t* tmp; + uint16_t uhMask; + + if(husart->State == HAL_USART_STATE_READY) + { + if((pRxData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + /* Process Locked */ + __HAL_LOCK(husart); + + husart->ErrorCode = HAL_USART_ERROR_NONE; + husart->State = HAL_USART_STATE_BUSY_RX; + + husart->RxXferSize = Size; + husart->RxXferCount = Size; + + /* Computation of USART mask to apply to RDR register */ + __HAL_USART_MASK_COMPUTATION(husart); + uhMask = husart->Mask; + + /* as long as data have to be received */ + while(husart->RxXferCount > 0) + { + husart->RxXferCount--; + + /* Wait until TC flag is set to send dummy byte in order to generate the + * clock for the slave to send data. + * Whatever the frame length (7, 8 or 9-bit long), the same dummy value + * can be written for all the cases. */ + if(USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_TC, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + husart->Instance->TDR = (DUMMY_DATA & (uint16_t)0x0FF); + + /* Wait for RXNE Flag */ + if(USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_RXNE, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + if((husart->Init.WordLength == USART_WORDLENGTH_9B) && (husart->Init.Parity == USART_PARITY_NONE)) + { + tmp = (uint16_t*) pRxData ; + *tmp = (uint16_t)(husart->Instance->RDR & uhMask); + pRxData +=2; + } + else + { + *pRxData++ = (uint8_t)(husart->Instance->RDR & (uint8_t)uhMask); + } + } + + husart->State = HAL_USART_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(husart); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Full-Duplex Send and Receive an amount of data in blocking mode + * @param husart: USART handle + * @param pTxData: pointer to TX data buffer + * @param pRxData: pointer to RX data buffer + * @param Size: amount of data to be sent (same amount to be received) + * @param Timeout : Timeout duration + * @retval HAL status + */ +HAL_StatusTypeDef HAL_USART_TransmitReceive(USART_HandleTypeDef *husart, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size, uint32_t Timeout) +{ + uint16_t* tmp; + uint16_t uhMask; + + if(husart->State == HAL_USART_STATE_READY) + { + if((pTxData == NULL) || (pRxData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + /* Process Locked */ + __HAL_LOCK(husart); + + husart->ErrorCode = HAL_USART_ERROR_NONE; + husart->State = HAL_USART_STATE_BUSY_RX; + + husart->RxXferSize = Size; + husart->TxXferSize = Size; + husart->TxXferCount = Size; + husart->RxXferCount = Size; + + /* Computation of USART mask to apply to RDR register */ + __HAL_USART_MASK_COMPUTATION(husart); + uhMask = husart->Mask; + + /* Check the remain data to be sent */ + while(husart->TxXferCount > 0) + { + husart->TxXferCount--; + husart->RxXferCount--; + + /* Wait until TC flag is set to send data */ + if(USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_TC, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + if((husart->Init.WordLength == USART_WORDLENGTH_9B) && (husart->Init.Parity == USART_PARITY_NONE)) + { + tmp = (uint16_t*) pTxData; + husart->Instance->TDR = (*tmp & uhMask); + pTxData += 2; + } + else + { + husart->Instance->TDR = (*pTxData++ & (uint8_t)uhMask); + } + + /* Wait for RXNE Flag */ + if(USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_RXNE, RESET, Timeout) != HAL_OK) + { + return HAL_TIMEOUT; + } + + if((husart->Init.WordLength == USART_WORDLENGTH_9B) && (husart->Init.Parity == USART_PARITY_NONE)) + { + tmp = (uint16_t*) pRxData ; + *tmp = (uint16_t)(husart->Instance->RDR & uhMask); + pRxData +=2; + } + else + { + *pRxData++ = (uint8_t)(husart->Instance->RDR & (uint8_t)uhMask); + } + } + + husart->State = HAL_USART_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(husart); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Send an amount of data in interrupt mode + * @param husart: USART handle + * @param pTxData: Pointer to data buffer + * @param Size: Amount of data to be sent + * @retval HAL status + */ +HAL_StatusTypeDef HAL_USART_Transmit_IT(USART_HandleTypeDef *husart, uint8_t *pTxData, uint16_t Size) +{ + if(husart->State == HAL_USART_STATE_READY) + { + if((pTxData == NULL ) || (Size == 0)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(husart); + + husart->pTxBuffPtr = pTxData; + husart->TxXferSize = Size; + husart->TxXferCount = Size; + + husart->ErrorCode = HAL_USART_ERROR_NONE; + husart->State = HAL_USART_STATE_BUSY_TX; + + /* The USART Error Interrupts: (Frame error, noise error, overrun error) + are not managed by the USART Transmit Process to avoid the overrun interrupt + when the usart mode is configured for transmit and receive "USART_MODE_TX_RX" + to benefit for the frame error and noise interrupts the usart mode should be + configured only for transmit "USART_MODE_TX" */ + + /* Process Unlocked */ + __HAL_UNLOCK(husart); + + /* Enable the USART Transmit Complete Interrupt */ + __HAL_USART_ENABLE_IT(husart, USART_IT_TC); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive an amount of data in blocking mode + * To receive synchronous data, dummy data are simultaneously transmitted + * @param husart: usart handle + * @param pRxData: pointer to data buffer + * @param Size: amount of data to be received + * @retval HAL status + */ +HAL_StatusTypeDef HAL_USART_Receive_IT(USART_HandleTypeDef *husart, uint8_t *pRxData, uint16_t Size) +{ + if(husart->State == HAL_USART_STATE_READY) + { + if((pRxData == NULL ) || (Size == 0)) + { + return HAL_ERROR; + } + /* Process Locked */ + __HAL_LOCK(husart); + + husart->pRxBuffPtr = pRxData; + husart->RxXferSize = Size; + husart->RxXferCount = Size; + + __HAL_USART_MASK_COMPUTATION(husart); + + husart->ErrorCode = HAL_USART_ERROR_NONE; + husart->State = HAL_USART_STATE_BUSY_RX; + + /* Enable the USART Parity Error Interrupt */ + __HAL_USART_ENABLE_IT(husart, USART_IT_PE); + + /* Enable the USART Error Interrupt: (Frame error, noise error, overrun error) */ + __HAL_USART_ENABLE_IT(husart, USART_IT_ERR); + + /* Enable the USART Data Register not empty Interrupt */ + __HAL_USART_ENABLE_IT(husart, USART_IT_RXNE); + + /* Process Unlocked */ + __HAL_UNLOCK(husart); + + /* Send dummy byte in order to generate the clock for the Slave to send the next data */ + if(husart->Init.WordLength == USART_WORDLENGTH_9B) + { + husart->Instance->TDR = (DUMMY_DATA & (uint16_t)0x01FF); + } + else + { + husart->Instance->TDR = (DUMMY_DATA & (uint16_t)0x00FF); + } + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Full-Duplex Send and Receive an amount of data in interrupt mode + * @param husart: USART handle + * @param pTxData: pointer to TX data buffer + * @param pRxData: pointer to RX data buffer + * @param Size: amount of data to be sent (same amount to be received) + * @retval HAL status + */ +HAL_StatusTypeDef HAL_USART_TransmitReceive_IT(USART_HandleTypeDef *husart, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size) +{ + if(husart->State == HAL_USART_STATE_READY) + { + if((pTxData == NULL) || (pRxData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + /* Process Locked */ + __HAL_LOCK(husart); + + husart->pRxBuffPtr = pRxData; + husart->RxXferSize = Size; + husart->RxXferCount = Size; + husart->pTxBuffPtr = pTxData; + husart->TxXferSize = Size; + husart->TxXferCount = Size; + + /* Computation of USART mask to apply to RDR register */ + __HAL_USART_MASK_COMPUTATION(husart); + + husart->ErrorCode = HAL_USART_ERROR_NONE; + husart->State = HAL_USART_STATE_BUSY_TX_RX; + + /* Enable the USART Data Register not empty Interrupt */ + __HAL_USART_ENABLE_IT(husart, USART_IT_RXNE); + + /* Enable the USART Parity Error Interrupt */ + __HAL_USART_ENABLE_IT(husart, USART_IT_PE); + + /* Enable the USART Error Interrupt: (Frame error, noise error, overrun error) */ + __HAL_USART_ENABLE_IT(husart, USART_IT_ERR); + + /* Process Unlocked */ + __HAL_UNLOCK(husart); + + /* Enable the USART Transmit Complete Interrupt */ + __HAL_USART_ENABLE_IT(husart, USART_IT_TC); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Send an amount of data in DMA mode + * @param husart: USART handle + * @param pTxData: pointer to data buffer + * @param Size: amount of data to be sent + * @retval HAL status + */ +HAL_StatusTypeDef HAL_USART_Transmit_DMA(USART_HandleTypeDef *husart, uint8_t *pTxData, uint16_t Size) +{ + uint32_t *tmp; + + if(husart->State == HAL_USART_STATE_READY) + { + if((pTxData == NULL ) || (Size == 0)) + { + return HAL_ERROR; + } + /* Process Locked */ + __HAL_LOCK(husart); + + husart->pTxBuffPtr = pTxData; + husart->TxXferSize = Size; + husart->TxXferCount = Size; + + husart->ErrorCode = HAL_USART_ERROR_NONE; + husart->State = HAL_USART_STATE_BUSY_TX; + + /* Set the USART DMA transfer complete callback */ + husart->hdmatx->XferCpltCallback = USART_DMATransmitCplt; + + /* Set the USART DMA Half transfer complete callback */ + husart->hdmatx->XferHalfCpltCallback = USART_DMATxHalfCplt; + + /* Set the DMA error callback */ + husart->hdmatx->XferErrorCallback = USART_DMAError; + + /* Enable the USART transmit DMA Stream */ + tmp = (uint32_t*)&pTxData; + HAL_DMA_Start_IT(husart->hdmatx, *(uint32_t*)tmp, (uint32_t)&husart->Instance->TDR, Size); + + /* Enable the DMA transfer for transmit request by setting the DMAT bit + in the USART CR3 register */ + husart->Instance->CR3 |= USART_CR3_DMAT; + + /* Process Unlocked */ + __HAL_UNLOCK(husart); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Receive an amount of data in DMA mode + * @param husart: USART handle + * @param pRxData: pointer to data buffer + * @param Size: amount of data to be received + * @note When the USART parity is enabled (PCE = 1), the received data contain + * the parity bit (MSB position) + * @retval HAL status + * @note The USART DMA transmit stream must be configured in order to generate the clock for the slave. + */ +HAL_StatusTypeDef HAL_USART_Receive_DMA(USART_HandleTypeDef *husart, uint8_t *pRxData, uint16_t Size) +{ + uint32_t *tmp; + + if(husart->State == HAL_USART_STATE_READY) + { + if((pRxData == NULL ) || (Size == 0)) + { + return HAL_ERROR; + } + + /* Process Locked */ + __HAL_LOCK(husart); + + husart->pRxBuffPtr = pRxData; + husart->RxXferSize = Size; + husart->pTxBuffPtr = pRxData; + husart->TxXferSize = Size; + + husart->ErrorCode = HAL_USART_ERROR_NONE; + husart->State = HAL_USART_STATE_BUSY_RX; + + /* Set the USART DMA Rx transfer complete callback */ + husart->hdmarx->XferCpltCallback = USART_DMAReceiveCplt; + + /* Set the USART DMA Half transfer complete callback */ + husart->hdmarx->XferHalfCpltCallback = USART_DMARxHalfCplt; + + /* Set the USART DMA Rx transfer error callback */ + husart->hdmarx->XferErrorCallback = USART_DMAError; + + /* Enable the USART receive DMA Stream */ + tmp = (uint32_t*)&pRxData; + HAL_DMA_Start_IT(husart->hdmarx, (uint32_t)&husart->Instance->RDR, *(uint32_t*)tmp, Size); + + /* Enable the USART transmit DMA Stream: the transmit stream is used in order + to generate in the non-blocking mode the clock to the slave device, + this mode isn't a simplex receive mode but a full-duplex receive mode */ + tmp = (uint32_t*)&pRxData; + HAL_DMA_Start_IT(husart->hdmatx, *(uint32_t*)tmp, (uint32_t)&husart->Instance->TDR, Size); + + /* Enable the DMA transfer for the receiver request by setting the DMAR bit + in the USART CR3 register */ + husart->Instance->CR3 |= USART_CR3_DMAR; + + /* Enable the DMA transfer for transmit request by setting the DMAT bit + in the USART CR3 register */ + husart->Instance->CR3 |= USART_CR3_DMAT; + + /* Process Unlocked */ + __HAL_UNLOCK(husart); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Full-Duplex Transmit Receive an amount of data in non blocking mode + * @param husart: usart handle + * @param pTxData: pointer to TX data buffer + * @param pRxData: pointer to RX data buffer + * @param Size: amount of data to be received/sent + * @note When the USART parity is enabled (PCE = 1) the data received contain the parity bit. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_USART_TransmitReceive_DMA(USART_HandleTypeDef *husart, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size) +{ + uint32_t *tmp; + + if(husart->State == HAL_USART_STATE_READY) + { + if((pTxData == NULL) || (pRxData == NULL) || (Size == 0)) + { + return HAL_ERROR; + } + /* Process Locked */ + __HAL_LOCK(husart); + + husart->pRxBuffPtr = pRxData; + husart->RxXferSize = Size; + husart->pTxBuffPtr = pTxData; + husart->TxXferSize = Size; + + husart->ErrorCode = HAL_USART_ERROR_NONE; + husart->State = HAL_USART_STATE_BUSY_TX_RX; + + /* Set the USART DMA Rx transfer complete callback */ + husart->hdmarx->XferCpltCallback = USART_DMAReceiveCplt; + + /* Set the USART DMA Half transfer complete callback */ + husart->hdmarx->XferHalfCpltCallback = USART_DMARxHalfCplt; + + /* Set the USART DMA Tx transfer complete callback */ + husart->hdmatx->XferCpltCallback = USART_DMATransmitCplt; + + /* Set the USART DMA Half transfer complete callback */ + husart->hdmatx->XferHalfCpltCallback = USART_DMATxHalfCplt; + + /* Set the USART DMA Tx transfer error callback */ + husart->hdmatx->XferErrorCallback = USART_DMAError; + + /* Set the USART DMA Rx transfer error callback */ + husart->hdmarx->XferErrorCallback = USART_DMAError; + + /* Enable the USART receive DMA Stream */ + tmp = (uint32_t*)&pRxData; + HAL_DMA_Start_IT(husart->hdmarx, (uint32_t)&husart->Instance->RDR, *(uint32_t*)tmp, Size); + + /* Enable the USART transmit DMA Stream */ + tmp = (uint32_t*)&pTxData; + HAL_DMA_Start_IT(husart->hdmatx, *(uint32_t*)tmp, (uint32_t)&husart->Instance->TDR, Size); + + /* Enable the DMA transfer for the receiver request by setting the DMAR bit + in the USART CR3 register */ + husart->Instance->CR3 |= USART_CR3_DMAR; + + /* Enable the DMA transfer for transmit request by setting the DMAT bit + in the USART CR3 register */ + husart->Instance->CR3 |= USART_CR3_DMAT; + + /* Process Unlocked */ + __HAL_UNLOCK(husart); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Pauses the DMA Transfer. + * @param husart: USART handle + * @retval None + */ +HAL_StatusTypeDef HAL_USART_DMAPause(USART_HandleTypeDef *husart) +{ + /* Process Locked */ + __HAL_LOCK(husart); + + if(husart->State == HAL_USART_STATE_BUSY_TX) + { + /* Disable the USART DMA Tx request */ + husart->Instance->CR3 &= (uint32_t)(~USART_CR3_DMAT); + } + else if(husart->State == HAL_USART_STATE_BUSY_RX) + { + /* Disable the USART DMA Rx request */ + husart->Instance->CR3 &= (uint32_t)(~USART_CR3_DMAR); + } + else if(husart->State == HAL_USART_STATE_BUSY_TX_RX) + { + /* Disable the USART DMA Tx request */ + husart->Instance->CR3 &= (uint32_t)(~USART_CR3_DMAT); + /* Disable the USART DMA Rx request */ + husart->Instance->CR3 &= (uint32_t)(~USART_CR3_DMAR); + } + + /* Process Unlocked */ + __HAL_UNLOCK(husart); + + return HAL_OK; +} + +/** + * @brief Resumes the DMA Transfer. + * @param husart: USART handle + * @retval None + */ +HAL_StatusTypeDef HAL_USART_DMAResume(USART_HandleTypeDef *husart) +{ + /* Process Locked */ + __HAL_LOCK(husart); + + if(husart->State == HAL_USART_STATE_BUSY_TX) + { + /* Enable the USART DMA Tx request */ + husart->Instance->CR3 |= USART_CR3_DMAT; + } + else if(husart->State == HAL_USART_STATE_BUSY_RX) + { + /* Enable the USART DMA Rx request */ + husart->Instance->CR3 |= USART_CR3_DMAR; + } + else if(husart->State == HAL_USART_STATE_BUSY_TX_RX) + { + /* Enable the USART DMA Rx request before the DMA Tx request */ + husart->Instance->CR3 |= USART_CR3_DMAR; + /* Enable the USART DMA Tx request */ + husart->Instance->CR3 |= USART_CR3_DMAT; + } + + /* If the USART peripheral is still not enabled, enable it */ + if((husart->Instance->CR1 & USART_CR1_UE) == 0) + { + /* Enable USART peripheral */ + __HAL_USART_ENABLE(husart); + } + + /* Process Unlocked */ + __HAL_UNLOCK(husart); + + return HAL_OK; +} + +/** + * @brief Stops the DMA Transfer. + * @param husart: USART handle + * @retval None + */ +HAL_StatusTypeDef HAL_USART_DMAStop(USART_HandleTypeDef *husart) +{ + /* Process Locked */ + __HAL_LOCK(husart); + + /* Disable the USART Tx/Rx DMA requests */ + husart->Instance->CR3 &= ~USART_CR3_DMAT; + husart->Instance->CR3 &= ~USART_CR3_DMAR; + + /* Abort the USART DMA tx Stream */ + if(husart->hdmatx != NULL) + { + HAL_DMA_Abort(husart->hdmatx); + } + /* Abort the USART DMA rx Stream */ + if(husart->hdmarx != NULL) + { + HAL_DMA_Abort(husart->hdmarx); + } + + /* Disable USART peripheral */ + __HAL_USART_DISABLE(husart); + + husart->State = HAL_USART_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(husart); + + return HAL_OK; +} + +/** + * @brief This function handles USART interrupt request. + * @param husart: USART handle + * @retval None + */ +void HAL_USART_IRQHandler(USART_HandleTypeDef *husart) +{ + + /* USART parity error interrupt occured ------------------------------------*/ + if((__HAL_USART_GET_IT(husart, USART_IT_PE) != RESET) && (__HAL_USART_GET_IT_SOURCE(husart, USART_IT_PE) != RESET)) + { + __HAL_USART_CLEAR_IT(husart, USART_IT_PE); + husart->ErrorCode |= HAL_USART_ERROR_PE; + /* Set the USART state ready to be able to start again the process */ + husart->State = HAL_USART_STATE_READY; + } + + /* USART frame error interrupt occured -------------------------------------*/ + if((__HAL_USART_GET_IT(husart, USART_IT_FE) != RESET) && (__HAL_USART_GET_IT_SOURCE(husart, USART_IT_ERR) != RESET)) + { + __HAL_USART_CLEAR_IT(husart, USART_IT_FE); + husart->ErrorCode |= HAL_USART_ERROR_FE; + /* Set the USART state ready to be able to start again the process */ + husart->State = HAL_USART_STATE_READY; + } + + /* USART noise error interrupt occured -------------------------------------*/ + if((__HAL_USART_GET_IT(husart, USART_IT_NE) != RESET) && (__HAL_USART_GET_IT_SOURCE(husart, USART_IT_ERR) != RESET)) + { + __HAL_USART_CLEAR_IT(husart, USART_IT_NE); + husart->ErrorCode |= HAL_USART_ERROR_NE; + /* Set the USART state ready to be able to start again the process */ + husart->State = HAL_USART_STATE_READY; + } + + /* USART Over-Run interrupt occured ----------------------------------------*/ + if((__HAL_USART_GET_IT(husart, USART_IT_ORE) != RESET) && (__HAL_USART_GET_IT_SOURCE(husart, USART_IT_ERR) != RESET)) + { + __HAL_USART_CLEAR_IT(husart, USART_IT_ORE); + husart->ErrorCode |= HAL_USART_ERROR_ORE; + /* Set the USART state ready to be able to start again the process */ + husart->State = HAL_USART_STATE_READY; + } + + /* Call USART Error Call back function if need be --------------------------*/ + if(husart->ErrorCode != HAL_USART_ERROR_NONE) + { + HAL_USART_ErrorCallback(husart); + } + + /* USART in mode Receiver --------------------------------------------------*/ + if((__HAL_USART_GET_IT(husart, USART_IT_RXNE) != RESET) && (__HAL_USART_GET_IT_SOURCE(husart, USART_IT_RXNE) != RESET)) + { + if(husart->State == HAL_USART_STATE_BUSY_RX) + { + USART_Receive_IT(husart); + } + else + { + USART_TransmitReceive_IT(husart); + } + } + + /* USART in mode Transmitter -----------------------------------------------*/ + if((__HAL_USART_GET_IT(husart, USART_IT_TC) != RESET) &&(__HAL_USART_GET_IT_SOURCE(husart, USART_IT_TC) != RESET)) + { + if(husart->State == HAL_USART_STATE_BUSY_TX) + { + USART_Transmit_IT(husart); + } + else + { + USART_TransmitReceive_IT(husart); + } + } +} + +/** + * @brief This function handles USART Communication Timeout. + * @param husart: USART handle + * @param Flag: specifies the USART flag to check. + * @param Status: The new Flag status (SET or RESET). + * @param Timeout: Timeout duration + * @retval HAL status + */ +static HAL_StatusTypeDef USART_WaitOnFlagUntilTimeout(USART_HandleTypeDef *husart, uint32_t Flag, FlagStatus Status, uint32_t Timeout) +{ + uint32_t tickstart = 0x00; + tickstart = HAL_GetTick(); + + /* Wait until flag is set */ + if(Status == RESET) + { + while(__HAL_USART_GET_FLAG(husart, Flag) == RESET) + { + /* Check for the Timeout */ + if(Timeout != HAL_MAX_DELAY) + { + if((HAL_GetTick() - tickstart ) > Timeout) + { + /* Disable TXE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts for the interrupt process */ + __HAL_USART_DISABLE_IT(husart, USART_IT_TXE); + __HAL_USART_DISABLE_IT(husart, USART_IT_RXNE); + __HAL_USART_DISABLE_IT(husart, USART_IT_PE); + __HAL_USART_DISABLE_IT(husart, USART_IT_ERR); + + husart->State= HAL_USART_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(husart); + + return HAL_TIMEOUT; + } + } + } + } + else + { + while(__HAL_USART_GET_FLAG(husart, Flag) != RESET) + { + /* Check for the Timeout */ + if(Timeout != HAL_MAX_DELAY) + { + if((HAL_GetTick() - tickstart ) > Timeout) + { + /* Disable TXE, RXNE, PE and ERR (Frame error, noise error, overrun error) interrupts for the interrupt process */ + __HAL_USART_DISABLE_IT(husart, USART_IT_TXE); + __HAL_USART_DISABLE_IT(husart, USART_IT_RXNE); + __HAL_USART_DISABLE_IT(husart, USART_IT_PE); + __HAL_USART_DISABLE_IT(husart, USART_IT_ERR); + + husart->State= HAL_USART_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(husart); + + return HAL_TIMEOUT; + } + } + } + } + return HAL_OK; +} + +/** + * @brief DMA USART transmit process complete callback. + * @param hdma: DMA handle + * @retval None + */ +static void USART_DMATransmitCplt(DMA_HandleTypeDef *hdma) +{ + USART_HandleTypeDef* husart = ( USART_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + + husart->TxXferCount = 0; + if(husart->State == HAL_USART_STATE_BUSY_TX) + { + /* Wait for USART TC Flag */ + if(USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_TC, RESET, HAL_USART_TXDMA_TIMEOUTVALUE) != HAL_OK) + { + /* Timeout Occured */ + husart->State = HAL_USART_STATE_TIMEOUT; + HAL_USART_ErrorCallback(husart); + } + else + { + /* No Timeout */ + /* Disable the DMA transfer for transmit request by setting the DMAT bit + in the USART CR3 register */ + husart->Instance->CR3 &= ~(USART_CR3_DMAT); + husart->State= HAL_USART_STATE_READY; + } + } + /* the usart state is HAL_USART_STATE_BUSY_TX_RX*/ + else + { + husart->State= HAL_USART_STATE_BUSY_RX; + HAL_USART_TxCpltCallback(husart); + } +} + +/** + * @brief DMA USART transmit process half complete callback + * @param hdma : DMA handle + * @retval None + */ +static void USART_DMATxHalfCplt(DMA_HandleTypeDef *hdma) +{ + USART_HandleTypeDef* husart = (USART_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent; + + HAL_USART_TxHalfCpltCallback(husart); +} + +/** + * @brief DMA USART receive process complete callback. + * @param hdma: DMA handle + * @retval None + */ +static void USART_DMAReceiveCplt(DMA_HandleTypeDef *hdma) +{ + USART_HandleTypeDef* husart = ( USART_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + + husart->RxXferCount = 0; + + /* Disable the DMA RX transfer for the Transmit/receiver request by resetting the DMAR bit + in USART CR3 register */ + husart->Instance->CR3 &= (uint32_t)~((uint32_t)USART_CR3_DMAR); + /* similarly, disable the DMA TX transfer that was started to provide the + clock to the slave device */ + husart->Instance->CR3 &= (uint32_t)~((uint32_t)USART_CR3_DMAT); + + husart->State= HAL_USART_STATE_READY; + + HAL_USART_RxCpltCallback(husart); +} + +/** + * @brief DMA USART receive process half complete callback + * @param hdma : DMA handle + * @retval None + */ +static void USART_DMARxHalfCplt(DMA_HandleTypeDef *hdma) +{ + USART_HandleTypeDef* husart = (USART_HandleTypeDef*)((DMA_HandleTypeDef*)hdma)->Parent; + + HAL_USART_RxHalfCpltCallback(husart); +} + +/** + * @brief DMA USART communication error callback. + * @param hdma: DMA handle + * @retval None + */ +static void USART_DMAError(DMA_HandleTypeDef *hdma) +{ + USART_HandleTypeDef* husart = ( USART_HandleTypeDef* )((DMA_HandleTypeDef* )hdma)->Parent; + + husart->RxXferCount = 0; + husart->TxXferCount = 0; + husart->ErrorCode |= HAL_USART_ERROR_DMA; + husart->State= HAL_USART_STATE_READY; + + HAL_USART_ErrorCallback(husart); +} + +/** + * @brief Tx Transfer completed callbacks. + * @param husart: USART handle + * @retval None + */ + __weak void HAL_USART_TxCpltCallback(USART_HandleTypeDef *husart) +{ + /* NOTE: This function Should not be modified, when the callback is needed, + the HAL_USART_TxCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Tx Half Transfer completed callbacks. + * @param husart: USART handle + * @retval None + */ + __weak void HAL_USART_TxHalfCpltCallback(USART_HandleTypeDef *husart) +{ + /* NOTE: This function Should not be modified, when the callback is needed, + the HAL_USART_TxCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Rx Transfer completed callbacks. + * @param husart: USART handle + * @retval None + */ +__weak void HAL_USART_RxCpltCallback(USART_HandleTypeDef *husart) +{ + /* NOTE: This function Should not be modified, when the callback is needed, + the HAL_USART_TxCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Rx Half Transfer completed callbacks. + * @param husart: USART handle + * @retval None + */ +__weak void HAL_USART_RxHalfCpltCallback(USART_HandleTypeDef *husart) +{ + /* NOTE: This function Should not be modified, when the callback is needed, + the HAL_USART_TxCpltCallback could be implemented in the user file + */ +} + +/** + * @brief Tx/Rx Transfers completed callback for the non-blocking process. + * @param husart: USART handle + * @retval None + */ +__weak void HAL_USART_TxRxCpltCallback(USART_HandleTypeDef *husart) +{ + /* NOTE: This function Should not be modified, when the callback is needed, + the HAL_USART_TxCpltCallback could be implemented in the user file + */ +} + +/** + * @brief USART error callbacks. + * @param husart: USART handle + * @retval None + */ + __weak void HAL_USART_ErrorCallback(USART_HandleTypeDef *husart) +{ + /* NOTE: This function Should not be modified, when the callback is needed, + the HAL_USART_ErrorCallback could be implemented in the user file + */ +} + +/** + * @brief Simplex Send an amount of data in non-blocking mode. + * Function called under interruption only, once + * interruptions have been enabled by HAL_USART_Transmit_IT() + * @param husart: USART handle + * @retval HAL status + * @note The USART errors are not managed to avoid the overrun error. + */ +static HAL_StatusTypeDef USART_Transmit_IT(USART_HandleTypeDef *husart) +{ + uint16_t* tmp; + + if(husart->State == HAL_USART_STATE_BUSY_TX) + { + /* Process Locked */ + __HAL_LOCK(husart); + + if(husart->TxXferCount == 0) + { + /* Disable the USART Transmit Complete Interrupt */ + __HAL_USART_DISABLE_IT(husart, USART_IT_TC); + + /* Disable the USART Error Interrupt: (Frame error, noise error, overrun error) */ + __HAL_USART_DISABLE_IT(husart, USART_IT_ERR); + + husart->State = HAL_USART_STATE_READY; + + /* Call the Process Unlocked before calling the Tx call back API to give the possibiity to + start again the Transmission under the Tx call back API */ + __HAL_UNLOCK(husart); + + HAL_USART_TxCpltCallback(husart); + + return HAL_OK; + } + else + { + if((husart->Init.WordLength == USART_WORDLENGTH_9B) && (husart->Init.Parity == USART_PARITY_NONE)) + { + tmp = (uint16_t*) husart->pTxBuffPtr; + husart->Instance->TDR = (*tmp & (uint16_t)0x01FF); + husart->pTxBuffPtr += 2; + } + else + { + husart->Instance->TDR = (uint8_t)(*husart->pTxBuffPtr++ & (uint8_t)0xFF); + } + husart->TxXferCount--; + + /* Process Unlocked */ + __HAL_UNLOCK(husart); + + return HAL_OK; + } + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Simplex Receive an amount of data in non-blocking mode. + * Function called under interruption only, once + * interruptions have been enabled by HAL_USART_Receive_IT() + * @param husart: USART handle + * @retval HAL status + */ +static HAL_StatusTypeDef USART_Receive_IT(USART_HandleTypeDef *husart) +{ + uint16_t* tmp; + uint16_t uhMask = husart->Mask; + + if(husart->State == HAL_USART_STATE_BUSY_RX) + { + /* Process Locked */ + __HAL_LOCK(husart); + + if((husart->Init.WordLength == USART_WORDLENGTH_9B) && (husart->Init.Parity == USART_PARITY_NONE)) + { + tmp = (uint16_t*) husart->pRxBuffPtr; + *tmp = (uint16_t)(husart->Instance->RDR & uhMask); + husart->pRxBuffPtr += 2; + } + else + { + *husart->pRxBuffPtr++ = (uint8_t)(husart->Instance->RDR & (uint8_t)uhMask); + } + /* Send dummy byte in order to generate the clock for the Slave to Send the next data */ + husart->Instance->TDR = (DUMMY_DATA & (uint16_t)0x00FF); + + if(--husart->RxXferCount == 0) + { + /* Wait for RXNE Flag */ + if(USART_WaitOnFlagUntilTimeout(husart, USART_FLAG_RXNE, RESET, HAL_USART_TXDMA_TIMEOUTVALUE) != HAL_OK) + { + return HAL_TIMEOUT; + } + + __HAL_USART_DISABLE_IT(husart, USART_IT_RXNE); + + /* Disable the USART Parity Error Interrupt */ + __HAL_USART_DISABLE_IT(husart, USART_IT_PE); + + /* Disable the USART Error Interrupt: (Frame error, noise error, overrun error) */ + __HAL_USART_DISABLE_IT(husart, USART_IT_ERR); + + husart->State = HAL_USART_STATE_READY; + + /* Call the Process Unlocked before calling the Rx call back API to give the possibility to + start again the reception under the Rx call back API */ + __HAL_UNLOCK(husart); + + HAL_USART_RxCpltCallback(husart); + + return HAL_OK; + } + + /* Process Unlocked */ + __HAL_UNLOCK(husart); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @brief Full-Duplex Send receive an amount of data in full-duplex mode (non-blocking). + * Function called under interruption only, once + * interruptions have been enabled by HAL_USART_TransmitReceive_IT() + * @param husart: USART handle + * @retval HAL status + */ +static HAL_StatusTypeDef USART_TransmitReceive_IT(USART_HandleTypeDef *husart) +{ + uint16_t* tmp; + uint16_t uhMask = husart->Mask; + + if(husart->State == HAL_USART_STATE_BUSY_TX_RX) + { + /* Process Locked */ + __HAL_LOCK(husart); + if(husart->TxXferCount != 0x00) + { + if(__HAL_USART_GET_FLAG(husart, USART_FLAG_TC) != RESET) + { + if((husart->Init.WordLength == USART_WORDLENGTH_9B) && (husart->Init.Parity == USART_PARITY_NONE)) + { + tmp = (uint16_t*) husart->pTxBuffPtr; + husart->Instance->TDR = (uint16_t)(*tmp & uhMask); + husart->pTxBuffPtr += 2; + } + else + { + husart->Instance->TDR = (uint8_t)(*husart->pTxBuffPtr++ & (uint8_t)uhMask); + } + husart->TxXferCount--; + + /* Check the latest data transmitted */ + if(husart->TxXferCount == 0) + { + __HAL_USART_DISABLE_IT(husart, USART_IT_TC); + } + } + } + + if(husart->RxXferCount != 0x00) + { + if(__HAL_USART_GET_FLAG(husart, USART_FLAG_RXNE) != RESET) + { + if((husart->Init.WordLength == USART_WORDLENGTH_9B) && (husart->Init.Parity == USART_PARITY_NONE)) + { + tmp = (uint16_t*) husart->pRxBuffPtr; + *tmp = (uint16_t)(husart->Instance->RDR & uhMask); + husart->pRxBuffPtr += 2; + } + else + { + *husart->pRxBuffPtr++ = (uint8_t)(husart->Instance->RDR & (uint8_t)uhMask); + } + husart->RxXferCount--; + } + } + + /* Check the latest data received */ + if(husart->RxXferCount == 0) + { + __HAL_USART_DISABLE_IT(husart, USART_IT_RXNE); + + /* Disable the USART Parity Error Interrupt */ + __HAL_USART_DISABLE_IT(husart, USART_IT_PE); + + /* Disable the USART Error Interrupt: (Frame error, noise error, overrun error) */ + __HAL_USART_DISABLE_IT(husart, USART_IT_ERR); + + husart->State = HAL_USART_STATE_READY; + + /* Call the Process Unlocked before calling the Tx\Rx call back API to give the possibility to + start again the Transmission\reception under the Tx\Rx call back API */ + __HAL_UNLOCK(husart); + + HAL_USART_TxRxCpltCallback(husart); + + return HAL_OK; + } + + /* Process Unlocked */ + __HAL_UNLOCK(husart); + + return HAL_OK; + } + else + { + return HAL_BUSY; + } +} + +/** + * @} + */ + +/** @defgroup HAL_USART_Group3 Peripheral State functions + * @brief USART State functions + * +@verbatim + =============================================================================== + ##### Peripheral State functions ##### + =============================================================================== + [..] + This subsection provides a set of functions allowing to control the USART. + (+) HAL_USART_GetState() API can be helpful to check in run-time the state of the USART peripheral. + (+) HAL_USART_GetError() API can be helpful to check in run-time the Error Code of the USART peripheral. + (+) USART_SetConfig() API is used to set the USART communication parameters. + (+) USART_CheckIdleState() APi ensures that TEACK and/or REACK bits are set after initialization + +@endverbatim + * @{ + */ + +/** + * @brief Returns the USART state. + * @param husart: USART handle + * @retval HAL state + */ +HAL_USART_StateTypeDef HAL_USART_GetState(USART_HandleTypeDef *husart) +{ + return husart->State; +} + +/** + * @brief Return the USART error code + * @param husart : pointer to a USART_HandleTypeDef structure that contains + * the configuration information for the specified USART. + * @retval USART Error Code + */ +uint32_t HAL_USART_GetError(USART_HandleTypeDef *husart) +{ + return husart->ErrorCode; +} + +/** + * @brief Configure the USART peripheral + * @param husart: USART handle + * @retval None + */ +static void USART_SetConfig(USART_HandleTypeDef *husart) +{ + uint32_t tmpreg = 0x0; + uint32_t clocksource = 0x0; + + /* Check the parameters */ + assert_param(IS_USART_INSTANCE(husart->Instance)); + assert_param(IS_USART_POLARITY(husart->Init.CLKPolarity)); + assert_param(IS_USART_PHASE(husart->Init.CLKPhase)); + assert_param(IS_USART_LASTBIT(husart->Init.CLKLastBit)); + assert_param(IS_USART_BAUDRATE(husart->Init.BaudRate)); + assert_param(IS_USART_WORD_LENGTH(husart->Init.WordLength)); + assert_param(IS_USART_STOPBITS(husart->Init.StopBits)); + assert_param(IS_USART_PARITY(husart->Init.Parity)); + assert_param(IS_USART_MODE(husart->Init.Mode)); + + /*-------------------------- USART CR1 Configuration -----------------------*/ + /* Clear M, PCE, PS, TE and RE bits and configure + * the USART Word Length, Parity, Mode and oversampling: + * set the M bits according to husart->Init.WordLength value + * set PCE and PS bits according to husart->Init.Parity value + * set TE and RE bits according to husart->Init.Mode value */ + tmpreg = (uint32_t)husart->Init.WordLength | husart->Init.Parity | husart->Init.Mode ; + MODIFY_REG(husart->Instance->CR1, USART_CR1_FIELDS, tmpreg); + + /*---------------------------- USART CR2 Configuration ---------------------*/ + /* Clear and configure the USART Clock, CPOL, CPHA, LBCL and STOP bits: + * set CPOL bit according to husart->Init.CLKPolarity value + * set CPHA bit according to husart->Init.CLKPhase value + * set LBCL bit according to husart->Init.CLKLastBit value + * set STOP[13:12] bits according to husart->Init.StopBits value */ + tmpreg = (uint32_t)(USART_CLOCK_ENABLED); + tmpreg |= (uint32_t)(husart->Init.CLKPolarity | husart->Init.CLKPhase); + tmpreg |= (uint32_t)(husart->Init.CLKLastBit | husart->Init.StopBits); + MODIFY_REG(husart->Instance->CR2, USART_CR2_FIELDS, tmpreg); + + /*-------------------------- USART CR3 Configuration -----------------------*/ + /* no CR3 register configuration */ + + /*-------------------------- USART BRR Configuration -----------------------*/ + __HAL_USART_GETCLOCKSOURCE(husart, clocksource); + switch (clocksource) + { + case USART_CLOCKSOURCE_PCLK1: + husart->Instance->BRR = (uint16_t)(HAL_RCC_GetPCLK1Freq() / husart->Init.BaudRate); + break; + case USART_CLOCKSOURCE_PCLK2: + husart->Instance->BRR = (uint16_t)(HAL_RCC_GetPCLK2Freq() / husart->Init.BaudRate); + break; + case USART_CLOCKSOURCE_HSI: + husart->Instance->BRR = (uint16_t)(HSI_VALUE / husart->Init.BaudRate); + break; + case USART_CLOCKSOURCE_SYSCLK: + husart->Instance->BRR = (uint16_t)(HAL_RCC_GetSysClockFreq() / husart->Init.BaudRate); + break; + case USART_CLOCKSOURCE_LSE: + husart->Instance->BRR = (uint16_t)(LSE_VALUE / husart->Init.BaudRate); + break; + default: + break; + } +} + +/** + * @brief Check the USART Idle State + * @param husart: USART handle + * @retval HAL status + */ +static HAL_StatusTypeDef USART_CheckIdleState(USART_HandleTypeDef *husart) +{ + /* Initialize the USART ErrorCode */ + husart->ErrorCode = HAL_USART_ERROR_NONE; + + /* Check if the Transmitter is enabled */ + if((husart->Instance->CR1 & USART_CR1_TE) == USART_CR1_TE) + { + /* Wait until TEACK flag is set */ + if(USART_WaitOnFlagUntilTimeout(husart, USART_ISR_TEACK, RESET, TEACK_REACK_TIMEOUT) != HAL_OK) + { + husart->State= HAL_USART_STATE_TIMEOUT; + return HAL_TIMEOUT; + } + } + /* Check if the Receiver is enabled */ + if((husart->Instance->CR1 & USART_CR1_RE) == USART_CR1_RE) + { + /* Wait until REACK flag is set */ + if(USART_WaitOnFlagUntilTimeout(husart, USART_ISR_REACK, RESET, TEACK_REACK_TIMEOUT) != HAL_OK) + { + husart->State= HAL_USART_STATE_TIMEOUT; + return HAL_TIMEOUT; + } + } + + /* Process Unlocked */ + __HAL_UNLOCK(husart); + + /* Initialize the USART state*/ + husart->State= HAL_USART_STATE_READY; + + return HAL_OK; +} + +/** + * @} + */ + +/** + * @} + */ + +#endif /* HAL_USART_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_usart.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_usart.h new file mode 100644 index 0000000000..4b898bde72 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_usart.h @@ -0,0 +1,557 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_usart.h + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief Header file of USART HAL module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32L0xx_HAL_USART_H +#define __STM32L0xx_HAL_USART_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal_def.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @addtogroup USART + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/** + * @brief USART Init Structure definition + */ +typedef struct +{ + uint32_t BaudRate; /*!< This member configures the Usart communication baud rate. + The baud rate is computed using the following formula: + Baud Rate Register = ((PCLKx) / ((huart->Init.BaudRate))) */ + + uint32_t WordLength; /*!< Specifies the number of data bits transmitted or received in a frame. + This parameter can be a value of @ref USART_Word_Length */ + + uint32_t StopBits; /*!< Specifies the number of stop bits transmitted. + This parameter can be a value of @ref USART_Stop_Bits */ + + uint32_t Parity; /*!< Specifies the parity mode. + This parameter can be a value of @ref USART_Parity + @note When parity is enabled, the computed parity is inserted + at the MSB position of the transmitted data (9th bit when + the word length is set to 9 data bits; 8th bit when the + word length is set to 8 data bits). */ + + uint32_t Mode; /*!< Specifies wether the Receive or Transmit mode is enabled or disabled. + This parameter can be a value of @ref USART_Mode */ + + uint32_t CLKPolarity; /*!< Specifies the steady state of the serial clock. + This parameter can be a value of @ref USART_Clock_Polarity */ + + uint32_t CLKPhase; /*!< Specifies the clock transition on which the bit capture is made. + This parameter can be a value of @ref USART_Clock_Phase */ + + uint32_t CLKLastBit; /*!< Specifies whether the clock pulse corresponding to the last transmitted + data bit (MSB) has to be output on the SCLK pin in synchronous mode. + This parameter can be a value of @ref USART_Last_Bit */ +}USART_InitTypeDef; + +/** + * @brief HAL State structures definition + */ +typedef enum +{ + HAL_USART_STATE_RESET = 0x00, /*!< Peripheral Reset state */ + HAL_USART_STATE_READY = 0x01, /*!< Peripheral Initialized and ready for use */ + HAL_USART_STATE_BUSY = 0x02, /*!< an internal process is ongoing */ + HAL_USART_STATE_BUSY_TX = 0x12, /*!< Data Transmission process is ongoing */ + HAL_USART_STATE_BUSY_RX = 0x22, /*!< Data Reception process is ongoing */ + HAL_USART_STATE_BUSY_TX_RX = 0x32, /*!< Data Transmission Reception process is ongoing */ + HAL_USART_STATE_TIMEOUT = 0x03, /*!< Timeout state */ + HAL_USART_STATE_ERROR = 0x04 /*!< Error */ +}HAL_USART_StateTypeDef; + +/** + * @brief HAL USART Error Code structure definition + */ +typedef enum +{ + HAL_USART_ERROR_NONE = 0x00, /*!< No error */ + HAL_USART_ERROR_PE = 0x01, /*!< Parity error */ + HAL_USART_ERROR_NE = 0x02, /*!< Noise error */ + HAL_USART_ERROR_FE = 0x04, /*!< frame error */ + HAL_USART_ERROR_ORE = 0x08, /*!< Overrun error */ + HAL_USART_ERROR_DMA = 0x10 /*!< DMA transfer error */ +}HAL_USART_ErrorTypeDef; + +/** + * @brief USART clock sources definitions + */ +typedef enum +{ + USART_CLOCKSOURCE_PCLK1 = 0x00, /*!< PCLK1 clock source */ + USART_CLOCKSOURCE_PCLK2 = 0x01, /*!< PCLK2 clock source */ + USART_CLOCKSOURCE_HSI = 0x02, /*!< HSI clock source */ + USART_CLOCKSOURCE_SYSCLK = 0x04, /*!< SYSCLK clock source */ + USART_CLOCKSOURCE_LSE = 0x08 /*!< LSE clock source */ +}USART_ClockSourceTypeDef; + + +/** + * @brief HAL USART Error Code structure definition + */ + +/** + * @brief USART handle Structure definition + */ +typedef struct +{ + USART_TypeDef *Instance; /*!< USART registers base address */ + + USART_InitTypeDef Init; /*!< Usart communication parameters */ + + uint8_t *pTxBuffPtr; /*!< Pointer to Usart Tx transfer Buffer */ + + uint16_t TxXferSize; /*!< Usart Tx Transfer size */ + + __IO uint16_t TxXferCount; /*!< Usart Tx Transfer Counter */ + + uint8_t *pRxBuffPtr; /*!< Pointer to Usart Rx transfer Buffer */ + + uint16_t RxXferSize; /*!< Usart Rx Transfer size */ + + __IO uint16_t RxXferCount; /*!< Usart Rx Transfer Counter */ + + uint16_t Mask; /* USART Rx RDR register mask */ + + DMA_HandleTypeDef *hdmatx; /*!< Usart Tx DMA Handle parameters */ + + DMA_HandleTypeDef *hdmarx; /*!< Usart Rx DMA Handle parameters */ + + HAL_LockTypeDef Lock; /*!< Locking object */ + + __IO HAL_USART_StateTypeDef State; /*!< Usart communication state */ + + __IO HAL_USART_ErrorTypeDef ErrorCode; /*!< USART Error code */ + +}USART_HandleTypeDef; + + +/* Exported constants --------------------------------------------------------*/ +/** @defgroup USART_Exported_Constants + * @{ + */ + +/** @defgroup USART_Stop_Bits USART Stop Bits + * @{ + */ +#define USART_STOPBITS_1 ((uint32_t)0x0000) +#define USART_STOPBITS_0_5 ((uint32_t)USART_CR2_STOP_0) +#define USART_STOPBITS_2 ((uint32_t)USART_CR2_STOP_1) +#define USART_STOPBITS_1_5 ((uint32_t)(USART_CR2_STOP_0 | USART_CR2_STOP_1)) +#define IS_USART_STOPBITS(STOPBITS) (((STOPBITS) == USART_STOPBITS_1) || \ + ((STOPBITS) == USART_STOPBITS_0_5) || \ + ((STOPBITS) == USART_STOPBITS_1_5) || \ + ((STOPBITS) == USART_STOPBITS_2)) +/** + * @} + */ + +/** @defgroup USART_Parity USART Parity + * @{ + */ +#define USART_PARITY_NONE ((uint32_t)0x0000) +#define USART_PARITY_EVEN ((uint32_t)USART_CR1_PCE) +#define USART_PARITY_ODD ((uint32_t)(USART_CR1_PCE | USART_CR1_PS)) +#define IS_USART_PARITY(PARITY) (((PARITY) == USART_PARITY_NONE) || \ + ((PARITY) == USART_PARITY_EVEN) || \ + ((PARITY) == USART_PARITY_ODD)) +/** + * @} + */ + +/** @defgroup USART_Mode USART Mode + * @{ + */ +#define USART_MODE_RX ((uint32_t)USART_CR1_RE) +#define USART_MODE_TX ((uint32_t)USART_CR1_TE) +#define USART_MODE_TX_RX ((uint32_t)(USART_CR1_TE |USART_CR1_RE)) +#define IS_USART_MODE(MODE) ((((MODE) & (uint32_t)0xFFFFFFF3) == 0x00) && ((MODE) != (uint32_t)0x00)) +/** + * @} + */ + +/** @defgroup USART_Clock USART Clock + * @{ + */ +#define USART_CLOCK_DISABLED ((uint32_t)0x0000) +#define USART_CLOCK_ENABLED ((uint32_t)USART_CR2_CLKEN) +#define IS_USART_CLOCK(CLOCK) (((CLOCK) == USART_CLOCK_DISABLED) || \ + ((CLOCK) == USART_CLOCK_ENABLED)) +/** + * @} + */ + +/** @defgroup USART_Clock_Polarity USART Clock Polarity + * @{ + */ +#define USART_POLARITY_LOW ((uint32_t)0x0000) +#define USART_POLARITY_HIGH ((uint32_t)USART_CR2_CPOL) +#define IS_USART_POLARITY(CPOL) (((CPOL) == USART_POLARITY_LOW) || ((CPOL) == USART_POLARITY_HIGH)) +/** + * @} + */ + +/** @defgroup USART_Clock_Phase + * @{ + */ +#define USART_PHASE_1EDGE ((uint32_t)0x0000) +#define USART_PHASE_2EDGE ((uint32_t)USART_CR2_CPHA) +#define IS_USART_PHASE(CPHA) (((CPHA) == USART_PHASE_1EDGE) || ((CPHA) == USART_PHASE_2EDGE)) +/** + * @} + */ + +/** @defgroup USART_Last_Bit + * @{ + */ +#define USART_LASTBIT_DISABLE ((uint32_t)0x0000) +#define USART_LASTBIT_ENABLE ((uint32_t)USART_CR2_LBCL) +#define IS_USART_LASTBIT(LASTBIT) (((LASTBIT) == USART_LASTBIT_DISABLE) || \ + ((LASTBIT) == USART_LASTBIT_ENABLE)) +/** + * @} + */ + + +/** @defgroup USART_Flags USART Flags + * Elements values convention: 0xXXXX + * - 0xXXXX : Flag mask in the ISR register + * @{ + */ +#define USART_FLAG_REACK ((uint32_t)0x00400000) +#define USART_FLAG_TEACK ((uint32_t)0x00200000) +#define USART_FLAG_BUSY ((uint32_t)0x00010000) +#define USART_FLAG_CTS ((uint32_t)0x00000400) +#define USART_FLAG_CTSIF ((uint32_t)0x00000200) +#define USART_FLAG_LBDF ((uint32_t)0x00000100) +#define USART_FLAG_TXE ((uint32_t)0x00000080) +#define USART_FLAG_TC ((uint32_t)0x00000040) +#define USART_FLAG_RXNE ((uint32_t)0x00000020) +#define USART_FLAG_IDLE ((uint32_t)0x00000010) +#define USART_FLAG_ORE ((uint32_t)0x00000008) +#define USART_FLAG_NE ((uint32_t)0x00000004) +#define USART_FLAG_FE ((uint32_t)0x00000002) +#define USART_FLAG_PE ((uint32_t)0x00000001) +/** + * @} + */ + +/** @defgroup USART_Interrupt_definition USART Interrupts Definition + * Elements values convention: 0000ZZZZ0XXYYYYYb + * - YYYYY : Interrupt source position in the XX register (5bits) + * - XX : Interrupt source register (2bits) + * - 01: CR1 register + * - 10: CR2 register + * - 11: CR3 register + * - ZZZZ : Flag position in the ISR register(4bits) + * @{ + */ + +#define USART_IT_PE ((uint16_t)0x0028) +#define USART_IT_TXE ((uint16_t)0x0727) +#define USART_IT_TC ((uint16_t)0x0626) +#define USART_IT_RXNE ((uint16_t)0x0525) +#define USART_IT_IDLE ((uint16_t)0x0424) +#define USART_IT_ERR ((uint16_t)0x0060) + +#define USART_IT_ORE ((uint16_t)0x0300) +#define USART_IT_NE ((uint16_t)0x0200) +#define USART_IT_FE ((uint16_t)0x0100) +/** + * @} + */ + +/** @defgroup USART_IT_CLEAR_Flags USART Interruption Clear Flags + * @{ + */ +#define USART_CLEAR_PEF USART_ICR_PECF /*!< Parity Error Clear Flag */ +#define USART_CLEAR_FEF USART_ICR_FECF /*!< Framing Error Clear Flag */ +#define USART_CLEAR_NEF USART_ICR_NCF /*!< Noise detected Clear Flag */ +#define USART_CLEAR_OREF USART_ICR_ORECF /*!< OverRun Error Clear Flag */ +#define USART_CLEAR_IDLEF USART_ICR_IDLECF /*!< IDLE line detected Clear Flag */ +#define USART_CLEAR_TCF USART_ICR_TCCF /*!< Transmission Complete Clear Flag */ +#define USART_CLEAR_CTSF USART_ICR_CTSCF /*!< CTS Interrupt Clear Flag */ +/** + * @} + */ + +/** @defgroup USART_Request_Parameters USART Request Parameters + * @{ + */ +#define USART_RXDATA_FLUSH_REQUEST ((uint32_t)USART_RQR_RXFRQ) /*!< Receive Data flush Request */ +#define USART_TXDATA_FLUSH_REQUEST ((uint32_t)USART_RQR_TXFRQ) /*!< Transmit data flush Request */ +#define IS_USART_REQUEST_PARAMETER(PARAM) (((PARAM) == USART_RXDATA_FLUSH_REQUEST) || \ + ((PARAM) == USART_TXDATA_FLUSH_REQUEST)) +/** + * @} + */ + +/** @defgroup USART_Interruption_Mask USART interruptions flag mask + * @{ + */ +#define USART_IT_MASK ((uint16_t)0x001F) +/** + * @} + */ + +/** + * @} + */ + + +/* Exported macro ------------------------------------------------------------*/ + +/** @defgroup USART_Exported_Macros + * @{ + */ +/** @brief Reset USART handle state + * @param __HANDLE__: specifies the UART Handle. + * The Handle Instance which can be USART1 or USART2. + * @retval None + */ +#define __HAL_USART_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_USART_STATE_RESET) + +/** @brief Checks whether the specified USART flag is set or not. + * @param __HANDLE__: specifies the USART Handle which can be USART1 or USART2. + * @param __FLAG__: specifies the flag to check. + * This parameter can be one of the following values: + * @arg USART_FLAG_REACK: Receive enable ackowledge flag + * @arg USART_FLAG_TEACK: Transmit enable ackowledge flag + * @arg USART_FLAG_BUSY: Busy flag + * @arg USART_FLAG_CTS: CTS Change flag + * @arg USART_FLAG_TXE: Transmit data register empty flag + * @arg USART_FLAG_TC: Transmission Complete flag + * @arg USART_FLAG_RXNE: Receive data register not empty flag + * @arg USART_FLAG_IDLE: Idle Line detection flag + * @arg USART_FLAG_ORE: OverRun Error flag + * @arg USART_FLAG_NE: Noise Error flag + * @arg USART_FLAG_FE: Framing Error flag + * @arg USART_FLAG_PE: Parity Error flag + * @retval The new state of __FLAG__ (TRUE or FALSE). + */ +#define __HAL_USART_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->ISR & (__FLAG__)) == (__FLAG__)) + + +/** @brief Enables the specified USART interrupt. + * @param __HANDLE__: specifies the USART Handle which can be USART1 or USART2. + * @param __INTERRUPT__: specifies the USART interrupt source to enable. + * This parameter can be one of the following values: + * @arg USART_IT_TXE: Transmit Data Register empty interrupt + * @arg USART_IT_TC: Transmission complete interrupt + * @arg USART_IT_RXNE: Receive Data register not empty interrupt + * @arg USART_IT_IDLE: Idle line detection interrupt + * @arg USART_IT_PE: Parity Error interrupt + * @arg USART_IT_ERR: Error interrupt(Frame error, noise error, overrun error) + * @retval None + */ +#define __HAL_USART_ENABLE_IT(__HANDLE__, __INTERRUPT__)(((((uint8_t)(__INTERRUPT__)) >> 5) == 1)? ((__HANDLE__)->Instance->CR1 |= (1 << ((__INTERRUPT__) & USART_IT_MASK))): \ + ((((uint8_t)(__INTERRUPT__)) >> 5) == 2)? ((__HANDLE__)->Instance->CR2 |= (1 << ((__INTERRUPT__) & USART_IT_MASK))): \ + ((__HANDLE__)->Instance->CR3 |= (1 << ((__INTERRUPT__) & USART_IT_MASK)))) + +/** @brief Disables the specified USART interrupt. + * @param __HANDLE__: specifies the USART Handle which can be USART1 or USART2. + * @param __INTERRUPT__: specifies the USART interrupt source to disable. + * This parameter can be one of the following values: + * @arg USART_IT_TXE: Transmit Data Register empty interrupt + * @arg USART_IT_TC: Transmission complete interrupt + * @arg USART_IT_RXNE: Receive Data register not empty interrupt + * @arg USART_IT_IDLE: Idle line detection interrupt + * @arg USART_IT_PE: Parity Error interrupt + * @arg USART_IT_ERR: Error interrupt(Frame error, noise error, overrun error) + * @retval None + */ +#define __HAL_USART_DISABLE_IT(__HANDLE__, __INTERRUPT__) (((((uint8_t)(__INTERRUPT__)) >> 5) == 1)? ((__HANDLE__)->Instance->CR1 &= ~ ((uint32_t)1 << ((__INTERRUPT__) & USART_IT_MASK))): \ + ((((uint8_t)(__INTERRUPT__)) >> 5) == 2)? ((__HANDLE__)->Instance->CR2 &= ~ ((uint32_t)1 << ((__INTERRUPT__) & USART_IT_MASK))): \ + ((__HANDLE__)->Instance->CR3 &= ~ ((uint32_t)1 << ((__INTERRUPT__) & USART_IT_MASK)))) + +/** @brief Checks whether the specified USART interrupt has occurred or not. + * @param __HANDLE__: specifies the USART Handle which can be USART1 or USART2. + * @param __IT__: specifies the USART interrupt source to check. + * This parameter can be one of the following values: + * @arg USART_IT_TXE: Transmit Data Register empty interrupt + * @arg USART_IT_TC: Transmission complete interrupt + * @arg USART_IT_RXNE: Receive Data register not empty interrupt + * @arg USART_IT_IDLE: Idle line detection interrupt + * @arg USART_IT_ORE: OverRun Error interrupt + * @arg USART_IT_NE: Noise Error interrupt + * @arg USART_IT_FE: Framing Error interrupt + * @arg USART_IT_PE: Parity Error interrupt + * @retval The new state of __IT__ (TRUE or FALSE). + */ +#define __HAL_USART_GET_IT(__HANDLE__, __IT__) ((__HANDLE__)->Instance->ISR & ((uint32_t)1 << ((__IT__)>> 0x08))) + +/** @brief Checks whether the specified USART interrupt source is enabled. + * @param __HANDLE__: specifies the USART Handle which can be USART1 or USART2. + * @param __IT__: specifies the USART interrupt source to check. + * This parameter can be one of the following values: + * @arg USART_IT_TXE: Transmit Data Register empty interrupt + * @arg USART_IT_TC: Transmission complete interrupt + * @arg USART_IT_RXNE: Receive Data register not empty interrupt + * @arg USART_IT_IDLE: Idle line detection interrupt + * @arg USART_IT_ORE: OverRun Error interrupt + * @arg USART_IT_NE: Noise Error interrupt + * @arg USART_IT_FE: Framing Error interrupt + * @arg USART_IT_PE: Parity Error interrupt + * @retval The new state of __IT__ (TRUE or FALSE). + */ +#define __HAL_USART_GET_IT_SOURCE(__HANDLE__, __IT__) ((((((uint8_t)(__IT__)) >> 5) == 1)? (__HANDLE__)->Instance->CR1:(((((uint8_t)(__IT__)) >> 5) == 2)? \ + (__HANDLE__)->Instance->CR2 : (__HANDLE__)->Instance->CR3)) & ((uint32_t)1 << \ + (((uint16_t)(__IT__)) & USART_IT_MASK))) + + +/** @brief Clears the specified USART ISR flag, in setting the proper ICR register flag. + * @param __HANDLE__: specifies the USART Handle which can be USART1 or USART2. + * @param __IT_CLEAR__: specifies the interrupt clear register flag that needs to be set + * to clear the corresponding interrupt + * This parameter can be one of the following values: + * @arg USART_CLEAR_PEF: Parity Error Clear Flag + * @arg USART_CLEAR_FEF: Framing Error Clear Flag + * @arg USART_CLEAR_NEF: Noise detected Clear Flag + * @arg USART_CLEAR_OREF: OverRun Error Clear Flag + * @arg USART_CLEAR_IDLEF: IDLE line detected Clear Flag + * @arg USART_CLEAR_TCF: Transmission Complete Clear Flag + * @arg USART_CLEAR_CTSF: CTS Interrupt Clear Flag + * @retval None + */ +#define __HAL_USART_CLEAR_IT(__HANDLE__, __IT_CLEAR__) ((__HANDLE__)->Instance->ICR |= (uint32_t)(__IT_CLEAR__)) + +/** @brief Set a specific USART request flag. + * @param __HANDLE__: specifies the USART Handle which can be USART1 or USART2. + * @param __REQ__: specifies the request flag to set + * This parameter can be one of the following values: + * @arg USART_RXDATA_FLUSH_REQUEST: Receive Data flush Request + * @arg USART_TXDATA_FLUSH_REQUEST: Transmit data flush Request + * + * @retval None + */ +#define __HAL_USART_SEND_REQ(__HANDLE__, __REQ__) ((__HANDLE__)->Instance->RQR |= (uint16_t)(__REQ__)) + +/** @brief Enable USART + * @param __HANDLE__: specifies the USART Handle. + * The Handle Instance which can be USART1 or USART2. + * @retval None + */ +#define __HAL_USART_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 |= USART_CR1_UE) + +/** @brief Disable USART + * @param __HANDLE__: specifies the USART Handle. + * The Handle Instance which can be USART1 or USART2. + * @retval None + */ +#define __HAL_USART_DISABLE(__HANDLE__) ((__HANDLE__)->Instance->CR1 &= ~USART_CR1_UE) + + +/** @brief Check USART Baud rate + * @param BAUDRATE: Baudrate specified by the user + * The maximum Baud Rate is derived from the maximum clock on L0 (i.e. 32 MHz) + * divided by the smallest oversampling used on the USART (i.e. 8) + * @retval Test result (TRUE or FALSE). + */ +#define IS_USART_BAUDRATE(BAUDRATE) ((BAUDRATE) < 4000001) + +/** + * @} + */ + +/* Include UART HAL Extension module */ +#include "stm32l0xx_hal_usart_ex.h" +/* Exported functions --------------------------------------------------------*/ + +/* Initialization/de-initialization functions ********************************/ +HAL_StatusTypeDef HAL_USART_Init(USART_HandleTypeDef *husart); +HAL_StatusTypeDef HAL_USART_DeInit(USART_HandleTypeDef *husart); +void HAL_USART_MspInit(USART_HandleTypeDef *husart); +void HAL_USART_MspDeInit(USART_HandleTypeDef *husart); +void HAL_USART_SetConfig(USART_HandleTypeDef *husart); +/* IO operation functions *****************************************************/ +HAL_StatusTypeDef HAL_USART_Transmit(USART_HandleTypeDef *husart, uint8_t *pTxData, uint16_t Size, uint32_t Timeout); +HAL_StatusTypeDef HAL_USART_Receive(USART_HandleTypeDef *husart, uint8_t *pRxData, uint16_t Size, uint32_t Timeout); +HAL_StatusTypeDef HAL_USART_TransmitReceive(USART_HandleTypeDef *husart, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size, uint32_t Timeout); +HAL_StatusTypeDef HAL_USART_Transmit_IT(USART_HandleTypeDef *husart, uint8_t *pTxData, uint16_t Size); +HAL_StatusTypeDef HAL_USART_Receive_IT(USART_HandleTypeDef *husart, uint8_t *pRxData, uint16_t Size); +HAL_StatusTypeDef HAL_USART_TransmitReceive_IT(USART_HandleTypeDef *husart, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size); +HAL_StatusTypeDef HAL_USART_Transmit_DMA(USART_HandleTypeDef *husart, uint8_t *pTxData, uint16_t Size); +HAL_StatusTypeDef HAL_USART_Receive_DMA(USART_HandleTypeDef *husart, uint8_t *pRxData, uint16_t Size); +HAL_StatusTypeDef HAL_USART_TransmitReceive_DMA(USART_HandleTypeDef *husart, uint8_t *pTxData, uint8_t *pRxData, uint16_t Size); +HAL_StatusTypeDef HAL_USART_DMAPause(USART_HandleTypeDef *husart); +HAL_StatusTypeDef HAL_USART_DMAResume(USART_HandleTypeDef *husart); +HAL_StatusTypeDef HAL_USART_DMAStop(USART_HandleTypeDef *husart); +void HAL_USART_IRQHandler(USART_HandleTypeDef *husart); +void HAL_USART_TxCpltCallback(USART_HandleTypeDef *husart); +void HAL_USART_TxHalfCpltCallback(USART_HandleTypeDef *husart); +void HAL_USART_RxCpltCallback(USART_HandleTypeDef *husart); +void HAL_USART_RxHalfCpltCallback(USART_HandleTypeDef *husart); +void HAL_USART_TxRxCpltCallback(USART_HandleTypeDef *husart); +void HAL_USART_ErrorCallback(USART_HandleTypeDef *husart); + +/* Peripheral State functions ************************************************/ +HAL_USART_StateTypeDef HAL_USART_GetState(USART_HandleTypeDef *husart); +uint32_t HAL_USART_GetError(USART_HandleTypeDef *husart); + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __STM32L0xx_HAL_USART_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_usart_ex.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_usart_ex.h new file mode 100644 index 0000000000..ff83d39d0b --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_usart_ex.h @@ -0,0 +1,207 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_usart_ex.h + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief Header file of USART HAL Extension module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32L0xx_HAL_USART_EX_H +#define __STM32L0xx_HAL_USART_EX_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal_def.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @addtogroup USARTEx + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ +/* Exported constants --------------------------------------------------------*/ +/** @defgroup USARTEx_Extended_Exported_Constants + * @{ + */ + +/** @defgroup USARTEx_Word_Length USART Word Length + * @{ + */ +#define USART_WORDLENGTH_7B ((uint32_t)USART_CR1_M_1) +#define USART_WORDLENGTH_8B ((uint32_t)0x00000000) +#define USART_WORDLENGTH_9B ((uint32_t)USART_CR1_M_0) +#define IS_USART_WORD_LENGTH(LENGTH) (((LENGTH) == USART_WORDLENGTH_7B) || \ + ((LENGTH) == USART_WORDLENGTH_8B) || \ + ((LENGTH) == USART_WORDLENGTH_9B)) +/** + * @} + */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ + +/** @defgroup USARTEx_Extended_Exported_Macros + * @{ + */ + +/** @brief Reports the USART clock source. + * @param __HANDLE__: specifies the USART Handle + * @param __CLOCKSOURCE__ : output variable + * @retval the USART clocking source, written in __CLOCKSOURCE__. + */ +#define __HAL_USART_GETCLOCKSOURCE(__HANDLE__,__CLOCKSOURCE__) \ + do { \ + if((__HANDLE__)->Instance == USART1) \ + { \ + switch(__HAL_RCC_GET_USART1_SOURCE()) \ + { \ + case RCC_USART1CLKSOURCE_PCLK2: \ + (__CLOCKSOURCE__) = USART_CLOCKSOURCE_PCLK2; \ + break; \ + case RCC_USART1CLKSOURCE_HSI: \ + (__CLOCKSOURCE__) = USART_CLOCKSOURCE_HSI; \ + break; \ + case RCC_USART1CLKSOURCE_SYSCLK: \ + (__CLOCKSOURCE__) = USART_CLOCKSOURCE_SYSCLK; \ + break; \ + case RCC_USART1CLKSOURCE_LSE: \ + (__CLOCKSOURCE__) = USART_CLOCKSOURCE_LSE; \ + break; \ + default: \ + break; \ + } \ + } \ + else if((__HANDLE__)->Instance == USART2) \ + { \ + switch(__HAL_RCC_GET_USART2_SOURCE()) \ + { \ + case RCC_USART2CLKSOURCE_PCLK1: \ + (__CLOCKSOURCE__) = USART_CLOCKSOURCE_PCLK1; \ + break; \ + case RCC_USART2CLKSOURCE_HSI: \ + (__CLOCKSOURCE__) = USART_CLOCKSOURCE_HSI; \ + break; \ + case RCC_USART2CLKSOURCE_SYSCLK: \ + (__CLOCKSOURCE__) = USART_CLOCKSOURCE_SYSCLK; \ + break; \ + case RCC_USART2CLKSOURCE_LSE: \ + (__CLOCKSOURCE__) = USART_CLOCKSOURCE_LSE; \ + break; \ + default: \ + break; \ + } \ + } \ + } while(0) + +/** @brief Reports the USART mask to apply to retrieve the received data + * according to the word length and to the parity bits activation. + * If PCE = 1, the parity bit is not included in the data extracted + * by the reception API(). + * This masking operation is not carried out in the case of + * DMA transfers. + * @param __HANDLE__: specifies the USART Handle + * @param __MASK__ : output variable + * @retval mask to apply to USART RDR register value. + */ +#define __HAL_USART_MASK_COMPUTATION(__HANDLE__) \ + do { \ + if ((__HANDLE__)->Init.WordLength == USART_WORDLENGTH_9B) \ + { \ + if ((__HANDLE__)->Init.Parity == USART_PARITY_NONE) \ + { \ + (__HANDLE__)->Mask = 0x01FF ; \ + } \ + else \ + { \ + (__HANDLE__)->Mask = 0x00FF ; \ + } \ + } \ + else if ((__HANDLE__)->Init.WordLength == USART_WORDLENGTH_8B) \ + { \ + if ((__HANDLE__)->Init.Parity == USART_PARITY_NONE) \ + { \ + (__HANDLE__)->Mask = 0x00FF ; \ + } \ + else \ + { \ + (__HANDLE__)->Mask = 0x007F ; \ + } \ + } \ + else if ((__HANDLE__)->Init.WordLength == USART_WORDLENGTH_7B) \ + { \ + if ((__HANDLE__)->Init.Parity == USART_PARITY_NONE) \ + { \ + (__HANDLE__)->Mask = 0x007F ; \ + } \ + else \ + { \ + (__HANDLE__)->Mask = 0x003F ; \ + } \ + } \ +} while(0) + +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ +/* Initialization/de-initialization methods **********************************/ +/* IO operation methods *******************************************************/ +/* Peripheral Control methods ************************************************/ +/* Peripheral State methods **************************************************/ + + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __STM32L0xx_HAL_USART_EX_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_wwdg.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_wwdg.c new file mode 100644 index 0000000000..e4bae6fd41 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_wwdg.c @@ -0,0 +1,456 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_wwdg.c + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief WWDG HAL module driver. + * This file provides firmware functions to manage the following + * functionalities of the Window Watchdog (WWDG) peripheral: + * + Initialization and de-initialization functions + * + IO operation functions + * + Peripheral State functions + @verbatim + ============================================================================== + ##### WWDG specific features ##### + ============================================================================== + [..] + Once enabled the WWDG generates a system reset on expiry of a programmed + time period, unless the program refreshes the counter (downcounter) + before reaching 0x3F value (i.e. a reset is generated when the counter + value rolls over from 0x40 to 0x3F). + + (+) An MCU reset is also generated if the counter value is refreshed + before the counter has reached the refresh window value. This + implies that the counter must be refreshed in a limited window. + (+) Once enabled the WWDG cannot be disabled except by a system reset. + (+) WWDGRST flag in RCC_CSR register can be used to inform when a WWDG + reset occurs. + (+) The WWDG counter input clock is derived from the APB clock divided + by a programmable prescaler. + (+) WWDG counter clock = PCLK1 / Prescaler + WWDG timeout = (WWDG counter clock) * (counter value) + (+) Min-max timeout value @32 MHz(PCLK1): ~128.0 us / ~65.54 ms + + + ##### How to use this driver ##### + ============================================================================== + [..] + (+) Enable WWDG APB1 clock using __WWDG_CLK_ENABLE(). + (+) Set the WWDG prescaler, refresh window and counter value + using HAL_WWDG_Init() function. + (+) Start the WWDG using HAL_WWDG_Start() function. + When the WWDG is enabled the counter value should be configured to + a value greater than 0x40 to prevent generating an immediate reset. + (+) Optionally you can enable the Early Wakeup Interrupt (EWI) which is + generated when the counter reaches 0x40, and then start the WWDG using + HAL_WWDG_Start_IT(). + Once enabled, EWI interrupt cannot be disabled except by a system reset. + (+) Then the application program must refresh the WWDG counter at regular + intervals during normal operation to prevent an MCU reset, using + HAL_WWDG_Refresh() function. This operation must occur only when + the counter is lower than the refresh window value already programmed. + + *** WWDG HAL driver macros list *** + ================================== + [..] + Below the list of most used macros in WWDG HAL driver. + + (+) __HAL_WWDG_ENABLE: Enable the WWDG peripheral + (+) __HAL_WWDG_GET_FLAG: Get the selected WWDG's flag status + (+) __HAL_WWDG_CLEAR_FLAG: Clear the WWDG's pending flags + (+) __HAL_WWDG_ENABLE_IT: Enables the WWDG early wakeup interrupt + + @endverbatim + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @defgroup WWDG + * @brief WWDG HAL module driver. + * @{ + */ + +#ifdef HAL_WWDG_MODULE_ENABLED + +/* Private typedef -----------------------------------------------------------*/ +/* Private define ------------------------------------------------------------*/ +/* Private macro -------------------------------------------------------------*/ +/* Private variables ---------------------------------------------------------*/ +/* Private function prototypes -----------------------------------------------*/ +/* Private functions ---------------------------------------------------------*/ + +/** @defgroup WWDG_Private_Functions + * @{ + */ + +/** @defgroup WWDG_Group1 Initialization and de-initialization functions + * @brief Initialization and Configuration functions. + * +@verbatim + ============================================================================== + ##### Initialization and de-initialization functions ##### + ============================================================================== + [..] + This section provides functions allowing to: + (+) Initialize the WWDG according to the specified parameters + in the WWDG_InitTypeDef and create the associated handle + (+) DeInitialize the WWDG peripheral + (+) Initialize the WWDG MSP + (+) DeInitialize the WWDG MSP + +@endverbatim + * @{ + */ + +/** + * @brief Initializes the WWDG according to the specified + * parameters in the WWDG_InitTypeDef and creates the associated handle. + * @param hwwdg: pointer to a WWDG_HandleTypeDef structure that contains + * the configuration information for the specified WWDG module. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_WWDG_Init(WWDG_HandleTypeDef *hwwdg) +{ + uint32_t tmp = 0; + + /* Check the WWDG handle allocation */ + if(hwwdg == NULL) + { + return HAL_ERROR; + } + + /* Check the parameters */ + assert_param(IS_WWDG_PRESCALER(hwwdg->Init.Prescaler)); + assert_param(IS_WWDG_WINDOW(hwwdg->Init.Window)); + assert_param(IS_WWDG_COUNTER(hwwdg->Init.Counter)); + + if(hwwdg->State == HAL_WWDG_STATE_RESET) + { + /* Init the low level hardware */ + HAL_WWDG_MspInit(hwwdg); + } + + /* Change WWDG peripheral state */ + hwwdg->State = HAL_WWDG_STATE_BUSY; + + /* Set WWDG Prescaler and Window */ + /* Get the CFR register value */ + tmp = hwwdg->Instance->CFR; + + /* Clear WDGTB[1:0] and W[6:0] bits */ + tmp &= ((uint32_t)~(WWDG_CFR_WDGTB | WWDG_CFR_W)); + + /* Prepare the WWDG Prescaler and Window parameters */ + tmp |= hwwdg->Init.Prescaler | hwwdg->Init.Window; + + /* Write to WWDG CFR */ + hwwdg->Instance->CFR = tmp; + + /* Set WWDG Counter */ + /* Get the CR register value */ + tmp = hwwdg->Instance->CR; + + /* Clear T[6:0] bits */ + tmp &= (uint32_t)~((uint32_t)WWDG_CR_T); + + /* Prepare the WWDG Counter parameter */ + tmp |= (hwwdg->Init.Counter); + + /* Write to WWDG CR */ + hwwdg->Instance->CR = tmp; + + /* Change WWDG peripheral state */ + hwwdg->State = HAL_WWDG_STATE_READY; + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief DeInitializes the WWDG peripheral. + * @param hwwdg: pointer to a WWDG_HandleTypeDef structure that contains + * the configuration information for the specified WWDG module. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_WWDG_DeInit(WWDG_HandleTypeDef *hwwdg) +{ + /* Change WWDG peripheral state */ + hwwdg->State = HAL_WWDG_STATE_BUSY; + + /* DeInit the low level hardware */ + HAL_WWDG_MspDeInit(hwwdg); + + /* Reset WWDG Control register */ + hwwdg->Instance->CR = (uint32_t)0x0000007F; + + /* Reset WWDG Configuration register */ + hwwdg->Instance->CFR = (uint32_t)0x0000007F; + + /* Reset WWDG Status register */ + hwwdg->Instance->SR = 0; + + /* Change WWDG peripheral state */ + hwwdg->State = HAL_WWDG_STATE_RESET; + + /* Release Lock */ + __HAL_UNLOCK(hwwdg); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Initializes the WWDG MSP. + * @param hwwdg: pointer to a WWDG_HandleTypeDef structure that contains + * the configuration information for the specified WWDG module. + * @retval None + */ +__weak void HAL_WWDG_MspInit(WWDG_HandleTypeDef *hwwdg) +{ + /* NOTE: This function Should not be modified, when the callback is needed, + the HAL_WWDG_MspInit could be implemented in the user file + */ +} + +/** + * @brief DeInitializes the WWDG MSP. + * @param hwwdg: pointer to a WWDG_HandleTypeDef structure that contains + * the configuration information for the specified WWDG module. + * @retval None + */ +__weak void HAL_WWDG_MspDeInit(WWDG_HandleTypeDef *hwwdg) +{ + /* NOTE: This function Should not be modified, when the callback is needed, + the HAL_WWDG_MspDeInit could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup WWDG_Group2 IO operation functions + * @brief IO operation functions + * +@verbatim + ============================================================================== + ##### IO operation functions ##### + ============================================================================== + [..] + This section provides functions allowing to: + (+) Start the WWDG. + (+) Refresh the WWDG. + (+) Handle WWDG interrupt request. + +@endverbatim + * @{ + */ + +/** + * @brief Starts the WWDG. + * @param hwwdg: pointer to a WWDG_HandleTypeDef structure that contains + * the configuration information for the specified WWDG module. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_WWDG_Start(WWDG_HandleTypeDef *hwwdg) +{ + /* Process Locked */ + __HAL_LOCK(hwwdg); + + /* Change WWDG peripheral state */ + hwwdg->State = HAL_WWDG_STATE_BUSY; + + /* Enable the peripheral */ + __HAL_WWDG_ENABLE(hwwdg); + + /* Change WWDG peripheral state */ + hwwdg->State = HAL_WWDG_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hwwdg); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Starts the WWDG with interrupt enabled. + * @param hwwdg: pointer to a WWDG_HandleTypeDef structure that contains + * the configuration information for the specified WWDG module. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_WWDG_Start_IT(WWDG_HandleTypeDef *hwwdg) +{ + /* Process Locked */ + __HAL_LOCK(hwwdg); + + /* Change WWDG peripheral state */ + hwwdg->State = HAL_WWDG_STATE_BUSY; + + /* Enable the Early Wakeup Interrupt */ + __HAL_WWDG_ENABLE_IT(WWDG_IT_EWI); + + /* Enable the peripheral */ + __HAL_WWDG_ENABLE(hwwdg); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Refreshes the WWDG. + * @param hwwdg: pointer to a WWDG_HandleTypeDef structure that contains + * the configuration information for the specified WWDG module. + * @retval HAL status + */ +HAL_StatusTypeDef HAL_WWDG_Refresh(WWDG_HandleTypeDef *hwwdg, uint32_t Counter) +{ + /* Process Locked */ + __HAL_LOCK(hwwdg); + + /* Change WWDG peripheral state */ + hwwdg->State = HAL_WWDG_STATE_BUSY; + + /* Check the parameters */ + assert_param(IS_WWDG_COUNTER(Counter)); + + /* Write to WWDG CR the WWDG Counter value to refresh with */ + MODIFY_REG(hwwdg->Instance->CR, (uint32_t)WWDG_CR_T, Counter); + + /* Change WWDG peripheral state */ + hwwdg->State = HAL_WWDG_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(hwwdg); + + /* Return function status */ + return HAL_OK; +} + +/** + * @brief Handles WWDG interrupt request. + * @note The Early Wakeup Interrupt (EWI) can be used if specific safety operations + * or data logging must be performed before the actual reset is generated. + * The EWI interrupt is enabled using __HAL_WWDG_ENABLE_IT() macro. + * When the downcounter reaches the value 0x40, and EWI interrupt is + * generated and the corresponding Interrupt Service Routine (ISR) can + * be used to trigger specific actions (such as communications or data + * logging), before resetting the device. + * @param hwwdg: pointer to a WWDG_HandleTypeDef structure that contains + * the configuration information for the specified WWDG module. + * @retval None + */ +void HAL_WWDG_IRQHandler(WWDG_HandleTypeDef *hwwdg) +{ + /* WWDG Early Wakeup Interrupt occurred */ + if(__HAL_WWDG_GET_FLAG(hwwdg, WWDG_FLAG_EWIF) != RESET) + { + /* Early Wakeup callback */ + HAL_WWDG_WakeupCallback(hwwdg); + + /* Change WWDG peripheral state */ + hwwdg->State = HAL_WWDG_STATE_READY; + + /* Clear the WWDG Data Ready flag */ + __HAL_WWDG_CLEAR_FLAG(hwwdg, WWDG_FLAG_EWIF); + + /* Process Unlocked */ + __HAL_UNLOCK(hwwdg); + } +} + +/** + * @brief Early Wakeup WWDG callback. + * @param hwwdg: pointer to a WWDG_HandleTypeDef structure that contains + * the configuration information for the specified WWDG module. + * @retval None + */ +__weak void HAL_WWDG_WakeupCallback(WWDG_HandleTypeDef* hwwdg) +{ + /* NOTE: This function Should not be modified, when the callback is needed, + the HAL_WWDG_WakeupCallback could be implemented in the user file + */ +} + +/** + * @} + */ + +/** @defgroup WWDG_Group3 Peripheral State functions + * @brief Peripheral State functions. + * +@verbatim + ============================================================================== + ##### Peripheral State functions ##### + ============================================================================== + [..] + This subsection permits to get in run-time the status of the peripheral + and the data flow. + +@endverbatim + * @{ + */ + +/** + * @brief Returns the WWDG state. + * @param hwwdg: pointer to a WWDG_HandleTypeDef structure that contains + * the configuration information for the specified WWDG module. + * @retval HAL state + */ +HAL_WWDG_StateTypeDef HAL_WWDG_GetState(WWDG_HandleTypeDef *hwwdg) +{ + return hwwdg->State; +} + +/** + * @} + */ + +/** + * @} + */ + +#endif /* HAL_WWDG_MODULE_ENABLED */ +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_wwdg.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_wwdg.h new file mode 100644 index 0000000000..f5063873fe --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/stm32l0xx_hal_wwdg.h @@ -0,0 +1,269 @@ +/** + ****************************************************************************** + * @file stm32l0xx_hal_wwdg.h + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief Header file of WWDG HAL module. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/* Define to prevent recursive inclusion -------------------------------------*/ +#ifndef __STM32L0xx_HAL_WWDG_H +#define __STM32L0xx_HAL_WWDG_H + +#ifdef __cplusplus + extern "C" { +#endif + +/* Includes ------------------------------------------------------------------*/ +#include "stm32l0xx_hal_def.h" + +/** @addtogroup STM32L0xx_HAL_Driver + * @{ + */ + +/** @addtogroup WWDG + * @{ + */ + +/* Exported types ------------------------------------------------------------*/ + +/** + * @brief WWDG HAL State Structure definition + */ +typedef enum +{ + HAL_WWDG_STATE_RESET = 0x00, /*!< WWDG not yet initialized or disabled */ + HAL_WWDG_STATE_READY = 0x01, /*!< WWDG initialized and ready for use */ + HAL_WWDG_STATE_BUSY = 0x02, /*!< WWDG internal process is ongoing */ + HAL_WWDG_STATE_TIMEOUT = 0x03, /*!< WWDG timeout state */ + HAL_WWDG_STATE_ERROR = 0x04 /*!< WWDG error state */ + +}HAL_WWDG_StateTypeDef; + +/** + * @brief WWDG Init structure definition + */ +typedef struct +{ + uint32_t Prescaler; /*!< Specifies the prescaler value of the WWDG. + This parameter can be a value of @ref WWDG_Prescaler */ + + uint32_t Window; /*!< Specifies the WWDG window value to be compared to the downcounter. + This parameter must be a number lower than Max_Data = 0x80 */ + + uint32_t Counter; /*!< Specifies the WWDG free-running downcounter value. + This parameter must be a number between Min_Data = 0x40 and Max_Data = 0x7F */ + +}WWDG_InitTypeDef; + +/** + * @brief WWDG handle Structure definition + */ +typedef struct +{ + WWDG_TypeDef *Instance; /*!< Register base address */ + + WWDG_InitTypeDef Init; /*!< WWDG required parameters */ + + HAL_LockTypeDef Lock; /*!< WWDG locking object */ + + __IO HAL_WWDG_StateTypeDef State; /*!< WWDG communication state */ + +}WWDG_HandleTypeDef; + +/* Exported constants --------------------------------------------------------*/ + +/** @defgroup WWDG_Exported_Constants + * @{ + */ + +/** @defgroup WWDG_BitAddress_AliasRegion + * @brief WWDG registers bit address in the alias region + * @{ + */ + +/* --- CFR Register ---*/ +/* Alias word address of EWI bit */ +#define CFR_BASE (uint32_t)(WWDG_BASE + 0x04) + +/** + * @} + */ + +/** @defgroup WWDG_Interrupt_definition + * @{ + */ +#define WWDG_IT_EWI ((uint32_t)WWDG_CFR_EWI) + +#define IS_WWDG_IT(IT) ((IT) == WWDG_IT_EWI) + +/** + * @} + */ + +/** @defgroup WWDG_Flag_definition + * @brief WWDG Flag definition + * @{ + */ +#define WWDG_FLAG_EWIF ((uint32_t)0x0001) /*!< Early wakeup interrupt flag */ + +#define IS_WWDG_FLAG(FLAG) ((FLAG) == WWDG_FLAG_EWIF)) + +/** + * @} + */ + +/** @defgroup WWDG_Prescaler + * @{ + */ +#define WWDG_PRESCALER_1 ((uint32_t)0x00000000) /*!< WWDG counter clock = (PCLK1/4096)/1 */ +#define WWDG_PRESCALER_2 ((uint32_t)0x00000080) /*!< WWDG counter clock = (PCLK1/4096)/2 */ +#define WWDG_PRESCALER_4 ((uint32_t)0x00000100) /*!< WWDG counter clock = (PCLK1/4096)/4 */ +#define WWDG_PRESCALER_8 ((uint32_t)0x00000180) /*!< WWDG counter clock = (PCLK1/4096)/8 */ + +#define IS_WWDG_PRESCALER(PRESCALER) (((PRESCALER) == WWDG_PRESCALER_1) || \ + ((PRESCALER) == WWDG_PRESCALER_2) || \ + ((PRESCALER) == WWDG_PRESCALER_4) || \ + ((PRESCALER) == WWDG_PRESCALER_8)) + +/** + * @} + */ + +/** @defgroup WWDG_Window + * @{ + */ +#define IS_WWDG_WINDOW(WINDOW) ((WINDOW) <= 0x7F) + +/** + * @} + */ + +/** @defgroup WWDG_Counter + * @{ + */ +#define IS_WWDG_COUNTER(COUNTER) (((COUNTER) >= 0x40) && ((COUNTER) <= 0x7F)) + +/** + * @} + */ + +/** + * @} + */ + +/* Exported macro ------------------------------------------------------------*/ + +/** @defgroup WWDG_Exported_Macro + * @{ + */ + +/** @brief Reset WWDG handle state + * @param __HANDLE__: WWDG handle + * @retval None + */ +#define __HAL_WWDG_RESET_HANDLE_STATE(__HANDLE__) ((__HANDLE__)->State = HAL_WWDG_STATE_RESET) + +/** + * @brief Enables the WWDG peripheral. + * @param __HANDLE__: WWDG handle + * @retval None + */ +#define __HAL_WWDG_ENABLE(__HANDLE__) ((__HANDLE__)->Instance->CR |= WWDG_CR_WDGA) + +/** + * @brief Gets the selected WWDG's flag status. + * @param __HANDLE__: WWDG handle + * @param __FLAG__: specifies the flag to check. + * This parameter can be one of the following values: + * @arg WWDG_FLAG_EWIF: Early wakeup interrupt flag + * @retval The new state of WWDG_FLAG (SET or RESET). + */ +#define __HAL_WWDG_GET_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->SR & (__FLAG__)) == (__FLAG__)) + +/** + * @brief Clears the WWDG's pending flags. + * @param __HANDLE__: WWDG handle + * @param __FLAG__: specifies the flag to clear. + * This parameter can be one of the following values: + * @arg WWDG_FLAG_EWIF: Early wakeup interrupt flag + * @retval None + */ +#define __HAL_WWDG_CLEAR_FLAG(__HANDLE__, __FLAG__) (((__HANDLE__)->Instance->SR) &= ~(__FLAG__)) + +/** + * @brief Enables the WWDG early wakeup interrupt. + * @param __INTERRUPT__: specifies the interrupt to enable. + * This parameter can be one of the following values: + * @arg WWDG_IT_EWI: Early wakeup interrupt + * @note Once enabled this interrupt cannot be disabled except by a system reset. + * @retval None + */ +#define __HAL_WWDG_ENABLE_IT(__INTERRUPT__) (*(__IO uint32_t *) CFR_BASE |= (__INTERRUPT__)) + +/** + * @} + */ + +/* Exported functions --------------------------------------------------------*/ + +/* Initialization/de-initialization functions **********************************/ +HAL_StatusTypeDef HAL_WWDG_Init(WWDG_HandleTypeDef *hwwdg); +HAL_StatusTypeDef HAL_WWDG_DeInit(WWDG_HandleTypeDef *hwwdg); +void HAL_WWDG_MspInit(WWDG_HandleTypeDef *hwwdg); +void HAL_WWDG_MspDeInit(WWDG_HandleTypeDef *hwwdg); +void HAL_WWDG_WakeupCallback(WWDG_HandleTypeDef* hwwdg); + +/* I/O operation functions ******************************************************/ +HAL_StatusTypeDef HAL_WWDG_Start(WWDG_HandleTypeDef *hwwdg); +HAL_StatusTypeDef HAL_WWDG_Start_IT(WWDG_HandleTypeDef *hwwdg); +HAL_StatusTypeDef HAL_WWDG_Refresh(WWDG_HandleTypeDef *hwwdg, uint32_t Counter); +void HAL_WWDG_IRQHandler(WWDG_HandleTypeDef *hwwdg); + +/* Peripheral State functions **************************************************/ +HAL_WWDG_StateTypeDef HAL_WWDG_GetState(WWDG_HandleTypeDef *hwwdg); + +/** + * @} + */ + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /* __STM32L0xx_HAL_WWDG_H */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/system_stm32l0xx.c b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/system_stm32l0xx.c new file mode 100644 index 0000000000..8cb06ff4e0 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/system_stm32l0xx.c @@ -0,0 +1,471 @@ +/** + ****************************************************************************** + * @file system_stm32l0xx.c + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief CMSIS Cortex-M0+ Device Peripheral Access Layer System Source File. + * + * This file provides two functions and one global variable to be called from + * user application: + * - SystemInit(): This function is called at startup just after reset and + * before branch to main program. This call is made inside + * the "startup_stm32l0xx.s" file. + * + * - SystemCoreClock variable: Contains the core clock (HCLK), it can be used + * by the user application to setup the SysTick + * timer or configure other parameters. + * + * - SystemCoreClockUpdate(): Updates the variable SystemCoreClock and must + * be called whenever the core clock is changed + * during program execution. + * + * This file configures the system clock as follows: + *----------------------------------------------------------------------------- + * System clock source | 1- PLL_HSE_EXTC | 3- PLL_HSI + * | (external 8 MHz clock) | (internal 16 MHz) + * | 2- PLL_HSE_XTAL | + * | (external 8 MHz xtal) | + *----------------------------------------------------------------------------- + * SYSCLK(MHz) | 32 | 32 + *----------------------------------------------------------------------------- + * AHBCLK (MHz) | 32 | 32 + *----------------------------------------------------------------------------- + * APB1CLK (MHz) | 32 | 32 + *----------------------------------------------------------------------------- + * APB2CLK (MHz) | 32 | 32 + *----------------------------------------------------------------------------- + * USB capable (48 MHz precise clock) | YES | YES + *----------------------------------------------------------------------------- + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/** @addtogroup CMSIS + * @{ + */ + +/** @addtogroup stm32l0xx_system + * @{ + */ + +/** @addtogroup STM32L0xx_System_Private_Includes + * @{ + */ + +#include "stm32l0xx.h" + +#if !defined (HSE_VALUE) + #define HSE_VALUE ((uint32_t)8000000) /*!< Value of the External oscillator in Hz */ +#endif /* HSE_VALUE */ + +#if !defined (MSI_VALUE) + #define MSI_VALUE ((uint32_t)2000000) /*!< Value of the Internal oscillator in Hz*/ +#endif /* MSI_VALUE */ + +#if !defined (HSI_VALUE) + #define HSI_VALUE ((uint32_t)16000000) /*!< Value of the Internal oscillator in Hz*/ +#endif /* HSI_VALUE */ + + +/** + * @} + */ + +/** @addtogroup STM32L0xx_System_Private_TypesDefinitions + * @{ + */ + +/** + * @} + */ + +/** @addtogroup STM32L0xx_System_Private_Defines + * @{ + */ +/************************* Miscellaneous Configuration ************************/ + +/*!< Uncomment the following line if you need to relocate your vector Table in + Internal SRAM. */ +/* #define VECT_TAB_SRAM */ +#define VECT_TAB_OFFSET 0x00 /*!< Vector Table base offset field. + This value must be a multiple of 0x200. */ +/******************************************************************************/ +/** + * @} + */ + +/** @addtogroup STM32L0xx_System_Private_Macros + * @{ + */ + +/* Select the clock sources (other than HSI) to start with (0=OFF, 1=ON) */ +#define USE_PLL_HSE_EXTC (1) /* Use external clock */ +#define USE_PLL_HSE_XTAL (1) /* Use external xtal */ + +/** + * @} + */ + +/** @addtogroup STM32L0xx_System_Private_Variables + * @{ + */ + /* This variable is updated in three ways: + 1) by calling CMSIS function SystemCoreClockUpdate() + 2) by calling HAL API function HAL_RCC_GetHCLKFreq() + 3) each time HAL_RCC_ClockConfig() is called to configure the system clock frequency + Note: If you use this function to configure the system clock; then there + is no need to call the 2 first functions listed above, since SystemCoreClock + variable is updated automatically. + */ +uint32_t SystemCoreClock = 32000000; + +const uint8_t AHBPrescTable[16] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 6, 7, 8, 9}; +const uint8_t PLLMulTable[9] = {3, 4, 6, 8, 12, 16, 24, 32, 48}; +const uint8_t APBAHBPrescTable[16] = {0, 0, 0, 0, 1, 2, 3, 4, 1, 2, 3, 4, 6, 7, 8, 9}; +const uint32_t MSIRangeTable[7] = {64000, 128000, 256000, 512000, 1000000, 2000000, 4000000}; + +/** + * @} + */ + +/** @addtogroup STM32L0xx_System_Private_FunctionPrototypes + * @{ + */ + +#if (USE_PLL_HSE_XTAL != 0) || (USE_PLL_HSE_EXTC != 0) +uint8_t SetSysClock_PLL_HSE(uint8_t bypass); +#endif + +uint8_t SetSysClock_PLL_HSI(void); + +/** + * @} + */ + +/** @addtogroup STM32L0xx_System_Private_Functions + * @{ + */ + +/** + * @brief Setup the microcontroller system. + * @param None + * @retval None + */ +void SystemInit (void) +{ +/*!< Set MSION bit */ + RCC->CR |= (uint32_t)0x00000100; + + /*!< Reset SW[1:0], HPRE[3:0], PPRE1[2:0], PPRE2[2:0], MCOSEL[2:0] and MCOPRE[2:0] bits */ + RCC->CFGR &= (uint32_t) 0x88FF400C; + + /*!< Reset HSION, HSIDIVEN, HSEON, CSSON and PLLON bits */ + RCC->CR &= (uint32_t)0xFEF6FFF6; + + /*!< Reset HSI48ON bit */ + RCC->CRRCR &= (uint32_t)0xFFFFFFFE; + + /*!< Reset HSEBYP bit */ + RCC->CR &= (uint32_t)0xFFFBFFFF; + + /*!< Reset PLLSRC, PLLMUL[3:0] and PLLDIV[1:0] bits */ + RCC->CFGR &= (uint32_t)0xFF02FFFF; + + /*!< Disable all interrupts */ + RCC->CIER = 0x00000000; + + /* Configure the Vector Table location add offset address ------------------*/ +#ifdef VECT_TAB_SRAM + SCB->VTOR = SRAM_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal SRAM */ +#else + SCB->VTOR = FLASH_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal FLASH */ +#endif + + /* Configure the Cube driver */ + HAL_Init(); + + /* Configure the System clock source, PLL Multiplier and Divider factors, + AHB/APBx prescalers and Flash settings */ + SetSysClock(); +} + +/** + * @brief Update SystemCoreClock according to Clock Register Values + * The SystemCoreClock variable contains the core clock (HCLK), it can + * be used by the user application to setup the SysTick timer or configure + * other parameters. + * + * @note Each time the core clock (HCLK) changes, this function must be called + * to update SystemCoreClock variable value. Otherwise, any configuration + * based on this variable will be incorrect. + * + * @note - The system frequency computed by this function is not the real + * frequency in the chip. It is calculated based on the predefined + * constant and the selected clock source: + * + * - If SYSCLK source is MSI, SystemCoreClock will contain the MSI + * value as defined by the MSI range. + * + * - If SYSCLK source is HSI, SystemCoreClock will contain the HSI_VALUE(*) + * + * - If SYSCLK source is HSE, SystemCoreClock will contain the HSE_VALUE(**) + * + * - If SYSCLK source is PLL, SystemCoreClock will contain the HSE_VALUE(**) + * or HSI_VALUE(*) multiplied/divided by the PLL factors. + * + * (*) HSI_VALUE is a constant defined in stm32l0xx_hal.h file (default value + * 16 MHz) but the real value may vary depending on the variations + * in voltage and temperature. + * + * (**) HSE_VALUE is a constant defined in stm32l0xx_hal.h file (default value + * 8 MHz), user has to ensure that HSE_VALUE is same as the real + * frequency of the crystal used. Otherwise, this function may + * have wrong result. + * + * - The result of this function could be not correct when using fractional + * value for HSE crystal. + * @param None + * @retval None + */ +void SystemCoreClockUpdate (void) +{ + uint32_t tmp = 0, pllmul = 0, plldiv = 0, pllsource = 0, msirange = 0; + + /* Get SYSCLK source -------------------------------------------------------*/ + tmp = RCC->CFGR & RCC_CFGR_SWS; + + switch (tmp) + { + case 0x00: /* MSI used as system clock */ + SystemCoreClock = ((1 <<((RCC->ICSCR & RCC_ICSCR_MSIRANGE)>>13 ))* 64000); + break; + case 0x04: /* HSI used as system clock */ + SystemCoreClock = HSI_VALUE; + break; + case 0x08: /* HSE used as system clock */ + SystemCoreClock = HSE_VALUE; + break; + case 0x0C: /* PLL used as system clock */ + /* Get PLL clock source and multiplication factor ----------------------*/ + pllmul = RCC->CFGR & RCC_CFGR_PLLMUL; + plldiv = RCC->CFGR & RCC_CFGR_PLLDIV; + pllmul = PLLMulTable[(pllmul >> 18)]; + plldiv = (plldiv >> 22) + 1; + + pllsource = RCC->CFGR & RCC_CFGR_PLLSRC; + + if (pllsource == 0x00) + { + /* HSI oscillator clock selected as PLL clock entry */ + SystemCoreClock = (((HSI_VALUE) * pllmul) / plldiv); + } + else + { + /* HSE selected as PLL clock entry */ + SystemCoreClock = (((HSE_VALUE) * pllmul) / plldiv); + } + break; + default: /* MSI used as system clock */ + msirange = (RCC->ICSCR & RCC_ICSCR_MSIRANGE) >> 13; + SystemCoreClock = (32768 * (1 << (msirange + 1))); + break; + } + /* Compute HCLK clock frequency --------------------------------------------*/ + /* Get HCLK prescaler */ + tmp = AHBPrescTable[((RCC->CFGR & RCC_CFGR_HPRE) >> 4)]; + /* HCLK clock frequency */ + SystemCoreClock >>= tmp; +} + +/** + * @brief Configures the System clock source, PLL Multiplier and Divider factors, + * AHB/APBx prescalers and Flash settings + * @note This function should be called only once the RCC clock configuration + * is reset to the default reset state (done in SystemInit() function). + * @param None + * @retval None + */ +void SetSysClock(void) +{ + /* 1- Try to start with HSE and external clock */ +#if USE_PLL_HSE_EXTC != 0 + if (SetSysClock_PLL_HSE(1) == 0) +#endif + { + /* 2- If fail try to start with HSE and external xtal */ + #if USE_PLL_HSE_XTAL != 0 + if (SetSysClock_PLL_HSE(0) == 0) + #endif + { + /* 3- If fail start with HSI clock */ + if (SetSysClock_PLL_HSI() == 0) + { + while(1) + { + // [TODO] Put something here to tell the user that a problem occured... + } + } + } + } + + /* Output clock on MCO1 pin(PA8) for debugging purpose */ + //HAL_RCC_MCOConfig(RCC_MCO1, RCC_MCO1SOURCE_SYSCLK, RCC_MCODIV_1); + //HAL_RCC_MCOConfig(RCC_MCO1, RCC_MCO1SOURCE_HSI48, RCC_MCODIV_1); +} + +#if (USE_PLL_HSE_XTAL != 0) || (USE_PLL_HSE_EXTC != 0) +/******************************************************************************/ +/* PLL (clocked by HSE) used as System clock source */ +/******************************************************************************/ +uint8_t SetSysClock_PLL_HSE(uint8_t bypass) +{ + RCC_ClkInitTypeDef RCC_ClkInitStruct; + RCC_OscInitTypeDef RCC_OscInitStruct; + + /* Used to gain time after DeepSleep in case HSI is used */ + if (__HAL_RCC_GET_FLAG(RCC_FLAG_HSIRDY) != RESET) + { + return 0; + } + + /* The voltage scaling allows optimizing the power consumption when the device is + clocked below the maximum system frequency, to update the voltage scaling value + regarding system frequency refer to product datasheet. */ + __PWR_CLK_ENABLE(); + __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1); + + /* Enable HSE and HSI48 oscillators and activate PLL with HSE as source */ + RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE | RCC_OSCILLATORTYPE_HSI | RCC_OSCILLATORTYPE_HSI48; + if (bypass == 0) + { + RCC_OscInitStruct.HSEState = RCC_HSE_ON; /* External 8 MHz xtal on OSC_IN/OSC_OUT */ + } + else + { + RCC_OscInitStruct.HSEState = RCC_HSE_BYPASS; /* External 8 MHz clock on OSC_IN */ + } + RCC_OscInitStruct.HSIState = RCC_HSI_OFF; + RCC_OscInitStruct.HSI48State = RCC_HSI48_ON; /* For USB and RNG clock */ + // PLLCLK = (8 MHz * 8)/2 = 32 MHz + RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; + RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE; + RCC_OscInitStruct.PLL.PLLMUL = RCC_PLLMUL_8; + RCC_OscInitStruct.PLL.PLLDIV = RCC_PLLDIV_2; + if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) + { + return 0; // FAIL + } + + /* Select PLL as system clock source and configure the HCLK, PCLK1 and PCLK2 clocks dividers */ + RCC_ClkInitStruct.ClockType = (RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2); + RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; // 32 MHz + RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; // 32 MHz + RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1; // 32 MHz + RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1; // 32 MHz + if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_1) != HAL_OK) + { + return 0; // FAIL + } + + /* Output clock on MCO1 pin(PA8) for debugging purpose */ + //if (bypass == 0) + // HAL_RCC_MCOConfig(RCC_MCO1, RCC_MCO1SOURCE_HSE, RCC_MCODIV_2); // 4 MHz + //else + // HAL_RCC_MCOConfig(RCC_MCO1, RCC_MCO1SOURCE_HSE, RCC_MCODIV_1); // 8 MHz + + return 1; // OK +} +#endif + +/******************************************************************************/ +/* PLL (clocked by HSI) used as System clock source */ +/******************************************************************************/ +uint8_t SetSysClock_PLL_HSI(void) +{ + RCC_ClkInitTypeDef RCC_ClkInitStruct; + RCC_OscInitTypeDef RCC_OscInitStruct; + + /* The voltage scaling allows optimizing the power consumption when the device is + clocked below the maximum system frequency, to update the voltage scaling value + regarding system frequency refer to product datasheet. */ + __PWR_CLK_ENABLE(); + __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1); + + /* Enable HSI and HSI48 oscillators and activate PLL with HSI as source */ + RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI | RCC_OSCILLATORTYPE_HSE | RCC_OSCILLATORTYPE_HSI48; + RCC_OscInitStruct.HSEState = RCC_HSE_OFF; + RCC_OscInitStruct.HSIState = RCC_HSI_ON; + RCC_OscInitStruct.HSI48State = RCC_HSI48_ON; /* For USB and RNG clock */ + // PLLCLK = (16 MHz * 4)/2 = 32 MHz + RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; + RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI; + RCC_OscInitStruct.PLL.PLLMUL = RCC_PLLMUL_4; + RCC_OscInitStruct.PLL.PLLDIV = RCC_PLLDIV_2; + if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) + { + return 0; // FAIL + } + + /* Select PLL as system clock source and configure the HCLK, PCLK1 and PCLK2 clocks dividers */ + RCC_ClkInitStruct.ClockType = (RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2); + RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; // 32 MHz + RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; // 32 MHz + RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1; // 32 MHz + RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1; // 32 MHz + if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_1) != HAL_OK) + { + return 0; // FAIL + } + + /* Output clock on MCO1 pin(PA8) for debugging purpose */ + //HAL_RCC_MCOConfig(RCC_MCO1, RCC_MCO1SOURCE_HSI, RCC_MCODIV_1); // 16 MHz + + return 1; // OK +} + +/* Used for the different timeouts in the HAL */ +void SysTick_Handler(void) +{ + HAL_IncTick(); +} + +/** + * @} + */ + +/** + * @} + */ + +/** + * @} + */ + +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/system_stm32l0xx.h b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/system_stm32l0xx.h new file mode 100644 index 0000000000..7b787aae83 --- /dev/null +++ b/libraries/mbed/targets/cmsis/TARGET_STM/TARGET_NUCLEO_L053R8/system_stm32l0xx.h @@ -0,0 +1,123 @@ +/** + ****************************************************************************** + * @file system_stm32l0xx.h + * @author MCD Application Team + * @version V1.0.0 + * @date 22-April-2014 + * @brief CMSIS Cortex-M0+ Device Peripheral Access Layer System Header File. + ****************************************************************************** + * @attention + * + *

© COPYRIGHT(c) 2014 STMicroelectronics

+ * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + ****************************************************************************** + */ + +/** @addtogroup CMSIS + * @{ + */ + +/** @addtogroup stm32l0xx_system + * @{ + */ + +/** + * @brief Define to prevent recursive inclusion + */ +#ifndef __SYSTEM_STM32L0XX_H +#define __SYSTEM_STM32L0XX_H + +#ifdef __cplusplus + extern "C" { +#endif + +/** @addtogroup STM32L0xx_System_Includes + * @{ + */ + +/** + * @} + */ + + +/** @addtogroup STM32L0xx_System_Exported_types + * @{ + */ + /* This variable is updated in three ways: + 1) by calling CMSIS function SystemCoreClockUpdate() + 2) by calling HAL API function HAL_RCC_GetSysClockFreq() + 3) each time HAL_RCC_ClockConfig() is called to configure the system clock frequency + Note: If you use this function to configure the system clock; then there + is no need to call the 2 first functions listed above, since SystemCoreClock + variable is updated automatically. + */ +extern uint32_t SystemCoreClock; /*!< System Clock Frequency (Core Clock) */ + +/** + * @} + */ + +/** @addtogroup STM32L0xx_System_Exported_Constants + * @{ + */ + +/** + * @} + */ + +/** @addtogroup STM32L0xx_System_Exported_Macros + * @{ + */ + +/** + * @} + */ + +/** @addtogroup STM32L0xx_System_Exported_Functions + * @{ + */ + +extern void SystemInit(void); +extern void SystemCoreClockUpdate(void); +extern void SetSysClock(void); + +/** + * @} + */ + +#ifdef __cplusplus +} +#endif + +#endif /*__SYSTEM_STM32L0XX_H */ + +/** + * @} + */ + +/** + * @} + */ +/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/ diff --git a/libraries/mbed/targets/hal/TARGET_Freescale/TARGET_K20D5M/i2c_api.c b/libraries/mbed/targets/hal/TARGET_Freescale/TARGET_K20D5M/i2c_api.c index 4cbdb2d42f..d6d476d6f0 100644 --- a/libraries/mbed/targets/hal/TARGET_Freescale/TARGET_K20D5M/i2c_api.c +++ b/libraries/mbed/targets/hal/TARGET_Freescale/TARGET_K20D5M/i2c_api.c @@ -48,8 +48,6 @@ static const uint16_t ICR[0x40] = { 2304, 2560, 3072, 3840 }; -static uint8_t first_read; - void i2c_init(i2c_t *obj, PinName sda, PinName scl) { // determine the I2C to use @@ -70,8 +68,11 @@ void i2c_init(i2c_t *obj, PinName sda, PinName scl) { pinmap_pinout(sda, PinMap_I2C_SDA); pinmap_pinout(scl, PinMap_I2C_SCL); - - first_read = 1; + /* enable open drain for I2C pins, only port b available */ + uint32_t pin_n = (uint32_t)(sda & 0x7C) >> 2; + PORTB->PCR[pin_n] |= PORT_PCR_ODE_MASK; + pin_n = (uint32_t)(scl & 0x7C) >> 2; + PORTB->PCR[pin_n] |= PORT_PCR_ODE_MASK; } int i2c_start(i2c_t *obj) { @@ -83,7 +84,6 @@ int i2c_start(i2c_t *obj) { obj->i2c->C1 |= I2C_C1_MST_MASK; obj->i2c->C1 |= I2C_C1_TX_MASK; } - first_read = 1; return 0; } @@ -98,12 +98,11 @@ int i2c_stop(i2c_t *obj) { // code provided with the freedom board for (n = 0; n < 100; n++) __NOP(); - first_read = 1; return 0; } static int timeout_status_poll(i2c_t *obj, uint32_t mask) { - uint32_t i, timeout = 1000; + uint32_t i, timeout = 100000; for (i = 0; i < timeout; i++) { if (obj->i2c->S & mask) @@ -279,30 +278,19 @@ void i2c_reset(i2c_t *obj) { int i2c_byte_read(i2c_t *obj, int last) { char data; - + // set rx mode obj->i2c->C1 &= ~I2C_C1_TX_MASK; - - if(first_read) { - // first dummy read - i2c_do_read(obj, &data, 0); - first_read = 0; - } - - if (last) { - // set tx mode - obj->i2c->C1 |= I2C_C1_TX_MASK; - return obj->i2c->D; - } - + + // Setup read i2c_do_read(obj, &data, last); - return data; + // set tx mode + obj->i2c->C1 |= I2C_C1_TX_MASK; + return obj->i2c->D; } int i2c_byte_write(i2c_t *obj, int data) { - first_read = 1; - // set tx mode obj->i2c->C1 |= I2C_C1_TX_MASK; diff --git a/libraries/mbed/targets/hal/TARGET_Freescale/TARGET_K20D5M/spi_api.c b/libraries/mbed/targets/hal/TARGET_Freescale/TARGET_K20D5M/spi_api.c index 3075a33a49..2bc6691dfa 100644 --- a/libraries/mbed/targets/hal/TARGET_Freescale/TARGET_K20D5M/spi_api.c +++ b/libraries/mbed/targets/hal/TARGET_Freescale/TARGET_K20D5M/spi_api.c @@ -54,7 +54,7 @@ void spi_init(spi_t *obj, PinName mosi, PinName miso, PinName sclk, PinName ssel SPIName spi_ssel = (SPIName)pinmap_peripheral(ssel, PinMap_SPI_SSEL); SPIName spi_data = (SPIName)pinmap_merge(spi_mosi, spi_miso); SPIName spi_cntl = (SPIName)pinmap_merge(spi_sclk, spi_ssel); - + obj->spi = (SPI_Type*)pinmap_merge(spi_data, spi_cntl); if ((int)obj->spi == NC) { error("SPI pinout mapping failed"); @@ -63,9 +63,8 @@ void spi_init(spi_t *obj, PinName mosi, PinName miso, PinName sclk, PinName ssel SIM->SCGC5 |= SIM_SCGC5_PORTC_MASK | SIM_SCGC5_PORTD_MASK; SIM->SCGC6 |= SIM_SCGC6_SPI0_MASK; - // halted state - obj->spi->MCR &= ~SPI_MCR_MDIS_MASK; - obj->spi->MCR |= SPI_MCR_HALT_MASK | SPI_MCR_DIS_RXF_MASK | SPI_MCR_DIS_TXF_MASK; + obj->spi->MCR &= ~(SPI_MCR_MDIS_MASK | SPI_MCR_HALT_MASK); + //obj->spi->MCR |= SPI_MCR_DIS_RXF_MASK | SPI_MCR_DIS_TXF_MASK; // set default format and frequency if (ssel == NC) { @@ -77,8 +76,6 @@ void spi_init(spi_t *obj, PinName mosi, PinName miso, PinName sclk, PinName ssel // not halt in the debug mode obj->spi->SR |= SPI_SR_EOQF_MASK; - // enable SPI - obj->spi->MCR &= (~SPI_MCR_HALT_MASK); // pin out the spi pins pinmap_pinout(mosi, PinMap_SPI_MOSI); @@ -93,9 +90,9 @@ void spi_free(spi_t *obj) { // [TODO] } void spi_format(spi_t *obj, int bits, int mode, int slave) { - if ((bits != 8) && (bits != 16)) { - error("Only 8/16 bits SPI supported"); - } + if ((bits < 4) || (bits > 16)) + error("SPI: Only frames between 4 and 16-bit supported"); + if ((mode < 0) || (mode > 3)) { error("SPI mode unsupported"); @@ -109,48 +106,45 @@ void spi_format(spi_t *obj, int bits, int mode, int slave) { obj->spi->MCR |= ((!slave) << SPI_MCR_MSTR_SHIFT); // CTAR0 is used - obj->spi->CTAR[0] &= ~(SPI_CTAR_CPHA_MASK | SPI_CTAR_CPOL_MASK); - obj->spi->CTAR[0] |= (polarity << SPI_CTAR_CPOL_SHIFT) | (phase << SPI_CTAR_CPHA_SHIFT); + obj->spi->CTAR[0] &= ~(SPI_CTAR_CPHA_MASK | SPI_CTAR_CPOL_MASK | SPI_CTAR_FMSZ_MASK); + obj->spi->CTAR[0] |= (polarity << SPI_CTAR_CPOL_SHIFT) | (phase << SPI_CTAR_CPHA_SHIFT) | ((bits - 1) << SPI_CTAR_FMSZ_SHIFT); } static const uint8_t baudrate_prescaler[] = {2,3,5,7}; -static const uint32_t baudrate_scaler[] = {2, 4, 6, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768}; -static const uint8_t delay_prescaler[] = {1, 3, 5, 7}; +static const uint16_t baudrate_scaler[] = {2,4,6,8,16,32,64,128,256,512,1024,2048,4096,8192,16384,32768}; void spi_frequency(spi_t *obj, int hz) { - uint32_t error = 0; + uint32_t f_error = 0; uint32_t p_error = 0xffffffff; uint32_t ref = 0; uint32_t br = 0; uint32_t ref_spr = 0; uint32_t ref_prescaler = 0; + uint32_t ref_dr = 0; // bus clk uint32_t PCLK = bus_frequency(); - uint32_t divisor = 2; - uint32_t prescaler; - /* TODO */ for (uint32_t i = 0; i < 4; i++) { - prescaler = baudrate_prescaler[i]; - divisor = 2; - for (br = 0; br <= 15; br++, divisor *= 2) { + for (br = 0; br <= 15; br++) { for (uint32_t dr = 0; dr < 2; dr++) { - ref = (PCLK / prescaler) * ((1U + dr) / divisor); + ref = (PCLK * (1U + dr) / baudrate_prescaler[i]) / baudrate_scaler[br]; if (ref > (uint32_t)hz) continue; - error = hz - ref; - if (error < p_error) { + f_error = hz - ref; + if (f_error < p_error) { ref_spr = br; ref_prescaler = i; - p_error = error; + ref_dr = dr; + p_error = f_error; } } } } // set PBR and BR - obj->spi->CTAR[0] = ((ref_prescaler & 0x3) << SPI_CTAR_PBR_SHIFT) | (ref_spr & 0xf); + obj->spi->CTAR[0] &= ~(SPI_CTAR_PBR_MASK | SPI_CTAR_BR_MASK | SPI_CTAR_DBR_MASK); + obj->spi->CTAR[0] |= (ref_prescaler << SPI_CTAR_PBR_SHIFT) | (ref_spr << SPI_CTAR_BR_SHIFT) | (ref_dr << SPI_CTAR_DBR_SHIFT); } static inline int spi_writeable(spi_t *obj) { @@ -158,15 +152,15 @@ static inline int spi_writeable(spi_t *obj) { } static inline int spi_readable(spi_t *obj) { - return (obj->spi->SR & SPI_SR_RFDF_MASK) ? 0 : 1; + return (obj->spi->SR & SPI_SR_RFDF_MASK) ? 1 : 0; } int spi_master_write(spi_t *obj, int value) { + //clear RX buffer flag + obj->spi->SR |= SPI_SR_RFDF_MASK; // wait tx buffer empty while(!spi_writeable(obj)); - obj->spi->PUSHR = SPI_PUSHR_TXDATA(value & 0xff) /*| SPI_PUSHR_EOQ_MASK*/; - - while (!obj->spi->SR & SPI_SR_TCF_MASK); // wait for transfer to be complete + obj->spi->PUSHR = SPI_PUSHR_TXDATA(value & 0xffff) /*| SPI_PUSHR_EOQ_MASK*/; // wait rx buffer full while (!spi_readable(obj)); diff --git a/libraries/mbed/targets/hal/TARGET_Freescale/TARGET_KLXX/i2c_api.c b/libraries/mbed/targets/hal/TARGET_Freescale/TARGET_KLXX/i2c_api.c index add00a6d7c..b0d80da6f9 100644 --- a/libraries/mbed/targets/hal/TARGET_Freescale/TARGET_KLXX/i2c_api.c +++ b/libraries/mbed/targets/hal/TARGET_Freescale/TARGET_KLXX/i2c_api.c @@ -37,8 +37,6 @@ static const uint16_t ICR[0x40] = { 2304, 2560, 3072, 3840 }; -static uint8_t first_read; - void i2c_init(i2c_t *obj, PinName sda, PinName scl) { // determine the I2C to use @@ -63,8 +61,6 @@ void i2c_init(i2c_t *obj, PinName sda, PinName scl) { pinmap_pinout(sda, PinMap_I2C_SDA); pinmap_pinout(scl, PinMap_I2C_SCL); - - first_read = 1; } int i2c_start(i2c_t *obj) { @@ -84,7 +80,6 @@ int i2c_start(i2c_t *obj) { obj->i2c->C1 |= I2C_C1_MST_MASK; obj->i2c->C1 |= I2C_C1_TX_MASK; } - first_read = 1; return 0; } @@ -98,12 +93,11 @@ int i2c_stop(i2c_t *obj) { // This wait is also included on the samples // code provided with the freedom board for (n = 0; n < 100; n++) __NOP(); - first_read = 1; return 0; } static int timeout_status_poll(i2c_t *obj, uint32_t mask) { - uint32_t i, timeout = 1000; + uint32_t i, timeout = 100000; for (i = 0; i < timeout; i++) { if (obj->i2c->S & mask) @@ -284,26 +278,15 @@ int i2c_byte_read(i2c_t *obj, int last) { // set rx mode obj->i2c->C1 &= ~I2C_C1_TX_MASK; - if(first_read) { - // first dummy read - i2c_do_read(obj, &data, 0); - first_read = 0; - } - - if (last) { - // set tx mode - obj->i2c->C1 |= I2C_C1_TX_MASK; - return obj->i2c->D; - } - + // Setup read i2c_do_read(obj, &data, last); - - return data; + + // set tx mode + obj->i2c->C1 |= I2C_C1_TX_MASK; + return obj->i2c->D; } int i2c_byte_write(i2c_t *obj, int data) { - first_read = 1; - // set tx mode obj->i2c->C1 |= I2C_C1_TX_MASK; diff --git a/libraries/mbed/targets/hal/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_K64F/i2c_api.c b/libraries/mbed/targets/hal/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_K64F/i2c_api.c index b505813ec7..7d8e7f8da5 100644 --- a/libraries/mbed/targets/hal/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_K64F/i2c_api.c +++ b/libraries/mbed/targets/hal/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_K64F/i2c_api.c @@ -20,6 +20,8 @@ #include "error.h" #include "fsl_clock_manager.h" #include "fsl_i2c_hal.h" +#include "fsl_port_hal.h" +#include "fsl_sim_hal.h" static const PinMap PinMap_I2C_SDA[] = { {PTE25, I2C_0, 5}, @@ -44,8 +46,6 @@ static const PinMap PinMap_I2C_SCL[] = { {NC , NC , 0} }; -static uint8_t first_read; - void i2c_init(i2c_t *obj, PinName sda, PinName scl) { uint32_t i2c_sda = pinmap_peripheral(sda, PinMap_I2C_SDA); uint32_t i2c_scl = pinmap_peripheral(scl, PinMap_I2C_SCL); @@ -55,17 +55,19 @@ void i2c_init(i2c_t *obj, PinName sda, PinName scl) { } clock_manager_set_gate(kClockModuleI2C, obj->instance, true); + clock_manager_set_gate(kClockModulePORT, sda >> GPIO_PORT_SHIFT, true); + clock_manager_set_gate(kClockModulePORT, scl >> GPIO_PORT_SHIFT, true); i2c_hal_enable(obj->instance); i2c_frequency(obj, 100000); pinmap_pinout(sda, PinMap_I2C_SDA); pinmap_pinout(scl, PinMap_I2C_SCL); - first_read = 1; + port_hal_configure_open_drain(sda >> GPIO_PORT_SHIFT, sda & 0xFF, true); + port_hal_configure_open_drain(scl >> GPIO_PORT_SHIFT, scl & 0xFF, true); } int i2c_start(i2c_t *obj) { i2c_hal_send_start(obj->instance); - first_read = 1; return 0; } @@ -77,13 +79,12 @@ int i2c_stop(i2c_t *obj) { // when there is no waiting time after a STOP. // This wait is also included on the samples // code provided with the freedom board - for (n = 0; n < 100; n++) __NOP(); - first_read = 1; + for (n = 0; n < 200; n++) __NOP(); return 0; } static int timeout_status_poll(i2c_t *obj, uint32_t mask) { - uint32_t i, timeout = 1000; + uint32_t i, timeout = 100000; for (i = 0; i < timeout; i++) { if (HW_I2C_S_RD(obj->instance) & mask) @@ -229,26 +230,15 @@ int i2c_byte_read(i2c_t *obj, int last) { // set rx mode i2c_hal_set_direction(obj->instance, kI2CReceive); - if(first_read) { - // first dummy read - i2c_do_read(obj, &data, 0); - first_read = 0; - } - - if (last) { - // set tx mode - i2c_hal_set_direction(obj->instance, kI2CTransmit); - return i2c_hal_read(obj->instance); - } - + // Setup read i2c_do_read(obj, &data, last); - return data; + // set tx mode + i2c_hal_set_direction(obj->instance, kI2CTransmit); + return i2c_hal_read(obj->instance); } int i2c_byte_write(i2c_t *obj, int data) { - first_read = 1; - // set tx mode i2c_hal_set_direction(obj->instance, kI2CTransmit); diff --git a/libraries/mbed/targets/hal/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_K64F/serial_api.c b/libraries/mbed/targets/hal/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_K64F/serial_api.c index 2be80cc4af..ec2dc689bd 100644 --- a/libraries/mbed/targets/hal/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_K64F/serial_api.c +++ b/libraries/mbed/targets/hal/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_K64F/serial_api.c @@ -192,7 +192,7 @@ void serial_irq_set(serial_t *obj, SerialIrq irq, uint32_t enable) { SerialIrq other_irq = (irq == RxIrq) ? (TxIrq) : (RxIrq); switch (irq) { case RxIrq: uart_hal_disable_rx_data_register_full_interrupt(obj->index); break; - case TxIrq: uart_hal_enable_tx_data_register_empty_interrupt(obj->index); break; + case TxIrq: uart_hal_disable_tx_data_register_empty_interrupt(obj->index); break; } switch (other_irq) { case RxIrq: all_disabled = uart_hal_is_receive_data_full_interrupt_enabled(obj->index) == 0; break; diff --git a/libraries/mbed/targets/hal/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/enet/fsl_enet_hal.c b/libraries/mbed/targets/hal/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/enet/fsl_enet_hal.c index a6919e4be3..d695ad9194 100644 --- a/libraries/mbed/targets/hal/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/enet/fsl_enet_hal.c +++ b/libraries/mbed/targets/hal/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/enet/fsl_enet_hal.c @@ -144,11 +144,11 @@ void enet_hal_config_tx_fifo(uint32_t instance, enet_config_tx_fifo_t *threshold { assert(instance < HW_ENET_INSTANCE_COUNT); assert(thresholdCfg); - assert(thresholdCfg->txFifoWrite <= BM_ENET_TFWR_TFWR); BW_ENET_TFWR_STRFWD(instance, thresholdCfg->isStoreForwardEnabled); /* Set store and forward mode*/ if(!thresholdCfg->isStoreForwardEnabled) { + assert(thresholdCfg->txFifoWrite <= BM_ENET_TFWR_TFWR); BW_ENET_TFWR_TFWR(instance, thresholdCfg->txFifoWrite); /* Set transmit FIFO write bytes*/ } BW_ENET_TSEM_TX_SECTION_EMPTY(instance,thresholdCfg->txEmpty); /* Set transmit FIFO empty threshold*/ diff --git a/libraries/mbed/targets/hal/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/enet/fsl_enet_hal.h b/libraries/mbed/targets/hal/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/enet/fsl_enet_hal.h index a0c3cb0ab8..b9e6ac3013 100644 --- a/libraries/mbed/targets/hal/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/enet/fsl_enet_hal.h +++ b/libraries/mbed/targets/hal/TARGET_Freescale/TARGET_KPSDK_MCUS/TARGET_KPSDK_CODE/hal/enet/fsl_enet_hal.h @@ -345,7 +345,7 @@ typedef struct ENETBdStruct uint16_t reserved3; uint16_t reserved4; } enet_bd_struct_t; - +#define TX_DESC_UPDATED_MASK (0x8000) #else /*! @brief Defines the buffer descriptors structure for the Big-Endian system.*/ typedef struct ENETBdStruct @@ -366,6 +366,7 @@ typedef struct ENETBdStruct uint16_t reserved3; uint16_t reserved4; } enet_bd_struct_t; +#define TX_DESC_UPDATED_MASK (0x0080) #endif /*! @brief Defines the configuration structure for the 1588 PTP timer.*/ diff --git a/libraries/mbed/targets/hal/TARGET_NORDIC/TARGET_NRF51822/analogin_api.c b/libraries/mbed/targets/hal/TARGET_NORDIC/TARGET_NRF51822/analogin_api.c index 74c848d4e2..45a1ab22b0 100644 --- a/libraries/mbed/targets/hal/TARGET_NORDIC/TARGET_NRF51822/analogin_api.c +++ b/libraries/mbed/targets/hal/TARGET_NORDIC/TARGET_NRF51822/analogin_api.c @@ -48,6 +48,7 @@ void analogin_init(analogin_t *obj, PinName pin) { } map++; } + obj->adc_pin = (uint8_t)analogInputPin; NRF_ADC->ENABLE = ADC_ENABLE_ENABLE_Enabled; NRF_ADC->CONFIG = (ADC_CONFIG_RES_10bit << ADC_CONFIG_RES_Pos) | @@ -58,6 +59,8 @@ void analogin_init(analogin_t *obj, PinName pin) { } uint16_t analogin_read_u16(analogin_t *obj) { + NRF_ADC->CONFIG &= ~ADC_CONFIG_PSEL_Msk; + NRF_ADC->CONFIG |= obj->adc_pin << ADC_CONFIG_PSEL_Pos; NRF_ADC->TASKS_START = 1; while ( ( (NRF_ADC->BUSY & ADC_BUSY_BUSY_Msk) >> ADC_BUSY_BUSY_Pos) == ADC_BUSY_BUSY_Busy) { diff --git a/libraries/mbed/targets/hal/TARGET_NORDIC/TARGET_NRF51822/objects.h b/libraries/mbed/targets/hal/TARGET_NORDIC/TARGET_NRF51822/objects.h index 71f82d9875..eef63283ac 100644 --- a/libraries/mbed/targets/hal/TARGET_NORDIC/TARGET_NRF51822/objects.h +++ b/libraries/mbed/targets/hal/TARGET_NORDIC/TARGET_NRF51822/objects.h @@ -57,6 +57,7 @@ struct i2c_s { struct analogin_s { ADCName adc; + uint8_t adc_pin; }; struct gpio_irq_s { diff --git a/libraries/mbed/targets/hal/TARGET_NORDIC/TARGET_NRF51822/spi_api.c b/libraries/mbed/targets/hal/TARGET_NORDIC/TARGET_NRF51822/spi_api.c index b403aa4aa5..c773fc2391 100644 --- a/libraries/mbed/targets/hal/TARGET_NORDIC/TARGET_NRF51822/spi_api.c +++ b/libraries/mbed/targets/hal/TARGET_NORDIC/TARGET_NRF51822/spi_api.c @@ -170,7 +170,7 @@ static inline void spi_enable(spi_t *obj, int slave) { } void spi_format(spi_t *obj, int bits, int mode, int slave) { - uint32_t config_mode; + uint32_t config_mode = 0; spi_disable(obj,slave); if (bits != 8) { diff --git a/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC11U6X/PeripheralNames.h b/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC11U6X/PeripheralNames.h index 963fc28afa..21a8a637ff 100644 --- a/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC11U6X/PeripheralNames.h +++ b/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC11U6X/PeripheralNames.h @@ -31,30 +31,18 @@ typedef enum { } UARTName; typedef enum { - ADC0_0 = 0, - ADC0_1, - ADC0_2, - ADC0_3, - ADC0_4, - ADC0_5, - ADC0_6, - ADC0_7, - ADC0_8, - ADC0_9, - ADC0_10, - ADC0_11, - ADC1_0, - ADC1_1, - ADC1_2, - ADC1_3, - ADC1_4, - ADC1_5, - ADC1_6, - ADC1_7, - ADC1_8, - ADC1_9, - ADC1_10, - ADC1_11, + ADC_0 = 0, + ADC_1, + ADC_2, + ADC_3, + ADC_4, + ADC_5, + ADC_6, + ADC_7, + ADC_8, + ADC_9, + ADC_10, + ADC_11, } ADCName; typedef enum { @@ -67,6 +55,16 @@ typedef enum { I2C_1 = (int)LPC_I2C1_BASE } I2CName; +typedef enum { + SCT0_0 = 0, + SCT0_1, + SCT0_2, + SCT0_3, + SCT1_0, + SCT1_1, + SCT1_2, + SCT1_3, +} PWMName; #ifdef __cplusplus } diff --git a/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC11U6X/PinNames.h b/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC11U6X/PinNames.h index 4d43a937ea..143c5775ea 100644 --- a/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC11U6X/PinNames.h +++ b/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC11U6X/PinNames.h @@ -121,10 +121,10 @@ typedef enum { LED_BLUE = P2_18, // mbed original LED naming - LED1 = LED_BLUE, + LED1 = LED_RED, LED2 = LED_GREEN, - LED3 = LED_RED, - LED4 = LED_RED, + LED3 = LED_BLUE, + LED4 = LED_BLUE, // Serial to USB pins USBTX = P0_19, diff --git a/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC11U6X/analogin_api.c b/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC11U6X/analogin_api.c new file mode 100644 index 0000000000..0930d0fe5a --- /dev/null +++ b/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC11U6X/analogin_api.c @@ -0,0 +1,135 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2013 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "analogin_api.h" +#include "cmsis.h" +#include "pinmap.h" +#include "error.h" + +#if DEVICE_ANALOGIN + +#define ANALOGIN_MEDIAN_FILTER 1 + +#define ADC_10BIT_RANGE 0x3FF +#define ADC_12BIT_RANGE 0xFFF +#define PDRUN_VALID_BITS 0x000025FFL +#define PDRUN_RESERVED_ONE 0x0000C800L + +#define ADC_RANGE ADC_12BIT_RANGE + +static const PinMap PinMap_ADC[] = { + {P1_9 , ADC_0, 3}, + {P0_23, ADC_1, 1}, + {P0_16, ADC_2, 1}, + {P0_15, ADC_3, 3}, + {P1_22, ADC_4, 3}, + {P1_3 , ADC_5, 4}, + {P0_14, ADC_6, 2}, + {P0_13, ADC_7, 2}, + {P0_12, ADC_8, 2}, + {P0_11, ADC_9, 2}, + {P1_29, ADC_10,4}, + {P0_22, ADC_11,1}, + {NC , NC ,0} +}; + + +void analogin_init(analogin_t *obj, PinName pin) { + volatile uint32_t tmp; + obj->adc = (ADCName)pinmap_peripheral(pin, PinMap_ADC); + if (obj->adc == (uint32_t)NC) { + error("ADC pin mapping failed"); + } + pinmap_pinout(pin, PinMap_ADC); + + __IO uint32_t *reg = (__IO uint32_t*)(LPC_IOCON_BASE + (pin & 0x1FF)); + // set pin to ADC mode + *reg &= ~(1 << 7); // set ADMODE = 0 (analog mode) + + // ADC Powered + tmp = (LPC_SYSCON->PDRUNCFG & PDRUN_VALID_BITS); + tmp &= ~((1 << 4) & PDRUN_VALID_BITS); + LPC_SYSCON->PDRUNCFG = (tmp | PDRUN_RESERVED_ONE); + + // Enable clock for ADC + LPC_SYSCON->SYSAHBCLKCTRL |= (1 << 13); + + // Start ADC self-calibration + LPC_ADC->CTRL = (1UL << 30); + do { + tmp = LPC_ADC->CTRL; + } while ((tmp & (1UL << 30)) != 0); + + LPC_ADC->CTRL = 1; // Sampling clock: SystemClock divided by 1 +} + +static inline uint32_t adc_read(analogin_t *obj) { + + // select channel + LPC_ADC->SEQA_CTRL &= ~(0xFFF); + LPC_ADC->SEQA_CTRL |= (1UL << obj->adc); + + // start conversion, sequence enable with async mode + LPC_ADC->SEQA_CTRL |= ((1UL << 26) | (1UL << 31) | (1UL << 19)); + + // Repeatedly get the sample data until DONE bit + volatile uint32_t data; + do { + data = LPC_ADC->SEQA_GDAT; + } while ((data & (1UL << 31)) == 0); + data = LPC_ADC->DAT[obj->adc]; + + // Stop conversion + LPC_ADC->SEQA_CTRL &= ~(1UL << 31); + + return ((data >> 4) & ADC_RANGE); +} + +static inline void order(uint32_t *a, uint32_t *b) { + if (*a > *b) { + uint32_t t = *a; + *a = *b; + *b = t; + } +} + +static inline uint32_t adc_read_u32(analogin_t *obj) { + uint32_t value; +#if ANALOGIN_MEDIAN_FILTER + uint32_t v1 = adc_read(obj); + uint32_t v2 = adc_read(obj); + uint32_t v3 = adc_read(obj); + order(&v1, &v2); + order(&v2, &v3); + order(&v1, &v2); + value = v2; +#else + value = adc_read(obj); +#endif + return value; +} + +uint16_t analogin_read_u16(analogin_t *obj) { + uint32_t value = adc_read_u32(obj); + return (value << 4) | ((value >> 8) & 0x000F); // 12 bit +} + +float analogin_read(analogin_t *obj) { + uint32_t value = adc_read_u32(obj); + return (float)value * (1.0f / (float)ADC_RANGE); +} + +#endif diff --git a/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC11U6X/device.h b/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC11U6X/device.h index 693b8bc2ae..38362a1794 100644 --- a/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC11U6X/device.h +++ b/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC11U6X/device.h @@ -22,14 +22,13 @@ #define DEVICE_INTERRUPTIN 1 -#define DEVICE_ANALOGIN 0 +#define DEVICE_ANALOGIN 1 #define DEVICE_ANALOGOUT 0 #define DEVICE_SERIAL 1 -#define DEVICE_SERIAL_FC 1 #define DEVICE_I2C 1 -#define DEVICE_I2CSLAVE 0 +#define DEVICE_I2CSLAVE 1 #define DEVICE_SPI 1 #define DEVICE_SPISLAVE 0 @@ -40,7 +39,7 @@ #define DEVICE_ETHERNET 0 -#define DEVICE_PWMOUT 0 +#define DEVICE_PWMOUT 1 #define DEVICE_SEMIHOST 0 #define DEVICE_LOCALFILESYSTEM 0 diff --git a/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC11U6X/gpio_api.c b/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC11U6X/gpio_api.c index c0702ae982..50727713da 100644 --- a/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC11U6X/gpio_api.c +++ b/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC11U6X/gpio_api.c @@ -26,10 +26,15 @@ static void gpio_enable(void) { } uint32_t gpio_set(PinName pin) { - if (!gpio_enabled) gpio_enable(); + int f = ((pin == P0_0) || + (pin == P0_10) || + (pin == P0_15)) ? (1) : (0); + + pin_function(pin, f); + return (1UL << ((int)pin >> PIN_SHIFT & 0x1F)); } diff --git a/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC11U6X/i2c_api.c b/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC11U6X/i2c_api.c index 48830e027b..d1e771d334 100644 --- a/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC11U6X/i2c_api.c +++ b/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC11U6X/i2c_api.c @@ -44,10 +44,9 @@ static const PinMap PinMap_I2C_SCL[] = { #define I2C_SCLL(x, val) (x->i2c->SCLL = val) #define I2C_SCLH(x, val) (x->i2c->SCLH = val) -#warning [TODO] just copied from LPC11UXX code, need to check static const uint32_t I2C_addr_offset[2][4] = { - {0x0C, 0x20, 0x24, 0x28}, - {0x30, 0x34, 0x38, 0x3C} + {0x0C, 0x20, 0x24, 0x28}, // slave address offset + {0x30, 0x34, 0x38, 0x3C} // slave address mask offset }; static inline void i2c_conclr(i2c_t *obj, int start, int stop, int interrupt, int acknowledge) { @@ -183,8 +182,7 @@ static inline int i2c_do_read(i2c_t *obj, int last) { void i2c_frequency(i2c_t *obj, int hz) { // No peripheral clock divider on the M0 -#warning "[TODO] This should be fixed to handle system core clock correctly." - uint32_t PCLK = 12000000; //SystemCoreClock; + uint32_t PCLK = SystemCoreClock; uint32_t pulse = PCLK / (hz * 2); diff --git a/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC11U6X/objects.h b/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC11U6X/objects.h index 58f05204f0..796b97abc4 100644 --- a/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC11U6X/objects.h +++ b/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC11U6X/objects.h @@ -41,6 +41,7 @@ struct pwmout_s { #if DEVICE_SERIAL struct serial_s { LPC_USART0_Type *uart; + LPC_USART4_Type *mini_uart; unsigned char index; }; #endif diff --git a/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC11U6X/pwmout_api.c b/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC11U6X/pwmout_api.c new file mode 100644 index 0000000000..d5e63a621d --- /dev/null +++ b/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC11U6X/pwmout_api.c @@ -0,0 +1,190 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2013 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "pwmout_api.h" +#include "cmsis.h" +#include "pinmap.h" +#include "error.h" + +#if DEVICE_PWMOUT + +#define SCT_CHANNELS 2 + +static const PinMap PinMap_PWM[] = { + {P1_19, SCT0_0, 2}, + {P2_2 , SCT0_1, 3}, + {P2_7 , SCT0_2, 2}, + {P1_13, SCT0_3, 2}, + {P2_16, SCT1_0, 1}, + {P2_17, SCT1_1, 1}, + {P2_18, SCT1_2, 1}, + {P2_19, SCT1_3, 1}, + {NC , NC ,0} +}; + + +static LPC_SCT0_Type *SCTs[SCT_CHANNELS] = { + (LPC_SCT0_Type*)LPC_SCT0, + (LPC_SCT0_Type*)LPC_SCT1, + +}; + +// bit flags for used SCTs +static unsigned char sct_used = 0; + +static int get_available_sct(void) { + int i; + for (i=0; ipwm = SCTs[sct_n]; + obj->pwm_ch = sct_n; + + // Enable the SCT clock + LPC_SYSCON->SYSAHBCLKCTRL |= (1UL << 31); + + // Clear peripheral reset the SCT: + LPC_SYSCON->PRESETCTRL |= (1 << (obj->pwm_ch + 9)); + pinmap_pinout(pin, PinMap_PWM); + LPC_SCT0_Type* pwm = obj->pwm; + + // Two 16-bit counters, autolimit + pwm->CONFIG &= ~(0x1); + pwm->CONFIG |= (1 << 17); + + // halt and clear the counter + pwm->CTRL |= (1 << 2) | (1 << 3); + + // System Clock -> us_ticker (1)MHz + pwm->CTRL &= ~(0x7F << 5); + pwm->CTRL |= (((SystemCoreClock/1000000 - 1) & 0x7F) << 5); + + switch(pwm_mapped) { + case SCT0_0: + case SCT1_0: + pwm->OUT0_SET = (1 << 0); // event 0 + pwm->OUT0_CLR = (1 << 1); // event 1 + break; + case SCT0_1: + case SCT1_1: + pwm->OUT1_SET = (1 << 0); // event 0 + pwm->OUT1_CLR = (1 << 1); // event 1 + break; + case SCT0_2: + case SCT1_2: + pwm->OUT2_SET = (1 << 0); // event 0 + pwm->OUT2_CLR = (1 << 1); // event 1 + break; + case SCT0_3: + case SCT1_3: + pwm->OUT3_SET = (1 << 0); // event 0 + pwm->OUT3_CLR = (1 << 1); // event 1 + break; + default: + break; + } + // Event 0 : MATCH and MATCHSEL=0 + pwm->EV0_CTRL = (1 << 12); + pwm->EV0_STATE = 0xFFFFFFFF; + // Event 1 : MATCH and MATCHSEL=1 + pwm->EV1_CTRL = (1 << 12) | (1 << 0); + pwm->EV1_STATE = 0xFFFFFFFF; + + // Match reload register + pwm->MATCHREL0 = 20000; // 20ms + pwm->MATCHREL1 = (pwm->MATCHREL0 / 4); // 50% duty + + // unhalt the counter: + // - clearing bit 2 of the CTRL register + pwm->CTRL &= ~(1 << 2); + + // default to 20ms: standard for servos, and fine for e.g. brightness control + pwmout_period_ms(obj, 20); + pwmout_write (obj, 0); +} + +void pwmout_free(pwmout_t* obj) { + sct_used &= ~(1 << obj->pwm_ch); + if (sct_used == 0) { + // Disable the SCT clock + LPC_SYSCON->SYSAHBCLKCTRL &= ~(1UL << 31); + } +} + +void pwmout_write(pwmout_t* obj, float value) { + if (value < 0.0f) { + value = 0.0; + } else if (value > 1.0f) { + value = 1.0; + } + uint32_t t_off = obj->pwm->MATCHREL0 - (uint32_t)((float)(obj->pwm->MATCHREL0) * value); + uint32_t t_on = (uint32_t)((float)(obj->pwm->MATCHREL0) * value); + obj->pwm->MATCHREL1 = t_on; +} + +float pwmout_read(pwmout_t* obj) { + uint32_t t_off = obj->pwm->MATCHREL0; + uint32_t t_on = obj->pwm->MATCHREL1; + float v = (float)t_on/(float)t_off; + return (v > 1.0f) ? (1.0f) : (v); +} + +void pwmout_period(pwmout_t* obj, float seconds) { + pwmout_period_us(obj, seconds * 1000000.0f); +} + +void pwmout_period_ms(pwmout_t* obj, int ms) { + pwmout_period_us(obj, ms * 1000); +} + +// Set the PWM period, keeping the duty cycle the same. +void pwmout_period_us(pwmout_t* obj, int us) { + uint32_t t_off = obj->pwm->MATCHREL0; + uint32_t t_on = obj->pwm->MATCHREL1; + float v = (float)t_on/(float)t_off; + obj->pwm->MATCHREL0 = (uint64_t)us; + obj->pwm->MATCHREL1 = (uint64_t)((float)us * (float)v); +} + +void pwmout_pulsewidth(pwmout_t* obj, float seconds) { + pwmout_pulsewidth_us(obj, seconds * 1000000.0f); +} + +void pwmout_pulsewidth_ms(pwmout_t* obj, int ms) { + pwmout_pulsewidth_us(obj, ms * 1000); +} + +void pwmout_pulsewidth_us(pwmout_t* obj, int us) { + obj->pwm->MATCHREL1 = (uint64_t)us; +} + +#endif diff --git a/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC11U6X/serial_api.c b/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC11U6X/serial_api.c index bd76671ada..9e51e10653 100644 --- a/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC11U6X/serial_api.c +++ b/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC11U6X/serial_api.c @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + // math.h required for floating point operations for baud rate calculation #include #include @@ -24,18 +25,31 @@ #include "error.h" #if DEVICE_SERIAL -#warning "[TODO] support from UART_1 to UART_4" + /****************************************************************************** * INITIALIZATION ******************************************************************************/ -#define UART_NUM 5 +#define UART_NUM 5 + +// CFG +#define UART_EN (0x01<<0) + +// CTL +#define TXBRKEN (0x01<<1) + +// STAT +#define RXRDY (0x01<<0) +#define TXRDY (0x01<<2) +#define DELTACTS (0x01<<5) +#define RXBRK (0x01<<10) +#define DELTARXBRK (0x01<<11) static const PinMap PinMap_UART_TX[] = { {P0_19, UART_0, 1}, {P1_18, UART_0, 2}, {P1_27, UART_0, 2}, - {P1_18, UART_1, 2}, + {P1_8 , UART_1, 2}, {P1_0 , UART_2, 3}, {P1_23, UART_2, 3}, {P2_4 , UART_3, 1}, @@ -72,27 +86,55 @@ void serial_init(serial_t *obj, PinName tx, PinName rx) { error("Serial pinout mapping failed"); } - obj->uart = (LPC_USART0_Type *)uart; - LPC_SYSCON->SYSAHBCLKCTRL |= ((1<<12) | (1<<20) | (1<<21) | (1<<22)); - - // [TODO] Consider more elegant approach - // disconnect USBTX/RX mapping mux, for case when switching ports -#ifdef USBTX - pin_function(USBTX, 0); - pin_function(USBRX, 0); -#endif + switch (uart) { + case UART_0: + obj->index = 0; + LPC_SYSCON->SYSAHBCLKCTRL |= (1 << 12); + break; + case UART_1: + obj->index = 1; + LPC_SYSCON->SYSAHBCLKCTRL |= (1 << 20); + LPC_SYSCON->PRESETCTRL |= (1 << 5); + break; + case UART_2: + obj->index = 2; + LPC_SYSCON->SYSAHBCLKCTRL |= (1 << 21); + LPC_SYSCON->PRESETCTRL |= (1 << 6); + break; + case UART_3: + obj->index = 3; + LPC_SYSCON->SYSAHBCLKCTRL |= (1 << 22); + LPC_SYSCON->PRESETCTRL |= (1 << 7); + break; + case UART_4: + obj->index = 4; + LPC_SYSCON->SYSAHBCLKCTRL |= (1 << 22); + LPC_SYSCON->PRESETCTRL |= (1 << 8); + break; + } - // enable fifos and default rx trigger level - obj->uart->FCR = 1 << 0 // FIFO Enable - 0 = Disables, 1 = Enabled - | 0 << 1 // Rx Fifo Clear - | 0 << 2 // Tx Fifo Clear - | 0 << 6; // Rx irq trigger level - 0 = 1 char, 1 = 4 chars, 2 = 8 chars, 3 = 14 chars - - // disable irqs - obj->uart->IER = 0 << 0 // Rx Data available irq enable - | 0 << 1 // Tx Fifo empty irq enable - | 0 << 2; // Rx Line Status irq enable + if (obj->index == 0) + obj->uart = (LPC_USART0_Type *)uart; + else + obj->mini_uart = (LPC_USART4_Type *)uart; + if (obj->index == 0) { + // enable fifos and default rx trigger level + obj->uart->FCR = 1 << 0 // FIFO Enable - 0 = Disables, 1 = Enabled + | 0 << 1 // Rx Fifo Clear + | 0 << 2 // Tx Fifo Clear + | 0 << 6; // Rx irq trigger level - 0 = 1 char, 1 = 4 chars, 2 = 8 chars, 3 = 14 chars + // disable irqs + obj->uart->IER = 0 << 0 // Rx Data available irq enable + | 0 << 1 // Tx Fifo empty irq enable + | 0 << 2; // Rx Line Status irq enable + } + else { + // Clear all status bits + obj->mini_uart->STAT = (DELTACTS | DELTARXBRK); + // Enable UART + obj->mini_uart->CFG |= UART_EN; + } // set default baud rate and format serial_baud (obj, 9600); serial_format(obj, 8, ParityNone, 1); @@ -105,17 +147,9 @@ void serial_init(serial_t *obj, PinName tx, PinName rx) { pin_mode(tx, PullUp); pin_mode(rx, PullUp); - switch (uart) { - case UART_0: obj->index = 0; break; - case UART_1: obj->index = 1; break; - case UART_2: obj->index = 2; break; - case UART_3: obj->index = 3; break; - case UART_4: obj->index = 4; break; - } - is_stdio_uart = (uart == STDIO_UART) ? (1) : (0); - if (is_stdio_uart) { + if (is_stdio_uart && (obj->index == 0)) { stdio_uart_inited = 1; memcpy(&stdio_uart, obj, sizeof(serial_t)); } @@ -128,81 +162,93 @@ void serial_free(serial_t *obj) { // serial_baud // set the baud rate, taking in to account the current SystemFrequency void serial_baud(serial_t *obj, int baudrate) { - LPC_SYSCON->USART0CLKDIV = 0x1; -#warning "[TODO] This should be fixed to handle system core clock correctly." - uint32_t PCLK = 12000000; //SystemCoreClock; - // First we check to see if the basic divide with no DivAddVal/MulVal - // ratio gives us an integer result. If it does, we set DivAddVal = 0, - // MulVal = 1. Otherwise, we search the valid ratio value range to find - // the closest match. This could be more elegant, using search methods - // and/or lookup tables, but the brute force method is not that much - // slower, and is more maintainable. - uint16_t DL = PCLK / (16 * baudrate); - - uint8_t DivAddVal = 0; - uint8_t MulVal = 1; - int hit = 0; - uint16_t dlv; - uint8_t mv, dav; - if ((PCLK % (16 * baudrate)) != 0) { // Checking for zero remainder - int err_best = baudrate, b; - for (mv = 1; mv < 16 && !hit; mv++) - { - for (dav = 0; dav < mv; dav++) + LPC_SYSCON->USART0CLKDIV = 1; + LPC_SYSCON->FRGCLKDIV = 1; + + if (obj->index == 0) { + uint32_t PCLK = SystemCoreClock; + // First we check to see if the basic divide with no DivAddVal/MulVal + // ratio gives us an integer result. If it does, we set DivAddVal = 0, + // MulVal = 1. Otherwise, we search the valid ratio value range to find + // the closest match. This could be more elegant, using search methods + // and/or lookup tables, but the brute force method is not that much + // slower, and is more maintainable. + uint16_t DL = PCLK / (16 * baudrate); + + uint8_t DivAddVal = 0; + uint8_t MulVal = 1; + int hit = 0; + uint16_t dlv; + uint8_t mv, dav; + if ((PCLK % (16 * baudrate)) != 0) { // Checking for zero remainder + int err_best = baudrate, b; + for (mv = 1; mv < 16 && !hit; mv++) { - // baudrate = PCLK / (16 * dlv * (1 + (DivAdd / Mul)) - // solving for dlv, we get dlv = mul * PCLK / (16 * baudrate * (divadd + mul)) - // mul has 4 bits, PCLK has 27 so we have 1 bit headroom which can be used for rounding - // for many values of mul and PCLK we have 2 or more bits of headroom which can be used to improve precision - // note: X / 32 doesn't round correctly. Instead, we use ((X / 16) + 1) / 2 for correct rounding - - if ((mv * PCLK * 2) & 0x80000000) // 1 bit headroom - dlv = ((((2 * mv * PCLK) / (baudrate * (dav + mv))) / 16) + 1) / 2; - else // 2 bits headroom, use more precision - dlv = ((((4 * mv * PCLK) / (baudrate * (dav + mv))) / 32) + 1) / 2; - - // datasheet says if DLL==DLM==0, then 1 is used instead since divide by zero is ungood - if (dlv == 0) - dlv = 1; - - // datasheet says if dav > 0 then DL must be >= 2 - if ((dav > 0) && (dlv < 2)) - dlv = 2; - - // integer rearrangement of the baudrate equation (with rounding) - b = ((PCLK * mv / (dlv * (dav + mv) * 8)) + 1) / 2; - - // check to see how we went - b = abs(b - baudrate); - if (b < err_best) + for (dav = 0; dav < mv; dav++) { - err_best = b; + // baudrate = PCLK / (16 * dlv * (1 + (DivAdd / Mul)) + // solving for dlv, we get dlv = mul * PCLK / (16 * baudrate * (divadd + mul)) + // mul has 4 bits, PCLK has 27 so we have 1 bit headroom which can be used for rounding + // for many values of mul and PCLK we have 2 or more bits of headroom which can be used to improve precision + // note: X / 32 doesn't round correctly. Instead, we use ((X / 16) + 1) / 2 for correct rounding - DL = dlv; - MulVal = mv; - DivAddVal = dav; + if ((mv * PCLK * 2) & 0x80000000) // 1 bit headroom + dlv = ((((2 * mv * PCLK) / (baudrate * (dav + mv))) / 16) + 1) / 2; + else // 2 bits headroom, use more precision + dlv = ((((4 * mv * PCLK) / (baudrate * (dav + mv))) / 32) + 1) / 2; - if (b == baudrate) + // datasheet says if DLL==DLM==0, then 1 is used instead since divide by zero is ungood + if (dlv == 0) + dlv = 1; + + // datasheet says if dav > 0 then DL must be >= 2 + if ((dav > 0) && (dlv < 2)) + dlv = 2; + + // integer rearrangement of the baudrate equation (with rounding) + b = ((PCLK * mv / (dlv * (dav + mv) * 8)) + 1) / 2; + + // check to see how we went + b = abs(b - baudrate); + if (b < err_best) { - hit = 1; - break; + err_best = b; + + DL = dlv; + MulVal = mv; + DivAddVal = dav; + + if (b == baudrate) + { + hit = 1; + break; + } } } } } + + // set LCR[DLAB] to enable writing to divider registers + obj->uart->LCR |= (1 << 7); + + // set divider values + obj->uart->DLM = (DL >> 8) & 0xFF; + obj->uart->DLL = (DL >> 0) & 0xFF; + obj->uart->FDR = (uint32_t) DivAddVal << 0 + | (uint32_t) MulVal << 4; + + // clear LCR[DLAB] + obj->uart->LCR &= ~(1 << 7); + } + else { + uint32_t UARTSysClk = SystemCoreClock / LPC_SYSCON->FRGCLKDIV; + obj->mini_uart->BRG = UARTSysClk / 16 / baudrate - 1; + + LPC_SYSCON->UARTFRGDIV = 0xFF; + LPC_SYSCON->UARTFRGMULT = ( ((UARTSysClk / 16) * (LPC_SYSCON->UARTFRGDIV + 1)) / + (baudrate * (obj->mini_uart->BRG + 1)) + ) - (LPC_SYSCON->UARTFRGDIV + 1); } - - // set LCR[DLAB] to enable writing to divider registers - obj->uart->LCR |= (1 << 7); - - // set divider values - obj->uart->DLM = (DL >> 8) & 0xFF; - obj->uart->DLL = (DL >> 0) & 0xFF; - obj->uart->FDR = (uint32_t) DivAddVal << 0 - | (uint32_t) MulVal << 4; - - // clear LCR[DLAB] - obj->uart->LCR &= ~(1 << 7); } void serial_format(serial_t *obj, int data_bits, SerialParity parity, int stop_bits) { @@ -212,35 +258,57 @@ void serial_format(serial_t *obj, int data_bits, SerialParity parity, int stop_b } stop_bits -= 1; - // 0: 5 data bits ... 3: 8 data bits - if (data_bits < 5 || data_bits > 8) { - error("Invalid number of bits (%d) in serial format, should be 5..8", data_bits); - } - data_bits -= 5; - - int parity_enable, parity_select; - switch (parity) { - case ParityNone: parity_enable = 0; parity_select = 0; break; - case ParityOdd : parity_enable = 1; parity_select = 0; break; - case ParityEven: parity_enable = 1; parity_select = 1; break; - case ParityForced1: parity_enable = 1; parity_select = 2; break; - case ParityForced0: parity_enable = 1; parity_select = 3; break; - default: - error("Invalid serial parity setting"); - return; - } + if (obj->index == 0) { + // 0: 5 data bits ... 3: 8 data bits + if (data_bits < 5 || data_bits > 8) { + error("Invalid number of bits (%d) in serial format, should be 5..8", data_bits); + } + data_bits -= 5; - obj->uart->LCR = data_bits << 0 - | stop_bits << 2 - | parity_enable << 3 - | parity_select << 4; + int parity_enable, parity_select; + switch (parity) { + case ParityNone: parity_enable = 0; parity_select = 0; break; + case ParityOdd : parity_enable = 1; parity_select = 0; break; + case ParityEven: parity_enable = 1; parity_select = 1; break; + case ParityForced1: parity_enable = 1; parity_select = 2; break; + case ParityForced0: parity_enable = 1; parity_select = 3; break; + default: + error("Invalid serial parity setting"); + return; + } + + obj->uart->LCR = data_bits << 0 + | stop_bits << 2 + | parity_enable << 3 + | parity_select << 4; + } + else { + // 0: 7 data bits ... 2: 9 data bits + if (data_bits < 7 || data_bits > 9) { + error("Invalid number of bits (%d) in serial format, should be 7..9", data_bits); + } + data_bits -= 7; + + int paritysel; + switch (parity) { + case ParityNone: paritysel = 0; break; + case ParityEven: paritysel = 2; break; + case ParityOdd : paritysel = 3; break; + default: + error("Invalid serial parity setting"); + return; + } + obj->mini_uart->CFG = (data_bits << 2) + | (paritysel << 4) + | (stop_bits << 6) + | UART_EN; + } } /****************************************************************************** * INTERRUPTS HANDLING ******************************************************************************/ static inline void uart_irq(uint32_t iir, uint32_t index) { - // [Chapter 14] LPC17xx UART0/2/3: UARTn Interrupt Handling SerialIrq irq_type; switch (iir) { case 1: irq_type = TxIrq; break; @@ -259,22 +327,22 @@ void uart0_irq() void uart1_irq() { - //uart_irq((LPC_USART4->IIR >> 1) & 0x7, 1); + uart_irq((LPC_USART1->STAT & (1 << 2)) ? 2 : 1, 1); } void uart2_irq() { - //uart_irq((LPC_USART4->IIR >> 1) & 0x7, 2); + uart_irq((LPC_USART1->STAT & (1 << 2)) ? 2 : 1, 2); } void uart3_irq() { - //uart_irq((LPC_USART4->IIR >> 1) & 0x7, 3); + uart_irq((LPC_USART1->STAT & (1 << 2)) ? 2 : 1, 3); } void uart4_irq() { - //uart_irq((LPC_USART4->IIR >> 1) & 0x7, 4); + uart_irq((LPC_USART1->STAT & (1 << 2)) ? 2 : 1, 4); } void serial_irq_handler(serial_t *obj, uart_irq_handler handler, uint32_t id) { @@ -294,16 +362,27 @@ void serial_irq_set(serial_t *obj, SerialIrq irq, uint32_t enable) { } if (enable) { - obj->uart->IER |= (1 << irq); + if (obj->index == 0) { + obj->uart->IER |= (1 << irq); + } + else { + obj->mini_uart->INTENSET = (1 << ((irq == RxIrq) ? 0 : 2)); + } NVIC_SetVector(irq_n, vector); NVIC_EnableIRQ(irq_n); } else { // disable int all_disabled = 0; SerialIrq other_irq = (irq == RxIrq) ? (TxIrq) : (RxIrq); - obj->uart->IER &= ~(1 << irq); - all_disabled = (obj->uart->IER & (1 << other_irq)) == 0; - + if (obj->index == 0) { + obj->uart->IER &= ~(1 << irq); + all_disabled = (obj->uart->IER & (1 << other_irq)) == 0; + } + else { + obj->mini_uart->INTENSET &= ~(1 << ((irq == RxIrq) ? 0 : 2)); + all_disabled = (obj->mini_uart->INTENSET & (1 << ((other_irq == RxIrq) ? 0 : 2))) == 0; + } + if (all_disabled) NVIC_DisableIRQ(irq_n); } @@ -314,26 +393,51 @@ void serial_irq_set(serial_t *obj, SerialIrq irq, uint32_t enable) { ******************************************************************************/ int serial_getc(serial_t *obj) { while (!serial_readable(obj)); - return obj->uart->RBR; + if (obj->index == 0) { + return obj->uart->RBR; + } + else { + return obj->mini_uart->RXDAT; + } } void serial_putc(serial_t *obj, int c) { while (!serial_writable(obj)); - obj->uart->THR = c; + if (obj->index == 0) { + obj->uart->THR = c; + } + else { + obj->mini_uart->TXDAT = c; + } } int serial_readable(serial_t *obj) { - return obj->uart->LSR & 0x01; + if (obj->index == 0) { + return obj->uart->LSR & 0x01; + } + else { + return obj->mini_uart->STAT & RXRDY; + } } int serial_writable(serial_t *obj) { - return obj->uart->LSR & 0x20; + if (obj->index == 0) { + return obj->uart->LSR & 0x20; + } + else { + return obj->mini_uart->STAT & TXRDY; + } } void serial_clear(serial_t *obj) { - obj->uart->FCR = 1 << 1 // rx FIFO reset - | 1 << 2 // tx FIFO reset - | 0 << 6; // interrupt depth + if (obj->index == 0) { + obj->uart->FCR = 1 << 1 // rx FIFO reset + | 1 << 2 // tx FIFO reset + | 0 << 6; // interrupt depth + } + else { + obj->mini_uart->STAT = 0; + } } void serial_pinout_tx(PinName tx) { @@ -341,11 +445,21 @@ void serial_pinout_tx(PinName tx) { } void serial_break_set(serial_t *obj) { - obj->uart->LCR |= (1 << 6); + if (obj->index == 0) { + obj->uart->LCR |= (1 << 6); + } + else { + obj->mini_uart->CTL |= TXBRKEN; + } } void serial_break_clear(serial_t *obj) { - obj->uart->LCR &= ~(1 << 6); + if (obj->index == 0) { + obj->uart->LCR &= ~(1 << 6); + } + else { + obj->mini_uart->CTL &= ~TXBRKEN; + } } diff --git a/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC11U6X/us_ticker.c b/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC11U6X/us_ticker.c index b3a8235f66..5ce7098cee 100644 --- a/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC11U6X/us_ticker.c +++ b/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC11U6X/us_ticker.c @@ -27,8 +27,7 @@ void us_ticker_init(void) { us_ticker_inited = 1; LPC_SYSCON->SYSAHBCLKCTRL |= (1<<10); // Clock CT32B1 -#warning "[TODO] this should read from SystemCoreClock grobal variable." - uint32_t PCLK = 12000000;//SystemCoreClock; + uint32_t PCLK = SystemCoreClock; US_TICKER_TIMER->TCR = 0x2; // reset diff --git a/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC11UXX/gpio_api.c b/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC11UXX/gpio_api.c index fc1120afde..4ddf5dc943 100644 --- a/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC11UXX/gpio_api.c +++ b/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC11UXX/gpio_api.c @@ -17,10 +17,13 @@ #include "pinmap.h" uint32_t gpio_set(PinName pin) { - int f = ((pin == P0_11) || + int f = ((pin == P0_0) || + (pin == P0_10) || + (pin == P0_11) || (pin == P0_12) || (pin == P0_13) || - (pin == P0_14)) ? (1) : (0); + (pin == P0_14) || + (pin == P0_15)) ? (1) : (0); pin_function(pin, f); diff --git a/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC11UXX/pwmout_api.c b/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC11UXX/pwmout_api.c index 4cf3f96481..29ebdbe000 100644 --- a/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC11UXX/pwmout_api.c +++ b/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC11UXX/pwmout_api.c @@ -113,9 +113,7 @@ void pwmout_write(pwmout_t* obj, float value) { LPC_CTxxBx_Type *timer = Timers[tid.timer]; uint32_t t_off = timer->MR3 - (uint32_t)((float)(timer->MR3) * value); - timer->TCR = TCR_RESET; timer->MR[tid.mr] = t_off; - timer->TCR = TCR_CNT_EN; } float pwmout_read(pwmout_t* obj) { diff --git a/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC11XX_11CXX/TARGET_LPC11CXX/can_api.c b/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC11XX_11CXX/TARGET_LPC11CXX/can_api.c index 509957e4c3..108bf6ef67 100644 --- a/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC11XX_11CXX/TARGET_LPC11CXX/can_api.c +++ b/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC11XX_11CXX/TARGET_LPC11CXX/can_api.c @@ -87,7 +87,7 @@ int can_filter(can_t *obj, uint32_t id, uint32_t mask, CANFormat format, int32_t LPC_CAN->IF1_CMDREQ = BFN_PREP(handle, CANIFn_CMDREQ_MN); // Wait until transfer to message ram complete - TODO: maybe not block?? - while( LPC_CAN->IF1_CMDREQ & CANIFn_CMDREQ_BUSY ); + while( LPC_CAN->IF1_CMDREQ & CANIFn_CMDREQ_BUSY ); } return handle; @@ -100,7 +100,7 @@ static inline void can_irq() { // Register CAN object's irq handler void can_irq_init(can_t *obj, can_irq_handler handler, uint32_t id) { irq_handler = handler; - can_irq_id = id; + can_irq_id = id; } // Unregister CAN object's irq handler @@ -264,18 +264,20 @@ int can_frequency(can_t *obj, int f) { btr = btr & 0xFFFF; if (btr > 0) { + uint32_t cntl_init = LPC_CAN->CNTL | CANCNTL_INIT; // Set the bit clock - LPC_CAN->CNTL |= CANCNTL_CCE; + LPC_CAN->CNTL |= CANCNTL_CCE | CANCNTL_INIT; LPC_CAN->CLKDIV = clkdiv; LPC_CAN->BT = btr; LPC_CAN->BRPE = 0x0000; - LPC_CAN->CNTL &= ~CANCNTL_CCE; + LPC_CAN->CNTL &= ~(CANCNTL_CCE | CANCNTL_INIT); + LPC_CAN->CNTL |= cntl_init; return 1; } return 0; } -int can_write(can_t *obj, CAN_Message msg, int cc) { +int can_write(can_t *obj, CAN_Message msg, int cc) { uint16_t msgnum = 0; // Make sure controller is enabled @@ -352,13 +354,13 @@ int can_read(can_t *obj, CAN_Message *msg, int handle) { // Wait until transfer to message ram complete while( LPC_CAN->IF2_CMDREQ & CANIFn_CMDREQ_BUSY ); - if (LPC_CAN->IF2_ARB2 & CANIFn_ARB2_XTD) { - msg->format = CANExtended; + if (LPC_CAN->IF2_ARB2 & CANIFn_ARB2_XTD) { + msg->format = CANExtended; msg->id = (LPC_CAN->IF2_ARB1 & CANIFn_ARB2_ID_MASK) << 16; msg->id |= (LPC_CAN->IF2_ARB2 & CANIFn_ARB2_ID_MASK); } else { - msg->format = CANStandard; + msg->format = CANStandard; msg->id = (LPC_CAN->IF2_ARB2 & CANIFn_ARB2_ID_MASK) >> 2; } diff --git a/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC13XX/pwmout_api.c b/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC13XX/pwmout_api.c index e306b24b48..6019056f21 100644 --- a/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC13XX/pwmout_api.c +++ b/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC13XX/pwmout_api.c @@ -119,9 +119,7 @@ void pwmout_write(pwmout_t* obj, float value) { LPC_CTxxBx_Type *timer = Timers[tid.timer]; uint32_t t_off = timer->MR3 - (uint32_t)((float)(timer->MR3) * value); - timer->TCR = TCR_RESET; timer->MR[tid.mr] = t_off; - timer->TCR = TCR_CNT_EN; } float pwmout_read(pwmout_t* obj) { diff --git a/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC15XX/PinNames.h b/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC15XX/PinNames.h index 5baa38bc5e..664d9b7161 100644 --- a/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC15XX/PinNames.h +++ b/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC15XX/PinNames.h @@ -39,10 +39,10 @@ typedef enum { LED_BLUE = P1_1, // mbed original LED naming - LED1 = LED_BLUE, + LED1 = LED_RED, LED2 = LED_GREEN, - LED3 = LED_RED, - LED4 = LED_RED, + LED3 = LED_BLUE, + LED4 = LED_BLUE, // Serial to USB pins USBTX = P0_18, diff --git a/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC15XX/analogin_api.c b/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC15XX/analogin_api.c index d5059fd5a0..57e835e875 100644 --- a/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC15XX/analogin_api.c +++ b/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC15XX/analogin_api.c @@ -59,25 +59,25 @@ void analogin_init(analogin_t *obj, PinName pin) { error("ADC pin mapping failed"); } uint32_t port = (pin >> 5); - // enable clock for GPIOx + // enable clock for GPIOx LPC_SYSCON->SYSAHBCLKCTRL0 |= (1UL << (14 + port)); - // pin enable - LPC_SWM->PINENABLE0 &= ~(1UL << obj->adc); + // pin enable + LPC_SWM->PINENABLE0 &= ~(1UL << obj->adc); // configure GPIO as input LPC_GPIO_PORT->DIR[port] &= ~(1UL << (pin & 0x1F)); - + // power up ADC if (obj->adc < ADC1_0) { // ADC0 LPC_SYSCON->PDRUNCFG &= ~(1 << 10); LPC_SYSCON->SYSAHBCLKCTRL0 |= (1 << 27); - } - else { - // ADC1 + } + else { + // ADC1 LPC_SYSCON->PDRUNCFG &= ~(1 << 11); LPC_SYSCON->SYSAHBCLKCTRL0 |= (1 << 28); - } + } // select IRC as async. clock, divided by 1 LPC_SYSCON->ADCASYNCCLKSEL = 0; @@ -95,12 +95,18 @@ void analogin_init(analogin_t *obj, PinName pin) { } static inline uint32_t adc_read(analogin_t *obj) { + uint32_t channels; __IO LPC_ADC0_Type *adc_reg = (obj->adc < ADC1_0) ? (__IO LPC_ADC0_Type*)(LPC_ADC0) : (__IO LPC_ADC0_Type*)(LPC_ADC1); + if (obj->adc >= ADC1_0) + channels = ((obj->adc - ADC1_0) & 0x1F); + else + channels = (obj->adc & 0x1F); + // select channel adc_reg->SEQA_CTRL &= ~(0xFFF); - adc_reg->SEQA_CTRL |= (1UL << (obj->adc & 0x1F)); + adc_reg->SEQA_CTRL |= (1UL << channels); // start conversion and sequence enable adc_reg->SEQA_CTRL |= ((1UL << 26) | (1UL << 31)); diff --git a/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC15XX/i2c_api.c b/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC15XX/i2c_api.c index 394b65ae89..09d7ec6b55 100644 --- a/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC15XX/i2c_api.c +++ b/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC15XX/i2c_api.c @@ -138,7 +138,7 @@ int i2c_read(i2c_t *obj, int address, char *data, int length, int stop) { LPC_I2C0->MSTCTL = (1 << 0); data[count] = (LPC_I2C0->MSTDAT & 0xFF); status = ((LPC_I2C0->STAT >> 1) & (0x07)); - if (status != 0x00) { + if (status != 0x01) { i2c_stop(obj); return count; } diff --git a/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC15XX/serial_api.c b/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC15XX/serial_api.c index 13667ff257..462b765f63 100644 --- a/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC15XX/serial_api.c +++ b/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC15XX/serial_api.c @@ -42,13 +42,13 @@ static const SWM_Map SWM_UART_RX[] = { static const SWM_Map SWM_UART_RTS[] = { {0, 16}, {1, 24}, - {3, 0}, + {3, 0}, // not available }; static const SWM_Map SWM_UART_CTS[] = { {0, 24}, {2, 0}, - {3, 8} + {3, 8} // not available }; // bit flags for used UARTs @@ -82,9 +82,29 @@ static uart_irq_handler irq_handler; int stdio_uart_inited = 0; serial_t stdio_uart; +static void switch_pin(const SWM_Map *swm, PinName pn) +{ + uint32_t regVal; + if (pn != NC) + { + // check if we have any function mapped to this pin already and remove it + for (int n = 0; n < sizeof(LPC_SWM->PINASSIGN)/sizeof(*LPC_SWM->PINASSIGN); n ++) { + regVal = LPC_SWM->PINASSIGN[n]; + for (int j = 0; j <= 24; j += 8) { + if (((regVal >> j) & 0xFF) == pn) + regVal |= (0xFF << j); + } + LPC_SWM->PINASSIGN[n] = regVal; + } + } + // now map it + regVal = LPC_SWM->PINASSIGN[swm->n] & ~(0xFF << swm->offset); + LPC_SWM->PINASSIGN[swm->n] = regVal | (pn << swm->offset); +} + void serial_init(serial_t *obj, PinName tx, PinName rx) { int is_stdio_uart = 0; - + int uart_n = get_available_uart(); if (uart_n == -1) { error("No available UART"); @@ -93,16 +113,8 @@ void serial_init(serial_t *obj, PinName tx, PinName rx) { obj->uart = (LPC_USART0_Type *)(LPC_USART0_BASE + (0x4000 * uart_n)); uart_used |= (1 << uart_n); - const SWM_Map *swm; - uint32_t regVal; - - swm = &SWM_UART_TX[uart_n]; - regVal = LPC_SWM->PINASSIGN[swm->n] & ~(0xFF << swm->offset); - LPC_SWM->PINASSIGN[swm->n] = regVal | (tx << swm->offset); - - swm = &SWM_UART_RX[uart_n]; - regVal = LPC_SWM->PINASSIGN[swm->n] & ~(0xFF << swm->offset); - LPC_SWM->PINASSIGN[swm->n] = regVal | (rx << swm->offset); + switch_pin(&SWM_UART_TX[uart_n], tx); + switch_pin(&SWM_UART_RX[uart_n], rx); /* uart clock divided by 6 */ LPC_SYSCON->UARTCLKDIV =6; @@ -296,33 +308,11 @@ void serial_break_clear(serial_t *obj) { } void serial_set_flow_control(serial_t *obj, FlowControl type, PinName rxflow, PinName txflow) { - const SWM_Map *swm_rts, *swm_cts; - uint32_t regVal_rts, regVal_cts; - - swm_rts = &SWM_UART_RTS[obj->index]; - swm_cts = &SWM_UART_CTS[obj->index]; - regVal_rts = LPC_SWM->PINASSIGN[swm_rts->n] & ~(0xFF << swm_rts->offset); - regVal_cts = LPC_SWM->PINASSIGN[swm_cts->n] & ~(0xFF << swm_cts->offset); - - if (FlowControlNone == type) { - LPC_SWM->PINASSIGN[swm_rts->n] = regVal_rts | (0xFF << swm_rts->offset); - LPC_SWM->PINASSIGN[swm_cts->n] = regVal_cts | (0xFF << swm_cts->offset); - obj->uart->CFG &= ~CTSEN; - return; - } - if ((FlowControlRTS == type || FlowControlRTSCTS == type) && (rxflow != NC)) { - LPC_SWM->PINASSIGN[swm_rts->n] = regVal_rts | (rxflow << swm_rts->offset); - if (FlowControlRTS == type) { - LPC_SWM->PINASSIGN[swm_cts->n] = regVal_cts | (0xFF << swm_cts->offset); - obj->uart->CFG &= ~CTSEN; - } - } - if ((FlowControlCTS == type || FlowControlRTSCTS == type) && (txflow != NC)) { - LPC_SWM->PINASSIGN[swm_cts->n] = regVal_cts | (txflow << swm_cts->offset); - obj->uart->CFG |= CTSEN; - if (FlowControlCTS == type) { - LPC_SWM->PINASSIGN[swm_rts->n] = regVal_rts | (0xFF << swm_rts->offset); - } - } + if ((FlowControlNone == type || FlowControlRTS == type)) txflow = NC; + if ((FlowControlNone == type || FlowControlCTS == type)) rxflow = NC; + switch_pin(&SWM_UART_RTS[obj->index], rxflow); + switch_pin(&SWM_UART_CTS[obj->index], txflow); + if (txflow == NC) obj->uart->CFG &= ~CTSEN; + else obj->uart->CFG |= CTSEN; } diff --git a/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC15XX/spi_api.c b/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC15XX/spi_api.c index 9d38588e43..10e03656da 100644 --- a/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC15XX/spi_api.c +++ b/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC15XX/spi_api.c @@ -191,7 +191,7 @@ static inline int spi_read(spi_t *obj) { return obj->spi->RXDAT; } -static inline int spi_busy(spi_t *obj) { +int spi_busy(spi_t *obj) { // checking RXOV(Receiver Overrun interrupt flag) return obj->spi->STAT & (1 << 2); } diff --git a/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC176X/TARGET_UBLOX_C027/C027_api.c b/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC176X/TARGET_UBLOX_C027/C027_api.c new file mode 100644 index 0000000000..cb290d45e7 --- /dev/null +++ b/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC176X/TARGET_UBLOX_C027/C027_api.c @@ -0,0 +1,81 @@ +/* mbed Microcontroller Library + * Copyright (c) 2006-2013 ARM Limited + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "gpio_api.h" +#include "wait_api.h" +#include "C027_api.h" + +static gpio_t mdmEn, mdmLvlOe, mdmILvlOe, mdmUsbDet; +static gpio_t gpsEn; + +void c027_init(void) { + gpio_t led, mdmRts, mdmRst, gpsRst, mdmPwrOn; + // start with modem disabled + gpio_init_out_ex(&mdmEn, MDMEN, 0); + gpio_init_out_ex(&mdmRst, MDMRST, 1); + gpio_init_out_ex(&mdmPwrOn, MDMPWRON, 1); + gpio_init_out_ex(&mdmLvlOe, MDMLVLOE, 1); // LVLEN: 1=disabled + gpio_init_out_ex(&mdmILvlOe, MDMILVLOE, 0); // ILVLEN: 0=disabled + gpio_init_out_ex(&mdmUsbDet, MDMUSBDET, 0); + gpio_init_out_ex(&mdmRts, MDMRTS, 0); + // start with gps disabled + gpio_init_out_ex(&gpsEn, GPSEN, 0); + gpio_init_out_ex(&gpsRst, GPSRST, 1); + // led should be off + gpio_init_out_ex(&led, LED, 0); + + wait_ms(50); // when USB cable is inserted the interface chip issues +} + +void c027_mdm_powerOn(int usb) { + // turn on the mode by enabling power with power on pin low and correct USB detect level + gpio_write(&mdmUsbDet, usb ? 1 : 0); // USBDET: 0=disabled, 1=enabled + if (!gpio_read(&mdmEn)) { // enable modem + gpio_write(&mdmEn, 1); // LDOEN: 1=on + wait_ms(1); // wait until supply switched off + // now we can safely enable the level shifters + gpio_write(&mdmLvlOe, 0); // LVLEN: 0=enabled (uart/gpio) + if (gpio_read(&gpsEn)) + gpio_write(&mdmILvlOe, 1); // ILVLEN: 1=enabled (i2c) + } +} + +void c027_mdm_powerOff(void) { + if (gpio_read(&mdmEn)) { + // diable all level shifters + gpio_write(&mdmILvlOe, 0); // ILVLEN: 0=disabled (i2c) + gpio_write(&mdmLvlOe, 1); // LVLEN: 1=disabled (uart/gpio) + gpio_write(&mdmUsbDet, 0); // USBDET: 0=disabled + // now we can savely switch off the ldo + gpio_write(&mdmEn, 0); // LDOEN: 0=off + } +} + +void c027_gps_powerOn(void) { + if (!gpio_read(&gpsEn)) { + // switch on power supply + gpio_write(&gpsEn, 1); // LDOEN: 1=on + wait_ms(1); // wait until supply switched off + if (gpio_read(&mdmEn)) + gpio_write(&mdmILvlOe, 1); // ILVLEN: 1=enabled (i2c) + } +} + +void c027_gps_powerOff(void) { + if (gpio_read(&gpsEn)) { + gpio_write(&mdmILvlOe, 0); // ILVLEN: 0=disabled (i2c) + gpio_write(&gpsEn, 0); // LDOEN: 0=off + } +} diff --git a/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC176X/TARGET_UBLOX_C027/C027_api.h b/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC176X/TARGET_UBLOX_C027/C027_api.h new file mode 100644 index 0000000000..46897945cb --- /dev/null +++ b/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC176X/TARGET_UBLOX_C027/C027_api.h @@ -0,0 +1,22 @@ +#ifndef C027_H +#define C027_H + +#ifdef __cplusplus +extern "C" { +#endif + +void c027_init(void); + +void c027_mdm_powerOn(int usb); + +void c027_mdm_powerOff(void); + +void c027_gps_powerOn(void); + +void c027_gps_powerOff(void); + +#ifdef __cplusplus +} +#endif + +#endif // C027_H diff --git a/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC176X/TARGET_UBLOX_C027/PinNames.h b/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC176X/TARGET_UBLOX_C027/PinNames.h index 7ec1b0ab08..0caa9b56df 100644 --- a/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC176X/TARGET_UBLOX_C027/PinNames.h +++ b/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC176X/TARGET_UBLOX_C027/PinNames.h @@ -145,6 +145,9 @@ typedef enum { // Other mbed Pin Names LED = P3_25, LED1 = LED, + LED2 = LED, + LED3 = LED, + LED4 = LED, LED_RED = LED, // mbed / debug IF (LPC11) diff --git a/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC176X/TARGET_UBLOX_C027/mbed_overrides.c b/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC176X/TARGET_UBLOX_C027/mbed_overrides.c index fba3793380..9d9eac1c19 100644 --- a/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC176X/TARGET_UBLOX_C027/mbed_overrides.c +++ b/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC176X/TARGET_UBLOX_C027/mbed_overrides.c @@ -13,31 +13,9 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#include "gpio_api.h" -#include "wait_api.h" +#include "C027_api.h" // called before main -void mbed_sdk_init() -{ - gpio_t modemEn, modemRst, modemPwrOn, modemLvlOe, modemILvlOe, modemUsbDet; - gpio_t gpsEn, gpsRst, led, modemRts; - - // start with modem disabled - gpio_init_out_ex(&modemEn, MDMEN, 0); - gpio_init_out_ex(&modemRst, MDMRST, 1); - gpio_init_out_ex(&modemPwrOn, MDMPWRON, 1); - gpio_init_out_ex(&modemLvlOe, MDMLVLOE, 1); - gpio_init_out_ex(&modemILvlOe, MDMILVLOE, 0); - gpio_init_out_ex(&modemUsbDet, MDMUSBDET, 0); - gpio_init_out_ex(&modemRts, MDMRTS, 0); - // start with gps disabled - gpio_init_out_ex(&gpsEn, GPSEN, 0); - gpio_init_out_ex(&gpsRst, GPSRST, 1); - // led should be off - gpio_init_out_ex(&led, LED, 0); - - wait_ms(50); // when USB cable is inserted the interface chip issues - // multiple resets to the target CPU We wait here for a short period to - // prevent those resets from propagating to the modem and other - // components. +void mbed_sdk_init() { + c027_init(); } diff --git a/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC176X/ethernet_api.c b/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC176X/ethernet_api.c index 97770bbd21..8b0d9cf860 100644 --- a/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC176X/ethernet_api.c +++ b/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC176X/ethernet_api.c @@ -52,27 +52,27 @@ const int ethernet_MTU_SIZE = 0x300; #define ETHERNET_ADDR_SIZE 6 -PACKED struct RX_DESC_TypeDef { /* RX Descriptor struct */ +struct RX_DESC_TypeDef { /* RX Descriptor struct */ unsigned int Packet; unsigned int Ctrl; -}; +} PACKED; typedef struct RX_DESC_TypeDef RX_DESC_TypeDef; -PACKED struct RX_STAT_TypeDef { /* RX Status struct */ +struct RX_STAT_TypeDef { /* RX Status struct */ unsigned int Info; unsigned int HashCRC; -}; +} PACKED; typedef struct RX_STAT_TypeDef RX_STAT_TypeDef; -PACKED struct TX_DESC_TypeDef { /* TX Descriptor struct */ +struct TX_DESC_TypeDef { /* TX Descriptor struct */ unsigned int Packet; unsigned int Ctrl; -}; +} PACKED; typedef struct TX_DESC_TypeDef TX_DESC_TypeDef; -PACKED struct TX_STAT_TypeDef { /* TX Status struct */ +struct TX_STAT_TypeDef { /* TX Status struct */ unsigned int Info; -}; +} PACKED; typedef struct TX_STAT_TypeDef TX_STAT_TypeDef; /* MAC Configuration Register 1 */ @@ -436,9 +436,9 @@ int ethernet_init() { int regv, tout; char mac[ETHERNET_ADDR_SIZE]; unsigned int clock = clockselect(); - + LPC_SC->PCONP |= 0x40000000; /* Power Up the EMAC controller. */ - + LPC_PINCON->PINSEL2 = 0x50150105; /* Enable P1 Ethernet Pins. */ LPC_PINCON->PINSEL3 = (LPC_PINCON->PINSEL3 & ~0x0000000F) | 0x00000005; @@ -531,9 +531,9 @@ int ethernet_init() { void ethernet_free() { LPC_EMAC->IntEnable &= ~(INT_RX_DONE | INT_TX_DONE); LPC_EMAC->IntClear = 0xFFFF; - + LPC_SC->PCONP &= ~0x40000000; /* Power down the EMAC controller. */ - + LPC_PINCON->PINSEL2 &= ~0x50150105; /* Disable P1 ethernet pins. */ LPC_PINCON->PINSEL3 = (LPC_PINCON->PINSEL3 & ~0x0000000F) | 0x00000000; } diff --git a/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC408X/PinNames.h b/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC408X/PinNames.h index b8290d1561..57b49d6aa8 100644 --- a/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC408X/PinNames.h +++ b/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC408X/PinNames.h @@ -83,6 +83,32 @@ typedef enum { USBTX = P0_2, USBRX = P0_3, + // QSB baseboard Arduino shield pins + D0 = p10, + D1 = p9, + D2 = p31, + D3 = p32, + D4 = p33, + D5 = p37, + D6 = p38, + D7 = p34, + D8 = p8, + D9 = p39, + D10 = p14, + D11 = p11, + D12 = p12, + D13 = p13, + D14 = p19, + D15 = p20, + + A0 = p15, + A1 = p16, + A2 = p17, + A3 = p18, + A4 = p19, + A5 = p20, + + // Not connected NC = (int)0xFFFFFFFF } PinName; diff --git a/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC81X/TARGET_LPC812/PinNames.h b/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC81X/TARGET_LPC812/PinNames.h index e220a86ea6..8696c143df 100644 --- a/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC81X/TARGET_LPC812/PinNames.h +++ b/libraries/mbed/targets/hal/TARGET_NXP/TARGET_LPC81X/TARGET_LPC812/PinNames.h @@ -60,6 +60,8 @@ typedef enum { D11 = P0_14, D12 = P0_15, D13 = P0_12, + D14 = P0_10, + D15 = P0_11, A4 = P0_10, A5 = P0_11, diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F030R8/PeripheralNames.h b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F030R8/PeripheralNames.h index eabfa62c03..220f5ad885 100644 --- a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F030R8/PeripheralNames.h +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F030R8/PeripheralNames.h @@ -46,7 +46,7 @@ typedef enum { } DACName; typedef enum { - UART_1 = (int)USART1_BASE, + UART_1 = (int)USART1_BASE, UART_2 = (int)USART2_BASE } UARTName; diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F030R8/analogin_api.c b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F030R8/analogin_api.c index 7283390b16..51277bde0d 100644 --- a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F030R8/analogin_api.c +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F030R8/analogin_api.c @@ -57,15 +57,15 @@ static const PinMap PinMap_ADC[] = { int adc_inited = 0; void analogin_init(analogin_t *obj, PinName pin) { - + ADC_TypeDef *adc; ADC_InitTypeDef ADC_InitStructure; - + // Get the peripheral name (ADC_1, ADC_2...) from the pin and assign it to the object obj->adc = (ADCName)pinmap_peripheral(pin, PinMap_ADC); - + if (obj->adc == (ADCName)NC) { - error("ADC pin mapping failed"); + error("ADC pin mapping failed"); } // Configure GPIO @@ -80,13 +80,13 @@ void analogin_init(analogin_t *obj, PinName pin) { // Get ADC registers structure address adc = (ADC_TypeDef *)(obj->adc); - + // Enable ADC clock RCC_APB2PeriphClockCmd(RCC_APB2Periph_ADC1, ENABLE); - + // Configure ADC ADC_InitStructure.ADC_Resolution = ADC_Resolution_12b; - ADC_InitStructure.ADC_ContinuousConvMode = DISABLE; + ADC_InitStructure.ADC_ContinuousConvMode = DISABLE; ADC_InitStructure.ADC_ExternalTrigConvEdge = ADC_ExternalTrigConvEdge_None; ADC_InitStructure.ADC_ExternalTrigConv = ADC_ExternalTrigConv_T1_TRGO; ADC_InitStructure.ADC_DataAlign = ADC_DataAlign_Right; @@ -102,81 +102,81 @@ void analogin_init(analogin_t *obj, PinName pin) { } static inline uint16_t adc_read(analogin_t *obj) { - // Get ADC registers structure address - ADC_TypeDef *adc = (ADC_TypeDef *)(obj->adc); - - adc->CHSELR = 0; // Clear all channels first - - // Configure ADC channel - switch (obj->pin) { - case PA_0: - ADC_ChannelConfig(adc, ADC_Channel_0, ADC_SampleTime_7_5Cycles); - break; - case PA_1: - ADC_ChannelConfig(adc, ADC_Channel_1, ADC_SampleTime_7_5Cycles); - break; - case PA_2: - ADC_ChannelConfig(adc, ADC_Channel_2, ADC_SampleTime_7_5Cycles); - break; - case PA_3: - ADC_ChannelConfig(adc, ADC_Channel_3, ADC_SampleTime_7_5Cycles); - break; - case PA_4: - ADC_ChannelConfig(adc, ADC_Channel_4, ADC_SampleTime_7_5Cycles); - break; - case PA_5: - ADC_ChannelConfig(adc, ADC_Channel_5, ADC_SampleTime_7_5Cycles); - break; - case PA_6: - ADC_ChannelConfig(adc, ADC_Channel_6, ADC_SampleTime_7_5Cycles); - break; - case PA_7: - ADC_ChannelConfig(adc, ADC_Channel_7, ADC_SampleTime_7_5Cycles); - break; - case PB_0: - ADC_ChannelConfig(adc, ADC_Channel_8, ADC_SampleTime_7_5Cycles); - break; - case PB_1: - ADC_ChannelConfig(adc, ADC_Channel_9, ADC_SampleTime_7_5Cycles); - break; - case PC_0: - ADC_ChannelConfig(adc, ADC_Channel_10, ADC_SampleTime_7_5Cycles); - break; - case PC_1: - ADC_ChannelConfig(adc, ADC_Channel_11, ADC_SampleTime_7_5Cycles); - break; - case PC_2: - ADC_ChannelConfig(adc, ADC_Channel_12, ADC_SampleTime_7_5Cycles); - break; - case PC_3: - ADC_ChannelConfig(adc, ADC_Channel_13, ADC_SampleTime_7_5Cycles); - break; - case PC_4: - ADC_ChannelConfig(adc, ADC_Channel_14, ADC_SampleTime_7_5Cycles); - break; - case PC_5: - ADC_ChannelConfig(adc, ADC_Channel_15, ADC_SampleTime_7_5Cycles); - break; - default: - return 0; - } + // Get ADC registers structure address + ADC_TypeDef *adc = (ADC_TypeDef *)(obj->adc); - while(!ADC_GetFlagStatus(adc, ADC_FLAG_ADRDY)); // Wait ADC ready + adc->CHSELR = 0; // Clear all channels first - ADC_StartOfConversion(adc); // Start conversion - - while(ADC_GetFlagStatus(adc, ADC_FLAG_EOC) == RESET); // Wait end of conversion - - return(ADC_GetConversionValue(adc)); // Get conversion value + // Configure ADC channel + switch (obj->pin) { + case PA_0: + ADC_ChannelConfig(adc, ADC_Channel_0, ADC_SampleTime_7_5Cycles); + break; + case PA_1: + ADC_ChannelConfig(adc, ADC_Channel_1, ADC_SampleTime_7_5Cycles); + break; + case PA_2: + ADC_ChannelConfig(adc, ADC_Channel_2, ADC_SampleTime_7_5Cycles); + break; + case PA_3: + ADC_ChannelConfig(adc, ADC_Channel_3, ADC_SampleTime_7_5Cycles); + break; + case PA_4: + ADC_ChannelConfig(adc, ADC_Channel_4, ADC_SampleTime_7_5Cycles); + break; + case PA_5: + ADC_ChannelConfig(adc, ADC_Channel_5, ADC_SampleTime_7_5Cycles); + break; + case PA_6: + ADC_ChannelConfig(adc, ADC_Channel_6, ADC_SampleTime_7_5Cycles); + break; + case PA_7: + ADC_ChannelConfig(adc, ADC_Channel_7, ADC_SampleTime_7_5Cycles); + break; + case PB_0: + ADC_ChannelConfig(adc, ADC_Channel_8, ADC_SampleTime_7_5Cycles); + break; + case PB_1: + ADC_ChannelConfig(adc, ADC_Channel_9, ADC_SampleTime_7_5Cycles); + break; + case PC_0: + ADC_ChannelConfig(adc, ADC_Channel_10, ADC_SampleTime_7_5Cycles); + break; + case PC_1: + ADC_ChannelConfig(adc, ADC_Channel_11, ADC_SampleTime_7_5Cycles); + break; + case PC_2: + ADC_ChannelConfig(adc, ADC_Channel_12, ADC_SampleTime_7_5Cycles); + break; + case PC_3: + ADC_ChannelConfig(adc, ADC_Channel_13, ADC_SampleTime_7_5Cycles); + break; + case PC_4: + ADC_ChannelConfig(adc, ADC_Channel_14, ADC_SampleTime_7_5Cycles); + break; + case PC_5: + ADC_ChannelConfig(adc, ADC_Channel_15, ADC_SampleTime_7_5Cycles); + break; + default: + return 0; + } + + while (!ADC_GetFlagStatus(adc, ADC_FLAG_ADRDY)); // Wait ADC ready + + ADC_StartOfConversion(adc); // Start conversion + + while (ADC_GetFlagStatus(adc, ADC_FLAG_EOC) == RESET); // Wait end of conversion + + return (ADC_GetConversionValue(adc)); // Get conversion value } uint16_t analogin_read_u16(analogin_t *obj) { - return(adc_read(obj)); + return (adc_read(obj)); } float analogin_read(analogin_t *obj) { - uint16_t value = adc_read(obj); - return (float)value * (1.0f / (float)0xFFF); // 12 bits range + uint16_t value = adc_read(obj); + return (float)value * (1.0f / (float)0xFFF); // 12 bits range } #endif diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F030R8/gpio_api.c b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F030R8/gpio_api.c index 443c99f57b..5686e79d03 100644 --- a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F030R8/gpio_api.c +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F030R8/gpio_api.c @@ -33,7 +33,7 @@ extern uint32_t Set_GPIO_Clock(uint32_t port_idx); -uint32_t gpio_set(PinName pin) { +uint32_t gpio_set(PinName pin) { if (pin == NC) return 0; pin_function(pin, STM_PIN_DATA(GPIO_Mode_IN, 0, GPIO_PuPd_NOPULL, 0xFF)); @@ -45,11 +45,11 @@ void gpio_init(gpio_t *obj, PinName pin) { if (pin == NC) return; uint32_t port_index = STM_PORT(pin); - + // Enable GPIO clock uint32_t gpio_add = Set_GPIO_Clock(port_index); GPIO_TypeDef *gpio = (GPIO_TypeDef *)gpio_add; - + // Fill GPIO object structure for future use obj->pin = pin; obj->mask = gpio_set(pin); @@ -65,8 +65,7 @@ void gpio_mode(gpio_t *obj, PinMode mode) { void gpio_dir(gpio_t *obj, PinDirection direction) { if (direction == PIN_OUTPUT) { pin_function(obj->pin, STM_PIN_DATA(GPIO_Mode_OUT, GPIO_OType_PP, GPIO_PuPd_NOPULL, 0xFF)); - } - else { // PIN_INPUT + } else { // PIN_INPUT pin_function(obj->pin, STM_PIN_DATA(GPIO_Mode_IN, 0, GPIO_PuPd_NOPULL, 0xFF)); } } diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F030R8/gpio_irq_api.c b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F030R8/gpio_irq_api.c index 80ffb8483b..3ec4449108 100644 --- a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F030R8/gpio_irq_api.c +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F030R8/gpio_irq_api.c @@ -53,26 +53,30 @@ static void handle_interrupt_in(uint32_t irq_index) { uint32_t pin = (uint32_t)(1 << channel_pin[irq_index]); // Clear interrupt flag - if (EXTI_GetITStatus(pin) != RESET) - { + if (EXTI_GetITStatus(pin) != RESET) { EXTI_ClearITPendingBit(pin); } - + if (channel_ids[irq_index] == 0) return; - + // Check which edge has generated the irq if ((gpio->IDR & pin) == 0) { irq_handler(channel_ids[irq_index], IRQ_FALL); - } - else { + } else { irq_handler(channel_ids[irq_index], IRQ_RISE); } } // The irq_index is passed to the function -static void gpio_irq0(void) {handle_interrupt_in(0);} -static void gpio_irq1(void) {handle_interrupt_in(1);} -static void gpio_irq2(void) {handle_interrupt_in(2);} +static void gpio_irq0(void) { + handle_interrupt_in(0); +} +static void gpio_irq1(void) { + handle_interrupt_in(1); +} +static void gpio_irq2(void) { + handle_interrupt_in(2); +} extern uint32_t Set_GPIO_Clock(uint32_t port_idx); @@ -91,18 +95,15 @@ int gpio_irq_init(gpio_irq_t *obj, PinName pin, gpio_irq_handler handler, uint32 irq_n = EXTI0_1_IRQn; vector = (uint32_t)&gpio_irq0; irq_index = 0; - } - else if ((pin_index == 2) || (pin_index == 3)) { + } else if ((pin_index == 2) || (pin_index == 3)) { irq_n = EXTI2_3_IRQn; vector = (uint32_t)&gpio_irq1; irq_index = 1; - } - else if ((pin_index > 3) && (pin_index < 16)) { + } else if ((pin_index > 3) && (pin_index < 16)) { irq_n = EXTI4_15_IRQn; vector = (uint32_t)&gpio_irq2; irq_index = 2; - } - else { + } else { error("InterruptIn error: pin not supported.\n"); return -1; } @@ -112,25 +113,25 @@ int gpio_irq_init(gpio_irq_t *obj, PinName pin, gpio_irq_handler handler, uint32 // Enable SYSCFG clock RCC_APB2PeriphClockCmd(RCC_APB2Periph_SYSCFG, ENABLE); - + // Connect EXTI line to pin SYSCFG_EXTILineConfig(port_index, pin_index); // Configure EXTI line - EXTI_InitTypeDef EXTI_InitStructure; + EXTI_InitTypeDef EXTI_InitStructure; EXTI_InitStructure.EXTI_Line = (uint32_t)(1 << pin_index); EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt; EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Falling; EXTI_InitStructure.EXTI_LineCmd = ENABLE; EXTI_Init(&EXTI_InitStructure); - + // Enable and set EXTI interrupt to the lowest priority NVIC_InitTypeDef NVIC_InitStructure; NVIC_InitStructure.NVIC_IRQChannel = irq_n; NVIC_InitStructure.NVIC_IRQChannelPriority = 0; NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&NVIC_InitStructure); - + NVIC_SetVector(irq_n, vector); NVIC_EnableIRQ(irq_n); @@ -141,9 +142,9 @@ int gpio_irq_init(gpio_irq_t *obj, PinName pin, gpio_irq_handler handler, uint32 channel_ids[irq_index] = id; channel_gpio[irq_index] = gpio_add; channel_pin[irq_index] = pin_index; - - irq_handler = handler; - + + irq_handler = handler; + return 0; } @@ -154,47 +155,44 @@ void gpio_irq_free(gpio_irq_t *obj) { // Disable EXTI line EXTI_InitTypeDef EXTI_InitStructure; EXTI_StructInit(&EXTI_InitStructure); - EXTI_Init(&EXTI_InitStructure); + EXTI_Init(&EXTI_InitStructure); obj->event = EDGE_NONE; } void gpio_irq_set(gpio_irq_t *obj, gpio_irq_event event, uint32_t enable) { EXTI_InitTypeDef EXTI_InitStructure; - + uint32_t pin_index = channel_pin[obj->irq_index]; EXTI_InitStructure.EXTI_Line = (uint32_t)(1 << pin_index); EXTI_InitStructure.EXTI_Mode = EXTI_Mode_Interrupt; - + if (event == IRQ_RISE) { if ((obj->event == EDGE_FALL) || (obj->event == EDGE_BOTH)) { EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Rising_Falling; obj->event = EDGE_BOTH; - } - else { // NONE or RISE + } else { // NONE or RISE EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Rising; obj->event = EDGE_RISE; } } - + if (event == IRQ_FALL) { if ((obj->event == EDGE_RISE) || (obj->event == EDGE_BOTH)) { EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Rising_Falling; obj->event = EDGE_BOTH; - } - else { // NONE or FALL + } else { // NONE or FALL EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Falling; obj->event = EDGE_FALL; } } - + if (enable) { EXTI_InitStructure.EXTI_LineCmd = ENABLE; - } - else { + } else { EXTI_InitStructure.EXTI_LineCmd = DISABLE; } - + EXTI_Init(&EXTI_InitStructure); } diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F030R8/gpio_object.h b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F030R8/gpio_object.h index ac414c2162..46fdf92515 100644 --- a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F030R8/gpio_object.h +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F030R8/gpio_object.h @@ -50,8 +50,7 @@ typedef struct { static inline void gpio_write(gpio_t *obj, int value) { if (value) { *obj->reg_set = obj->mask; - } - else { + } else { *obj->reg_clr = obj->mask; } } diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F030R8/i2c_api.c b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F030R8/i2c_api.c index 82f7a4c1a2..0d5b571427 100644 --- a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F030R8/i2c_api.c +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F030R8/i2c_api.c @@ -36,8 +36,8 @@ #include "error.h" /* Timeout values for flags and events waiting loops. These timeouts are - not based on accurate values, they just guarantee that the application will - not remain stuck if the I2C communication is corrupted. */ + not based on accurate values, they just guarantee that the application will + not remain stuck if the I2C communication is corrupted. */ #define FLAG_TIMEOUT ((int)0x1000) #define LONG_TIMEOUT ((int)0x8000) @@ -55,19 +55,19 @@ static const PinMap PinMap_I2C_SCL[] = { {NC, NC, 0} }; -void i2c_init(i2c_t *obj, PinName sda, PinName scl) { +void i2c_init(i2c_t *obj, PinName sda, PinName scl) { // Determine the I2C to use I2CName i2c_sda = (I2CName)pinmap_peripheral(sda, PinMap_I2C_SDA); I2CName i2c_scl = (I2CName)pinmap_peripheral(scl, PinMap_I2C_SCL); obj->i2c = (I2CName)pinmap_merge(i2c_sda, i2c_scl); - + if (obj->i2c == (I2CName)NC) { error("I2C pin mapping failed"); } // Enable I2C clock - if (obj->i2c == I2C_1) { + if (obj->i2c == I2C_1) { RCC_APB1PeriphClockCmd(RCC_APB1Periph_I2C1, ENABLE); RCC_I2CCLKConfig(RCC_I2C1CLK_SYSCLK); } @@ -80,12 +80,12 @@ void i2c_init(i2c_t *obj, PinName sda, PinName scl) { pin_mode(scl, OpenDrain); pinmap_pinout(sda, PinMap_I2C_SDA); pin_mode(sda, OpenDrain); - + // Reset to clear pending flags if any i2c_reset(obj); - + // I2C configuration - i2c_frequency(obj, 100000); // 100 kHz per default + i2c_frequency(obj, 100000); // 100 kHz per default } void i2c_frequency(i2c_t *obj, int hz) { @@ -97,7 +97,7 @@ void i2c_frequency(i2c_t *obj, int hz) { RCC_APB2PeriphClockCmd(RCC_APB2Periph_SYSCFG, ENABLE); // Enable SYSCFG clock SYSCFG_I2CFastModePlusConfig(SYSCFG_I2CFastModePlus_I2C1, DISABLE); SYSCFG_I2CFastModePlusConfig(SYSCFG_I2CFastModePlus_I2C2, DISABLE); - + /* Values calculated with I2C_Timing_Configuration_V1.0.1.xls file (see AN4235) * Standard mode (up to 100 kHz) @@ -111,30 +111,30 @@ void i2c_frequency(i2c_t *obj, int hz) { - Fall time = 10ns */ switch (hz) { - case 100000: - tim = 0x10805E89; // Standard mode - break; - case 200000: - tim = 0x00905E82; // Fast Mode - break; - case 400000: - tim = 0x00901850; // Fast Mode - break; - case 1000000: - tim = 0x00700818; // Fast Mode Plus - // Enable the Fast Mode Plus capability - if (obj->i2c == I2C_1) { - SYSCFG_I2CFastModePlusConfig(SYSCFG_I2CFastModePlus_I2C1, ENABLE); - } - if (obj->i2c == I2C_2) { - SYSCFG_I2CFastModePlusConfig(SYSCFG_I2CFastModePlus_I2C2, ENABLE); - } - break; - default: - error("Only 100kHz, 200kHz, 400kHz and 1MHz I2C frequencies are supported."); - break; + case 100000: + tim = 0x10805E89; // Standard mode + break; + case 200000: + tim = 0x00905E82; // Fast Mode + break; + case 400000: + tim = 0x00901850; // Fast Mode + break; + case 1000000: + tim = 0x00700818; // Fast Mode Plus + // Enable the Fast Mode Plus capability + if (obj->i2c == I2C_1) { + SYSCFG_I2CFastModePlusConfig(SYSCFG_I2CFastModePlus_I2C1, ENABLE); + } + if (obj->i2c == I2C_2) { + SYSCFG_I2CFastModePlusConfig(SYSCFG_I2CFastModePlus_I2C2, ENABLE); + } + break; + default: + error("Only 100kHz, 200kHz, 400kHz and 1MHz I2C frequencies are supported."); + break; } - + // I2C configuration I2C_DeInit(i2c); I2C_InitStructure.I2C_Mode = I2C_Mode_I2C; @@ -145,7 +145,7 @@ void i2c_frequency(i2c_t *obj, int hz) { I2C_InitStructure.I2C_AcknowledgedAddress = I2C_AcknowledgedAddress_7bit; I2C_InitStructure.I2C_Timing = tim; I2C_Init(i2c, &I2C_InitStructure); - + I2C_Cmd(i2c, ENABLE); } @@ -169,55 +169,63 @@ inline int i2c_start(i2c_t *obj) { inline int i2c_stop(i2c_t *obj) { I2C_TypeDef *i2c = (I2C_TypeDef *)(obj->i2c); - + I2C_GenerateSTOP(i2c, ENABLE); - + return 0; } int i2c_read(i2c_t *obj, int address, char *data, int length, int stop) { I2C_TypeDef *i2c = (I2C_TypeDef *)(obj->i2c); int count; + int timeout; int value; - + if (length == 0) return 0; // Configure slave address, nbytes, reload, end mode and start or stop generation - I2C_TransferHandling(i2c, address, length, I2C_AutoEnd_Mode, I2C_Generate_Start_Read); - + I2C_TransferHandling(i2c, address, length, I2C_SoftEnd_Mode, I2C_Generate_Start_Read); + // Read all bytes for (count = 0; count < length; count++) { value = i2c_byte_read(obj, 0); data[count] = (char)value; } - + + timeout = FLAG_TIMEOUT; + while (!I2C_GetFlagStatus(i2c, I2C_FLAG_TC)) { + timeout--; + if (timeout == 0) return 0; + } + + if (stop) i2c_stop(obj); + return length; } int i2c_write(i2c_t *obj, int address, const char *data, int length, int stop) { I2C_TypeDef *i2c = (I2C_TypeDef *)(obj->i2c); - //int timeout; + int timeout; int count; - + if (length == 0) return 0; - // Configure slave address, nbytes, reload, end mode and start or stop generation - if (stop) { - I2C_TransferHandling(i2c, address, length, I2C_AutoEnd_Mode, I2C_Generate_Start_Write); - - } - else { - I2C_TransferHandling(i2c, address, length, I2C_SoftEnd_Mode, I2C_Generate_Start_Write); - } - + // Configure slave address, nbytes, reload, end mode and start generation + I2C_TransferHandling(i2c, address, length, I2C_SoftEnd_Mode, I2C_Generate_Start_Write); + // Write all bytes for (count = 0; count < length; count++) { - if (i2c_byte_write(obj, data[count]) != 1) { - if(!stop) i2c_stop(obj); - return 0; - } + i2c_byte_write(obj, data[count]); } + timeout = FLAG_TIMEOUT; + while (!I2C_GetFlagStatus(i2c, I2C_FLAG_TC)) { + timeout--; + if (timeout == 0) return 0; + } + + if (stop) i2c_stop(obj); + return count; } @@ -225,9 +233,9 @@ int i2c_byte_read(i2c_t *obj, int last) { I2C_TypeDef *i2c = (I2C_TypeDef *)(obj->i2c); uint8_t data; int timeout; - + // Wait until the byte is received - timeout = FLAG_TIMEOUT; + timeout = FLAG_TIMEOUT; while (I2C_GetFlagStatus(i2c, I2C_ISR_RXNE) == RESET) { timeout--; if (timeout == 0) { @@ -236,7 +244,7 @@ int i2c_byte_read(i2c_t *obj, int last) { } data = I2C_ReceiveData(i2c); - + return (int)data; } @@ -252,20 +260,20 @@ int i2c_byte_write(i2c_t *obj, int data) { return 0; } } - + I2C_SendData(i2c, (uint8_t)data); - + return 1; } void i2c_reset(i2c_t *obj) { - if (obj->i2c == I2C_1) { + if (obj->i2c == I2C_1) { RCC_APB1PeriphResetCmd(RCC_APB1Periph_I2C1, ENABLE); RCC_APB1PeriphResetCmd(RCC_APB1Periph_I2C1, DISABLE); } if (obj->i2c == I2C_2) { RCC_APB1PeriphResetCmd(RCC_APB1Periph_I2C2, ENABLE); - RCC_APB1PeriphResetCmd(RCC_APB1Periph_I2C2, DISABLE); + RCC_APB1PeriphResetCmd(RCC_APB1Periph_I2C2, DISABLE); } } @@ -274,10 +282,10 @@ void i2c_reset(i2c_t *obj) { void i2c_slave_address(i2c_t *obj, int idx, uint32_t address, uint32_t mask) { I2C_TypeDef *i2c = (I2C_TypeDef *)(obj->i2c); uint16_t tmpreg; - + // reset own address enable - i2c->OAR1 &=~ I2C_OAR1_OA1EN; - + i2c->OAR1 &= ~ I2C_OAR1_OA1EN; + // Get the old register value tmpreg = i2c->OAR1; // Reset address bits @@ -301,16 +309,15 @@ void i2c_slave_mode(i2c_t *obj, int enable_slave) { int i2c_slave_receive(i2c_t *obj) { I2C_TypeDef *i2c = (I2C_TypeDef *)(obj->i2c); int event = NoData; - - if(I2C_GetFlagStatus(i2c, I2C_ISR_BUSY) == SET) { - if(I2C_GetFlagStatus(i2c, I2C_ISR_ADDR) == SET) { - // Check direction + + if (I2C_GetFlagStatus(i2c, I2C_ISR_BUSY) == SET) { + if (I2C_GetFlagStatus(i2c, I2C_ISR_ADDR) == SET) { + // Check direction if (I2C_GetFlagStatus(i2c, I2C_ISR_DIR) == SET) { - event = ReadAddressed; - } - else event = WriteAddressed; - // Clear adress match flag to generate an acknowledge - i2c->ICR |= I2C_ICR_ADDRCF; + event = ReadAddressed; + } else event = WriteAddressed; + // Clear adress match flag to generate an acknowledge + i2c->ICR |= I2C_ICR_ADDRCF; } } return event; @@ -318,23 +325,23 @@ int i2c_slave_receive(i2c_t *obj) { int i2c_slave_read(i2c_t *obj, char *data, int length) { int count = 0; - + // Read all bytes for (count = 0; count < length; count++) { data[count] = i2c_byte_read(obj, 0); } - + return count; } int i2c_slave_write(i2c_t *obj, const char *data, int length) { int count = 0; - + // Write all bytes for (count = 0; count < length; count++) { i2c_byte_write(obj, data[count]); } - + return count; } diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F030R8/objects.h b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F030R8/objects.h index 5bbd4ed4fc..9ac85e0f41 100644 --- a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F030R8/objects.h +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F030R8/objects.h @@ -48,7 +48,7 @@ struct gpio_irq_s { struct port_s { PortName port; uint32_t mask; - PinDirection direction; + PinDirection direction; __IO uint16_t *reg_in; __IO uint16_t *reg_out; }; @@ -58,18 +58,15 @@ struct analogin_s { PinName pin; }; -struct dac_s { - DACName dac; - PinName channel; -}; - struct serial_s { UARTName uart; int index; // Used by irq uint32_t baudrate; uint32_t databits; uint32_t stopbits; - uint32_t parity; + uint32_t parity; + PinName pin_tx; + PinName pin_rx; }; struct spi_s { @@ -80,6 +77,10 @@ struct spi_s { uint32_t mode; uint32_t nss; uint32_t br_presc; + PinName pin_miso; + PinName pin_mosi; + PinName pin_sclk; + PinName pin_ssel; }; struct i2c_s { diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F030R8/pinmap.c b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F030R8/pinmap.c index c4f21316b1..30b6e15d3b 100644 --- a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F030R8/pinmap.c +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F030R8/pinmap.c @@ -86,7 +86,7 @@ void pin_function(PinName pin, int data) { if (afnum != 0xFF) { GPIO_PinAFConfig(gpio, (uint16_t)pin_index, afnum); } - + // Configure GPIO GPIO_InitTypeDef GPIO_InitStructure; GPIO_InitStructure.GPIO_Pin = (uint16_t)(1 << pin_index); @@ -95,7 +95,7 @@ void pin_function(PinName pin, int data) { GPIO_InitStructure.GPIO_OType = (GPIOOType_TypeDef)otype; GPIO_InitStructure.GPIO_PuPd = (GPIOPuPd_TypeDef)pupd; GPIO_Init(gpio, &GPIO_InitStructure); - + // *** TODO *** // Disconnect JTAG-DP + SW-DP signals. // Warning: Need to reconnect under reset @@ -104,7 +104,7 @@ void pin_function(PinName pin, int data) { //} //if ((pin == PA_15) || (pin == PB_3) || (pin == PB_4)) { // - //} + //} } /** @@ -125,5 +125,5 @@ void pin_mode(PinName pin, PinMode mode) { if (pupd > 2) pupd = 0; // Open-drain = No pull-up/No pull-down gpio->PUPDR &= (uint32_t)(~(GPIO_PUPDR_PUPDR0 << (pin_index * 2))); gpio->PUPDR |= (uint32_t)(pupd << (pin_index * 2)); - + } diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F030R8/port_api.c b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F030R8/port_api.c index 3549b81e33..78ae7da93c 100644 --- a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F030R8/port_api.c +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F030R8/port_api.c @@ -40,7 +40,7 @@ extern uint32_t Set_GPIO_Clock(uint32_t port_idx); // high nibble = port number (0=A, 1=B, 2=C, 3=D, 4=E, 5=F, ...) // low nibble = pin number PinName port_pin(PortName port, int pin_n) { - return (PinName)(pin_n + (port << 4)); + return (PinName)(pin_n + (port << 4)); } void port_init(port_t *obj, PortName port, int mask, PinDirection dir) { @@ -53,9 +53,9 @@ void port_init(port_t *obj, PortName port, int mask, PinDirection dir) { // Fill PORT object structure for future use obj->port = port; obj->mask = mask; - obj->direction = dir; + obj->direction = dir; obj->reg_in = &gpio->IDR; - obj->reg_out = &gpio->ODR; + obj->reg_out = &gpio->ODR; port_dir(obj, dir); } @@ -67,16 +67,15 @@ void port_dir(port_t *obj, PinDirection dir) { if (obj->mask & (1 << i)) { // If the pin is used if (dir == PIN_OUTPUT) { pin_function(port_pin(obj->port, i), STM_PIN_DATA(GPIO_Mode_OUT, GPIO_OType_PP, GPIO_PuPd_NOPULL, 0xFF)); - } - else { // PIN_INPUT + } else { // PIN_INPUT pin_function(port_pin(obj->port, i), STM_PIN_DATA(GPIO_Mode_IN, 0, GPIO_PuPd_NOPULL, 0xFF)); } } - } + } } void port_mode(port_t *obj, PinMode mode) { - uint32_t i; + uint32_t i; for (i = 0; i < 16; i++) { // Process all pins if (obj->mask & (1 << i)) { // If the pin is used pin_mode(port_pin(obj->port, i), mode); @@ -91,8 +90,7 @@ void port_write(port_t *obj, int value) { int port_read(port_t *obj) { if (obj->direction == PIN_OUTPUT) { return (*obj->reg_out & obj->mask); - } - else { // PIN_INPUT + } else { // PIN_INPUT return (*obj->reg_in & obj->mask); } } diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F030R8/pwmout_api.c b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F030R8/pwmout_api.c index 6b6da8dccf..b4b6f5eb43 100644 --- a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F030R8/pwmout_api.c +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F030R8/pwmout_api.c @@ -40,7 +40,7 @@ static const PinMap PinMap_PWM[] = { {PA_4, TIM_14, STM_PIN_DATA(GPIO_Mode_AF, GPIO_OType_PP, GPIO_PuPd_NOPULL, GPIO_AF_4)}, // TIM14_CH1 {PA_6, TIM_3, STM_PIN_DATA(GPIO_Mode_AF, GPIO_OType_PP, GPIO_PuPd_NOPULL, GPIO_AF_1)}, // TIM3_CH1 // {PA_6, TIM_16, STM_PIN_DATA(GPIO_Mode_AF, GPIO_OType_PP, GPIO_PuPd_NOPULL, GPIO_AF_5)}, // TIM16_CH1 - {PA_7, TIM_3, STM_PIN_DATA(GPIO_Mode_AF, GPIO_OType_PP, GPIO_PuPd_NOPULL, GPIO_AF_1)}, // TIM3_CH1 + {PA_7, TIM_3, STM_PIN_DATA(GPIO_Mode_AF, GPIO_OType_PP, GPIO_PuPd_NOPULL, GPIO_AF_1)}, // TIM3_CH2 // {PA_7, TIM_14, STM_PIN_DATA(GPIO_Mode_AF, GPIO_OType_PP, GPIO_PuPd_NOPULL, GPIO_AF_4)}, // TIM14_CH1 // {PA_7, TIM_17, STM_PIN_DATA(GPIO_Mode_AF, GPIO_OType_PP, GPIO_PuPd_NOPULL, GPIO_AF_5)}, // TIM17_CH1 {PB_0, TIM_3, STM_PIN_DATA(GPIO_Mode_AF, GPIO_OType_PP, GPIO_PuPd_NOPULL, GPIO_AF_1)}, // TIM3_CH3 @@ -62,14 +62,14 @@ static const PinMap PinMap_PWM[] = { {NC, NC, 0} }; -void pwmout_init(pwmout_t* obj, PinName pin) { +void pwmout_init(pwmout_t* obj, PinName pin) { // Get the peripheral name from the pin and assign it to the object obj->pwm = (PWMName)pinmap_peripheral(pin, PinMap_PWM); - + if (obj->pwm == (PWMName)NC) { error("PWM pinout mapping failed"); } - + // Enable TIM clock if (obj->pwm == TIM_3) RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE); if (obj->pwm == TIM_14) RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM14, ENABLE); @@ -79,32 +79,31 @@ void pwmout_init(pwmout_t* obj, PinName pin) { // Configure GPIO pinmap_pinout(pin, PinMap_PWM); - //pin_mode(pin, PullUp); - + obj->pin = pin; obj->period = 0; obj->pulse = 0; - + pwmout_period_us(obj, 20000); // 20 ms per default } void pwmout_free(pwmout_t* obj) { - TIM_TypeDef *tim = (TIM_TypeDef *)(obj->pwm); - TIM_DeInit(tim); + // Configure GPIOs + pin_function(obj->pin, STM_PIN_DATA(GPIO_Mode_IN, 0, GPIO_PuPd_NOPULL, 0xFF)); } void pwmout_write(pwmout_t* obj, float value) { TIM_TypeDef *tim = (TIM_TypeDef *)(obj->pwm); TIM_OCInitTypeDef TIM_OCInitStructure; - + if (value < 0.0) { value = 0.0; } else if (value > 1.0) { value = 1.0; } - + obj->pulse = (uint32_t)((float)obj->period * value); - + // Configure channels TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1; TIM_OCInitStructure.TIM_Pulse = obj->pulse; @@ -117,7 +116,6 @@ void pwmout_write(pwmout_t* obj, float value) { // Channels 1 case PA_4: case PA_6: - case PA_7: case PB_1: case PB_4: case PB_8: @@ -136,13 +134,13 @@ void pwmout_write(pwmout_t* obj, float value) { TIM_OC1Init(tim, &TIM_OCInitStructure); break; // Channels 2 -// case PA_7: + case PA_7: case PB_5: case PC_7: TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; TIM_OC2PreloadConfig(tim, TIM_OCPreload_Enable); TIM_OC2Init(tim, &TIM_OCInitStructure); - break; + break; // Channels 3 case PB_0: case PC_8: @@ -150,7 +148,7 @@ void pwmout_write(pwmout_t* obj, float value) { TIM_OC3PreloadConfig(tim, TIM_OCPreload_Enable); TIM_OC3Init(tim, &TIM_OCInitStructure); break; - // Channels 4 + // Channels 4 // case PB_1: case PC_9: TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; @@ -158,11 +156,11 @@ void pwmout_write(pwmout_t* obj, float value) { TIM_OC4Init(tim, &TIM_OCInitStructure); break; default: - return; - } - - TIM_CtrlPWMOutputs(tim, ENABLE); - + return; + } + + TIM_CtrlPWMOutputs(tim, ENABLE); + } float pwmout_read(pwmout_t* obj) { @@ -186,10 +184,10 @@ void pwmout_period_us(pwmout_t* obj, int us) { TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure; float dc = pwmout_read(obj); - TIM_Cmd(tim, DISABLE); - + TIM_Cmd(tim, DISABLE); + obj->period = us; - + TIM_TimeBaseStructure.TIM_Period = obj->period - 1; TIM_TimeBaseStructure.TIM_Prescaler = (uint16_t)(SystemCoreClock / 1000000) - 1; // 1 µs tick TIM_TimeBaseStructure.TIM_ClockDivision = 0; @@ -198,7 +196,7 @@ void pwmout_period_us(pwmout_t* obj, int us) { // Set duty cycle again pwmout_write(obj, dc); - + TIM_ARRPreloadConfig(tim, ENABLE); TIM_Cmd(tim, ENABLE); diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F030R8/rtc_api.c b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F030R8/rtc_api.c index 4792ba8004..16b88ccb45 100644 --- a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F030R8/rtc_api.c +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F030R8/rtc_api.c @@ -49,7 +49,7 @@ void rtc_init(void) { // Reset back up registers RCC_BackupResetCmd(ENABLE); RCC_BackupResetCmd(DISABLE); - + // Enable LSE clock RCC_LSEConfig(RCC_LSE_ON); @@ -58,40 +58,48 @@ void rtc_init(void) { LSEStatus = RCC_GetFlagStatus(RCC_FLAG_LSERDY); wait_ms(1); StartUpCounter++; - } while((LSEStatus == 0) && (StartUpCounter <= LSE_STARTUP_TIMEOUT)); + } while ((LSEStatus == 0) && (StartUpCounter <= LSE_STARTUP_TIMEOUT)); if (StartUpCounter > LSE_STARTUP_TIMEOUT) { // The LSE has not started, use LSI instead. - // The RTC Clock may vary due to LSI frequency dispersion. - RCC_LSEConfig(RCC_LSE_OFF); + // The RTC Clock may vary due to LSI frequency dispersion. + RCC_LSEConfig(RCC_LSE_OFF); RCC_LSICmd(ENABLE); // Enable LSI while (RCC_GetFlagStatus(RCC_FLAG_LSIRDY) == RESET) {} // Wait until ready RCC_RTCCLKConfig(RCC_RTCCLKSource_LSI); // Select the RTC Clock Source - rtc_freq = 40000; // [TODO] To be measured precisely using a timer input capture - } - else { + rtc_freq = 40000; // [TODO] To be measured precisely using a timer input capture + } else { // The LSE has correctly started RCC_RTCCLKConfig(RCC_RTCCLKSource_LSE); // Select the RTC Clock Source rtc_freq = LSE_VALUE; } - - RCC_RTCCLKCmd(ENABLE); // Enable RTC Clock - + + RCC_RTCCLKCmd(ENABLE); // Enable RTC Clock + RTC_WaitForSynchro(); // Wait for RTC registers synchronization RTC_InitTypeDef RTC_InitStructure; RTC_InitStructure.RTC_AsynchPrediv = 127; - RTC_InitStructure.RTC_SynchPrediv = (rtc_freq / 128) - 1; + RTC_InitStructure.RTC_SynchPrediv = (rtc_freq / 128) - 1; RTC_InitStructure.RTC_HourFormat = RTC_HourFormat_24; RTC_Init(&RTC_InitStructure); - + PWR_BackupAccessCmd(DISABLE); // Disable access to Backup domain - + rtc_inited = 1; } void rtc_free(void) { - RCC_DeInit(); // Resets the RCC clock configuration to the default reset state + // Reset RTC + PWR_BackupAccessCmd(ENABLE); // Enable access to Backup Domain + RTC_DeInit(); + RCC_BackupResetCmd(ENABLE); + RCC_BackupResetCmd(DISABLE); + // Disable RTC, LSE and LSI clocks + RCC_RTCCLKCmd(DISABLE); + RCC_LSEConfig(RCC_LSE_OFF); + RCC_LSICmd(DISABLE); + rtc_inited = 0; } @@ -120,11 +128,11 @@ time_t rtc_read(void) { RTC_DateTypeDef dateStruct; RTC_TimeTypeDef timeStruct; struct tm timeinfo; - + // Read actual date and time RTC_GetTime(RTC_Format_BIN, &timeStruct); RTC_GetDate(RTC_Format_BIN, &dateStruct); - + // Setup a tm structure based on the RTC timeinfo.tm_wday = dateStruct.RTC_WeekDay; timeinfo.tm_mon = dateStruct.RTC_Month - 1; @@ -133,11 +141,11 @@ time_t rtc_read(void) { timeinfo.tm_hour = timeStruct.RTC_Hours; timeinfo.tm_min = timeStruct.RTC_Minutes; timeinfo.tm_sec = timeStruct.RTC_Seconds; - + // Convert to timestamp time_t t = mktime(&timeinfo); - - return t; + + return t; } void rtc_write(time_t t) { @@ -146,7 +154,7 @@ void rtc_write(time_t t) { // Convert the time into a tm struct tm *timeinfo = localtime(&t); - + // Fill RTC structures dateStruct.RTC_WeekDay = timeinfo->tm_wday; dateStruct.RTC_Month = timeinfo->tm_mon + 1; @@ -156,11 +164,11 @@ void rtc_write(time_t t) { timeStruct.RTC_Minutes = timeinfo->tm_min; timeStruct.RTC_Seconds = timeinfo->tm_sec; timeStruct.RTC_H12 = RTC_HourFormat_24; - + // Change the RTC current date/time - PWR_BackupAccessCmd(ENABLE); // Enable access to RTC + PWR_BackupAccessCmd(ENABLE); // Enable access to RTC RTC_SetDate(RTC_Format_BIN, &dateStruct); - RTC_SetTime(RTC_Format_BIN, &timeStruct); + RTC_SetTime(RTC_Format_BIN, &timeStruct); PWR_BackupAccessCmd(DISABLE); // Disable access to RTC } diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F030R8/serial_api.c b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F030R8/serial_api.c index 63027e8c04..ce3b92f7cd 100644 --- a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F030R8/serial_api.c +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F030R8/serial_api.c @@ -44,7 +44,7 @@ static const PinMap PinMap_UART_TX[] = { }; static const PinMap PinMap_UART_RX[] = { - {PA_3, UART_2, STM_PIN_DATA(GPIO_Mode_AF, GPIO_OType_PP, GPIO_PuPd_UP, GPIO_AF_1)}, + {PA_3, UART_2, STM_PIN_DATA(GPIO_Mode_AF, GPIO_OType_PP, GPIO_PuPd_UP, GPIO_AF_1)}, {PA_10, UART_1, STM_PIN_DATA(GPIO_Mode_AF, GPIO_OType_PP, GPIO_PuPd_UP, GPIO_AF_1)}, {PA_15, UART_2, STM_PIN_DATA(GPIO_Mode_AF, GPIO_OType_PP, GPIO_PuPd_UP, GPIO_AF_1)}, {PB_7, UART_1, STM_PIN_DATA(GPIO_Mode_AF, GPIO_OType_PP, GPIO_PuPd_UP, GPIO_AF_0)}, @@ -63,7 +63,7 @@ serial_t stdio_uart; static void init_usart(serial_t *obj) { USART_TypeDef *usart = (USART_TypeDef *)(obj->uart); USART_InitTypeDef USART_InitStructure; - + USART_Cmd(usart, DISABLE); USART_InitStructure.USART_BaudRate = obj->baudrate; @@ -73,15 +73,15 @@ static void init_usart(serial_t *obj) { USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None; USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx; USART_Init(usart, &USART_InitStructure); - + USART_Cmd(usart, ENABLE); } -void serial_init(serial_t *obj, PinName tx, PinName rx) { +void serial_init(serial_t *obj, PinName tx, PinName rx) { // Determine the UART to use (UART_1, UART_2, ...) UARTName uart_tx = (UARTName)pinmap_peripheral(tx, PinMap_UART_TX); UARTName uart_rx = (UARTName)pinmap_peripheral(rx, PinMap_UART_RX); - + // Get the peripheral name (UART_1, UART_2, ...) from the pin and assign it to the object obj->uart = (UARTName)pinmap_merge(uart_tx, uart_rx); @@ -91,12 +91,14 @@ void serial_init(serial_t *obj, PinName tx, PinName rx) { // Enable USART clock if (obj->uart == UART_1) { - RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE); + RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE); + obj->index = 0; } if (obj->uart == UART_2) { - RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE); + RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE); + obj->index = 1; } - + // Configure the UART pins pinmap_pinout(tx, PinMap_UART_TX); pinmap_pinout(rx, PinMap_UART_RX); @@ -107,23 +109,38 @@ void serial_init(serial_t *obj, PinName tx, PinName rx) { obj->baudrate = 9600; obj->databits = USART_WordLength_8b; obj->stopbits = USART_StopBits_1; - obj->parity = USART_Parity_No; + obj->parity = USART_Parity_No; + + obj->pin_tx = tx; + obj->pin_rx = rx; init_usart(obj); - // The index is used by irq - if (obj->uart == UART_1) obj->index = 0; - if (obj->uart == UART_2) obj->index = 1; - // For stdio management if (obj->uart == STDIO_UART) { stdio_uart_inited = 1; memcpy(&stdio_uart, obj, sizeof(serial_t)); } - + } void serial_free(serial_t *obj) { + // Reset UART and disable clock + if (obj->uart == UART_1) { + RCC_APB2PeriphResetCmd(RCC_APB2Periph_USART1, ENABLE); + RCC_APB2PeriphResetCmd(RCC_APB2Periph_USART1, DISABLE); + RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, DISABLE); + } + if (obj->uart == UART_2) { + RCC_APB1PeriphResetCmd(RCC_APB1Periph_USART2, ENABLE); + RCC_APB1PeriphResetCmd(RCC_APB1Periph_USART2, DISABLE); + RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, DISABLE); + } + + // Configure GPIOs + pin_function(obj->pin_tx, STM_PIN_DATA(GPIO_Mode_IN, 0, GPIO_PuPd_NOPULL, 0xFF)); + pin_function(obj->pin_rx, STM_PIN_DATA(GPIO_Mode_IN, 0, GPIO_PuPd_NOPULL, 0xFF)); + serial_irq_ids[obj->index] = 0; } @@ -135,29 +152,27 @@ void serial_baud(serial_t *obj, int baudrate) { void serial_format(serial_t *obj, int data_bits, SerialParity parity, int stop_bits) { if (data_bits == 8) { obj->databits = USART_WordLength_8b; - } - else { + } else { obj->databits = USART_WordLength_9b; } switch (parity) { - case ParityOdd: - case ParityForced0: - obj->parity = USART_Parity_Odd; - break; - case ParityEven: - case ParityForced1: - obj->parity = USART_Parity_Even; - break; - default: // ParityNone - obj->parity = USART_Parity_No; - break; + case ParityOdd: + case ParityForced0: + obj->parity = USART_Parity_Odd; + break; + case ParityEven: + case ParityForced1: + obj->parity = USART_Parity_Even; + break; + default: // ParityNone + obj->parity = USART_Parity_No; + break; } - + if (stop_bits == 2) { obj->stopbits = USART_StopBits_2; - } - else { + } else { obj->stopbits = USART_StopBits_1; } @@ -182,8 +197,12 @@ static void uart_irq(USART_TypeDef* usart, int id) { } } -static void uart1_irq(void) {uart_irq((USART_TypeDef*)UART_1, 0);} -static void uart2_irq(void) {uart_irq((USART_TypeDef*)UART_2, 1);} +static void uart1_irq(void) { + uart_irq((USART_TypeDef*)UART_1, 0); +} +static void uart2_irq(void) { + uart_irq((USART_TypeDef*)UART_2, 1); +} void serial_irq_handler(serial_t *obj, uart_irq_handler handler, uint32_t id) { irq_handler = handler; @@ -196,45 +215,43 @@ void serial_irq_set(serial_t *obj, SerialIrq irq, uint32_t enable) { USART_TypeDef *usart = (USART_TypeDef *)(obj->uart); if (obj->uart == UART_1) { - irq_n = USART1_IRQn; - vector = (uint32_t)&uart1_irq; + irq_n = USART1_IRQn; + vector = (uint32_t)&uart1_irq; } - + if (obj->uart == UART_2) { - irq_n = USART2_IRQn; - vector = (uint32_t)&uart2_irq; + irq_n = USART2_IRQn; + vector = (uint32_t)&uart2_irq; } - + if (enable) { - + if (irq == RxIrq) { USART_ITConfig(usart, USART_IT_RXNE, ENABLE); - } - else { // TxIrq + } else { // TxIrq USART_ITConfig(usart, USART_IT_TC, ENABLE); - } - + } + NVIC_SetVector(irq_n, vector); NVIC_EnableIRQ(irq_n); - + } else { // disable - + int all_disabled = 0; - + if (irq == RxIrq) { USART_ITConfig(usart, USART_IT_RXNE, DISABLE); // Check if TxIrq is disabled too if ((usart->CR1 & USART_CR1_TXEIE) == 0) all_disabled = 1; - } - else { // TxIrq + } else { // TxIrq USART_ITConfig(usart, USART_IT_TXE, DISABLE); // Check if RxIrq is disabled too - if ((usart->CR1 & USART_CR1_RXNEIE) == 0) all_disabled = 1; + if ((usart->CR1 & USART_CR1_RXNEIE) == 0) all_disabled = 1; } - + if (all_disabled) NVIC_DisableIRQ(irq_n); - - } + + } } /****************************************************************************** diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F030R8/sleep.c b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F030R8/sleep.c index d18f7c06cb..7ae5927502 100644 --- a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F030R8/sleep.c +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F030R8/sleep.c @@ -33,28 +33,26 @@ #include "cmsis.h" -void sleep(void) -{ +void sleep(void) { // Disable us_ticker update interrupt TIM_ITConfig(TIM1, TIM_IT_Update, DISABLE); - + SCB->SCR = 0; // Normal sleep mode for ARM core __WFI(); - + // Re-enable us_ticker update interrupt - TIM_ITConfig(TIM1, TIM_IT_Update, ENABLE); + TIM_ITConfig(TIM1, TIM_IT_Update, ENABLE); } // MCU STOP mode // Wake-up with external interrupt -void deepsleep(void) -{ +void deepsleep(void) { // Enable PWR clock RCC_APB1PeriphClockCmd(RCC_APB1Periph_PWR, ENABLE); - + // Request to enter STOP mode with regulator in low power mode PWR_EnterSTOPMode(PWR_Regulator_LowPower, PWR_STOPEntry_WFI); - + // After wake-up from STOP reconfigure the PLL SetSysClock(); } diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F030R8/spi_api.c b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F030R8/spi_api.c index 35cb465b9d..6f88dea70e 100644 --- a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F030R8/spi_api.c +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F030R8/spi_api.c @@ -72,11 +72,11 @@ static void init_spi(spi_t *obj) { SPI_Cmd(spi, DISABLE); SPI_InitStructure.SPI_Mode = obj->mode; - SPI_InitStructure.SPI_NSS = obj->nss; - SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_FullDuplex; + SPI_InitStructure.SPI_NSS = obj->nss; + SPI_InitStructure.SPI_Direction = SPI_Direction_2Lines_FullDuplex; SPI_InitStructure.SPI_DataSize = obj->bits; SPI_InitStructure.SPI_CPOL = obj->cpol; - SPI_InitStructure.SPI_CPHA = obj->cpha; + SPI_InitStructure.SPI_CPHA = obj->cpha; SPI_InitStructure.SPI_BaudRatePrescaler = obj->br_presc; SPI_InitStructure.SPI_FirstBit = SPI_FirstBit_MSB; SPI_InitStructure.SPI_CRCPolynomial = 7; @@ -93,40 +93,44 @@ void spi_init(spi_t *obj, PinName mosi, PinName miso, PinName sclk, PinName ssel SPIName spi_miso = (SPIName)pinmap_peripheral(miso, PinMap_SPI_MISO); SPIName spi_sclk = (SPIName)pinmap_peripheral(sclk, PinMap_SPI_SCLK); SPIName spi_ssel = (SPIName)pinmap_peripheral(ssel, PinMap_SPI_SSEL); - + SPIName spi_data = (SPIName)pinmap_merge(spi_mosi, spi_miso); SPIName spi_cntl = (SPIName)pinmap_merge(spi_sclk, spi_ssel); - + obj->spi = (SPIName)pinmap_merge(spi_data, spi_cntl); - + if (obj->spi == (SPIName)NC) { error("SPI pinout mapping failed"); } - + // Enable SPI clock if (obj->spi == SPI_1) { - RCC_APB2PeriphClockCmd(RCC_APB2Periph_SPI1, ENABLE); + RCC_APB2PeriphClockCmd(RCC_APB2Periph_SPI1, ENABLE); } if (obj->spi == SPI_2) { - RCC_APB1PeriphClockCmd(RCC_APB1Periph_SPI2, ENABLE); + RCC_APB1PeriphClockCmd(RCC_APB1Periph_SPI2, ENABLE); } - + // Configure the SPI pins pinmap_pinout(mosi, PinMap_SPI_MOSI); pinmap_pinout(miso, PinMap_SPI_MISO); pinmap_pinout(sclk, PinMap_SPI_SCLK); - + // Save new values obj->bits = SPI_DataSize_8b; obj->cpol = SPI_CPOL_Low; obj->cpha = SPI_CPHA_1Edge; obj->br_presc = SPI_BaudRatePrescaler_8; // 1 MHz - + + obj->pin_miso = miso; + obj->pin_mosi = mosi; + obj->pin_sclk = sclk; + obj->pin_ssel = ssel; + if (ssel == NC) { // Master obj->mode = SPI_Mode_Master; obj->nss = SPI_NSS_Soft; - } - else { // Slave + } else { // Slave pinmap_pinout(ssel, PinMap_SPI_SSEL); obj->mode = SPI_Mode_Slave; obj->nss = SPI_NSS_Hard; @@ -136,47 +140,61 @@ void spi_init(spi_t *obj, PinName mosi, PinName miso, PinName sclk, PinName ssel } void spi_free(spi_t *obj) { - SPI_TypeDef *spi = (SPI_TypeDef *)(obj->spi); - SPI_I2S_DeInit(spi); + // Reset SPI and disable clock + if (obj->spi == SPI_1) { + RCC_APB2PeriphResetCmd(RCC_APB2Periph_SPI1, ENABLE); + RCC_APB2PeriphResetCmd(RCC_APB2Periph_SPI1, DISABLE); + RCC_APB2PeriphClockCmd(RCC_APB2Periph_SPI1, DISABLE); + } + + if (obj->spi == SPI_2) { + RCC_APB1PeriphResetCmd(RCC_APB1Periph_SPI2, ENABLE); + RCC_APB1PeriphResetCmd(RCC_APB1Periph_SPI2, DISABLE); + RCC_APB1PeriphClockCmd(RCC_APB1Periph_SPI2, DISABLE); + } + + // Configure GPIOs + pin_function(obj->pin_miso, STM_PIN_DATA(GPIO_Mode_IN, 0, GPIO_PuPd_NOPULL, 0xFF)); + pin_function(obj->pin_mosi, STM_PIN_DATA(GPIO_Mode_IN, 0, GPIO_PuPd_NOPULL, 0xFF)); + pin_function(obj->pin_sclk, STM_PIN_DATA(GPIO_Mode_IN, 0, GPIO_PuPd_NOPULL, 0xFF)); + pin_function(obj->pin_ssel, STM_PIN_DATA(GPIO_Mode_IN, 0, GPIO_PuPd_NOPULL, 0xFF)); } -void spi_format(spi_t *obj, int bits, int mode, int slave) { +void spi_format(spi_t *obj, int bits, int mode, int slave) { // Save new values if (bits == 8) { obj->bits = SPI_DataSize_8b; - } - else { + } else { obj->bits = SPI_DataSize_16b; } - + switch (mode) { case 0: - obj->cpol = SPI_CPOL_Low; - obj->cpha = SPI_CPHA_1Edge; - break; + obj->cpol = SPI_CPOL_Low; + obj->cpha = SPI_CPHA_1Edge; + break; case 1: - obj->cpol = SPI_CPOL_Low; - obj->cpha = SPI_CPHA_2Edge; - break; + obj->cpol = SPI_CPOL_Low; + obj->cpha = SPI_CPHA_2Edge; + break; case 2: - obj->cpol = SPI_CPOL_High; - obj->cpha = SPI_CPHA_1Edge; - break; + obj->cpol = SPI_CPOL_High; + obj->cpha = SPI_CPHA_1Edge; + break; default: - obj->cpol = SPI_CPOL_High; - obj->cpha = SPI_CPHA_2Edge; - break; + obj->cpol = SPI_CPOL_High; + obj->cpha = SPI_CPHA_2Edge; + break; } - + if (slave == 0) { obj->mode = SPI_Mode_Master; obj->nss = SPI_NSS_Soft; - } - else { + } else { obj->mode = SPI_Mode_Slave; - obj->nss = SPI_NSS_Hard; + obj->nss = SPI_NSS_Hard; } - + init_spi(obj); } @@ -184,26 +202,19 @@ void spi_frequency(spi_t *obj, int hz) { // Note: The frequencies are obtained with SPI clock = 48 MHz (APB1 & APB2 clocks) if (hz < 300000) { obj->br_presc = SPI_BaudRatePrescaler_256; // 188 kHz - } - else if ((hz >= 300000) && (hz < 700000)) { + } else if ((hz >= 300000) && (hz < 700000)) { obj->br_presc = SPI_BaudRatePrescaler_128; // 375 kHz - } - else if ((hz >= 700000) && (hz < 1000000)) { + } else if ((hz >= 700000) && (hz < 1000000)) { obj->br_presc = SPI_BaudRatePrescaler_64; // 750 kHz - } - else if ((hz >= 1000000) && (hz < 3000000)) { + } else if ((hz >= 1000000) && (hz < 3000000)) { obj->br_presc = SPI_BaudRatePrescaler_32; // 1.5 MHz - } - else if ((hz >= 3000000) && (hz < 6000000)) { + } else if ((hz >= 3000000) && (hz < 6000000)) { obj->br_presc = SPI_BaudRatePrescaler_16; // 3 MHz - } - else if ((hz >= 6000000) && (hz < 12000000)) { + } else if ((hz >= 6000000) && (hz < 12000000)) { obj->br_presc = SPI_BaudRatePrescaler_8; // 6 MHz - } - else if ((hz >= 12000000) && (hz < 24000000)) { + } else if ((hz >= 12000000) && (hz < 24000000)) { obj->br_presc = SPI_BaudRatePrescaler_4; // 12 MHz - } - else { // >= 24000000 + } else { // >= 24000000 obj->br_presc = SPI_BaudRatePrescaler_2; // 24 MHz } init_spi(obj); @@ -214,7 +225,7 @@ static inline int ssp_readable(spi_t *obj) { SPI_TypeDef *spi = (SPI_TypeDef *)(obj->spi); // Check if data is received status = ((SPI_I2S_GetFlagStatus(spi, SPI_I2S_FLAG_RXNE) != RESET) ? 1 : 0); - return status; + return status; } static inline int ssp_writeable(spi_t *obj) { @@ -226,23 +237,21 @@ static inline int ssp_writeable(spi_t *obj) { } static inline void ssp_write(spi_t *obj, int value) { - SPI_TypeDef *spi = (SPI_TypeDef *)(obj->spi); + SPI_TypeDef *spi = (SPI_TypeDef *)(obj->spi); while (!ssp_writeable(obj)); if (obj->bits == SPI_DataSize_8b) { SPI_SendData8(spi, (uint8_t)value); - } - else { // 16-bit + } else { // 16-bit SPI_I2S_SendData16(spi, (uint16_t)value); } } static inline int ssp_read(spi_t *obj) { - SPI_TypeDef *spi = (SPI_TypeDef *)(obj->spi); + SPI_TypeDef *spi = (SPI_TypeDef *)(obj->spi); while (!ssp_readable(obj)); if (obj->bits == SPI_DataSize_8b) { return (int)SPI_ReceiveData8(spi); - } - else { // 16-bit + } else { // 16-bit return (int)SPI_I2S_ReceiveData16(spi); } } @@ -267,19 +276,17 @@ int spi_slave_read(spi_t *obj) { SPI_TypeDef *spi = (SPI_TypeDef *)(obj->spi); if (obj->bits == SPI_DataSize_8b) { return (int)SPI_ReceiveData8(spi); - } - else { // 16-bit + } else { // 16-bit return (int)SPI_I2S_ReceiveData16(spi); } } void spi_slave_write(spi_t *obj, int value) { - SPI_TypeDef *spi = (SPI_TypeDef *)(obj->spi); - while (!ssp_writeable(obj)); + SPI_TypeDef *spi = (SPI_TypeDef *)(obj->spi); + while (!ssp_writeable(obj)); if (obj->bits == SPI_DataSize_8b) { SPI_SendData8(spi, (uint8_t)value); - } - else { // 16-bit + } else { // 16-bit SPI_I2S_SendData16(spi, (uint16_t)value); } } diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F030R8/us_ticker.c b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F030R8/us_ticker.c index 3882b0003e..09bd402ed4 100644 --- a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F030R8/us_ticker.c +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F030R8/us_ticker.c @@ -58,7 +58,7 @@ static void tim_update_irq_handler(void) { // Used by interrupt system static void tim_oc_irq_handler(void) { uint16_t cval = TIM_MST->CNT; - + // Clear interrupt flag if (TIM_GetITStatus(TIM_MST, TIM_IT_CC1) == SET) { TIM_ClearITPendingBit(TIM_MST, TIM_IT_CC1); @@ -67,14 +67,12 @@ static void tim_oc_irq_handler(void) { if (oc_rem_part > 0) { set_compare(oc_rem_part); // Finish the remaining time left oc_rem_part = 0; - } - else { + } else { if (oc_int_part > 0) { set_compare(0xFFFF); oc_rem_part = cval; // To finish the counter loop the next time oc_int_part--; - } - else { + } else { us_ticker_irq_handler(); } } @@ -82,13 +80,13 @@ static void tim_oc_irq_handler(void) { void us_ticker_init(void) { TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure; - + if (us_ticker_inited) return; us_ticker_inited = 1; - + // Enable Timer clock TIM_MST_RCC; - + // Configure time base TIM_TimeBaseStructInit(&TIM_TimeBaseStructure); TIM_TimeBaseStructure.TIM_Period = 0xFFFF; @@ -96,18 +94,18 @@ void us_ticker_init(void) { TIM_TimeBaseStructure.TIM_ClockDivision = 0; TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; TIM_TimeBaseInit(TIM_MST, &TIM_TimeBaseStructure); - + // Configure interrupts TIM_ITConfig(TIM_MST, TIM_IT_Update, ENABLE); - + // Update interrupt used for 32-bit counter NVIC_SetVector(TIM_MST_UP_IRQ, (uint32_t)tim_update_irq_handler); NVIC_EnableIRQ(TIM_MST_UP_IRQ); - + // Output compare interrupt used for timeout feature NVIC_SetVector(TIM_MST_OC_IRQ, (uint32_t)tim_oc_irq_handler); NVIC_EnableIRQ(TIM_MST_OC_IRQ); - + // Enable timer TIM_Cmd(TIM_MST, ENABLE); } @@ -139,8 +137,7 @@ void us_ticker_set_interrupt(unsigned int timestamp) { if (delta <= 0) { // This event was in the past us_ticker_irq_handler(); - } - else { + } else { oc_int_part = (uint32_t)(delta >> 16); oc_rem_part = (uint16_t)(delta & 0xFFFF); if (oc_rem_part <= (0xFFFF - cval)) { diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F072RB/PeripheralNames.h b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F072RB/PeripheralNames.h new file mode 100644 index 0000000000..d36c040134 --- /dev/null +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F072RB/PeripheralNames.h @@ -0,0 +1,82 @@ +/* mbed Microcontroller Library + ******************************************************************************* + * Copyright (c) 2014, STMicroelectronics + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ******************************************************************************* + */ +#ifndef MBED_PERIPHERALNAMES_H +#define MBED_PERIPHERALNAMES_H + +#include "cmsis.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum { + ADC_1 = (int)ADC1_BASE +} ADCName; + +typedef enum { + DAC_1 = (int)DAC_BASE +} DACName; + +typedef enum { + UART_1 = (int)USART1_BASE, + UART_2 = (int)USART2_BASE, + UART_3 = (int)USART3_BASE, + UART_4 = (int)USART4_BASE +} UARTName; + +#define STDIO_UART_TX PA_2 +#define STDIO_UART_RX PA_3 +#define STDIO_UART UART_2 + +typedef enum { + SPI_1 = (int)SPI1_BASE, + SPI_2 = (int)SPI2_BASE +} SPIName; + +typedef enum { + I2C_1 = (int)I2C1_BASE, + I2C_2 = (int)I2C2_BASE +} I2CName; + +typedef enum { + PWM_1 = (int)TIM1_BASE, + PWM_2 = (int)TIM2_BASE, + PWM_3 = (int)TIM3_BASE, + PWM_14 = (int)TIM14_BASE, + PWM_15 = (int)TIM15_BASE, + PWM_16 = (int)TIM16_BASE, + PWM_17 = (int)TIM17_BASE +} PWMName; + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F072RB/PinNames.h b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F072RB/PinNames.h new file mode 100644 index 0000000000..0549793cd5 --- /dev/null +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F072RB/PinNames.h @@ -0,0 +1,183 @@ +/* mbed Microcontroller Library + ******************************************************************************* + * Copyright (c) 2014, STMicroelectronics + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ******************************************************************************* + */ +#ifndef MBED_PINNAMES_H +#define MBED_PINNAMES_H + +#include "cmsis.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#define STM_PIN_DATA(MODE, PUPD, AFNUM) ((int)(((AFNUM) << 7) | ((PUPD) << 4) | ((MODE) << 0))) + +#define STM_PIN_MODE(X) (((X) >> 0) & 0x0F) +#define STM_PIN_PUPD(X) (((X) >> 4) & 0x07) +#define STM_PIN_AFNUM(X) (((X) >> 7) & 0x0F) + +#define STM_MODE_INPUT (0) +#define STM_MODE_OUTPUT_PP (1) +#define STM_MODE_OUTPUT_OD (2) +#define STM_MODE_AF_PP (3) +#define STM_MODE_AF_OD (4) +#define STM_MODE_ANALOG (5) +#define STM_MODE_IT_RISING (6) +#define STM_MODE_IT_FALLING (7) +#define STM_MODE_IT_RISING_FALLING (8) +#define STM_MODE_EVT_RISING (9) +#define STM_MODE_EVT_FALLING (10) +#define STM_MODE_EVT_RISING_FALLING (11) + +// High nibble = port number (0=A, 1=B, 2=C, 3=D, 4=E, 5=F, 6=G, 7=H) +// Low nibble = pin number +#define STM_PORT(X) (((uint32_t)(X) >> 4) & 0xF) +#define STM_PIN(X) ((uint32_t)(X) & 0xF) + +typedef enum { + PIN_INPUT, + PIN_OUTPUT +} PinDirection; + +typedef enum { + PA_0 = 0x00, + PA_1 = 0x01, + PA_2 = 0x02, + PA_3 = 0x03, + PA_4 = 0x04, + PA_5 = 0x05, + PA_6 = 0x06, + PA_7 = 0x07, + PA_8 = 0x08, + PA_9 = 0x09, + PA_10 = 0x0A, + PA_11 = 0x0B, + PA_12 = 0x0C, + PA_13 = 0x0D, + PA_14 = 0x0E, + PA_15 = 0x0F, + + PB_0 = 0x10, + PB_1 = 0x11, + PB_2 = 0x12, + PB_3 = 0x13, + PB_4 = 0x14, + PB_5 = 0x15, + PB_6 = 0x16, + PB_7 = 0x17, + PB_8 = 0x18, + PB_9 = 0x19, + PB_10 = 0x1A, + PB_11 = 0x1B, + PB_12 = 0x1C, + PB_13 = 0x1D, + PB_14 = 0x1E, + PB_15 = 0x1F, + + PC_0 = 0x20, + PC_1 = 0x21, + PC_2 = 0x22, + PC_3 = 0x23, + PC_4 = 0x24, + PC_5 = 0x25, + PC_6 = 0x26, + PC_7 = 0x27, + PC_8 = 0x28, + PC_9 = 0x29, + PC_10 = 0x2A, + PC_11 = 0x2B, + PC_12 = 0x2C, + PC_13 = 0x2D, + PC_14 = 0x2E, + PC_15 = 0x2F, + + PD_2 = 0x32, + + PF_0 = 0x50, + PF_1 = 0x51, + + // Arduino connector namings + A0 = PA_0, + A1 = PA_1, + A2 = PA_4, + A3 = PB_0, + A4 = PC_1, + A5 = PC_0, + D0 = PA_3, + D1 = PA_2, + D2 = PA_10, + D3 = PB_3, + D4 = PB_5, + D5 = PB_4, + D6 = PB_10, + D7 = PA_8, + D8 = PA_9, + D9 = PC_7, + D10 = PB_6, + D11 = PA_7, + D12 = PA_6, + D13 = PA_5, + D14 = PB_9, + D15 = PB_8, + + // Generic signals namings + LED1 = PA_5, + LED2 = PA_5, + LED3 = PA_5, + LED4 = PA_5, + USER_BUTTON = PC_13, + SERIAL_TX = PA_2, + SERIAL_RX = PA_3, + USBTX = PA_2, + USBRX = PA_3, + I2C_SCL = PB_8, + I2C_SDA = PB_9, + SPI_MOSI = PA_7, + SPI_MISO = PA_6, + SPI_SCK = PA_5, + SPI_CS = PB_6, + PWM_OUT = PB_3, + + // Not connected + NC = (int)0xFFFFFFFF +} PinName; + +typedef enum { + PullNone = 0, + PullUp = 1, + PullDown = 2, + OpenDrain = 3, + PullDefault = PullNone +} PinMode; + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F072RB/PortNames.h b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F072RB/PortNames.h new file mode 100644 index 0000000000..b1d7307ed0 --- /dev/null +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F072RB/PortNames.h @@ -0,0 +1,48 @@ +/* mbed Microcontroller Library + ******************************************************************************* + * Copyright (c) 2014, STMicroelectronics + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ******************************************************************************* + */ +#ifndef MBED_PORTNAMES_H +#define MBED_PORTNAMES_H + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum { + PortA = 0, + PortB = 1, + PortC = 2, + PortD = 3, + PortF = 5 +} PortName; + +#ifdef __cplusplus +} +#endif +#endif diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F072RB/analogin_api.c b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F072RB/analogin_api.c new file mode 100644 index 0000000000..7dfd74622a --- /dev/null +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F072RB/analogin_api.c @@ -0,0 +1,190 @@ +/* mbed Microcontroller Library + * Copyright (c) 2014, STMicroelectronics + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +#include "analogin_api.h" + +#if DEVICE_ANALOGIN + +#include "wait_api.h" +#include "cmsis.h" +#include "pinmap.h" +#include "error.h" + +static const PinMap PinMap_ADC[] = { + {PA_0, ADC_1, STM_PIN_DATA(STM_MODE_ANALOG, GPIO_NOPULL, 0)}, // ADC1_IN0 + {PA_1, ADC_1, STM_PIN_DATA(STM_MODE_ANALOG, GPIO_NOPULL, 0)}, // ADC1_IN1 + {PA_2, ADC_1, STM_PIN_DATA(STM_MODE_ANALOG, GPIO_NOPULL, 0)}, // ADC1_IN2 + {PA_3, ADC_1, STM_PIN_DATA(STM_MODE_ANALOG, GPIO_NOPULL, 0)}, // ADC1_IN3 + {PA_4, ADC_1, STM_PIN_DATA(STM_MODE_ANALOG, GPIO_NOPULL, 0)}, // ADC1_IN4 + {PA_5, ADC_1, STM_PIN_DATA(STM_MODE_ANALOG, GPIO_NOPULL, 0)}, // ADC1_IN5 + {PA_6, ADC_1, STM_PIN_DATA(STM_MODE_ANALOG, GPIO_NOPULL, 0)}, // ADC1_IN6 + {PA_7, ADC_1, STM_PIN_DATA(STM_MODE_ANALOG, GPIO_NOPULL, 0)}, // ADC1_IN7 + {PB_0, ADC_1, STM_PIN_DATA(STM_MODE_ANALOG, GPIO_NOPULL, 0)}, // ADC1_IN8 + {PB_1, ADC_1, STM_PIN_DATA(STM_MODE_ANALOG, GPIO_NOPULL, 0)}, // ADC1_IN9 + {PC_0, ADC_1, STM_PIN_DATA(STM_MODE_ANALOG, GPIO_NOPULL, 0)}, // ADC1_IN10 + {PC_1, ADC_1, STM_PIN_DATA(STM_MODE_ANALOG, GPIO_NOPULL, 0)}, // ADC1_IN11 + {PC_2, ADC_1, STM_PIN_DATA(STM_MODE_ANALOG, GPIO_NOPULL, 0)}, // ADC1_IN12 + {PC_3, ADC_1, STM_PIN_DATA(STM_MODE_ANALOG, GPIO_NOPULL, 0)}, // ADC1_IN13 + {PC_4, ADC_1, STM_PIN_DATA(STM_MODE_ANALOG, GPIO_NOPULL, 0)}, // ADC1_IN14 + {PC_5, ADC_1, STM_PIN_DATA(STM_MODE_ANALOG, GPIO_NOPULL, 0)}, // ADC1_IN15 + {NC, NC, 0} +}; + +ADC_HandleTypeDef AdcHandle; + +int adc_inited = 0; + +void analogin_init(analogin_t *obj, PinName pin) { + // Get the peripheral name from the pin and assign it to the object + obj->adc = (ADCName)pinmap_peripheral(pin, PinMap_ADC); + + if (obj->adc == (ADCName)NC) { + error("ADC error: pinout mapping failed."); + } + + // Configure GPIO + pinmap_pinout(pin, PinMap_ADC); + + // Save pin number for the read function + obj->pin = pin; + + // The ADC initialization is done once + if (adc_inited == 0) { + adc_inited = 1; + + // Enable ADC clock + __ADC1_CLK_ENABLE(); + + // Configure ADC + AdcHandle.Instance = (ADC_TypeDef *)(obj->adc); + AdcHandle.Init.ClockPrescaler = ADC_CLOCK_SYNC_PCLK_DIV4; + AdcHandle.Init.Resolution = ADC_RESOLUTION12b; + AdcHandle.Init.DataAlign = ADC_DATAALIGN_RIGHT; + AdcHandle.Init.ScanConvMode = DISABLE; + AdcHandle.Init.EOCSelection = EOC_SINGLE_CONV; + AdcHandle.Init.LowPowerAutoWait = DISABLE; + AdcHandle.Init.LowPowerAutoPowerOff = DISABLE; + AdcHandle.Init.ContinuousConvMode = DISABLE; + AdcHandle.Init.DiscontinuousConvMode = DISABLE; + AdcHandle.Init.ExternalTrigConv = ADC_SOFTWARE_START; + AdcHandle.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_NONE; + AdcHandle.Init.DMAContinuousRequests = DISABLE; + AdcHandle.Init.Overrun = OVR_DATA_OVERWRITTEN; + HAL_ADC_Init(&AdcHandle); + + // Run the ADC calibration + HAL_ADCEx_Calibration_Start(&AdcHandle); + } +} + +static inline uint16_t adc_read(analogin_t *obj) { + ADC_ChannelConfTypeDef sConfig; + + AdcHandle.Instance = (ADC_TypeDef *)(obj->adc); + + // Configure ADC channel + sConfig.Rank = ADC_RANK_CHANNEL_NUMBER; + sConfig.SamplingTime = ADC_SAMPLETIME_7CYCLES_5; + + switch (obj->pin) { + case PA_0: + sConfig.Channel = ADC_CHANNEL_0; + break; + case PA_1: + sConfig.Channel = ADC_CHANNEL_1; + break; + case PA_2: + sConfig.Channel = ADC_CHANNEL_2; + break; + case PA_3: + sConfig.Channel = ADC_CHANNEL_3; + break; + case PA_4: + sConfig.Channel = ADC_CHANNEL_4; + break; + case PA_5: + sConfig.Channel = ADC_CHANNEL_5; + break; + case PA_6: + sConfig.Channel = ADC_CHANNEL_6; + break; + case PA_7: + sConfig.Channel = ADC_CHANNEL_7; + break; + case PB_0: + sConfig.Channel = ADC_CHANNEL_8; + break; + case PB_1: + sConfig.Channel = ADC_CHANNEL_9; + break; + case PC_0: + sConfig.Channel = ADC_CHANNEL_10; + break; + case PC_1: + sConfig.Channel = ADC_CHANNEL_11; + break; + case PC_2: + sConfig.Channel = ADC_CHANNEL_12; + break; + case PC_3: + sConfig.Channel = ADC_CHANNEL_13; + break; + case PC_4: + sConfig.Channel = ADC_CHANNEL_14; + break; + case PC_5: + sConfig.Channel = ADC_CHANNEL_15; + break; + default: + return 0; + } + + // Clear all channels as it is not done in HAL_ADC_ConfigChannel() + AdcHandle.Instance->CHSELR = 0; + + HAL_ADC_ConfigChannel(&AdcHandle, &sConfig); + + HAL_ADC_Start(&AdcHandle); // Start conversion + + // Wait end of conversion and get value + if (HAL_ADC_PollForConversion(&AdcHandle, 10) == HAL_OK) { + return (HAL_ADC_GetValue(&AdcHandle)); + } else { + return 0; + } +} + +uint16_t analogin_read_u16(analogin_t *obj) { + return (adc_read(obj)); +} + +float analogin_read(analogin_t *obj) { + uint16_t value = adc_read(obj); + return (float)value * (1.0f / (float)0xFFF); // 12 bits range +} + +#endif diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F072RB/analogout_api.c b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F072RB/analogout_api.c new file mode 100644 index 0000000000..dc6bf5f041 --- /dev/null +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F072RB/analogout_api.c @@ -0,0 +1,135 @@ +/* mbed Microcontroller Library + * Copyright (c) 2014, STMicroelectronics + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +#include "analogout_api.h" + +#if DEVICE_ANALOGOUT + +#include "cmsis.h" +#include "pinmap.h" +#include "error.h" + +#define DAC_RANGE (0xFFF) // 12 bits + +static const PinMap PinMap_DAC[] = { + {PA_4, DAC_1, STM_PIN_DATA(STM_MODE_ANALOG, GPIO_NOPULL, 0)}, // DAC_OUT1 + {PA_5, DAC_1, STM_PIN_DATA(STM_MODE_ANALOG, GPIO_NOPULL, 0)}, // DAC_OUT2 (Warning: LED1 is also on this pin) + {NC, NC, 0} +}; + +static DAC_HandleTypeDef DacHandle; + +void analogout_init(dac_t *obj, PinName pin) { + DAC_ChannelConfTypeDef sConfig; + + DacHandle.Instance = DAC; + + // Get the peripheral name (DAC_1, ...) from the pin and assign it to the object + obj->dac = (DACName)pinmap_peripheral(pin, PinMap_DAC); + + if (obj->dac == (DACName)NC) { + error("DAC pin mapping failed"); + } + + // Configure GPIO + pinmap_pinout(pin, PinMap_DAC); + + // Save the channel for future use + obj->pin = pin; + + // Enable DAC clock + __DAC1_CLK_ENABLE(); + + // Configure DAC + sConfig.DAC_Trigger = DAC_TRIGGER_NONE; + sConfig.DAC_OutputBuffer = DAC_OUTPUTBUFFER_DISABLE; + + if (pin == PA_4) { + HAL_DAC_ConfigChannel(&DacHandle, &sConfig, DAC_CHANNEL_1); + } else { // PA_5 + HAL_DAC_ConfigChannel(&DacHandle, &sConfig, DAC_CHANNEL_2); + } + + analogout_write_u16(obj, 0); +} + +void analogout_free(dac_t *obj) { + // Reset DAC and disable clock + __DAC1_FORCE_RESET(); + __DAC1_RELEASE_RESET(); + __DAC1_CLK_DISABLE(); + + // Configure GPIO + pin_function(obj->pin, STM_PIN_DATA(STM_MODE_INPUT, GPIO_NOPULL, 0)); +} + +static inline void dac_write(dac_t *obj, uint16_t value) { + if (obj->pin == PA_4) { + HAL_DAC_SetValue(&DacHandle, DAC_CHANNEL_1, DAC_ALIGN_12B_R, value); + HAL_DAC_Start(&DacHandle, DAC_CHANNEL_1); + } else { // PA_5 + HAL_DAC_SetValue(&DacHandle, DAC_CHANNEL_2, DAC_ALIGN_12B_R, value); + HAL_DAC_Start(&DacHandle, DAC_CHANNEL_2); + } +} + +static inline int dac_read(dac_t *obj) { + if (obj->pin == PA_4) { + return (int)HAL_DAC_GetValue(&DacHandle, DAC_CHANNEL_1); + } else { // PA_5 + return (int)HAL_DAC_GetValue(&DacHandle, DAC_CHANNEL_2); + } +} + +void analogout_write(dac_t *obj, float value) { + if (value < 0.0f) { + dac_write(obj, 0); // Min value + } else if (value > 1.0f) { + dac_write(obj, (uint16_t)DAC_RANGE); // Max value + } else { + dac_write(obj, (uint16_t)(value * (float)DAC_RANGE)); + } +} + +void analogout_write_u16(dac_t *obj, uint16_t value) { + if (value > (uint16_t)DAC_RANGE) { + dac_write(obj, (uint16_t)DAC_RANGE); // Max value + } else { + dac_write(obj, value); + } +} + +float analogout_read(dac_t *obj) { + uint32_t value = dac_read(obj); + return (float)((float)value * (1.0f / (float)DAC_RANGE)); +} + +uint16_t analogout_read_u16(dac_t *obj) { + return (uint16_t)dac_read(obj); +} + +#endif // DEVICE_ANALOGOUT diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F072RB/device.h b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F072RB/device.h new file mode 100644 index 0000000000..fd151e3566 --- /dev/null +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F072RB/device.h @@ -0,0 +1,70 @@ +/* mbed Microcontroller Library + ******************************************************************************* + * Copyright (c) 2014, STMicroelectronics + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ******************************************************************************* + */ +#ifndef MBED_DEVICE_H +#define MBED_DEVICE_H + +#define DEVICE_PORTIN 1 +#define DEVICE_PORTOUT 1 +#define DEVICE_PORTINOUT 1 + +#define DEVICE_INTERRUPTIN 1 + +#define DEVICE_ANALOGIN 1 +#define DEVICE_ANALOGOUT 1 + +#define DEVICE_SERIAL 1 + +#define DEVICE_I2C 1 +#define DEVICE_I2CSLAVE 1 + +#define DEVICE_SPI 1 +#define DEVICE_SPISLAVE 1 + +#define DEVICE_RTC 1 + +#define DEVICE_PWMOUT 1 + +#define DEVICE_SLEEP 1 + +//======================================= + +#define DEVICE_SEMIHOST 0 +#define DEVICE_LOCALFILESYSTEM 0 +#define DEVICE_ID_LENGTH 24 + +#define DEVICE_DEBUG_AWARENESS 0 + +#define DEVICE_STDIO_MESSAGES 1 + +#define DEVICE_ERROR_RED 0 + +#include "objects.h" + +#endif diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F072RB/gpio_api.c b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F072RB/gpio_api.c new file mode 100644 index 0000000000..8a4f8cb4a3 --- /dev/null +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F072RB/gpio_api.c @@ -0,0 +1,71 @@ +/* mbed Microcontroller Library + ******************************************************************************* + * Copyright (c) 2014, STMicroelectronics + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ******************************************************************************* + */ +#include "gpio_api.h" +#include "pinmap.h" +#include "error.h" + +extern uint32_t Set_GPIO_Clock(uint32_t port_idx); + +uint32_t gpio_set(PinName pin) { + if (pin == NC) return 0; + + pin_function(pin, STM_PIN_DATA(STM_MODE_INPUT, GPIO_NOPULL, 0)); + + return (uint32_t)(1 << ((uint32_t)pin & 0xF)); // Return the pin mask +} + +void gpio_init(gpio_t *obj, PinName pin) { + if (pin == NC) return; + + uint32_t port_index = STM_PORT(pin); + + // Enable GPIO clock + uint32_t gpio_add = Set_GPIO_Clock(port_index); + GPIO_TypeDef *gpio = (GPIO_TypeDef *)gpio_add; + + // Fill GPIO object structure for future use + obj->pin = pin; + obj->mask = gpio_set(pin); + obj->reg_in = &gpio->IDR; + obj->reg_set = &gpio->BSRRL; + obj->reg_clr = &gpio->BSRRH; +} + +void gpio_mode(gpio_t *obj, PinMode mode) { + pin_mode(obj->pin, mode); +} + +void gpio_dir(gpio_t *obj, PinDirection direction) { + if (direction == PIN_OUTPUT) { + pin_function(obj->pin, STM_PIN_DATA(STM_MODE_OUTPUT_PP, GPIO_NOPULL, 0)); + } else { // PIN_INPUT + pin_function(obj->pin, STM_PIN_DATA(STM_MODE_INPUT, GPIO_NOPULL, 0)); + } +} diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F072RB/gpio_irq_api.c b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F072RB/gpio_irq_api.c new file mode 100644 index 0000000000..bfc8ae58b8 --- /dev/null +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F072RB/gpio_irq_api.c @@ -0,0 +1,189 @@ +/* mbed Microcontroller Library + ******************************************************************************* + * Copyright (c) 2014, STMicroelectronics + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ******************************************************************************* + */ +#include +#include "cmsis.h" +#include "gpio_irq_api.h" +#include "pinmap.h" +#include "error.h" + +#define EDGE_NONE (0) +#define EDGE_RISE (1) +#define EDGE_FALL (2) +#define EDGE_BOTH (3) + +// EXTI lines: 0-1, 2-3 and 4-15 +#define CHANNEL_NUM (3) + +static uint32_t channel_ids[CHANNEL_NUM] = {0, 0, 0}; +static uint32_t channel_gpio[CHANNEL_NUM] = {0, 0, 0}; +static uint32_t channel_pin[CHANNEL_NUM] = {0, 0, 0}; + +static gpio_irq_handler irq_handler; + +static void handle_interrupt_in(uint32_t irq_index) { + // Retrieve the gpio and pin that generate the irq + GPIO_TypeDef *gpio = (GPIO_TypeDef *)(channel_gpio[irq_index]); + uint32_t pin = (uint32_t)(1 << channel_pin[irq_index]); + + // Clear interrupt flag + if (__HAL_GPIO_EXTI_GET_FLAG(pin) != RESET) { + __HAL_GPIO_EXTI_CLEAR_FLAG(pin); + } + + if (channel_ids[irq_index] == 0) return; + + // Check which edge has generated the irq + if ((gpio->IDR & pin) == 0) { + irq_handler(channel_ids[irq_index], IRQ_FALL); + } else { + irq_handler(channel_ids[irq_index], IRQ_RISE); + } +} + +// EXTI lines 0 to 1 +static void gpio_irq0(void) { + handle_interrupt_in(0); +} +// EXTI lines 2 to 3 +static void gpio_irq1(void) { + handle_interrupt_in(1); +} +// EXTI lines 4 to 15 +static void gpio_irq2(void) { + handle_interrupt_in(2); +} + +extern uint32_t Set_GPIO_Clock(uint32_t port_idx); + +int gpio_irq_init(gpio_irq_t *obj, PinName pin, gpio_irq_handler handler, uint32_t id) { + IRQn_Type irq_n = (IRQn_Type)0; + uint32_t vector = 0; + uint32_t irq_index; + + if (pin == NC) return -1; + + uint32_t port_index = STM_PORT(pin); + uint32_t pin_index = STM_PIN(pin); + + // Select irq number and interrupt routine + if ((pin_index == 0) || (pin_index == 1)) { + irq_n = EXTI0_1_IRQn; + vector = (uint32_t)&gpio_irq0; + irq_index = 0; + } else if ((pin_index == 2) || (pin_index == 3)) { + irq_n = EXTI2_3_IRQn; + vector = (uint32_t)&gpio_irq1; + irq_index = 1; + } else if ((pin_index > 3) && (pin_index < 16)) { + irq_n = EXTI4_15_IRQn; + vector = (uint32_t)&gpio_irq2; + irq_index = 2; + } else { + error("InterruptIn error: pin not supported.\n"); + return -1; + } + + // Enable GPIO clock + uint32_t gpio_add = Set_GPIO_Clock(port_index); + + // Configure GPIO + pin_function(pin, STM_PIN_DATA(STM_MODE_IT_FALLING, GPIO_NOPULL, 0)); + + // Enable EXTI interrupt + NVIC_SetVector(irq_n, vector); + NVIC_EnableIRQ(irq_n); + + // Save informations for future use + obj->irq_n = irq_n; + obj->irq_index = irq_index; + obj->event = EDGE_NONE; + obj->pin = pin; + channel_ids[irq_index] = id; + channel_gpio[irq_index] = gpio_add; + channel_pin[irq_index] = pin_index; + + irq_handler = handler; + + return 0; +} + +void gpio_irq_free(gpio_irq_t *obj) { + channel_ids[obj->irq_index] = 0; + channel_gpio[obj->irq_index] = 0; + channel_pin[obj->irq_index] = 0; + // Disable EXTI line + pin_function(obj->pin, STM_PIN_DATA(STM_MODE_INPUT, GPIO_NOPULL, 0)); + obj->event = EDGE_NONE; +} + +void gpio_irq_set(gpio_irq_t *obj, gpio_irq_event event, uint32_t enable) { + uint32_t mode = STM_MODE_INPUT; + uint32_t pull = GPIO_NOPULL; + + if (enable) { + + pull = GPIO_NOPULL; + + if (event == IRQ_RISE) { + if ((obj->event == EDGE_FALL) || (obj->event == EDGE_BOTH)) { + mode = STM_MODE_IT_RISING_FALLING; + obj->event = EDGE_BOTH; + } else { // NONE or RISE + mode = STM_MODE_IT_RISING; + obj->event = EDGE_RISE; + } + } + + if (event == IRQ_FALL) { + if ((obj->event == EDGE_RISE) || (obj->event == EDGE_BOTH)) { + mode = STM_MODE_IT_RISING_FALLING; + obj->event = EDGE_BOTH; + } else { // NONE or FALL + mode = STM_MODE_IT_FALLING; + obj->event = EDGE_FALL; + } + } + } else { + mode = STM_MODE_INPUT; + pull = GPIO_NOPULL; + obj->event = EDGE_NONE; + } + + pin_function(obj->pin, STM_PIN_DATA(mode, pull, 0)); +} + +void gpio_irq_enable(gpio_irq_t *obj) { + NVIC_EnableIRQ(obj->irq_n); +} + +void gpio_irq_disable(gpio_irq_t *obj) { + NVIC_DisableIRQ(obj->irq_n); + obj->event = EDGE_NONE; +} diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F072RB/gpio_object.h b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F072RB/gpio_object.h new file mode 100644 index 0000000000..c3ae5ac506 --- /dev/null +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F072RB/gpio_object.h @@ -0,0 +1,66 @@ +/* mbed Microcontroller Library + ******************************************************************************* + * Copyright (c) 2014, STMicroelectronics + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ******************************************************************************* + */ +#ifndef MBED_GPIO_OBJECT_H +#define MBED_GPIO_OBJECT_H + +#include "cmsis.h" +#include "PortNames.h" +#include "PeripheralNames.h" +#include "PinNames.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct { + PinName pin; + uint32_t mask; + __IO uint16_t *reg_in; + __IO uint16_t *reg_set; + __IO uint16_t *reg_clr; +} gpio_t; + +static inline void gpio_write(gpio_t *obj, int value) { + if (value) { + *obj->reg_set = obj->mask; + } else { + *obj->reg_clr = obj->mask; + } +} + +static inline int gpio_read(gpio_t *obj) { + return ((*obj->reg_in & obj->mask) ? 1 : 0); +} + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F072RB/i2c_api.c b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F072RB/i2c_api.c new file mode 100644 index 0000000000..ed2209ada9 --- /dev/null +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F072RB/i2c_api.c @@ -0,0 +1,384 @@ +/* mbed Microcontroller Library + ******************************************************************************* + * Copyright (c) 2014, STMicroelectronics + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ******************************************************************************* + */ +#include "i2c_api.h" + +#if DEVICE_I2C + +#include "cmsis.h" +#include "pinmap.h" +#include "error.h" + +/* Timeout values for flags and events waiting loops. These timeouts are + not based on accurate values, they just guarantee that the application will + not remain stuck if the I2C communication is corrupted. */ +#define FLAG_TIMEOUT ((int)0x1000) +#define LONG_TIMEOUT ((int)0x8000) + +static const PinMap PinMap_I2C_SDA[] = { + {PB_7, I2C_1, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF1_I2C1)}, + {PB_9, I2C_1, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF1_I2C1)}, + {PB_11, I2C_2, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF1_I2C2)}, + {PB_14, I2C_2, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF5_I2C2)}, + {NC, NC, 0} +}; + +static const PinMap PinMap_I2C_SCL[] = { + {PB_6, I2C_1, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF1_I2C1)}, + {PB_8, I2C_1, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF1_I2C1)}, + {PB_10, I2C_2, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF1_I2C2)}, + {PB_13, I2C_2, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF5_I2C2)}, + {NC, NC, 0} +}; + +I2C_HandleTypeDef I2cHandle; + +void i2c_init(i2c_t *obj, PinName sda, PinName scl) { + // Determine the I2C to use + I2CName i2c_sda = (I2CName)pinmap_peripheral(sda, PinMap_I2C_SDA); + I2CName i2c_scl = (I2CName)pinmap_peripheral(scl, PinMap_I2C_SCL); + + obj->i2c = (I2CName)pinmap_merge(i2c_sda, i2c_scl); + + if (obj->i2c == (I2CName)NC) { + error("I2C error: pinout mapping failed."); + } + + // Enable I2C clock + if (obj->i2c == I2C_1) { + __HAL_RCC_I2C1_CONFIG(RCC_I2C1CLKSOURCE_SYSCLK); + __I2C1_CLK_ENABLE(); + } + if (obj->i2c == I2C_2) { + __I2C2_CLK_ENABLE(); + } + + // Configure I2C pins + pinmap_pinout(sda, PinMap_I2C_SDA); + pinmap_pinout(scl, PinMap_I2C_SCL); + pin_mode(sda, OpenDrain); + pin_mode(scl, OpenDrain); + + // Reset to clear pending flags if any + i2c_reset(obj); + + // I2C configuration + i2c_frequency(obj, 100000); // 100 kHz per default +} + +void i2c_frequency(i2c_t *obj, int hz) { + I2cHandle.Instance = (I2C_TypeDef *)(obj->i2c); + + // Common settings: I2C clock = 48 MHz, Analog filter = ON, Digital filter coefficient = 0 + switch (hz) { + case 100000: + I2cHandle.Init.Timing = 0x10805E89; // Standard mode with Rise Time = 400ns and Fall Time = 100ns + break; + case 400000: + I2cHandle.Init.Timing = 0x00901850; // Fast mode with Rise Time = 250ns and Fall Time = 100ns + break; + case 1000000: + I2cHandle.Init.Timing = 0x00700818; // Fast mode Plus with Rise Time = 60ns and Fall Time = 100ns + break; + default: + error("Only 100kHz, 400kHz and 1MHz I2C frequencies are supported."); + break; + } + + // I2C configuration + I2cHandle.Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT; + I2cHandle.Init.DualAddressMode = I2C_DUALADDRESS_DISABLED; + I2cHandle.Init.GeneralCallMode = I2C_GENERALCALL_DISABLED; + I2cHandle.Init.NoStretchMode = I2C_NOSTRETCH_DISABLED; + I2cHandle.Init.OwnAddress1 = 0; + I2cHandle.Init.OwnAddress2 = 0; + I2cHandle.Init.OwnAddress2Masks = I2C_OA2_NOMASK; + HAL_I2C_Init(&I2cHandle); +} + +inline int i2c_start(i2c_t *obj) { + I2C_TypeDef *i2c = (I2C_TypeDef *)(obj->i2c); + int timeout; + + I2cHandle.Instance = (I2C_TypeDef *)(obj->i2c); + + // Clear Acknowledge failure flag + __HAL_I2C_CLEAR_FLAG(&I2cHandle, I2C_FLAG_AF); + + // Generate the START condition + i2c->CR2 |= I2C_CR2_START; + + // Wait the START condition has been correctly sent + timeout = FLAG_TIMEOUT; + while (__HAL_I2C_GET_FLAG(&I2cHandle, I2C_FLAG_BUSY) == RESET) { + if ((timeout--) == 0) { + return 1; + } + } + + return 0; +} + +inline int i2c_stop(i2c_t *obj) { + I2C_TypeDef *i2c = (I2C_TypeDef *)(obj->i2c); + + // Generate the STOP condition + i2c->CR2 |= I2C_CR2_STOP; + + return 0; +} + +int i2c_read(i2c_t *obj, int address, char *data, int length, int stop) { + I2C_TypeDef *i2c = (I2C_TypeDef *)(obj->i2c); + I2cHandle.Instance = (I2C_TypeDef *)(obj->i2c); + int timeout; + int count; + int value; + + if (length == 0) return 0; + + /* update CR2 register */ + i2c->CR2 = (i2c->CR2 & (uint32_t)~((uint32_t)(I2C_CR2_SADD | I2C_CR2_NBYTES | I2C_CR2_RELOAD | I2C_CR2_AUTOEND | I2C_CR2_RD_WRN | I2C_CR2_START | I2C_CR2_STOP))) + | (uint32_t)(((uint32_t)address & I2C_CR2_SADD) | (((uint32_t)length << 16) & I2C_CR2_NBYTES) | (uint32_t)I2C_SOFTEND_MODE | (uint32_t)I2C_GENERATE_START_READ); + + // Read all bytes + for (count = 0; count < length; count++) { + value = i2c_byte_read(obj, 0); + data[count] = (char)value; + } + + // Wait transfer complete + timeout = FLAG_TIMEOUT; + while (__HAL_I2C_GET_FLAG(&I2cHandle, I2C_FLAG_TC) == RESET) { + timeout--; + if (timeout == 0) { + return 0; + } + } + __HAL_I2C_CLEAR_FLAG(&I2cHandle, I2C_FLAG_TC); + + // If not repeated start, send stop. + if (stop) { + i2c_stop(obj); + /* Wait until STOPF flag is set */ + timeout = FLAG_TIMEOUT; + while (__HAL_I2C_GET_FLAG(&I2cHandle, I2C_FLAG_STOPF) == RESET) { + timeout--; + if (timeout == 0) { + return 0; + } + } + /* Clear STOP Flag */ + __HAL_I2C_CLEAR_FLAG(&I2cHandle, I2C_FLAG_STOPF); + } + + return length; +} + +int i2c_write(i2c_t *obj, int address, const char *data, int length, int stop) { + I2C_TypeDef *i2c = (I2C_TypeDef *)(obj->i2c); + I2cHandle.Instance = (I2C_TypeDef *)(obj->i2c); + int timeout; + int count; + + if (length == 0) return 0; + + /* update CR2 register */ + i2c->CR2 = (i2c->CR2 & (uint32_t)~((uint32_t)(I2C_CR2_SADD | I2C_CR2_NBYTES | I2C_CR2_RELOAD | I2C_CR2_AUTOEND | I2C_CR2_RD_WRN | I2C_CR2_START | I2C_CR2_STOP))) + | (uint32_t)(((uint32_t)address & I2C_CR2_SADD) | (((uint32_t)length << 16) & I2C_CR2_NBYTES) | (uint32_t)I2C_SOFTEND_MODE | (uint32_t)I2C_GENERATE_START_WRITE); + + + + for (count = 0; count < length; count++) { + i2c_byte_write(obj, data[count]); + } + + // Wait transfer complete + timeout = FLAG_TIMEOUT; + while (__HAL_I2C_GET_FLAG(&I2cHandle, I2C_FLAG_TC) == RESET) { + timeout--; + if (timeout == 0) { + return 0; + } + } + __HAL_I2C_CLEAR_FLAG(&I2cHandle, I2C_FLAG_TC); + + // If not repeated start, send stop. + if (stop) { + i2c_stop(obj); + /* Wait until STOPF flag is set */ + timeout = FLAG_TIMEOUT; + while (__HAL_I2C_GET_FLAG(&I2cHandle, I2C_FLAG_STOPF) == RESET) { + timeout--; + if (timeout == 0) { + return 0; + } + } + /* Clear STOP Flag */ + __HAL_I2C_CLEAR_FLAG(&I2cHandle, I2C_FLAG_STOPF); + } + + return count; +} + +int i2c_byte_read(i2c_t *obj, int last) { + I2C_TypeDef *i2c = (I2C_TypeDef *)(obj->i2c); + int timeout; + + // Wait until the byte is received + timeout = FLAG_TIMEOUT; + while (__HAL_I2C_GET_FLAG(&I2cHandle, I2C_FLAG_RXNE) == RESET) { + if ((timeout--) == 0) { + return 0; + } + } + + return (int)i2c->RXDR; +} + +int i2c_byte_write(i2c_t *obj, int data) { + I2C_TypeDef *i2c = (I2C_TypeDef *)(obj->i2c); + int timeout; + + // Wait until the previous byte is transmitted + timeout = FLAG_TIMEOUT; + while (__HAL_I2C_GET_FLAG(&I2cHandle, I2C_FLAG_TXIS) == RESET) { + if ((timeout--) == 0) { + return 0; + } + } + + i2c->TXDR = (uint8_t)data; + + return 1; +} + +void i2c_reset(i2c_t *obj) { + if (obj->i2c == I2C_1) { + __I2C1_FORCE_RESET(); + __I2C1_RELEASE_RESET(); + } + if (obj->i2c == I2C_2) { + __I2C2_FORCE_RESET(); + __I2C2_RELEASE_RESET(); + } +} + +#if DEVICE_I2CSLAVE + +void i2c_slave_address(i2c_t *obj, int idx, uint32_t address, uint32_t mask) { + I2C_TypeDef *i2c = (I2C_TypeDef *)(obj->i2c); + uint16_t tmpreg = 0; + + // disable + i2c->OAR1 &= (uint32_t)(~I2C_OAR1_OA1EN); + // Get the old register value + tmpreg = i2c->OAR1; + // Reset address bits + tmpreg &= 0xFC00; + // Set new address + tmpreg |= (uint16_t)((uint16_t)address & (uint16_t)0x00FE); // 7-bits + // Store the new register value + i2c->OAR1 = tmpreg; + // enable + i2c->OAR1 |= I2C_OAR1_OA1EN; +} + +void i2c_slave_mode(i2c_t *obj, int enable_slave) { + + I2C_TypeDef *i2c = (I2C_TypeDef *)(obj->i2c); + uint16_t tmpreg; + + // Get the old register value + tmpreg = i2c->OAR1; + + // Enable / disable slave + if (enable_slave == 1) { + tmpreg |= I2C_OAR1_OA1EN; + } else { + tmpreg &= (uint32_t)(~I2C_OAR1_OA1EN); + } + + // Set new mode + i2c->OAR1 = tmpreg; + +} + +// See I2CSlave.h +#define NoData 0 // the slave has not been addressed +#define ReadAddressed 1 // the master has requested a read from this slave (slave = transmitter) +#define WriteGeneral 2 // the master is writing to all slave +#define WriteAddressed 3 // the master is writing to this slave (slave = receiver) + +int i2c_slave_receive(i2c_t *obj) { + I2cHandle.Instance = (I2C_TypeDef *)(obj->i2c); + int retValue = NoData; + + if (__HAL_I2C_GET_FLAG(&I2cHandle, I2C_FLAG_BUSY) == 1) { + if (__HAL_I2C_GET_FLAG(&I2cHandle, I2C_FLAG_ADDR) == 1) { + if (__HAL_I2C_GET_FLAG(&I2cHandle, I2C_FLAG_DIR) == 1) + retValue = ReadAddressed; + else + retValue = WriteAddressed; + + __HAL_I2C_CLEAR_FLAG(&I2cHandle, I2C_FLAG_ADDR); + } + } + + return (retValue); +} + +int i2c_slave_read(i2c_t *obj, char *data, int length) { + char size = 0; + + if (length == 0) return 0; + + while (size < length) data[size++] = (char)i2c_byte_read(obj, 0); + + return size; +} + +int i2c_slave_write(i2c_t *obj, const char *data, int length) { + char size = 0; + I2cHandle.Instance = (I2C_TypeDef *)(obj->i2c); + + if (length == 0) return 0; + + do { + i2c_byte_write(obj, data[size]); + size++; + } while (size < length); + + return size; +} + + +#endif // DEVICE_I2CSLAVE + +#endif // DEVICE_I2C diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F072RB/mbed_overrides.c b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F072RB/mbed_overrides.c new file mode 100644 index 0000000000..60d7941d83 --- /dev/null +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F072RB/mbed_overrides.c @@ -0,0 +1,34 @@ +/* mbed Microcontroller Library + * Copyright (c) 2014, STMicroelectronics + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +#include "cmsis.h" + +// This function is called after RAM initialization and before main. +void mbed_sdk_init() { + // Update the SystemCoreClock variable. + SystemCoreClockUpdate(); +} diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F072RB/objects.h b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F072RB/objects.h new file mode 100644 index 0000000000..e3a1c2abe1 --- /dev/null +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F072RB/objects.h @@ -0,0 +1,109 @@ +/* mbed Microcontroller Library + ******************************************************************************* + * Copyright (c) 2014, STMicroelectronics + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ******************************************************************************* + */ +#ifndef MBED_OBJECTS_H +#define MBED_OBJECTS_H + +#include "cmsis.h" +#include "PortNames.h" +#include "PeripheralNames.h" +#include "PinNames.h" + +#ifdef __cplusplus +extern "C" { +#endif + +struct gpio_irq_s { + IRQn_Type irq_n; + uint32_t irq_index; + uint32_t event; + PinName pin; +}; + +struct port_s { + PortName port; + uint32_t mask; + PinDirection direction; + __IO uint16_t *reg_in; + __IO uint16_t *reg_out; +}; + +struct analogin_s { + ADCName adc; + PinName pin; +}; + +struct dac_s { + DACName dac; + PinName pin; +}; + +struct serial_s { + UARTName uart; + int index; // Used by irq + uint32_t baudrate; + uint32_t databits; + uint32_t stopbits; + uint32_t parity; + PinName pin_tx; + PinName pin_rx; +}; + +struct spi_s { + SPIName spi; + uint32_t bits; + uint32_t cpol; + uint32_t cpha; + uint32_t mode; + uint32_t nss; + uint32_t br_presc; + PinName pin_miso; + PinName pin_mosi; + PinName pin_sclk; + PinName pin_ssel; +}; + +struct i2c_s { + I2CName i2c; +}; + +struct pwmout_s { + PWMName pwm; + PinName pin; + uint32_t period; + uint32_t pulse; +}; + +#include "gpio_object.h" + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F072RB/pinmap.c b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F072RB/pinmap.c new file mode 100644 index 0000000000..cd50ce013d --- /dev/null +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F072RB/pinmap.c @@ -0,0 +1,134 @@ +/* mbed Microcontroller Library + ******************************************************************************* + * Copyright (c) 2014, STMicroelectronics + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ******************************************************************************* + */ +#include "pinmap.h" +#include "PortNames.h" +#include "error.h" + +// GPIO mode look-up table +static const uint32_t gpio_mode[12] = { + 0x00000000, // 0 = GPIO_MODE_INPUT + 0x00000001, // 1 = GPIO_MODE_OUTPUT_PP + 0x00000011, // 2 = GPIO_MODE_OUTPUT_OD + 0x00000002, // 3 = GPIO_MODE_AF_PP + 0x00000012, // 4 = GPIO_MODE_AF_OD + 0x00000003, // 5 = GPIO_MODE_ANALOG + 0x10110000, // 6 = GPIO_MODE_IT_RISING + 0x10210000, // 7 = GPIO_MODE_IT_FALLING + 0x10310000, // 8 = GPIO_MODE_IT_RISING_FALLING + 0x10120000, // 9 = GPIO_MODE_EVT_RISING + 0x10220000, // 10 = GPIO_MODE_EVT_FALLING + 0x10320000 // 11 = GPIO_MODE_EVT_RISING_FALLING +}; + +// Enable GPIO clock and return GPIO base address +uint32_t Set_GPIO_Clock(uint32_t port_idx) { + uint32_t gpio_add = 0; + switch (port_idx) { + case PortA: + gpio_add = GPIOA_BASE; + __GPIOA_CLK_ENABLE(); + break; + case PortB: + gpio_add = GPIOB_BASE; + __GPIOB_CLK_ENABLE(); + break; + case PortC: + gpio_add = GPIOC_BASE; + __GPIOC_CLK_ENABLE(); + break; + case PortD: + gpio_add = GPIOD_BASE; + __GPIOD_CLK_ENABLE(); + break; + case PortF: + gpio_add = GPIOF_BASE; + __GPIOF_CLK_ENABLE(); + break; + default: + error("Pinmap error: wrong port number."); + break; + } + return gpio_add; +} + +/** + * Configure pin (mode, speed, output type and pull-up/pull-down) + */ +void pin_function(PinName pin, int data) { + if (pin == NC) return; + + // Get the pin informations + uint32_t mode = STM_PIN_MODE(data); + uint32_t pupd = STM_PIN_PUPD(data); + uint32_t afnum = STM_PIN_AFNUM(data); + + uint32_t port_index = STM_PORT(pin); + uint32_t pin_index = STM_PIN(pin); + + // Enable GPIO clock + uint32_t gpio_add = Set_GPIO_Clock(port_index); + GPIO_TypeDef *gpio = (GPIO_TypeDef *)gpio_add; + + // Configure GPIO + GPIO_InitTypeDef GPIO_InitStructure; + GPIO_InitStructure.Pin = (uint32_t)(1 << pin_index); + GPIO_InitStructure.Mode = gpio_mode[mode]; + GPIO_InitStructure.Pull = pupd; + GPIO_InitStructure.Speed = GPIO_SPEED_HIGH; + GPIO_InitStructure.Alternate = afnum; + HAL_GPIO_Init(gpio, &GPIO_InitStructure); + + // [TODO] Disconnect SWDIO and SWCLK signals ? + // Warning: For debugging it is necessary to reconnect under reset if this is done. + //if ((pin == PA_13) || (pin == PA_14)) { + // + //} +} + +/** + * Configure pin pull-up/pull-down + */ +void pin_mode(PinName pin, PinMode mode) { + if (pin == NC) return; + + uint32_t port_index = STM_PORT(pin); + uint32_t pin_index = STM_PIN(pin); + + // Enable GPIO clock + uint32_t gpio_add = Set_GPIO_Clock(port_index); + GPIO_TypeDef *gpio = (GPIO_TypeDef *)gpio_add; + + // Configure pull-up/pull-down resistors + uint32_t pupd = (uint32_t)mode; + if (pupd > 2) pupd = 0; // Open-drain = No pull-up/No pull-down + gpio->PUPDR &= (uint32_t)(~(GPIO_PUPDR_PUPDR0 << (pin_index * 2))); + gpio->PUPDR |= (uint32_t)(pupd << (pin_index * 2)); + +} diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F072RB/port_api.c b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F072RB/port_api.c new file mode 100644 index 0000000000..9a6ad5e5f4 --- /dev/null +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F072RB/port_api.c @@ -0,0 +1,97 @@ +/* mbed Microcontroller Library + ******************************************************************************* + * Copyright (c) 2014, STMicroelectronics + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ******************************************************************************* + */ +#include "port_api.h" +#include "pinmap.h" +#include "gpio_api.h" +#include "error.h" + +#if DEVICE_PORTIN || DEVICE_PORTOUT + +extern uint32_t Set_GPIO_Clock(uint32_t port_idx); + +// high nibble = port number (0=A, 1=B, 2=C, 3=D, 4=E, 5=F, ...) +// low nibble = pin number +PinName port_pin(PortName port, int pin_n) { + return (PinName)(pin_n + (port << 4)); +} + +void port_init(port_t *obj, PortName port, int mask, PinDirection dir) { + uint32_t port_index = (uint32_t)port; + + // Enable GPIO clock + uint32_t gpio_add = Set_GPIO_Clock(port_index); + GPIO_TypeDef *gpio = (GPIO_TypeDef *)gpio_add; + + // Fill PORT object structure for future use + obj->port = port; + obj->mask = mask; + obj->direction = dir; + obj->reg_in = &gpio->IDR; + obj->reg_out = &gpio->ODR; + + port_dir(obj, dir); +} + +void port_dir(port_t *obj, PinDirection dir) { + uint32_t i; + obj->direction = dir; + for (i = 0; i < 16; i++) { // Process all pins + if (obj->mask & (1 << i)) { // If the pin is used + if (dir == PIN_OUTPUT) { + pin_function(port_pin(obj->port, i), STM_PIN_DATA(STM_MODE_OUTPUT_PP, GPIO_NOPULL, 0)); + } else { // PIN_INPUT + pin_function(port_pin(obj->port, i), STM_PIN_DATA(STM_MODE_INPUT, GPIO_NOPULL, 0)); + } + } + } +} + +void port_mode(port_t *obj, PinMode mode) { + uint32_t i; + for (i = 0; i < 16; i++) { // Process all pins + if (obj->mask & (1 << i)) { // If the pin is used + pin_mode(port_pin(obj->port, i), mode); + } + } +} + +void port_write(port_t *obj, int value) { + *obj->reg_out = (*obj->reg_out & ~obj->mask) | (value & obj->mask); +} + +int port_read(port_t *obj) { + if (obj->direction == PIN_OUTPUT) { + return (*obj->reg_out & obj->mask); + } else { // PIN_INPUT + return (*obj->reg_in & obj->mask); + } +} + +#endif diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F072RB/pwmout_api.c b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F072RB/pwmout_api.c new file mode 100644 index 0000000000..4f2790a556 --- /dev/null +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F072RB/pwmout_api.c @@ -0,0 +1,254 @@ +/* mbed Microcontroller Library + ******************************************************************************* + * Copyright (c) 2014, STMicroelectronics + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ******************************************************************************* + */ +#include "pwmout_api.h" + +#if DEVICE_PWMOUT + +#include "cmsis.h" +#include "pinmap.h" +#include "error.h" + +// TIM2 cannot be used because already used by the us_ticker +static const PinMap PinMap_PWM[] = { +// {PA_1, PWM_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM2)}, // TIM2_CH2 + {PA_1, PWM_15, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_TIM15)}, // TIM15_CH1N + {PA_2, PWM_15, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_TIM15)}, // TIM15_CH1 +// {PA_2, PWM_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM2)}, // TIM2_CH3 + {PA_3, PWM_15, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_TIM15)}, // TIM15_CH2 +// {PA_3, PWM_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM2)}, // TIM2_CH4 + {PA_4, PWM_14, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF4_TIM14)}, // TIM14_CH1 +// {PA_6, PWM_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM3)}, // TIM3_CH1 + {PA_6, PWM_16, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_TIM16)}, // TIM16_CH1 +// {PA_7, PWM_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM3)}, // TIM3_CH2 +// {PA_7, PWM_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM1)}, // TIM1_CH1N +// {PA_7, PWM_14, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF4_TIM14)}, // TIM14_CH1 + {PA_7, PWM_17, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_TIM17)}, // TIM17_CH1 + {PA_8, PWM_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM1)}, // TIM1_CH1 + {PA_9, PWM_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM1)}, // TIM1_CH2 + {PA_10, PWM_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM1)}, // TIM1_CH3 + {PA_11, PWM_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM1)}, // TIM1_CH4 + + {PB_0, PWM_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM3)}, // TIM3_CH3 +// {PB_0, PWM_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM1)}, // TIM1_CH2N + {PB_1, PWM_14, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_TIM14)}, // TIM14_CH1 +// {PB_1, PWM_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM3)}, // TIM3_CH4 +// {PB_1, PWM_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM1)}, // TIM1_CH3N +// {PB_3, PWM_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM2)}, // TIM2_CH2 + {PB_4, PWM_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM3)}, // TIM3_CH1 + {PB_5, PWM_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM3)}, // TIM3_CH2 + {PB_6, PWM_16, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM16)}, // TIM16_CH1N + {PB_7, PWM_17, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM17)}, // TIM17_CH1N + {PB_8, PWM_16, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM16)}, // TIM16_CH1 + {PB_9, PWM_17, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM17)}, // TIM17_CH1 +// {PB_10, PWM_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM2)}, // TIM2_CH3 +// {PB_11, PWM_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM2)}, // TIM2_CH4 + {PB_13, PWM_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM1)}, // TIM1_CH1N + {PB_14, PWM_15, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM15)}, // TIM15_CH1 +// {PB_14, PWM_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM1)}, // TIM1_CH2N + {PB_15, PWM_15, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM15)}, // TIM15_CH2 +// {PB_15, PWM_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM1)}, // TIM1_CH3N +// {PB_15, PWM_15, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF3_TIM15)}, // TIM15_CH1N + + {PC_6, PWM_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_TIM3)}, // TIM3_CH1 + {PC_7, PWM_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_TIM3)}, // TIM3_CH2 + {PC_8, PWM_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_TIM3)}, // TIM3_CH3 + {PC_9, PWM_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_TIM3)}, // TIM3_CH4 + + {NC, NC, 0} +}; + +static TIM_HandleTypeDef TimHandle; + +void pwmout_init(pwmout_t* obj, PinName pin) { + // Get the peripheral name from the pin and assign it to the object + obj->pwm = (PWMName)pinmap_peripheral(pin, PinMap_PWM); + + if (obj->pwm == (PWMName)NC) { + error("PWM error: pinout mapping failed."); + } + + // Enable TIM clock + if (obj->pwm == PWM_1) __TIM1_CLK_ENABLE(); + if (obj->pwm == PWM_2) __TIM2_CLK_ENABLE(); + if (obj->pwm == PWM_3) __TIM3_CLK_ENABLE(); + if (obj->pwm == PWM_14) __TIM14_CLK_ENABLE(); + if (obj->pwm == PWM_15) __TIM15_CLK_ENABLE(); + if (obj->pwm == PWM_16) __TIM16_CLK_ENABLE(); + if (obj->pwm == PWM_17) __TIM17_CLK_ENABLE(); + + // Configure GPIO + pinmap_pinout(pin, PinMap_PWM); + + obj->pin = pin; + obj->period = 0; + obj->pulse = 0; + + pwmout_period_us(obj, 20000); // 20 ms per default +} + +void pwmout_free(pwmout_t* obj) { + // Configure GPIO + pin_function(obj->pin, STM_PIN_DATA(STM_MODE_INPUT, GPIO_NOPULL, 0)); +} + +void pwmout_write(pwmout_t* obj, float value) { + TIM_OC_InitTypeDef sConfig; + int channel = 0; + int complementary_channel = 0; + + TimHandle.Instance = (TIM_TypeDef *)(obj->pwm); + + if (value < (float)0.0) { + value = 0.0; + } else if (value > (float)1.0) { + value = 1.0; + } + + obj->pulse = (uint32_t)((float)obj->period * value); + + // Configure channels + sConfig.OCMode = TIM_OCMODE_PWM1; + sConfig.Pulse = obj->pulse; + sConfig.OCPolarity = TIM_OCPOLARITY_HIGH; + sConfig.OCNPolarity = TIM_OCNPOLARITY_HIGH; + sConfig.OCFastMode = TIM_OCFAST_DISABLE; + sConfig.OCIdleState = TIM_OCIDLESTATE_RESET; + sConfig.OCNIdleState = TIM_OCNIDLESTATE_RESET; + + switch (obj->pin) { + // Channels 1 + case PA_2: + case PA_4: + case PA_6: + case PA_7: + case PA_8: + case PB_1: + case PB_4: + case PB_8: + case PB_9: + case PB_14: + case PC_6: + channel = TIM_CHANNEL_1; + break; + // Channels 1N + case PA_1: + case PB_6: + case PB_7: + case PB_13: + channel = TIM_CHANNEL_1; + complementary_channel = 1; + break; + // Channels 2 + case PA_3: + case PA_9: + case PB_5: + case PB_15: + case PC_7: + channel = TIM_CHANNEL_2; + break; + // Channels 3 + case PA_10: + case PB_0: + case PC_8: + channel = TIM_CHANNEL_3; + break; + // Channels 4 + case PA_11: + case PC_9: + channel = TIM_CHANNEL_4; + break; + default: + return; + } + + HAL_TIM_PWM_ConfigChannel(&TimHandle, &sConfig, channel); + + if (complementary_channel) { + HAL_TIMEx_PWMN_Start(&TimHandle, channel); + } else { + HAL_TIM_PWM_Start(&TimHandle, channel); + } +} + +float pwmout_read(pwmout_t* obj) { + float value = 0; + if (obj->period > 0) { + value = (float)(obj->pulse) / (float)(obj->period); + } + return ((value > (float)1.0) ? (float)(1.0) : (value)); +} + +void pwmout_period(pwmout_t* obj, float seconds) { + pwmout_period_us(obj, seconds * 1000000.0f); +} + +void pwmout_period_ms(pwmout_t* obj, int ms) { + pwmout_period_us(obj, ms * 1000); +} + +void pwmout_period_us(pwmout_t* obj, int us) { + TimHandle.Instance = (TIM_TypeDef *)(obj->pwm); + + float dc = pwmout_read(obj); + + __HAL_TIM_DISABLE(&TimHandle); + + // Update the SystemCoreClock variable + SystemCoreClockUpdate(); + + TimHandle.Init.Period = us - 1; + TimHandle.Init.Prescaler = (uint16_t)(SystemCoreClock / 1000000) - 1; // 1 µs tick + TimHandle.Init.ClockDivision = 0; + TimHandle.Init.CounterMode = TIM_COUNTERMODE_UP; + HAL_TIM_PWM_Init(&TimHandle); + + // Set duty cycle again + pwmout_write(obj, dc); + + // Save for future use + obj->period = us; + + __HAL_TIM_ENABLE(&TimHandle); +} + +void pwmout_pulsewidth(pwmout_t* obj, float seconds) { + pwmout_pulsewidth_us(obj, seconds * 1000000.0f); +} + +void pwmout_pulsewidth_ms(pwmout_t* obj, int ms) { + pwmout_pulsewidth_us(obj, ms * 1000); +} + +void pwmout_pulsewidth_us(pwmout_t* obj, int us) { + float value = (float)us / (float)obj->period; + pwmout_write(obj, value); +} + +#endif diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F072RB/rtc_api.c b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F072RB/rtc_api.c new file mode 100644 index 0000000000..10d34dfbbe --- /dev/null +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F072RB/rtc_api.c @@ -0,0 +1,196 @@ +/* mbed Microcontroller Library + ******************************************************************************* + * Copyright (c) 2014, STMicroelectronics + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ******************************************************************************* + */ +#include "rtc_api.h" + +#if DEVICE_RTC + +#include "error.h" + +static int rtc_inited = 0; + +static RTC_HandleTypeDef RtcHandle; + +void rtc_init(void) { + RCC_OscInitTypeDef RCC_OscInitStruct; + uint32_t rtc_freq = 0; + + if (rtc_inited) return; + rtc_inited = 1; + + RtcHandle.Instance = RTC; + + // Enable Power clock + __PWR_CLK_ENABLE(); + + // Enable access to Backup domain + HAL_PWR_EnableBkUpAccess(); + + // Reset Backup domain + __HAL_RCC_BACKUPRESET_FORCE(); + __HAL_RCC_BACKUPRESET_RELEASE(); + + // Enable LSE Oscillator + RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSE; + RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE; /* Mandatory, otherwise the PLL is reconfigured! */ + RCC_OscInitStruct.LSEState = RCC_LSE_ON; /* External 32.768 kHz clock on OSC_IN/OSC_OUT */ + if (HAL_RCC_OscConfig(&RCC_OscInitStruct) == HAL_OK) { + // Connect LSE to RTC + __HAL_RCC_RTC_CONFIG(RCC_RTCCLKSOURCE_LSE); + rtc_freq = LSE_VALUE; + } else { + // Enable LSI clock + RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSI | RCC_OSCILLATORTYPE_LSE; + RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE; // Mandatory, otherwise the PLL is reconfigured! + RCC_OscInitStruct.LSEState = RCC_LSE_OFF; + RCC_OscInitStruct.LSIState = RCC_LSI_ON; + if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { + error("RTC error: LSI clock initialization failed."); + } + // Connect LSI to RTC + __HAL_RCC_RTC_CONFIG(RCC_RTCCLKSOURCE_LSI); + // [TODO] This value is LSI typical value. To be measured precisely using a timer input capture. + rtc_freq = 32000; + } + + // Enable RTC + __HAL_RCC_RTC_ENABLE(); + + RtcHandle.Init.HourFormat = RTC_HOURFORMAT_24; + RtcHandle.Init.AsynchPrediv = 127; + RtcHandle.Init.SynchPrediv = (rtc_freq / 128) - 1; + RtcHandle.Init.OutPut = RTC_OUTPUT_DISABLE; + RtcHandle.Init.OutPutPolarity = RTC_OUTPUT_POLARITY_HIGH; + RtcHandle.Init.OutPutType = RTC_OUTPUT_TYPE_OPENDRAIN; + + if (HAL_RTC_Init(&RtcHandle) != HAL_OK) { + error("RTC error: RTC initialization failed."); + } +} + +void rtc_free(void) { + // Enable Power clock + __PWR_CLK_ENABLE(); + + // Enable access to Backup domain + HAL_PWR_EnableBkUpAccess(); + + // Reset Backup domain + __HAL_RCC_BACKUPRESET_FORCE(); + __HAL_RCC_BACKUPRESET_RELEASE(); + + // Disable access to Backup domain + HAL_PWR_DisableBkUpAccess(); + + // Disable LSI and LSE clocks + RCC_OscInitTypeDef RCC_OscInitStruct; + RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSI | RCC_OSCILLATORTYPE_LSE; + RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE; + RCC_OscInitStruct.LSIState = RCC_LSI_OFF; + RCC_OscInitStruct.LSEState = RCC_LSE_OFF; + HAL_RCC_OscConfig(&RCC_OscInitStruct); + + rtc_inited = 0; +} + +int rtc_isenabled(void) { + return rtc_inited; +} + +/* + RTC Registers + RTC_WeekDay 1=monday, 2=tuesday, ..., 7=sunday + RTC_Month 1=january, 2=february, ..., 12=december + RTC_Date day of the month 1-31 + RTC_Year year 0-99 + struct tm + tm_sec seconds after the minute 0-61 + tm_min minutes after the hour 0-59 + tm_hour hours since midnight 0-23 + tm_mday day of the month 1-31 + tm_mon months since January 0-11 + tm_year years since 1900 + tm_wday days since Sunday 0-6 + tm_yday days since January 1 0-365 + tm_isdst Daylight Saving Time flag +*/ +time_t rtc_read(void) { + RTC_DateTypeDef dateStruct; + RTC_TimeTypeDef timeStruct; + struct tm timeinfo; + + RtcHandle.Instance = RTC; + + // Read actual date and time + // Warning: the time must be read first! + HAL_RTC_GetTime(&RtcHandle, &timeStruct, FORMAT_BIN); + HAL_RTC_GetDate(&RtcHandle, &dateStruct, FORMAT_BIN); + + // Setup a tm structure based on the RTC + timeinfo.tm_wday = dateStruct.WeekDay; + timeinfo.tm_mon = dateStruct.Month - 1; + timeinfo.tm_mday = dateStruct.Date; + timeinfo.tm_year = dateStruct.Year + 100; + timeinfo.tm_hour = timeStruct.Hours; + timeinfo.tm_min = timeStruct.Minutes; + timeinfo.tm_sec = timeStruct.Seconds; + + // Convert to timestamp + time_t t = mktime(&timeinfo); + + return t; +} + +void rtc_write(time_t t) { + RTC_DateTypeDef dateStruct; + RTC_TimeTypeDef timeStruct; + + RtcHandle.Instance = RTC; + + // Convert the time into a tm + struct tm *timeinfo = localtime(&t); + + // Fill RTC structures + dateStruct.WeekDay = timeinfo->tm_wday; + dateStruct.Month = timeinfo->tm_mon + 1; + dateStruct.Date = timeinfo->tm_mday; + dateStruct.Year = timeinfo->tm_year - 100; + timeStruct.Hours = timeinfo->tm_hour; + timeStruct.Minutes = timeinfo->tm_min; + timeStruct.Seconds = timeinfo->tm_sec; + timeStruct.TimeFormat = RTC_HOURFORMAT12_PM; + timeStruct.DayLightSaving = RTC_DAYLIGHTSAVING_NONE; + timeStruct.StoreOperation = RTC_STOREOPERATION_RESET; + + // Change the RTC current date/time + HAL_RTC_SetDate(&RtcHandle, &dateStruct, FORMAT_BIN); + HAL_RTC_SetTime(&RtcHandle, &timeStruct, FORMAT_BIN); +} + +#endif diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F072RB/serial_api.c b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F072RB/serial_api.c new file mode 100644 index 0000000000..27762ba2b1 --- /dev/null +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F072RB/serial_api.c @@ -0,0 +1,361 @@ +/* mbed Microcontroller Library + ******************************************************************************* + * Copyright (c) 2014, STMicroelectronics + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ******************************************************************************* + */ +#include "serial_api.h" + +#if DEVICE_SERIAL + +#include "cmsis.h" +#include "pinmap.h" +#include "error.h" +#include + +static const PinMap PinMap_UART_TX[] = { + {PA_0, UART_4, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF4_USART4)}, + {PA_2, UART_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_USART2)}, + {PA_9, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_USART1)}, + {PA_14, UART_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_USART2)}, // Warning: SWCLK is also on this pin + {PB_6, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_USART1)}, + {PB_10, UART_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF4_USART3)}, + {PC_4, UART_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_USART3)}, + {PC_10, UART_4, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_USART4)}, +// {PC_10, UART_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_USART3)}, + {NC, NC, 0} +}; + +static const PinMap PinMap_UART_RX[] = { + {PA_1, UART_4, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF4_USART4)}, + {PA_3, UART_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_USART2)}, + {PA_10, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_USART1)}, + {PA_15, UART_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_USART2)}, + {PB_7, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_USART1)}, + {PB_11, UART_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF4_USART3)}, + {PC_5, UART_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_USART3)}, + {PC_11, UART_4, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_USART4)}, +// {PC_11, UART_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_USART3)}, + {NC, NC, 0} +}; + +#define UART_NUM (4) + +static uint32_t serial_irq_ids[UART_NUM] = {0, 0, 0, 0}; + +static uart_irq_handler irq_handler; + +UART_HandleTypeDef UartHandle; + +int stdio_uart_inited = 0; +serial_t stdio_uart; + +static void init_uart(serial_t *obj) { + UartHandle.Instance = (USART_TypeDef *)(obj->uart); + + UartHandle.Init.BaudRate = obj->baudrate; + UartHandle.Init.WordLength = obj->databits; + UartHandle.Init.StopBits = obj->stopbits; + UartHandle.Init.Parity = obj->parity; + UartHandle.Init.HwFlowCtl = UART_HWCONTROL_NONE; + + if (obj->pin_rx == NC) { + UartHandle.Init.Mode = UART_MODE_TX; + } else if (obj->pin_tx == NC) { + UartHandle.Init.Mode = UART_MODE_RX; + } else { + UartHandle.Init.Mode = UART_MODE_TX_RX; + } + + HAL_UART_Init(&UartHandle); +} + +void serial_init(serial_t *obj, PinName tx, PinName rx) { + // Determine the UART to use (UART_1, UART_2, ...) + UARTName uart_tx = (UARTName)pinmap_peripheral(tx, PinMap_UART_TX); + UARTName uart_rx = (UARTName)pinmap_peripheral(rx, PinMap_UART_RX); + + // Get the peripheral name (UART_1, UART_2, ...) from the pin and assign it to the object + obj->uart = (UARTName)pinmap_merge(uart_tx, uart_rx); + + if (obj->uart == (UARTName)NC) { + error("Serial error: pinout mapping failed."); + } + + // Enable USART clock + if (obj->uart == UART_1) { + __USART1_CLK_ENABLE(); + obj->index = 0; + } + if (obj->uart == UART_2) { + __USART2_CLK_ENABLE(); + obj->index = 1; + } + + if (obj->uart == UART_3) { + __USART3_CLK_ENABLE(); + obj->index = 2; + } + if (obj->uart == UART_4) { + __USART4_CLK_ENABLE(); + obj->index = 3; + } + + // Configure the UART pins + pinmap_pinout(tx, PinMap_UART_TX); + pinmap_pinout(rx, PinMap_UART_RX); + pin_mode(tx, PullUp); + pin_mode(rx, PullUp); + + // Configure UART + obj->baudrate = 9600; + obj->databits = UART_WORDLENGTH_8B; + obj->stopbits = UART_STOPBITS_1; + obj->parity = UART_PARITY_NONE; + + obj->pin_tx = tx; + obj->pin_rx = rx; + + init_uart(obj); + + // For stdio management + if (obj->uart == STDIO_UART) { + stdio_uart_inited = 1; + memcpy(&stdio_uart, obj, sizeof(serial_t)); + } +} + +void serial_free(serial_t *obj) { + // Reset UART and disable clock + if (obj->uart == UART_1) { + __USART1_FORCE_RESET(); + __USART1_RELEASE_RESET(); + __USART1_CLK_DISABLE(); + } + if (obj->uart == UART_2) { + __USART2_FORCE_RESET(); + __USART2_RELEASE_RESET(); + __USART2_CLK_DISABLE(); + } + if (obj->uart == UART_3) { + __USART3_FORCE_RESET(); + __USART3_RELEASE_RESET(); + __USART3_CLK_DISABLE(); + } + if (obj->uart == UART_4) { + __USART4_FORCE_RESET(); + __USART4_RELEASE_RESET(); + __USART4_CLK_DISABLE(); + } + + // Configure GPIOs + pin_function(obj->pin_tx, STM_PIN_DATA(STM_MODE_INPUT, GPIO_NOPULL, 0)); + pin_function(obj->pin_rx, STM_PIN_DATA(STM_MODE_INPUT, GPIO_NOPULL, 0)); + + serial_irq_ids[obj->index] = 0; +} + +void serial_baud(serial_t *obj, int baudrate) { + obj->baudrate = baudrate; + init_uart(obj); +} + +void serial_format(serial_t *obj, int data_bits, SerialParity parity, int stop_bits) { + if (data_bits == 8) { + obj->databits = UART_WORDLENGTH_8B; + } else { + obj->databits = UART_WORDLENGTH_9B; + } + + switch (parity) { + case ParityOdd: + case ParityForced0: + obj->parity = UART_PARITY_ODD; + break; + case ParityEven: + case ParityForced1: + obj->parity = UART_PARITY_EVEN; + break; + default: // ParityNone + obj->parity = UART_PARITY_NONE; + break; + } + + if (stop_bits == 2) { + obj->stopbits = UART_STOPBITS_2; + } else { + obj->stopbits = UART_STOPBITS_1; + } + + init_uart(obj); +} + +/****************************************************************************** + * INTERRUPTS HANDLING + ******************************************************************************/ + +static void uart_irq(UARTName name, int id) { + UartHandle.Instance = (USART_TypeDef *)name; + if (serial_irq_ids[id] != 0) { + if (__HAL_UART_GET_FLAG(&UartHandle, UART_FLAG_TC) != RESET) { + irq_handler(serial_irq_ids[id], TxIrq); + __HAL_UART_CLEAR_IT(&UartHandle, UART_FLAG_TC); + } + if (__HAL_UART_GET_FLAG(&UartHandle, UART_FLAG_RXNE) != RESET) { + irq_handler(serial_irq_ids[id], RxIrq); + __HAL_UART_CLEAR_IT(&UartHandle, UART_FLAG_RXNE); + } + } +} + +static void uart1_irq(void) { + uart_irq(UART_1, 0); +} + +static void uart2_irq(void) { + uart_irq(UART_2, 1); +} + +static void uart3_irq(void) { + uart_irq(UART_3, 2); +} + +static void uart4_irq(void) { + uart_irq(UART_4, 3); +} + +void serial_irq_handler(serial_t *obj, uart_irq_handler handler, uint32_t id) { + irq_handler = handler; + serial_irq_ids[obj->index] = id; +} + +void serial_irq_set(serial_t *obj, SerialIrq irq, uint32_t enable) { + IRQn_Type irq_n = (IRQn_Type)0; + uint32_t vector = 0; + + UartHandle.Instance = (USART_TypeDef *)(obj->uart); + + if (obj->uart == UART_1) { + irq_n = USART1_IRQn; + vector = (uint32_t)&uart1_irq; + } + + if (obj->uart == UART_2) { + irq_n = USART2_IRQn; + vector = (uint32_t)&uart2_irq; + } + + if (obj->uart == UART_3) { + irq_n = USART3_4_IRQn; + vector = (uint32_t)&uart3_irq; + } + + if (obj->uart == UART_4) { + irq_n = USART3_4_IRQn; + vector = (uint32_t)&uart4_irq; + } + + if (enable) { + + if (irq == RxIrq) { + __HAL_UART_ENABLE_IT(&UartHandle, UART_IT_RXNE); + } else { // TxIrq + __HAL_UART_ENABLE_IT(&UartHandle, UART_IT_TC); + } + + NVIC_SetVector(irq_n, vector); + NVIC_EnableIRQ(irq_n); + + } else { // disable + + int all_disabled = 0; + + if (irq == RxIrq) { + __HAL_UART_DISABLE_IT(&UartHandle, UART_IT_RXNE); + // Check if TxIrq is disabled too + if ((UartHandle.Instance->CR1 & USART_CR1_TXEIE) == 0) all_disabled = 1; + } else { // TxIrq + __HAL_UART_DISABLE_IT(&UartHandle, UART_IT_TXE); + // Check if RxIrq is disabled too + if ((UartHandle.Instance->CR1 & USART_CR1_RXNEIE) == 0) all_disabled = 1; + } + + if (all_disabled) NVIC_DisableIRQ(irq_n); + + } +} + +/****************************************************************************** + * READ/WRITE + ******************************************************************************/ + +int serial_getc(serial_t *obj) { + USART_TypeDef *uart = (USART_TypeDef *)(obj->uart); + while (!serial_readable(obj)); + return (int)(uart->RDR & (uint16_t)0xFF); +} + +void serial_putc(serial_t *obj, int c) { + USART_TypeDef *uart = (USART_TypeDef *)(obj->uart); + while (!serial_writable(obj)); + uart->TDR = (uint32_t)(c & (uint16_t)0xFF); +} + +int serial_readable(serial_t *obj) { + int status; + UartHandle.Instance = (USART_TypeDef *)(obj->uart); + // Check if data is received + status = ((__HAL_UART_GET_FLAG(&UartHandle, UART_FLAG_RXNE) != RESET) ? 1 : 0); + return status; +} + +int serial_writable(serial_t *obj) { + int status; + UartHandle.Instance = (USART_TypeDef *)(obj->uart); + // Check if data is transmitted + status = ((__HAL_UART_GET_FLAG(&UartHandle, UART_FLAG_TXE) != RESET) ? 1 : 0); + return status; +} + +void serial_clear(serial_t *obj) { + UartHandle.Instance = (USART_TypeDef *)(obj->uart); + __HAL_UART_CLEAR_IT(&UartHandle, UART_FLAG_TXE); + __HAL_UART_CLEAR_IT(&UartHandle, UART_FLAG_RXNE); +} + +void serial_pinout_tx(PinName tx) { + pinmap_pinout(tx, PinMap_UART_TX); +} + +void serial_break_set(serial_t *obj) { + // [TODO] +} + +void serial_break_clear(serial_t *obj) { + // [TODO] +} + +#endif diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F072RB/sleep.c b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F072RB/sleep.c new file mode 100644 index 0000000000..eff34206d0 --- /dev/null +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F072RB/sleep.c @@ -0,0 +1,53 @@ +/* mbed Microcontroller Library + ******************************************************************************* + * Copyright (c) 2014, STMicroelectronics + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ******************************************************************************* + */ +#include "sleep_api.h" + +#if DEVICE_SLEEP + +#include "cmsis.h" + +void sleep(void) { + // Stop HAL systick + HAL_SuspendTick(); + // Request to enter SLEEP mode + HAL_PWR_EnterSLEEPMode(PWR_MAINREGULATOR_ON, PWR_SLEEPENTRY_WFI); + // Restart HAL systick + HAL_ResumeTick(); +} + +void deepsleep(void) { + // Request to enter STOP mode with regulator in low power mode + HAL_PWR_EnterSTOPMode(PWR_LOWPOWERREGULATOR_ON, PWR_STOPENTRY_WFI); + + // After wake-up from STOP reconfigure the PLL + SetSysClock(); +} + +#endif diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F072RB/spi_api.c b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F072RB/spi_api.c new file mode 100644 index 0000000000..8fb83ca748 --- /dev/null +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F072RB/spi_api.c @@ -0,0 +1,304 @@ +/* mbed Microcontroller Library + ******************************************************************************* + * Copyright (c) 2014, STMicroelectronics + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ******************************************************************************* + */ +#include "spi_api.h" + +#if DEVICE_SPI + +#include +#include "cmsis.h" +#include "pinmap.h" +#include "error.h" + +static const PinMap PinMap_SPI_MOSI[] = { + {PA_7, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_SPI1)}, + {PB_5, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_SPI1)}, + {PB_15, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_SPI2)}, + {PC_3, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_SPI2)}, + {NC, NC, 0} +}; + +static const PinMap PinMap_SPI_MISO[] = { + {PA_6, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_SPI1)}, + {PB_4, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_SPI1)}, + {PB_14, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_SPI2)}, + {PC_2, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_SPI2)}, + {NC, NC, 0} +}; + +static const PinMap PinMap_SPI_SCLK[] = { + {PA_5, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_SPI1)}, + {PB_3, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_SPI1)}, + {PB_10, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI2)}, + {PB_13, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_SPI2)}, + {NC, NC, 0} +}; + +static const PinMap PinMap_SPI_SSEL[] = { + {PA_4, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_SPI1)}, + {PA_15, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_SPI1)}, + {PB_9, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI2)}, + {PB_12, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_SPI2)}, + {NC, NC, 0} +}; + +static SPI_HandleTypeDef SpiHandle; + +static void init_spi(spi_t *obj) { + SpiHandle.Instance = (SPI_TypeDef *)(obj->spi); + + __HAL_SPI_DISABLE(&SpiHandle); + + SpiHandle.Init.Mode = obj->mode; + SpiHandle.Init.BaudRatePrescaler = obj->br_presc; + SpiHandle.Init.Direction = SPI_DIRECTION_2LINES; + SpiHandle.Init.CLKPhase = obj->cpha; + SpiHandle.Init.CLKPolarity = obj->cpol; + SpiHandle.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLED; + SpiHandle.Init.CRCPolynomial = 7; + SpiHandle.Init.DataSize = obj->bits; + SpiHandle.Init.FirstBit = SPI_FIRSTBIT_MSB; + SpiHandle.Init.NSS = obj->nss; + SpiHandle.Init.TIMode = SPI_TIMODE_DISABLED; + + HAL_SPI_Init(&SpiHandle); + + __HAL_SPI_ENABLE(&SpiHandle); +} + +void spi_init(spi_t *obj, PinName mosi, PinName miso, PinName sclk, PinName ssel) { + // Determine the SPI to use + SPIName spi_mosi = (SPIName)pinmap_peripheral(mosi, PinMap_SPI_MOSI); + SPIName spi_miso = (SPIName)pinmap_peripheral(miso, PinMap_SPI_MISO); + SPIName spi_sclk = (SPIName)pinmap_peripheral(sclk, PinMap_SPI_SCLK); + SPIName spi_ssel = (SPIName)pinmap_peripheral(ssel, PinMap_SPI_SSEL); + + SPIName spi_data = (SPIName)pinmap_merge(spi_mosi, spi_miso); + SPIName spi_cntl = (SPIName)pinmap_merge(spi_sclk, spi_ssel); + + obj->spi = (SPIName)pinmap_merge(spi_data, spi_cntl); + + if (obj->spi == (SPIName)NC) { + error("SPI error: pinout mapping failed."); + } + + // Enable SPI clock + if (obj->spi == SPI_1) { + __SPI1_CLK_ENABLE(); + } + if (obj->spi == SPI_2) { + __SPI2_CLK_ENABLE(); + } + + // Configure the SPI pins + pinmap_pinout(mosi, PinMap_SPI_MOSI); + pinmap_pinout(miso, PinMap_SPI_MISO); + pinmap_pinout(sclk, PinMap_SPI_SCLK); + + // Save new values + obj->bits = SPI_DATASIZE_8BIT; + obj->cpol = SPI_POLARITY_LOW; + obj->cpha = SPI_PHASE_1EDGE; + obj->br_presc = SPI_BAUDRATEPRESCALER_256; + + obj->pin_miso = miso; + obj->pin_mosi = mosi; + obj->pin_sclk = sclk; + obj->pin_ssel = ssel; + + if (ssel == NC) { // SW NSS Master mode + obj->mode = SPI_MODE_MASTER; + obj->nss = SPI_NSS_SOFT; + } else { // Slave + pinmap_pinout(ssel, PinMap_SPI_SSEL); + obj->mode = SPI_MODE_SLAVE; + obj->nss = SPI_NSS_HARD_INPUT; + } + + init_spi(obj); +} + +void spi_free(spi_t *obj) { + // Reset SPI and disable clock + if (obj->spi == SPI_1) { + __SPI1_FORCE_RESET(); + __SPI1_RELEASE_RESET(); + __SPI1_CLK_DISABLE(); + } + + if (obj->spi == SPI_2) { + __SPI2_FORCE_RESET(); + __SPI2_RELEASE_RESET(); + __SPI2_CLK_DISABLE(); + } + + // Configure GPIO + pin_function(obj->pin_miso, STM_PIN_DATA(STM_MODE_INPUT, GPIO_NOPULL, 0)); + pin_function(obj->pin_mosi, STM_PIN_DATA(STM_MODE_INPUT, GPIO_NOPULL, 0)); + pin_function(obj->pin_sclk, STM_PIN_DATA(STM_MODE_INPUT, GPIO_NOPULL, 0)); + pin_function(obj->pin_ssel, STM_PIN_DATA(STM_MODE_INPUT, GPIO_NOPULL, 0)); +} + +void spi_format(spi_t *obj, int bits, int mode, int slave) { + // Save new values + if (bits == 16) { + obj->bits = SPI_DATASIZE_16BIT; + } else { + obj->bits = SPI_DATASIZE_8BIT; + } + + switch (mode) { + case 0: + obj->cpol = SPI_POLARITY_LOW; + obj->cpha = SPI_PHASE_1EDGE; + break; + case 1: + obj->cpol = SPI_POLARITY_LOW; + obj->cpha = SPI_PHASE_2EDGE; + break; + case 2: + obj->cpol = SPI_POLARITY_HIGH; + obj->cpha = SPI_PHASE_1EDGE; + break; + default: + obj->cpol = SPI_POLARITY_HIGH; + obj->cpha = SPI_PHASE_2EDGE; + break; + } + + if (slave == 0) { + obj->mode = SPI_MODE_MASTER; + obj->nss = SPI_NSS_SOFT; + } else { + obj->mode = SPI_MODE_SLAVE; + obj->nss = SPI_NSS_HARD_INPUT; + } + + init_spi(obj); +} + +void spi_frequency(spi_t *obj, int hz) { + // Note: The frequencies are obtained with SPI clock = 48 MHz (APB clock) + if (hz < 375000) { + obj->br_presc = SPI_BAUDRATEPRESCALER_256; // 188 kHz + } else if ((hz >= 375000) && (hz < 750000)) { + obj->br_presc = SPI_BAUDRATEPRESCALER_128; // 375 kHz + } else if ((hz >= 750000) && (hz < 1000000)) { + obj->br_presc = SPI_BAUDRATEPRESCALER_64; // 750 kHz + } else if ((hz >= 1000000) && (hz < 3000000)) { + obj->br_presc = SPI_BAUDRATEPRESCALER_32; // 1.5 MHz + } else if ((hz >= 3000000) && (hz < 6000000)) { + obj->br_presc = SPI_BAUDRATEPRESCALER_16; // 3 MHz + } else if ((hz >= 6000000) && (hz < 12000000)) { + obj->br_presc = SPI_BAUDRATEPRESCALER_8; // 6 MHz + } else if ((hz >= 12000000) && (hz < 24000000)) { + obj->br_presc = SPI_BAUDRATEPRESCALER_4; // 12 MHz + } else { // >= 24000000 + obj->br_presc = SPI_BAUDRATEPRESCALER_2; // 24 MHz + } + init_spi(obj); +} + +static inline int ssp_readable(spi_t *obj) { + int status; + SpiHandle.Instance = (SPI_TypeDef *)(obj->spi); + // Check if data is received + status = ((__HAL_SPI_GET_FLAG(&SpiHandle, SPI_FLAG_RXNE) != RESET) ? 1 : 0); + return status; +} + +static inline int ssp_writeable(spi_t *obj) { + int status; + SpiHandle.Instance = (SPI_TypeDef *)(obj->spi); + // Check if data is transmitted + status = ((__HAL_SPI_GET_FLAG(&SpiHandle, SPI_FLAG_TXE) != RESET) ? 1 : 0); + return status; +} + +static inline void ssp_write(spi_t *obj, int value) { + SPI_TypeDef *spi = (SPI_TypeDef *)(obj->spi); + while (!ssp_writeable(obj)); + + if (obj->bits <= SPI_DATASIZE_8BIT) { + // force 8-bit access the data register due to SPI data buffer in this device + uint8_t *p_spi_dr = 0; + p_spi_dr = (uint8_t *) & (spi->DR); + *p_spi_dr = (uint8_t)value; + } else { + spi->DR = (uint16_t)value; + } +} + +static inline int ssp_read(spi_t *obj) { + SPI_TypeDef *spi = (SPI_TypeDef *)(obj->spi); + while (!ssp_readable(obj)); + + if (obj->bits <= SPI_DATASIZE_8BIT) { + // force 8-bit access the data register due to SPI data buffer in this device + uint8_t *p_spi_dr = 0; + p_spi_dr = (uint8_t *) & (spi->DR); + return (int)(*p_spi_dr); + } else { + return (int)spi->DR; + } +} + +static inline int ssp_busy(spi_t *obj) { + int status; + SpiHandle.Instance = (SPI_TypeDef *)(obj->spi); + status = ((__HAL_SPI_GET_FLAG(&SpiHandle, SPI_FLAG_BSY) != RESET) ? 1 : 0); + return status; +} + +int spi_master_write(spi_t *obj, int value) { + ssp_write(obj, value); + return ssp_read(obj); +} + +int spi_slave_receive(spi_t *obj) { + return (ssp_readable(obj) && !ssp_busy(obj)) ? (1) : (0); +}; + +int spi_slave_read(spi_t *obj) { + SPI_TypeDef *spi = (SPI_TypeDef *)(obj->spi); + while (!ssp_readable(obj)); + return (int)spi->DR; +} + +void spi_slave_write(spi_t *obj, int value) { + SPI_TypeDef *spi = (SPI_TypeDef *)(obj->spi); + while (!ssp_writeable(obj)); + spi->DR = (uint16_t)value; +} + +int spi_busy(spi_t *obj) { + return ssp_busy(obj); +} + +#endif diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F072RB/us_ticker.c b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F072RB/us_ticker.c new file mode 100644 index 0000000000..dd887fa1cb --- /dev/null +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F072RB/us_ticker.c @@ -0,0 +1,84 @@ +/* mbed Microcontroller Library + * Copyright (c) 2014, STMicroelectronics + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +#include +#include "us_ticker_api.h" +#include "PeripheralNames.h" + +// 32-bit timer selection +#define TIM_MST TIM2 +#define TIM_MST_IRQ TIM2_IRQn +#define TIM_MST_RCC __TIM2_CLK_ENABLE() + +static TIM_HandleTypeDef TimMasterHandle; +static int us_ticker_inited = 0; + +void us_ticker_init(void) { + if (us_ticker_inited) return; + us_ticker_inited = 1; + + // Update the SystemCoreClock variable + SystemCoreClockUpdate(); + + // Enable timer clock + TIM_MST_RCC; + + // Configure time base + TimMasterHandle.Instance = TIM_MST; + TimMasterHandle.Init.Period = 0xFFFFFFFF; + TimMasterHandle.Init.Prescaler = (uint32_t)(SystemCoreClock / 1000000) - 1; // 1 µs tick + TimMasterHandle.Init.ClockDivision = 0; + TimMasterHandle.Init.CounterMode = TIM_COUNTERMODE_UP; + TimMasterHandle.Init.RepetitionCounter = 0; + HAL_TIM_OC_Init(&TimMasterHandle); + + NVIC_SetVector(TIM_MST_IRQ, (uint32_t)us_ticker_irq_handler); + NVIC_EnableIRQ(TIM_MST_IRQ); + + // Enable timer + HAL_TIM_OC_Start(&TimMasterHandle, TIM_CHANNEL_1); +} + +uint32_t us_ticker_read() { + if (!us_ticker_inited) us_ticker_init(); + return TIM_MST->CNT; +} + +void us_ticker_set_interrupt(unsigned int timestamp) { + // Set new output compare value + __HAL_TIM_SetCompare(&TimMasterHandle, TIM_CHANNEL_1, timestamp); + // Enable IT + __HAL_TIM_ENABLE_IT(&TimMasterHandle, TIM_IT_CC1); +} + +void us_ticker_disable_interrupt(void) { + __HAL_TIM_DISABLE_IT(&TimMasterHandle, TIM_IT_CC1); +} + +void us_ticker_clear_interrupt(void) { + __HAL_TIM_CLEAR_IT(&TimMasterHandle, TIM_IT_CC1); +} diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F103RB/PinNames.h b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F103RB/PinNames.h index 1fd8048cb1..5f362087ca 100644 --- a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F103RB/PinNames.h +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F103RB/PinNames.h @@ -104,8 +104,6 @@ typedef enum { PC_14 = 0x2E, PC_15 = 0x2F, - PD_0 = 0x30, - PD_1 = 0x31, PD_2 = 0x32, // Arduino connector namings diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F103RB/device.h b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F103RB/device.h index af26f8f36d..57a7aa227d 100644 --- a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F103RB/device.h +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F103RB/device.h @@ -42,10 +42,10 @@ #define DEVICE_SERIAL 1 #define DEVICE_I2C 1 -#define DEVICE_I2CSLAVE 0 // Not yet supported +#define DEVICE_I2CSLAVE 1 #define DEVICE_SPI 1 -#define DEVICE_SPISLAVE 0 // Not yet supported +#define DEVICE_SPISLAVE 1 #define DEVICE_RTC 1 diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F103RB/i2c_api.c b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F103RB/i2c_api.c index 8725e17b52..48e9e0bf3e 100644 --- a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F103RB/i2c_api.c +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F103RB/i2c_api.c @@ -295,7 +295,45 @@ void i2c_slave_mode(i2c_t *obj, int enable_slave) { #define WriteAddressed 3 // the master is writing to this slave (slave = receiver) int i2c_slave_receive(i2c_t *obj) { - return (0); + int retValue = NoData; + uint32_t event; + I2C_TypeDef *i2c = (I2C_TypeDef *)(obj->i2c); + + event = I2C_GetLastEvent(i2c); + if (event != 0) { + switch (event) { + case I2C_EVENT_SLAVE_RECEIVER_ADDRESS_MATCHED: + retValue = WriteAddressed; + break; + case I2C_EVENT_SLAVE_TRANSMITTER_ADDRESS_MATCHED: + retValue = ReadAddressed; + break; + case I2C_EVENT_SLAVE_GENERALCALLADDRESS_MATCHED: + retValue = WriteGeneral; + break; + default: + retValue = NoData; + break; + } + + // clear ADDR + if ((retValue == WriteAddressed) || (retValue == ReadAddressed)) { + // read SR to clear ADDR flag + i2c->SR1; + i2c->SR2; + } + // clear stopf + if (I2C_GetFlagStatus(i2c, I2C_FLAG_STOPF) == SET) { + // read SR1 and write CR1 to clear STOP flag + i2c->SR1; + I2C_Cmd(i2c, ENABLE); + } + // clear AF + if (I2C_GetFlagStatus(i2c, I2C_FLAG_AF) == SET) { + I2C_ClearFlag(i2c, I2C_FLAG_AF); + } + } + return (retValue); } int i2c_slave_read(i2c_t *obj, char *data, int length) { diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F103RB/objects.h b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F103RB/objects.h index ad2dd17809..3b8a442be8 100644 --- a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F103RB/objects.h +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F103RB/objects.h @@ -65,6 +65,8 @@ struct serial_s { uint32_t databits; uint32_t stopbits; uint32_t parity; + PinName pin_tx; + PinName pin_rx; }; struct spi_s { @@ -75,6 +77,10 @@ struct spi_s { uint32_t mode; uint32_t nss; uint32_t br_presc; + PinName pin_miso; + PinName pin_mosi; + PinName pin_sclk; + PinName pin_ssel; }; struct i2c_s { diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F103RB/pwmout_api.c b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F103RB/pwmout_api.c index e12688196b..9fa74d67d3 100644 --- a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F103RB/pwmout_api.c +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F103RB/pwmout_api.c @@ -98,8 +98,8 @@ void pwmout_init(pwmout_t* obj, PinName pin) { } void pwmout_free(pwmout_t* obj) { - TIM_TypeDef *tim = (TIM_TypeDef *)(obj->pwm); - TIM_DeInit(tim); + // Configure GPIO + pin_function(obj->pin, STM_PIN_DATA(GPIO_Mode_IN_FLOATING, 0)); } void pwmout_write(pwmout_t* obj, float value) { diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F103RB/rtc_api.c b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F103RB/rtc_api.c index 1acdfc8387..819e6ff3b6 100644 --- a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F103RB/rtc_api.c +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F103RB/rtc_api.c @@ -87,7 +87,12 @@ void rtc_init(void) { } void rtc_free(void) { - RCC_DeInit(); // Resets the RCC clock configuration to the default reset state + // Disable RTC, LSE and LSI clocks + PWR_BackupAccessCmd(ENABLE); // Allow access to Backup Domain + RCC_RTCCLKCmd(DISABLE); + RCC_LSEConfig(RCC_LSE_OFF); + RCC_LSICmd(DISABLE); + rtc_inited = 0; } diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F103RB/serial_api.c b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F103RB/serial_api.c index e810885042..869639ce14 100644 --- a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F103RB/serial_api.c +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F103RB/serial_api.c @@ -95,12 +95,15 @@ void serial_init(serial_t *obj, PinName tx, PinName rx) { // Enable USART clock if (obj->uart == UART_1) { RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE); + obj->index = 0; } if (obj->uart == UART_2) { RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE); + obj->index = 1; } if (obj->uart == UART_3) { RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART3, ENABLE); + obj->index = 2; } // Configure the UART pins @@ -113,12 +116,10 @@ void serial_init(serial_t *obj, PinName tx, PinName rx) { obj->stopbits = USART_StopBits_1; obj->parity = USART_Parity_No; - init_usart(obj); + obj->pin_tx = tx; + obj->pin_rx = rx; - // The index is used by irq - if (obj->uart == UART_1) obj->index = 0; - if (obj->uart == UART_2) obj->index = 1; - if (obj->uart == UART_3) obj->index = 2; + init_usart(obj); // For stdio management if (obj->uart == STDIO_UART) { @@ -128,6 +129,27 @@ void serial_init(serial_t *obj, PinName tx, PinName rx) { } void serial_free(serial_t *obj) { + // Reset UART and disable clock + if (obj->uart == UART_1) { + RCC_APB2PeriphResetCmd(RCC_APB2Periph_USART1, ENABLE); + RCC_APB2PeriphResetCmd(RCC_APB2Periph_USART1, DISABLE); + RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, DISABLE); + } + if (obj->uart == UART_2) { + RCC_APB1PeriphResetCmd(RCC_APB1Periph_USART2, ENABLE); + RCC_APB1PeriphResetCmd(RCC_APB1Periph_USART2, DISABLE); + RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, DISABLE); + } + if (obj->uart == UART_3) { + RCC_APB1PeriphResetCmd(RCC_APB1Periph_USART3, ENABLE); + RCC_APB1PeriphResetCmd(RCC_APB1Periph_USART3, DISABLE); + RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART3, DISABLE); + } + + // Configure GPIOs + pin_function(obj->pin_tx, STM_PIN_DATA(GPIO_Mode_IN_FLOATING, 0)); + pin_function(obj->pin_rx, STM_PIN_DATA(GPIO_Mode_IN_FLOATING, 0)); + serial_irq_ids[obj->index] = 0; } diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F103RB/spi_api.c b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F103RB/spi_api.c index 9099ff96eb..466f3c03b2 100644 --- a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F103RB/spi_api.c +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F103RB/spi_api.c @@ -119,21 +119,42 @@ void spi_init(spi_t *obj, PinName mosi, PinName miso, PinName sclk, PinName ssel obj->cpha = SPI_CPHA_1Edge; obj->br_presc = SPI_BaudRatePrescaler_256; + obj->pin_miso = miso; + obj->pin_mosi = mosi; + obj->pin_sclk = sclk; + obj->pin_ssel = ssel; + if (ssel == NC) { // Master obj->mode = SPI_Mode_Master; obj->nss = SPI_NSS_Soft; } else { // Slave pinmap_pinout(ssel, PinMap_SPI_SSEL); obj->mode = SPI_Mode_Slave; - obj->nss = SPI_NSS_Soft; + obj->nss = SPI_NSS_Hard; } init_spi(obj); } void spi_free(spi_t *obj) { - SPI_TypeDef *spi = (SPI_TypeDef *)(obj->spi); - SPI_I2S_DeInit(spi); + // Reset SPI and disable clock + if (obj->spi == SPI_1) { + RCC_APB2PeriphResetCmd(RCC_APB2Periph_SPI1, ENABLE); + RCC_APB2PeriphResetCmd(RCC_APB2Periph_SPI1, DISABLE); + RCC_APB2PeriphClockCmd(RCC_APB2Periph_SPI1, DISABLE); + } + + if (obj->spi == SPI_2) { + RCC_APB1PeriphResetCmd(RCC_APB1Periph_SPI2, ENABLE); + RCC_APB1PeriphResetCmd(RCC_APB1Periph_SPI2, DISABLE); + RCC_APB1PeriphClockCmd(RCC_APB1Periph_SPI2, DISABLE); + } + + // Configure GPIOs + pin_function(obj->pin_miso, STM_PIN_DATA(GPIO_Mode_IN_FLOATING, 0)); + pin_function(obj->pin_mosi, STM_PIN_DATA(GPIO_Mode_IN_FLOATING, 0)); + pin_function(obj->pin_sclk, STM_PIN_DATA(GPIO_Mode_IN_FLOATING, 0)); + pin_function(obj->pin_ssel, STM_PIN_DATA(GPIO_Mode_IN_FLOATING, 0)); } void spi_format(spi_t *obj, int bits, int mode, int slave) { diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F302R8/PinNames.h b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F302R8/PinNames.h index 1227a5e849..3b317a7d65 100644 --- a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F302R8/PinNames.h +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F302R8/PinNames.h @@ -138,10 +138,10 @@ typedef enum { D15 = PB_8, // Generic signals namings - LED1 = PA_5, - LED2 = PA_5, - LED3 = PA_5, - LED4 = PA_5, + LED1 = PB_13, + LED2 = PB_13, + LED3 = PB_13, + LED4 = PB_13, USER_BUTTON = PC_13, SERIAL_TX = PA_2, SERIAL_RX = PA_3, diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F302R8/analogout_api.c b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F302R8/analogout_api.c index cb34f694e6..cb2ce0009c 100644 --- a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F302R8/analogout_api.c +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F302R8/analogout_api.c @@ -57,7 +57,7 @@ void analogout_init(dac_t *obj, PinName pin) { pinmap_pinout(pin, PinMap_DAC); // Save the channel for future use - obj->channel = pin; + obj->pin = pin; // Enable DAC clock RCC_APB1PeriphClockCmd(RCC_APB1Periph_DAC, ENABLE); @@ -76,7 +76,7 @@ void analogout_free(dac_t *obj) { DAC_DeInit(dac); RCC_APB1PeriphClockCmd(RCC_APB1Periph_DAC, DISABLE); // Configure GPIO - pin_function(obj->channel, STM_PIN_DATA(GPIO_Mode_IN, 0, GPIO_PuPd_NOPULL, 0xFF)); + pin_function(obj->pin, STM_PIN_DATA(GPIO_Mode_IN, 0, GPIO_PuPd_NOPULL, 0xFF)); } static inline void dac_write(dac_t *obj, uint16_t value) { diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F302R8/device.h b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F302R8/device.h index c33d82e508..427710270e 100644 --- a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F302R8/device.h +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F302R8/device.h @@ -42,7 +42,7 @@ #define DEVICE_SERIAL 1 #define DEVICE_I2C 1 -#define DEVICE_I2CSLAVE 0 // Not yet supported +#define DEVICE_I2CSLAVE 1 #define DEVICE_SPI 1 #define DEVICE_SPISLAVE 0 // Not yet supported diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F302R8/i2c_api.c b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F302R8/i2c_api.c index 7a2c93962d..96ccaf7617 100644 --- a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F302R8/i2c_api.c +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F302R8/i2c_api.c @@ -76,6 +76,7 @@ void i2c_init(i2c_t *obj, PinName sda, PinName scl) { // Enable I2C clock if (obj->i2c == I2C_1) { RCC_APB1PeriphClockCmd(RCC_APB1Periph_I2C1, ENABLE); + RCC_I2CCLKConfig(RCC_I2C1CLK_SYSCLK); } if (obj->i2c == I2C_2) { RCC_APB1PeriphClockCmd(RCC_APB1Periph_I2C2, ENABLE); @@ -113,35 +114,64 @@ void i2c_frequency(i2c_t *obj, int hz) { * Fast Mode (up to 400 kHz) * Fast Mode Plus (up to 1 MHz) Below values obtained with: - - I2C clock source = 8 MHz (HSI clock per default) + - I2C clock source = 64 MHz (System Clock w/ HSI) or 72 (System Clock w/ HSE) - Analog filter delay = ON - Digital filter coefficient = 0 - Rise time = 100 ns - Fall time = 10ns */ - switch (hz) { - case 100000: - tim = 0x00201D2B; // Standard mode - break; - case 200000: - tim = 0x0010021E; // Fast Mode - break; - case 400000: - tim = 0x0010020A; // Fast Mode - break; - case 1000000: - tim = 0x00100001; // Fast Mode Plus - // Enable the Fast Mode Plus capability - if (obj->i2c == I2C_1) { - SYSCFG_I2CFastModePlusConfig(SYSCFG_I2CFastModePlus_I2C1, ENABLE); - } - if (obj->i2c == I2C_2) { - SYSCFG_I2CFastModePlusConfig(SYSCFG_I2CFastModePlus_I2C2, ENABLE); - } - break; - default: - error("Only 100kHz, 200kHz, 400kHz and 1MHz I2C frequencies are supported."); - break; + if (SystemCoreClock == 64000000) { + switch (hz) { + case 100000: + tim = 0x60302730; // Standard mode + break; + case 200000: + tim = 0x00C07AB3; // Fast Mode + break; + case 400000: + tim = 0x00C0216C; // Fast Mode + break; + case 1000000: + tim = 0x00900B22; // Fast Mode Plus + // Enable the Fast Mode Plus capability + if (obj->i2c == I2C_1) { + SYSCFG_I2CFastModePlusConfig(SYSCFG_I2CFastModePlus_I2C1, ENABLE); + } + if (obj->i2c == I2C_2) { + SYSCFG_I2CFastModePlusConfig(SYSCFG_I2CFastModePlus_I2C2, ENABLE); + } + break; + default: + error("Only 100kHz, 200kHz, 400kHz and 1MHz I2C frequencies are supported."); + break; + } + } else if (SystemCoreClock == 72000000) { + switch (hz) { + case 100000: + tim = 0x10C08DCF; // Standard mode + break; + case 200000: + tim = 0xA010031A; // Fast Mode + break; + case 400000: + tim = 0x00E0257A; // Fast Mode + break; + case 1000000: + tim = 0x00A00D26; // Fast Mode Plus + // Enable the Fast Mode Plus capability + if (obj->i2c == I2C_1) { + SYSCFG_I2CFastModePlusConfig(SYSCFG_I2CFastModePlus_I2C1, ENABLE); + } + if (obj->i2c == I2C_2) { + SYSCFG_I2CFastModePlusConfig(SYSCFG_I2CFastModePlus_I2C2, ENABLE); + } + break; + default: + error("Only 100kHz, 200kHz, 400kHz and 1MHz I2C frequencies are supported."); + break; + } + } else { + error("System clock setting is not supported."); } // I2C configuration @@ -184,15 +214,17 @@ inline int i2c_stop(i2c_t *obj) { return 0; } + int i2c_read(i2c_t *obj, int address, char *data, int length, int stop) { I2C_TypeDef *i2c = (I2C_TypeDef *)(obj->i2c); int count; + int timeout; int value; if (length == 0) return 0; // Configure slave address, nbytes, reload, end mode and start or stop generation - I2C_TransferHandling(i2c, address, length, I2C_AutoEnd_Mode, I2C_Generate_Start_Read); + I2C_TransferHandling(i2c, address, length, I2C_SoftEnd_Mode, I2C_Generate_Start_Read); // Read all bytes for (count = 0; count < length; count++) { @@ -200,48 +232,40 @@ int i2c_read(i2c_t *obj, int address, char *data, int length, int stop) { data[count] = (char)value; } + timeout = FLAG_TIMEOUT; + while (!I2C_GetFlagStatus(i2c, I2C_FLAG_TC)) { + timeout--; + if (timeout == 0) return 0; + } + + if (stop) i2c_stop(obj); + return length; } + int i2c_write(i2c_t *obj, int address, const char *data, int length, int stop) { I2C_TypeDef *i2c = (I2C_TypeDef *)(obj->i2c); - //int timeout; + int timeout; int count; if (length == 0) return 0; - // [TODO] The stop is always sent even with I2C_SoftEnd_Mode. To be corrected. - - // Configure slave address, nbytes, reload, end mode and start or stop generation - //if (stop) { - I2C_TransferHandling(i2c, address, length, I2C_AutoEnd_Mode, I2C_Generate_Start_Write); - //} - //else { - // I2C_TransferHandling(i2c, address, length, I2C_SoftEnd_Mode, I2C_Generate_Start_Write); - //} + // Configure slave address, nbytes, reload, end mode and start generation + I2C_TransferHandling(i2c, address, length, I2C_SoftEnd_Mode, I2C_Generate_Start_Write); // Write all bytes for (count = 0; count < length; count++) { - if (i2c_byte_write(obj, data[count]) != 1) { - i2c_stop(obj); - return 0; - } + i2c_byte_write(obj, data[count]); } - /* - if (stop) { - // Wait until STOPF flag is set - timeout = LONG_TIMEOUT; - while (I2C_GetFlagStatus(i2c, I2C_ISR_STOPF) == RESET) { - timeout--; - if (timeout == 0) { - return 0; - } - } - // Clear STOPF flag - I2C_ClearFlag(i2c, I2C_ICR_STOPCF); + timeout = FLAG_TIMEOUT; + while (!I2C_GetFlagStatus(i2c, I2C_FLAG_TC)) { + timeout--; + if (timeout == 0) return 0; } - */ + + if (stop) i2c_stop(obj); return count; } @@ -304,6 +328,9 @@ void i2c_slave_address(i2c_t *obj, int idx, uint32_t address, uint32_t mask) { I2C_TypeDef *i2c = (I2C_TypeDef *)(obj->i2c); uint16_t tmpreg; + // reset own address enable + i2c->OAR1 &= ~ I2C_OAR1_OA1EN; + // Get the old register value tmpreg = i2c->OAR1; // Reset address bits @@ -311,7 +338,7 @@ void i2c_slave_address(i2c_t *obj, int idx, uint32_t address, uint32_t mask) { // Set new address tmpreg |= (uint16_t)((uint16_t)address & (uint16_t)0x00FE); // 7-bits // Store the new register value - i2c->OAR1 = tmpreg; + i2c->OAR1 = tmpreg | I2C_OAR1_OA1EN; } void i2c_slave_mode(i2c_t *obj, int enable_slave) { @@ -325,8 +352,20 @@ void i2c_slave_mode(i2c_t *obj, int enable_slave) { #define WriteAddressed 3 // the master is writing to this slave (slave = receiver) int i2c_slave_receive(i2c_t *obj) { - // TO BE DONE - return (0); + I2C_TypeDef *i2c = (I2C_TypeDef *)(obj->i2c); + int event = NoData; + + if (I2C_GetFlagStatus(i2c, I2C_ISR_BUSY) == SET) { + if (I2C_GetFlagStatus(i2c, I2C_ISR_ADDR) == SET) { + // Check direction + if (I2C_GetFlagStatus(i2c, I2C_ISR_DIR) == SET) { + event = ReadAddressed; + } else event = WriteAddressed; + // Clear adress match flag to generate an acknowledge + i2c->ICR |= I2C_ICR_ADDRCF; + } + } + return event; } int i2c_slave_read(i2c_t *obj, char *data, int length) { diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F302R8/objects.h b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F302R8/objects.h index 5b8c7ad918..f9ced75296 100644 --- a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F302R8/objects.h +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F302R8/objects.h @@ -60,7 +60,7 @@ struct analogin_s { struct dac_s { DACName dac; - PinName channel; + PinName pin; }; struct serial_s { @@ -70,6 +70,8 @@ struct serial_s { uint32_t databits; uint32_t stopbits; uint32_t parity; + PinName pin_tx; + PinName pin_rx; }; struct spi_s { @@ -80,10 +82,14 @@ struct spi_s { uint32_t mode; uint32_t nss; uint32_t br_presc; + PinName pin_miso; + PinName pin_mosi; + PinName pin_sclk; + PinName pin_ssel; }; struct i2c_s { - I2CName i2c; + I2CName i2c; }; struct pwmout_s { diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F302R8/pwmout_api.c b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F302R8/pwmout_api.c index a371e8ee15..3405f27cc3 100644 --- a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F302R8/pwmout_api.c +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F302R8/pwmout_api.c @@ -112,8 +112,8 @@ void pwmout_init(pwmout_t* obj, PinName pin) { } void pwmout_free(pwmout_t* obj) { - TIM_TypeDef *tim = (TIM_TypeDef *)(obj->pwm); - TIM_DeInit(tim); + // Configure GPIO + pin_function(obj->pin, STM_PIN_DATA(GPIO_Mode_IN, 0, GPIO_PuPd_NOPULL, 0xFF)); } void pwmout_write(pwmout_t* obj, float value) { diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F302R8/rtc_api.c b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F302R8/rtc_api.c index 110a8eaa21..16b88ccb45 100644 --- a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F302R8/rtc_api.c +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F302R8/rtc_api.c @@ -49,7 +49,7 @@ void rtc_init(void) { // Reset back up registers RCC_BackupResetCmd(ENABLE); RCC_BackupResetCmd(DISABLE); - + // Enable LSE clock RCC_LSEConfig(RCC_LSE_ON); @@ -58,40 +58,48 @@ void rtc_init(void) { LSEStatus = RCC_GetFlagStatus(RCC_FLAG_LSERDY); wait_ms(1); StartUpCounter++; - } while((LSEStatus == 0) && (StartUpCounter <= LSE_STARTUP_TIMEOUT)); + } while ((LSEStatus == 0) && (StartUpCounter <= LSE_STARTUP_TIMEOUT)); if (StartUpCounter > LSE_STARTUP_TIMEOUT) { // The LSE has not started, use LSI instead. - // The RTC Clock may vary due to LSI frequency dispersion. - RCC_LSEConfig(RCC_LSE_OFF); + // The RTC Clock may vary due to LSI frequency dispersion. + RCC_LSEConfig(RCC_LSE_OFF); RCC_LSICmd(ENABLE); // Enable LSI while (RCC_GetFlagStatus(RCC_FLAG_LSIRDY) == RESET) {} // Wait until ready RCC_RTCCLKConfig(RCC_RTCCLKSource_LSI); // Select the RTC Clock Source - rtc_freq = 40000; // [TODO] To be measured precisely using a timer input capture - } - else { + rtc_freq = 40000; // [TODO] To be measured precisely using a timer input capture + } else { // The LSE has correctly started RCC_RTCCLKConfig(RCC_RTCCLKSource_LSE); // Select the RTC Clock Source rtc_freq = LSE_VALUE; } - - RCC_RTCCLKCmd(ENABLE); // Enable RTC Clock - + + RCC_RTCCLKCmd(ENABLE); // Enable RTC Clock + RTC_WaitForSynchro(); // Wait for RTC registers synchronization RTC_InitTypeDef RTC_InitStructure; RTC_InitStructure.RTC_AsynchPrediv = 127; - RTC_InitStructure.RTC_SynchPrediv = (rtc_freq / 128) - 1; + RTC_InitStructure.RTC_SynchPrediv = (rtc_freq / 128) - 1; RTC_InitStructure.RTC_HourFormat = RTC_HourFormat_24; RTC_Init(&RTC_InitStructure); - + PWR_BackupAccessCmd(DISABLE); // Disable access to Backup domain - + rtc_inited = 1; } void rtc_free(void) { - RCC_DeInit(); // Resets the RCC clock configuration to the default reset state + // Reset RTC + PWR_BackupAccessCmd(ENABLE); // Enable access to Backup Domain + RTC_DeInit(); + RCC_BackupResetCmd(ENABLE); + RCC_BackupResetCmd(DISABLE); + // Disable RTC, LSE and LSI clocks + RCC_RTCCLKCmd(DISABLE); + RCC_LSEConfig(RCC_LSE_OFF); + RCC_LSICmd(DISABLE); + rtc_inited = 0; } diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F302R8/serial_api.c b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F302R8/serial_api.c index 89907255f5..85c8155223 100644 --- a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F302R8/serial_api.c +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F302R8/serial_api.c @@ -103,12 +103,15 @@ void serial_init(serial_t *obj, PinName tx, PinName rx) { // Enable USART clock if (obj->uart == UART_1) { RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE); + obj->index = 0; } if (obj->uart == UART_2) { RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE); + obj->index = 1; } if (obj->uart == UART_3) { RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART3, ENABLE); + obj->index = 2; } // Configure the UART pins @@ -123,12 +126,10 @@ void serial_init(serial_t *obj, PinName tx, PinName rx) { obj->stopbits = USART_StopBits_1; obj->parity = USART_Parity_No; - init_usart(obj); + obj->pin_tx = tx; + obj->pin_rx = rx; - // The index is used by irq - if (obj->uart == UART_1) obj->index = 0; - if (obj->uart == UART_2) obj->index = 1; - if (obj->uart == UART_3) obj->index = 2; + init_usart(obj); // For stdio management if (obj->uart == STDIO_UART) { @@ -139,6 +140,27 @@ void serial_init(serial_t *obj, PinName tx, PinName rx) { } void serial_free(serial_t *obj) { + // Reset UART and disable clock + if (obj->uart == UART_1) { + RCC_APB2PeriphResetCmd(RCC_APB2Periph_USART1, ENABLE); + RCC_APB2PeriphResetCmd(RCC_APB2Periph_USART1, DISABLE); + RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, DISABLE); + } + if (obj->uart == UART_2) { + RCC_APB1PeriphResetCmd(RCC_APB1Periph_USART2, ENABLE); + RCC_APB1PeriphResetCmd(RCC_APB1Periph_USART2, DISABLE); + RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, DISABLE); + } + if (obj->uart == UART_3) { + RCC_APB1PeriphResetCmd(RCC_APB1Periph_USART3, ENABLE); + RCC_APB1PeriphResetCmd(RCC_APB1Periph_USART3, DISABLE); + RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART3, DISABLE); + } + + // Configure GPIOs + pin_function(obj->pin_tx, STM_PIN_DATA(GPIO_Mode_IN, 0, GPIO_PuPd_NOPULL, 0xFF)); + pin_function(obj->pin_rx, STM_PIN_DATA(GPIO_Mode_IN, 0, GPIO_PuPd_NOPULL, 0xFF)); + serial_irq_ids[obj->index] = 0; } diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F302R8/spi_api.c b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F302R8/spi_api.c index 67d890ccbe..08b1d4c21b 100644 --- a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F302R8/spi_api.c +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F302R8/spi_api.c @@ -125,21 +125,41 @@ void spi_init(spi_t *obj, PinName mosi, PinName miso, PinName sclk, PinName ssel obj->cpha = SPI_CPHA_1Edge; obj->br_presc = SPI_BaudRatePrescaler_256; + obj->pin_miso = miso; + obj->pin_mosi = mosi; + obj->pin_sclk = sclk; + obj->pin_ssel = ssel; + if (ssel == NC) { // Master obj->mode = SPI_Mode_Master; obj->nss = SPI_NSS_Soft; } else { // Slave pinmap_pinout(ssel, PinMap_SPI_SSEL); obj->mode = SPI_Mode_Slave; - obj->nss = SPI_NSS_Soft; + obj->nss = SPI_NSS_Hard; } init_spi(obj); } void spi_free(spi_t *obj) { - SPI_TypeDef *spi = (SPI_TypeDef *)(obj->spi); - SPI_I2S_DeInit(spi); + // Reset SPI and disable clock + if (obj->spi == SPI_2) { + RCC_APB1PeriphResetCmd(RCC_APB1Periph_SPI2, ENABLE); + RCC_APB1PeriphResetCmd(RCC_APB1Periph_SPI2, DISABLE); + RCC_APB1PeriphClockCmd(RCC_APB1Periph_SPI2, DISABLE); + } + if (obj->spi == SPI_3) { + RCC_APB1PeriphResetCmd(RCC_APB1Periph_SPI3, ENABLE); + RCC_APB1PeriphResetCmd(RCC_APB1Periph_SPI3, DISABLE); + RCC_APB1PeriphClockCmd(RCC_APB1Periph_SPI3, DISABLE); + } + + // Configure GPIOs + pin_function(obj->pin_miso, STM_PIN_DATA(GPIO_Mode_IN, 0, GPIO_PuPd_NOPULL, 0xFF)); + pin_function(obj->pin_mosi, STM_PIN_DATA(GPIO_Mode_IN, 0, GPIO_PuPd_NOPULL, 0xFF)); + pin_function(obj->pin_sclk, STM_PIN_DATA(GPIO_Mode_IN, 0, GPIO_PuPd_NOPULL, 0xFF)); + pin_function(obj->pin_ssel, STM_PIN_DATA(GPIO_Mode_IN, 0, GPIO_PuPd_NOPULL, 0xFF)); } void spi_format(spi_t *obj, int bits, int mode, int slave) { diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F401RE/analogin_api.c b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F401RE/analogin_api.c index a876b50d67..9be09ab146 100644 --- a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F401RE/analogin_api.c +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F401RE/analogin_api.c @@ -41,8 +41,8 @@ static const PinMap PinMap_ADC[] = { {PA_3, ADC_1, STM_PIN_DATA(STM_MODE_ANALOG, GPIO_NOPULL, 0)}, // ADC1_IN3 {PA_4, ADC_1, STM_PIN_DATA(STM_MODE_ANALOG, GPIO_NOPULL, 0)}, // ADC1_IN4 {PA_5, ADC_1, STM_PIN_DATA(STM_MODE_ANALOG, GPIO_NOPULL, 0)}, // ADC1_IN5 - {PA_5, ADC_1, STM_PIN_DATA(STM_MODE_ANALOG, GPIO_NOPULL, 0)}, // ADC1_IN6 - {PA_6, ADC_1, STM_PIN_DATA(STM_MODE_ANALOG, GPIO_NOPULL, 0)}, // ADC1_IN7 + {PA_6, ADC_1, STM_PIN_DATA(STM_MODE_ANALOG, GPIO_NOPULL, 0)}, // ADC1_IN6 + {PA_7, ADC_1, STM_PIN_DATA(STM_MODE_ANALOG, GPIO_NOPULL, 0)}, // ADC1_IN7 {PB_0, ADC_1, STM_PIN_DATA(STM_MODE_ANALOG, GPIO_NOPULL, 0)}, // ADC1_IN8 {PB_1, ADC_1, STM_PIN_DATA(STM_MODE_ANALOG, GPIO_NOPULL, 0)}, // ADC1_IN9 {PC_0, ADC_1, STM_PIN_DATA(STM_MODE_ANALOG, GPIO_NOPULL, 0)}, // ADC1_IN10 diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F401RE/device.h b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F401RE/device.h index 302ed7582d..57a7aa227d 100644 --- a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F401RE/device.h +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F401RE/device.h @@ -42,10 +42,10 @@ #define DEVICE_SERIAL 1 #define DEVICE_I2C 1 -#define DEVICE_I2CSLAVE 0 // Not supported yet +#define DEVICE_I2CSLAVE 1 #define DEVICE_SPI 1 -#define DEVICE_SPISLAVE 0 // Not supported yet +#define DEVICE_SPISLAVE 1 #define DEVICE_RTC 1 diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F401RE/i2c_api.c b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F401RE/i2c_api.c index bb6fc1443d..7a29bf78de 100644 --- a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F401RE/i2c_api.c +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F401RE/i2c_api.c @@ -93,13 +93,16 @@ void i2c_init(i2c_t *obj, PinName sda, PinName scl) { // I2C configuration i2c_frequency(obj, 100000); // 100 kHz per default + + // I2C master by default + obj->slave = 0; } void i2c_frequency(i2c_t *obj, int hz) { I2cHandle.Instance = (I2C_TypeDef *)(obj->i2c); if ((hz != 0) && (hz <= 400000)) { - // I2C configuration + // I2C configuration I2cHandle.Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT; I2cHandle.Init.ClockSpeed = hz; I2cHandle.Init.DualAddressMode = I2C_DUALADDRESS_DISABLED; @@ -108,9 +111,12 @@ void i2c_frequency(i2c_t *obj, int hz) { I2cHandle.Init.NoStretchMode = I2C_NOSTRETCH_DISABLED; I2cHandle.Init.OwnAddress1 = 0; I2cHandle.Init.OwnAddress2 = 0; - HAL_I2C_Init(&I2cHandle); - } - else { + HAL_I2C_Init(&I2cHandle); + if (obj->slave) { + /* Enable Address Acknowledge */ + I2cHandle.Instance->CR1 |= I2C_CR1_ACK; + } + } else { error("I2C error: frequency setting failed (max 400kHz)."); } } @@ -148,29 +154,101 @@ inline int i2c_stop(i2c_t *obj) { } int i2c_read(i2c_t *obj, int address, char *data, int length, int stop) { + I2C_TypeDef *i2c = (I2C_TypeDef *)(obj->i2c); + I2cHandle.Instance = (I2C_TypeDef *)(obj->i2c); + int timeout; + int count; + int value; + if (length == 0) return 0; - I2cHandle.Instance = (I2C_TypeDef *)(obj->i2c); + i2c_start(obj); - // Reception process with 5 seconds timeout - if (HAL_I2C_Master_Receive(&I2cHandle, (uint16_t)address, (uint8_t *)data, length, 5000) != HAL_OK) { - return 0; // Error + // Wait until SB flag is set + timeout = FLAG_TIMEOUT; + while (__HAL_I2C_GET_FLAG(&I2cHandle, I2C_FLAG_SB) == RESET) { + timeout--; + if (timeout == 0) { + return 0; + } } + i2c->DR = __HAL_I2C_7BIT_ADD_READ(address); + + + // Wait address is acknowledged + timeout = FLAG_TIMEOUT; + while (__HAL_I2C_GET_FLAG(&I2cHandle, I2C_FLAG_ADDR) == RESET) { + timeout--; + if (timeout == 0) { + return 0; + } + } + __HAL_I2C_CLEAR_ADDRFLAG(&I2cHandle); + + // Read all bytes except last one + for (count = 0; count < (length - 1); count++) { + value = i2c_byte_read(obj, 0); + data[count] = (char)value; + } + + // If not repeated start, send stop. + // Warning: must be done BEFORE the data is read. + if (stop) { + i2c_stop(obj); + } + + // Read the last byte + value = i2c_byte_read(obj, 1); + data[count] = (char)value; + return length; } int i2c_write(i2c_t *obj, int address, const char *data, int length, int stop) { - if (length == 0) return 0; - + I2C_TypeDef *i2c = (I2C_TypeDef *)(obj->i2c); I2cHandle.Instance = (I2C_TypeDef *)(obj->i2c); + int timeout; + int count; - // Transmission process with 5 seconds timeout - if (HAL_I2C_Master_Transmit(&I2cHandle, (uint16_t)address, (uint8_t *)data, length, 5000) != HAL_OK) { - return 0; // Error + if (length == 0) return 0; + i2c_start(obj); + + // Wait until SB flag is set + timeout = FLAG_TIMEOUT; + while (__HAL_I2C_GET_FLAG(&I2cHandle, I2C_FLAG_SB) == RESET) { + timeout--; + if (timeout == 0) { + return 0; + } } - return length; + i2c->DR = __HAL_I2C_7BIT_ADD_WRITE(address); + + + // Wait address is acknowledged + timeout = FLAG_TIMEOUT; + while (__HAL_I2C_GET_FLAG(&I2cHandle, I2C_FLAG_ADDR) == RESET) { + timeout--; + if (timeout == 0) { + return 0; + } + } + __HAL_I2C_CLEAR_ADDRFLAG(&I2cHandle); + + for (count = 0; count < length; count++) { + if (i2c_byte_write(obj, data[count]) != 1) { + i2c_stop(obj); + return 0; + } + } + + // If not repeated start, send stop. + if (stop) { + i2c_stop(obj); + } + + return count; } int i2c_byte_read(i2c_t *obj, int last) { @@ -205,7 +283,7 @@ int i2c_byte_write(i2c_t *obj, int data) { // Wait until the byte is transmitted timeout = FLAG_TIMEOUT; while ((__HAL_I2C_GET_FLAG(&I2cHandle, I2C_FLAG_TXE) == RESET) && - (__HAL_I2C_GET_FLAG(&I2cHandle, I2C_FLAG_BTF) == RESET)) { + (__HAL_I2C_GET_FLAG(&I2cHandle, I2C_FLAG_BTF) == RESET)) { if ((timeout--) == 0) { return 0; } @@ -233,7 +311,7 @@ void i2c_reset(i2c_t *obj) { void i2c_slave_address(i2c_t *obj, int idx, uint32_t address, uint32_t mask) { I2C_TypeDef *i2c = (I2C_TypeDef *)(obj->i2c); - uint16_t tmpreg; + uint16_t tmpreg = 0; // Get the old register value tmpreg = i2c->OAR1; @@ -246,7 +324,12 @@ void i2c_slave_address(i2c_t *obj, int idx, uint32_t address, uint32_t mask) { } void i2c_slave_mode(i2c_t *obj, int enable_slave) { - // Nothing to do + I2cHandle.Instance = (I2C_TypeDef *)(obj->i2c); + if (enable_slave) { + obj->slave = 1; + /* Enable Address Acknowledge */ + I2cHandle.Instance->CR1 |= I2C_CR1_ACK; + } } // See I2CSlave.h @@ -256,34 +339,137 @@ void i2c_slave_mode(i2c_t *obj, int enable_slave) { #define WriteAddressed 3 // the master is writing to this slave (slave = receiver) int i2c_slave_receive(i2c_t *obj) { - // TO BE DONE - return(0); + int retValue = NoData; + + if (__HAL_I2C_GET_FLAG(&I2cHandle, I2C_FLAG_BUSY) == 1) { + if (__HAL_I2C_GET_FLAG(&I2cHandle, I2C_FLAG_ADDR) == 1) { + if (__HAL_I2C_GET_FLAG(&I2cHandle, I2C_FLAG_TRA) == 1) + retValue = ReadAddressed; + else + retValue = WriteAddressed; + + __HAL_I2C_CLEAR_FLAG(&I2cHandle, I2C_FLAG_ADDR); + } + } + + return (retValue); } int i2c_slave_read(i2c_t *obj, char *data, int length) { + uint32_t Timeout; + int size = 0; if (length == 0) return 0; I2cHandle.Instance = (I2C_TypeDef *)(obj->i2c); - // Reception process with 5 seconds timeout - if (HAL_I2C_Slave_Receive(&I2cHandle, (uint8_t *)data, length, 5000) != HAL_OK) { - return 0; // Error + while (length > 0) { + /* Wait until RXNE flag is set */ + // Wait until the byte is received + Timeout = FLAG_TIMEOUT; + while (__HAL_I2C_GET_FLAG(&I2cHandle, I2C_FLAG_RXNE) == RESET) { + Timeout--; + if (Timeout == 0) { + return 0; + } + } + + /* Read data from DR */ + (*data++) = I2cHandle.Instance->DR; + length--; + size++; + + if ((__HAL_I2C_GET_FLAG(&I2cHandle, I2C_FLAG_BTF) == SET) && (length != 0)) { + /* Read data from DR */ + (*data++) = I2cHandle.Instance->DR; + length--; + size++; + } } - return length; + /* Wait until STOP flag is set */ + Timeout = FLAG_TIMEOUT; + while (__HAL_I2C_GET_FLAG(&I2cHandle, I2C_FLAG_STOPF) == RESET) { + Timeout--; + if (Timeout == 0) { + return 0; + } + } + + /* Clear STOP flag */ + __HAL_I2C_CLEAR_STOPFLAG(&I2cHandle); + + /* Wait until BUSY flag is reset */ + Timeout = FLAG_TIMEOUT; + while (__HAL_I2C_GET_FLAG(&I2cHandle, I2C_FLAG_BUSY) == SET) { + Timeout--; + if (Timeout == 0) { + return 0; + } + } + + return size; } int i2c_slave_write(i2c_t *obj, const char *data, int length) { + uint32_t Timeout; + int size = 0; if (length == 0) return 0; I2cHandle.Instance = (I2C_TypeDef *)(obj->i2c); - // Transmission process with 5 seconds timeout - if (HAL_I2C_Slave_Transmit(&I2cHandle, (uint8_t *)data, length, 5000) != HAL_OK) { - return 0; // Error + while (length > 0) { + /* Wait until TXE flag is set */ + Timeout = FLAG_TIMEOUT; + while (__HAL_I2C_GET_FLAG(&I2cHandle, I2C_FLAG_TXE) == RESET) { + Timeout--; + if (Timeout == 0) { + return 0; + } + } + + + /* Write data to DR */ + I2cHandle.Instance->DR = (*data++); + length--; + size++; + + if ((__HAL_I2C_GET_FLAG(&I2cHandle, I2C_FLAG_BTF) == SET) && (length != 0)) { + /* Write data to DR */ + I2cHandle.Instance->DR = (*data++); + length--; + size++; + } } - return length; + /* Wait until AF flag is set */ + Timeout = FLAG_TIMEOUT; + while (__HAL_I2C_GET_FLAG(&I2cHandle, I2C_FLAG_AF) == RESET) { + Timeout--; + if (Timeout == 0) { + return 0; + } + } + + + /* Clear AF flag */ + __HAL_I2C_CLEAR_FLAG(&I2cHandle, I2C_FLAG_AF); + + + /* Wait until BUSY flag is reset */ + Timeout = FLAG_TIMEOUT; + while (__HAL_I2C_GET_FLAG(&I2cHandle, I2C_FLAG_BUSY) == SET) { + Timeout--; + if (Timeout == 0) { + return 0; + } + } + + I2cHandle.State = HAL_I2C_STATE_READY; + + /* Process Unlocked */ + __HAL_UNLOCK(&I2cHandle); + + return size; } diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F401RE/objects.h b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F401RE/objects.h index a1346adf1e..2fbfffd863 100644 --- a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F401RE/objects.h +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F401RE/objects.h @@ -66,6 +66,8 @@ struct serial_s { uint32_t databits; uint32_t stopbits; uint32_t parity; + PinName pin_tx; + PinName pin_rx; }; struct spi_s { @@ -76,10 +78,15 @@ struct spi_s { uint32_t mode; uint32_t nss; uint32_t br_presc; + PinName pin_miso; + PinName pin_mosi; + PinName pin_sclk; + PinName pin_ssel; }; struct i2c_s { I2CName i2c; + uint32_t slave; }; struct pwmout_s { diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F401RE/pwmout_api.c b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F401RE/pwmout_api.c index 47913a61a2..d9e42f0bae 100644 --- a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F401RE/pwmout_api.c +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F401RE/pwmout_api.c @@ -74,12 +74,12 @@ static const PinMap PinMap_PWM[] = { {PB_13, PWM_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1)}, // TIM1_CH1N {PB_14, PWM_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1)}, // TIM1_CH2N {PB_15, PWM_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF1_TIM1)}, // TIM1_CH3N - + {PC_6, PWM_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3)}, // TIM3_CH1 {PC_7, PWM_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3)}, // TIM3_CH2 {PC_8, PWM_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3)}, // TIM3_CH3 {PC_9, PWM_3, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM3)}, // TIM3_CH4 - + {NC, NC, 0} }; @@ -170,7 +170,7 @@ void pwmout_write(pwmout_t* obj, float value) { case PB_3: case PB_5: case PB_7: - case PC_7: + case PC_7: channel = TIM_CHANNEL_2; break; // Channels 2N @@ -191,7 +191,7 @@ void pwmout_write(pwmout_t* obj, float value) { break; // Channels 3N case PB_1: - case PB_15: + case PB_15: channel = TIM_CHANNEL_3; complementary_channel = 1; break; @@ -210,8 +210,7 @@ void pwmout_write(pwmout_t* obj, float value) { HAL_TIM_PWM_ConfigChannel(&TimHandle, &sConfig, channel); if (complementary_channel) { HAL_TIMEx_PWMN_Start(&TimHandle, channel); - } - else { + } else { HAL_TIM_PWM_Start(&TimHandle, channel); } } diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F401RE/rtc_api.c b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F401RE/rtc_api.c index 8ab50e9886..ee7e84242a 100644 --- a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F401RE/rtc_api.c +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F401RE/rtc_api.c @@ -60,8 +60,7 @@ void rtc_init(void) { RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSE; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE; /* Mandatory, otherwise the PLL is reconfigured! */ RCC_OscInitStruct.LSEState = RCC_LSE_ON; /* External 32.768 kHz clock on OSC_IN/OSC_OUT */ - if (HAL_RCC_OscConfig(&RCC_OscInitStruct) == HAL_OK) - { + if (HAL_RCC_OscConfig(&RCC_OscInitStruct) == HAL_OK) { // Connect LSE to RTC __HAL_RCC_RTC_CLKPRESCALER(RCC_RTCCLKSOURCE_LSE); __HAL_RCC_RTC_CONFIG(RCC_RTCCLKSOURCE_LSE); diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F401RE/serial_api.c b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F401RE/serial_api.c index 65732b0b05..f9630f7f92 100644 --- a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F401RE/serial_api.c +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F401RE/serial_api.c @@ -93,12 +93,15 @@ void serial_init(serial_t *obj, PinName tx, PinName rx) { // Enable USART clock if (obj->uart == UART_1) { __USART1_CLK_ENABLE(); + obj->index = 0; } if (obj->uart == UART_2) { __USART2_CLK_ENABLE(); + obj->index = 1; } if (obj->uart == UART_6) { __USART6_CLK_ENABLE(); + obj->index = 2; } // Configure the UART pins @@ -113,12 +116,10 @@ void serial_init(serial_t *obj, PinName tx, PinName rx) { obj->stopbits = UART_STOPBITS_1; obj->parity = UART_PARITY_NONE; - init_uart(obj); + obj->pin_tx = tx; + obj->pin_rx = rx; - // The index is used by irq - if (obj->uart == UART_1) obj->index = 0; - if (obj->uart == UART_2) obj->index = 1; - if (obj->uart == UART_6) obj->index = 2; + init_uart(obj); // For stdio management if (obj->uart == STDIO_UART) { @@ -129,6 +130,27 @@ void serial_init(serial_t *obj, PinName tx, PinName rx) { } void serial_free(serial_t *obj) { + // Reset UART and disable clock + if (obj->uart == UART_1) { + __USART1_FORCE_RESET(); + __USART1_RELEASE_RESET(); + __USART1_CLK_DISABLE(); + } + if (obj->uart == UART_2) { + __USART2_FORCE_RESET(); + __USART2_RELEASE_RESET(); + __USART2_CLK_DISABLE(); + } + if (obj->uart == UART_6) { + __USART6_FORCE_RESET(); + __USART6_RELEASE_RESET(); + __USART6_CLK_DISABLE(); + } + + // Configure GPIOs + pin_function(obj->pin_tx, STM_PIN_DATA(STM_MODE_INPUT, GPIO_NOPULL, 0)); + pin_function(obj->pin_rx, STM_PIN_DATA(STM_MODE_INPUT, GPIO_NOPULL, 0)); + serial_irq_ids[obj->index] = 0; } diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F401RE/spi_api.c b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F401RE/spi_api.c index bf94d48fe3..28b68efac1 100644 --- a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F401RE/spi_api.c +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_F401RE/spi_api.c @@ -138,6 +138,11 @@ void spi_init(spi_t *obj, PinName mosi, PinName miso, PinName sclk, PinName ssel obj->cpha = SPI_PHASE_1EDGE; obj->br_presc = SPI_BAUDRATEPRESCALER_256; + obj->pin_miso = miso; + obj->pin_mosi = mosi; + obj->pin_sclk = sclk; + obj->pin_ssel = ssel; + if (ssel == NC) { // SW NSS Master mode obj->mode = SPI_MODE_MASTER; obj->nss = SPI_NSS_SOFT; @@ -151,8 +156,30 @@ void spi_init(spi_t *obj, PinName mosi, PinName miso, PinName sclk, PinName ssel } void spi_free(spi_t *obj) { - SpiHandle.Instance = (SPI_TypeDef *)(obj->spi); - HAL_SPI_DeInit(&SpiHandle); + // Reset SPI and disable clock + if (obj->spi == SPI_1) { + __SPI1_FORCE_RESET(); + __SPI1_RELEASE_RESET(); + __SPI1_CLK_DISABLE(); + } + + if (obj->spi == SPI_2) { + __SPI2_FORCE_RESET(); + __SPI2_RELEASE_RESET(); + __SPI2_CLK_DISABLE(); + } + + if (obj->spi == SPI_3) { + __SPI3_FORCE_RESET(); + __SPI3_RELEASE_RESET(); + __SPI3_CLK_DISABLE(); + } + + // Configure GPIOs + pin_function(obj->pin_miso, STM_PIN_DATA(STM_MODE_INPUT, GPIO_NOPULL, 0)); + pin_function(obj->pin_mosi, STM_PIN_DATA(STM_MODE_INPUT, GPIO_NOPULL, 0)); + pin_function(obj->pin_sclk, STM_PIN_DATA(STM_MODE_INPUT, GPIO_NOPULL, 0)); + pin_function(obj->pin_ssel, STM_PIN_DATA(STM_MODE_INPUT, GPIO_NOPULL, 0)); } void spi_format(spi_t *obj, int bits, int mode, int slave) { @@ -256,7 +283,7 @@ int spi_master_write(spi_t *obj, int value) { } int spi_slave_receive(spi_t *obj) { - return (!ssp_busy(obj)) ? (1) : (0); + return (ssp_readable(obj) && !ssp_busy(obj)) ? (1) : (0); }; int spi_slave_read(spi_t *obj) { diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L053R8/PeripheralNames.h b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L053R8/PeripheralNames.h new file mode 100644 index 0000000000..2a26ecb449 --- /dev/null +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L053R8/PeripheralNames.h @@ -0,0 +1,77 @@ +/* mbed Microcontroller Library + ******************************************************************************* + * Copyright (c) 2014, STMicroelectronics + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ******************************************************************************* + */ +#ifndef MBED_PERIPHERALNAMES_H +#define MBED_PERIPHERALNAMES_H + +#include "cmsis.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum { + ADC_1 = (int)ADC1_BASE +} ADCName; + +typedef enum { + DAC_1 = (int)DAC_BASE +} DACName; + +typedef enum { + UART_1 = (int)USART1_BASE, + UART_2 = (int)USART2_BASE, + LPUART_1 = (int)LPUART1_BASE +} UARTName; + +#define STDIO_UART_TX PA_2 +#define STDIO_UART_RX PA_3 +#define STDIO_UART UART_2 + +typedef enum { + SPI_1 = (int)SPI1_BASE, + SPI_2 = (int)SPI2_BASE +} SPIName; + +typedef enum { + I2C_1 = (int)I2C1_BASE, + I2C_2 = (int)I2C2_BASE +} I2CName; + +typedef enum { + PWM_2 = (int)TIM2_BASE, + PWM_21 = (int)TIM21_BASE, + PWM_22 = (int)TIM22_BASE +} PWMName; + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L053R8/PinNames.h b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L053R8/PinNames.h new file mode 100644 index 0000000000..fd545eb892 --- /dev/null +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L053R8/PinNames.h @@ -0,0 +1,182 @@ +/* mbed Microcontroller Library + ******************************************************************************* + * Copyright (c) 2014, STMicroelectronics + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ******************************************************************************* + */ +#ifndef MBED_PINNAMES_H +#define MBED_PINNAMES_H + +#include "cmsis.h" + +#ifdef __cplusplus +extern "C" { +#endif + +// See stm32l0xx_hal_gpio.h and stm32l0xx_hal_gpio_ex.h for values of MODE, PUPD and AFNUM +#define STM_PIN_DATA(MODE, PUPD, AFNUM) ((int)(((AFNUM) << 7) | ((PUPD) << 4) | ((MODE) << 0))) +#define STM_PIN_MODE(X) (((X) >> 0) & 0x0F) +#define STM_PIN_PUPD(X) (((X) >> 4) & 0x07) +#define STM_PIN_AFNUM(X) (((X) >> 7) & 0x0F) +#define STM_MODE_INPUT (0) +#define STM_MODE_OUTPUT_PP (1) +#define STM_MODE_OUTPUT_OD (2) +#define STM_MODE_AF_PP (3) +#define STM_MODE_AF_OD (4) +#define STM_MODE_ANALOG (5) +#define STM_MODE_IT_RISING (6) +#define STM_MODE_IT_FALLING (7) +#define STM_MODE_IT_RISING_FALLING (8) +#define STM_MODE_EVT_RISING (9) +#define STM_MODE_EVT_FALLING (10) +#define STM_MODE_EVT_RISING_FALLING (11) + +// High nibble = port number (0=A, 1=B, 2=C, 3=D, 4=E, 5=F, 6=G, 7=H) +// Low nibble = pin number +#define STM_PORT(X) (((uint32_t)(X) >> 4) & 0xF) +#define STM_PIN(X) ((uint32_t)(X) & 0xF) + +typedef enum { + PIN_INPUT, + PIN_OUTPUT +} PinDirection; + +typedef enum { + PA_0 = 0x00, + PA_1 = 0x01, + PA_2 = 0x02, + PA_3 = 0x03, + PA_4 = 0x04, + PA_5 = 0x05, + PA_6 = 0x06, + PA_7 = 0x07, + PA_8 = 0x08, + PA_9 = 0x09, + PA_10 = 0x0A, + PA_11 = 0x0B, + PA_12 = 0x0C, + PA_13 = 0x0D, + PA_14 = 0x0E, + PA_15 = 0x0F, + + PB_0 = 0x10, + PB_1 = 0x11, + PB_2 = 0x12, + PB_3 = 0x13, + PB_4 = 0x14, + PB_5 = 0x15, + PB_6 = 0x16, + PB_7 = 0x17, + PB_8 = 0x18, + PB_9 = 0x19, + PB_10 = 0x1A, + PB_11 = 0x1B, + PB_12 = 0x1C, + PB_13 = 0x1D, + PB_14 = 0x1E, + PB_15 = 0x1F, + + PC_0 = 0x20, + PC_1 = 0x21, + PC_2 = 0x22, + PC_3 = 0x23, + PC_4 = 0x24, + PC_5 = 0x25, + PC_6 = 0x26, + PC_7 = 0x27, + PC_8 = 0x28, + PC_9 = 0x29, + PC_10 = 0x2A, + PC_11 = 0x2B, + PC_12 = 0x2C, + PC_13 = 0x2D, + PC_14 = 0x2E, + PC_15 = 0x2F, + + PD_2 = 0x32, + + PH_0 = 0x70, + PH_1 = 0x71, + + // Arduino connector namings + A0 = PA_0, + A1 = PA_1, + A2 = PA_4, + A3 = PB_0, + A4 = PC_1, + A5 = PC_0, + D0 = PA_3, + D1 = PA_2, + D2 = PA_10, + D3 = PB_3, + D4 = PB_5, + D5 = PB_4, + D6 = PB_10, + D7 = PA_8, + D8 = PA_9, + D9 = PC_7, + D10 = PB_6, + D11 = PA_7, + D12 = PA_6, + D13 = PA_5, + D14 = PB_9, + D15 = PB_8, + + // Generic signals namings + LED1 = PA_5, + LED2 = PA_5, + LED3 = PA_5, + LED4 = PA_5, + USER_BUTTON = PC_13, + SERIAL_TX = PA_2, + SERIAL_RX = PA_3, + USBTX = PA_2, + USBRX = PA_3, + I2C_SCL = PB_8, + I2C_SDA = PB_9, + SPI_MOSI = PA_7, + SPI_MISO = PA_6, + SPI_SCK = PA_5, + SPI_CS = PB_6, + PWM_OUT = PB_3, + + // Not connected + NC = (int)0xFFFFFFFF +} PinName; + +typedef enum { + PullNone = 0, + PullUp = 1, + PullDown = 2, + OpenDrain = 3, + PullDefault = PullNone +} PinMode; + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L053R8/PortNames.h b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L053R8/PortNames.h new file mode 100644 index 0000000000..14295a0b4d --- /dev/null +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L053R8/PortNames.h @@ -0,0 +1,48 @@ +/* mbed Microcontroller Library + ******************************************************************************* + * Copyright (c) 2014, STMicroelectronics + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ******************************************************************************* + */ +#ifndef MBED_PORTNAMES_H +#define MBED_PORTNAMES_H + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum { + PortA = 0, + PortB = 1, + PortC = 2, + PortD = 3, + PortH = 7 +} PortName; + +#ifdef __cplusplus +} +#endif +#endif diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L053R8/analogin_api.c b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L053R8/analogin_api.c new file mode 100644 index 0000000000..a24d97c689 --- /dev/null +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L053R8/analogin_api.c @@ -0,0 +1,184 @@ +/* mbed Microcontroller Library + * Copyright (c) 2014, STMicroelectronics + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +#include "analogin_api.h" + +#if DEVICE_ANALOGIN + +#include "wait_api.h" +#include "cmsis.h" +#include "pinmap.h" +#include "error.h" + +static const PinMap PinMap_ADC[] = { + {PA_0, ADC_1, STM_PIN_DATA(STM_MODE_ANALOG, GPIO_NOPULL, 0)}, // ADC1_IN0 + {PA_1, ADC_1, STM_PIN_DATA(STM_MODE_ANALOG, GPIO_NOPULL, 0)}, // ADC1_IN1 + {PA_2, ADC_1, STM_PIN_DATA(STM_MODE_ANALOG, GPIO_NOPULL, 0)}, // ADC1_IN2 + {PA_3, ADC_1, STM_PIN_DATA(STM_MODE_ANALOG, GPIO_NOPULL, 0)}, // ADC1_IN3 + {PA_4, ADC_1, STM_PIN_DATA(STM_MODE_ANALOG, GPIO_NOPULL, 0)}, // ADC1_IN4 + {PA_5, ADC_1, STM_PIN_DATA(STM_MODE_ANALOG, GPIO_NOPULL, 0)}, // ADC1_IN5 + {PA_6, ADC_1, STM_PIN_DATA(STM_MODE_ANALOG, GPIO_NOPULL, 0)}, // ADC1_IN6 + {PA_7, ADC_1, STM_PIN_DATA(STM_MODE_ANALOG, GPIO_NOPULL, 0)}, // ADC1_IN7 + {PB_0, ADC_1, STM_PIN_DATA(STM_MODE_ANALOG, GPIO_NOPULL, 0)}, // ADC1_IN8 + {PB_1, ADC_1, STM_PIN_DATA(STM_MODE_ANALOG, GPIO_NOPULL, 0)}, // ADC1_IN9 + {PC_0, ADC_1, STM_PIN_DATA(STM_MODE_ANALOG, GPIO_NOPULL, 0)}, // ADC1_IN10 + {PC_1, ADC_1, STM_PIN_DATA(STM_MODE_ANALOG, GPIO_NOPULL, 0)}, // ADC1_IN11 + {PC_2, ADC_1, STM_PIN_DATA(STM_MODE_ANALOG, GPIO_NOPULL, 0)}, // ADC1_IN12 + {PC_3, ADC_1, STM_PIN_DATA(STM_MODE_ANALOG, GPIO_NOPULL, 0)}, // ADC1_IN13 + {PC_4, ADC_1, STM_PIN_DATA(STM_MODE_ANALOG, GPIO_NOPULL, 0)}, // ADC1_IN14 + {PC_5, ADC_1, STM_PIN_DATA(STM_MODE_ANALOG, GPIO_NOPULL, 0)}, // ADC1_IN15 + {NC, NC, 0} +}; + +ADC_HandleTypeDef AdcHandle; + +int adc_inited = 0; + +void analogin_init(analogin_t *obj, PinName pin) { + // Get the peripheral name from the pin and assign it to the object + obj->adc = (ADCName)pinmap_peripheral(pin, PinMap_ADC); + + if (obj->adc == (ADCName)NC) { + error("ADC error: pinout mapping failed."); + } + + // Configure GPIO + pinmap_pinout(pin, PinMap_ADC); + + // Save pin number for the read function + obj->pin = pin; + + // The ADC initialization is done once + if (adc_inited == 0) { + adc_inited = 1; + + // Enable ADC clock + __ADC1_CLK_ENABLE(); + + // Configure ADC + AdcHandle.Init.OversamplingMode = DISABLE; + AdcHandle.Init.ClockPrescaler = ADC_CLOCKPRESCALER_PCLK_DIV2; // ADCCLK = 8 MHz (HSI 16 MHz / 2) + AdcHandle.Init.Resolution = ADC_RESOLUTION12b; + AdcHandle.Init.SamplingTime = ADC_SAMPLETIME_1CYCLE_5; + AdcHandle.Init.ScanDirection = ADC_SCAN_DIRECTION_UPWARD; + AdcHandle.Init.DataAlign = ADC_DATAALIGN_RIGHT; + AdcHandle.Init.ContinuousConvMode = DISABLE; + AdcHandle.Init.DiscontinuousConvMode = DISABLE; + AdcHandle.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIG_EDGE_NONE; + AdcHandle.Init.ExternalTrigConv = ADC_EXTERNALTRIG0_T6_TRGO; // Not used here + AdcHandle.Init.DMAContinuousRequests = DISABLE; + AdcHandle.Init.EOCSelection = EOC_SINGLE_CONV; + AdcHandle.Init.Overrun = OVR_DATA_PRESERVED; + AdcHandle.Init.LowPowerAutoWait = ENABLE; + AdcHandle.Init.LowPowerFrequencyMode = DISABLE; // To be enabled only if ADC clock < 2.8 MHz + AdcHandle.Init.LowPowerAutoOff = ENABLE; + HAL_ADC_Init(&AdcHandle); + } +} + +static inline uint16_t adc_read(analogin_t *obj) { + ADC_ChannelConfTypeDef sConfig; + + AdcHandle.Instance = (ADC_TypeDef *)(obj->adc); + + // Configure ADC channel + switch (obj->pin) { + case PA_0: + sConfig.Channel = ADC_CHANNEL_0; + break; + case PA_1: + sConfig.Channel = ADC_CHANNEL_1; + break; + case PA_2: + sConfig.Channel = ADC_CHANNEL_2; + break; + case PA_3: + sConfig.Channel = ADC_CHANNEL_3; + break; + case PA_4: + sConfig.Channel = ADC_CHANNEL_4; + break; + case PA_5: + sConfig.Channel = ADC_CHANNEL_5; + break; + case PA_6: + sConfig.Channel = ADC_CHANNEL_6; + break; + case PA_7: + sConfig.Channel = ADC_CHANNEL_7; + break; + case PB_0: + sConfig.Channel = ADC_CHANNEL_8; + break; + case PB_1: + sConfig.Channel = ADC_CHANNEL_9; + break; + case PC_0: + sConfig.Channel = ADC_CHANNEL_10; + break; + case PC_1: + sConfig.Channel = ADC_CHANNEL_11; + break; + case PC_2: + sConfig.Channel = ADC_CHANNEL_12; + break; + case PC_3: + sConfig.Channel = ADC_CHANNEL_13; + break; + case PC_4: + sConfig.Channel = ADC_CHANNEL_14; + break; + case PC_5: + sConfig.Channel = ADC_CHANNEL_15; + break; + default: + return 0; + } + + ADC1->CHSELR = 0; // [TODO] Workaround. To be removed after Cube driver is corrected. + HAL_ADC_ConfigChannel(&AdcHandle, &sConfig); + + HAL_ADC_Start(&AdcHandle); // Start conversion + + // Wait end of conversion and get value + if (HAL_ADC_PollForConversion(&AdcHandle, 10) == HAL_OK) { + return (HAL_ADC_GetValue(&AdcHandle)); + } else { + return 0; + } +} + +uint16_t analogin_read_u16(analogin_t *obj) { + return (adc_read(obj)); +} + +float analogin_read(analogin_t *obj) { + uint16_t value = adc_read(obj); + return (float)value * (1.0f / (float)0xFFF); // 12 bits range +} + +#endif diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L053R8/analogout_api.c b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L053R8/analogout_api.c new file mode 100644 index 0000000000..1e81a42d51 --- /dev/null +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L053R8/analogout_api.c @@ -0,0 +1,121 @@ +/* mbed Microcontroller Library + * Copyright (c) 2014, STMicroelectronics + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +#include "analogout_api.h" + +#if DEVICE_ANALOGOUT + +#include "cmsis.h" +#include "pinmap.h" +#include "error.h" + +#define DAC_RANGE (0xFFF) // 12 bits + +static const PinMap PinMap_DAC[] = { + {PA_4, DAC_1, STM_PIN_DATA(STM_MODE_ANALOG, GPIO_NOPULL, 0)}, // DAC_OUT + {NC, NC, 0} +}; + +static DAC_HandleTypeDef DacHandle; + +void analogout_init(dac_t *obj, PinName pin) { + DAC_ChannelConfTypeDef sConfig; + + DacHandle.Instance = DAC; + + // Get the peripheral name (DAC_1, ...) from the pin and assign it to the object + obj->dac = (DACName)pinmap_peripheral(pin, PinMap_DAC); + + if (obj->dac == (DACName)NC) { + error("DAC pin mapping failed"); + } + + // Configure GPIO + pinmap_pinout(pin, PinMap_DAC); + + // Save the channel for future use + obj->pin = pin; + + // Enable DAC clock + __DAC_CLK_ENABLE(); + + // Configure DAC + sConfig.DAC_Trigger = DAC_TRIGGER_NONE; + sConfig.DAC_OutputBuffer = DAC_OUTPUTBUFFER_DISABLE; + + HAL_DAC_ConfigChannel(&DacHandle, &sConfig, DAC_CHANNEL_1); + + analogout_write_u16(obj, 0); +} + +void analogout_free(dac_t *obj) { + // Reset DAC and disable clock + __DAC_FORCE_RESET(); + __DAC_RELEASE_RESET(); + __DAC_CLK_DISABLE(); + + // Configure GPIO + pin_function(obj->pin, STM_PIN_DATA(STM_MODE_INPUT, GPIO_NOPULL, 0)); +} + +static inline void dac_write(dac_t *obj, uint16_t value) { + HAL_DAC_SetValue(&DacHandle, DAC_CHANNEL_1, DAC_ALIGN_12B_R, value); + HAL_DAC_Start(&DacHandle, DAC_CHANNEL_1); +} + +static inline int dac_read(dac_t *obj) { + return (int)HAL_DAC_GetValue(&DacHandle, DAC_CHANNEL_1); +} + +void analogout_write(dac_t *obj, float value) { + if (value < 0.0f) { + dac_write(obj, 0); // Min value + } else if (value > 1.0f) { + dac_write(obj, (uint16_t)DAC_RANGE); // Max value + } else { + dac_write(obj, (uint16_t)(value * (float)DAC_RANGE)); + } +} + +void analogout_write_u16(dac_t *obj, uint16_t value) { + if (value > (uint16_t)DAC_RANGE) { + dac_write(obj, (uint16_t)DAC_RANGE); // Max value + } else { + dac_write(obj, value); + } +} + +float analogout_read(dac_t *obj) { + uint32_t value = dac_read(obj); + return (float)((float)value * (1.0f / (float)DAC_RANGE)); +} + +uint16_t analogout_read_u16(dac_t *obj) { + return (uint16_t)dac_read(obj); +} + +#endif // DEVICE_ANALOGOUT diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L053R8/device.h b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L053R8/device.h new file mode 100644 index 0000000000..fd151e3566 --- /dev/null +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L053R8/device.h @@ -0,0 +1,70 @@ +/* mbed Microcontroller Library + ******************************************************************************* + * Copyright (c) 2014, STMicroelectronics + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ******************************************************************************* + */ +#ifndef MBED_DEVICE_H +#define MBED_DEVICE_H + +#define DEVICE_PORTIN 1 +#define DEVICE_PORTOUT 1 +#define DEVICE_PORTINOUT 1 + +#define DEVICE_INTERRUPTIN 1 + +#define DEVICE_ANALOGIN 1 +#define DEVICE_ANALOGOUT 1 + +#define DEVICE_SERIAL 1 + +#define DEVICE_I2C 1 +#define DEVICE_I2CSLAVE 1 + +#define DEVICE_SPI 1 +#define DEVICE_SPISLAVE 1 + +#define DEVICE_RTC 1 + +#define DEVICE_PWMOUT 1 + +#define DEVICE_SLEEP 1 + +//======================================= + +#define DEVICE_SEMIHOST 0 +#define DEVICE_LOCALFILESYSTEM 0 +#define DEVICE_ID_LENGTH 24 + +#define DEVICE_DEBUG_AWARENESS 0 + +#define DEVICE_STDIO_MESSAGES 1 + +#define DEVICE_ERROR_RED 0 + +#include "objects.h" + +#endif diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L053R8/gpio_api.c b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L053R8/gpio_api.c new file mode 100644 index 0000000000..7c2bf1d792 --- /dev/null +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L053R8/gpio_api.c @@ -0,0 +1,71 @@ +/* mbed Microcontroller Library + ******************************************************************************* + * Copyright (c) 2014, STMicroelectronics + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ******************************************************************************* + */ +#include "gpio_api.h" +#include "pinmap.h" +#include "error.h" + +extern uint32_t Set_GPIO_Clock(uint32_t port_idx); + +uint32_t gpio_set(PinName pin) { + if (pin == NC) return 0; + + pin_function(pin, STM_PIN_DATA(STM_MODE_INPUT, GPIO_NOPULL, 0)); + + return (uint32_t)(1 << ((uint32_t)pin & 0xF)); // Return the pin mask +} + +void gpio_init(gpio_t *obj, PinName pin) { + if (pin == NC) return; + + uint32_t port_index = STM_PORT(pin); + + // Enable GPIO clock + uint32_t gpio_add = Set_GPIO_Clock(port_index); + GPIO_TypeDef *gpio = (GPIO_TypeDef *)gpio_add; + + // Fill GPIO object structure for future use + obj->pin = pin; + obj->mask = gpio_set(pin); + obj->reg_in = &gpio->IDR; + obj->reg_set = &gpio->BSRR; + obj->reg_clr = &gpio->BRR; +} + +void gpio_mode(gpio_t *obj, PinMode mode) { + pin_mode(obj->pin, mode); +} + +void gpio_dir(gpio_t *obj, PinDirection direction) { + if (direction == PIN_OUTPUT) { + pin_function(obj->pin, STM_PIN_DATA(STM_MODE_OUTPUT_PP, GPIO_NOPULL, 0)); + } else { // PIN_INPUT + pin_function(obj->pin, STM_PIN_DATA(STM_MODE_INPUT, GPIO_NOPULL, 0)); + } +} diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L053R8/gpio_irq_api.c b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L053R8/gpio_irq_api.c new file mode 100644 index 0000000000..5ee15601c8 --- /dev/null +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L053R8/gpio_irq_api.c @@ -0,0 +1,189 @@ +/* mbed Microcontroller Library + ******************************************************************************* + * Copyright (c) 2014, STMicroelectronics + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ******************************************************************************* + */ +#include +#include "cmsis.h" +#include "gpio_irq_api.h" +#include "pinmap.h" +#include "error.h" + +#define EDGE_NONE (0) +#define EDGE_RISE (1) +#define EDGE_FALL (2) +#define EDGE_BOTH (3) + +#define CHANNEL_NUM (3) + +static uint32_t channel_ids[CHANNEL_NUM] = {0, 0, 0}; +static uint32_t channel_gpio[CHANNEL_NUM] = {0, 0, 0}; +static uint32_t channel_pin[CHANNEL_NUM] = {0, 0, 0}; + +static gpio_irq_handler irq_handler; + +static void handle_interrupt_in(uint32_t irq_index) { + // Retrieve the gpio and pin that generate the irq + GPIO_TypeDef *gpio = (GPIO_TypeDef *)(channel_gpio[irq_index]); + uint32_t pin = (uint32_t)(1 << channel_pin[irq_index]); + + // Clear interrupt flag + if (__HAL_GPIO_EXTI_GET_FLAG(pin) != RESET) { + __HAL_GPIO_EXTI_CLEAR_FLAG(pin); + } + + if (channel_ids[irq_index] == 0) return; + + // Check which edge has generated the irq + if ((gpio->IDR & pin) == 0) { + irq_handler(channel_ids[irq_index], IRQ_FALL); + } else { + irq_handler(channel_ids[irq_index], IRQ_RISE); + } +} + +// The irq_index is passed to the function +// EXTI lines 0 to 1 +static void gpio_irq0(void) { + handle_interrupt_in(0); +} +// EXTI lines 2 to 3 +static void gpio_irq1(void) { + handle_interrupt_in(1); +} +// EXTI lines 4 to 15 +static void gpio_irq2(void) { + handle_interrupt_in(2); +} + +extern uint32_t Set_GPIO_Clock(uint32_t port_idx); + +int gpio_irq_init(gpio_irq_t *obj, PinName pin, gpio_irq_handler handler, uint32_t id) { + IRQn_Type irq_n = (IRQn_Type)0; + uint32_t vector = 0; + uint32_t irq_index; + + if (pin == NC) return -1; + + uint32_t port_index = STM_PORT(pin); + uint32_t pin_index = STM_PIN(pin); + + // Select irq number and interrupt routine + if ((pin_index == 0) || (pin_index == 1)) { + irq_n = EXTI0_1_IRQn; + vector = (uint32_t)&gpio_irq0; + irq_index = 0; + } else if ((pin_index == 2) || (pin_index == 3)) { + irq_n = EXTI2_3_IRQn; + vector = (uint32_t)&gpio_irq1; + irq_index = 1; + } else if ((pin_index > 3) && (pin_index < 16)) { + irq_n = EXTI4_15_IRQn; + vector = (uint32_t)&gpio_irq2; + irq_index = 2; + } else { + error("InterruptIn error: pin not supported.\n"); + return -1; + } + + // Enable GPIO clock + uint32_t gpio_add = Set_GPIO_Clock(port_index); + + // Configure GPIO + pin_function(pin, STM_PIN_DATA(STM_MODE_IT_FALLING, GPIO_NOPULL, 0)); + + // Enable EXTI interrupt + NVIC_SetVector(irq_n, vector); + NVIC_EnableIRQ(irq_n); + + // Save informations for future use + obj->irq_n = irq_n; + obj->irq_index = irq_index; + obj->event = EDGE_NONE; + obj->pin = pin; + channel_ids[irq_index] = id; + channel_gpio[irq_index] = gpio_add; + channel_pin[irq_index] = pin_index; + + irq_handler = handler; + + return 0; +} + +void gpio_irq_free(gpio_irq_t *obj) { + channel_ids[obj->irq_index] = 0; + channel_gpio[obj->irq_index] = 0; + channel_pin[obj->irq_index] = 0; + // Disable EXTI line + pin_function(obj->pin, STM_PIN_DATA(STM_MODE_INPUT, GPIO_NOPULL, 0)); + obj->event = EDGE_NONE; +} + +void gpio_irq_set(gpio_irq_t *obj, gpio_irq_event event, uint32_t enable) { + uint32_t mode = STM_MODE_INPUT; + uint32_t pull = GPIO_NOPULL; + + if (enable) { + + pull = GPIO_NOPULL; + + if (event == IRQ_RISE) { + if ((obj->event == EDGE_FALL) || (obj->event == EDGE_BOTH)) { + mode = STM_MODE_IT_RISING_FALLING; + obj->event = EDGE_BOTH; + } else { // NONE or RISE + mode = STM_MODE_IT_RISING; + obj->event = EDGE_RISE; + } + } + + if (event == IRQ_FALL) { + if ((obj->event == EDGE_RISE) || (obj->event == EDGE_BOTH)) { + mode = STM_MODE_IT_RISING_FALLING; + obj->event = EDGE_BOTH; + } else { // NONE or FALL + mode = STM_MODE_IT_FALLING; + obj->event = EDGE_FALL; + } + } + } else { + mode = STM_MODE_INPUT; + pull = GPIO_NOPULL; + obj->event = EDGE_NONE; + } + + pin_function(obj->pin, STM_PIN_DATA(mode, pull, 0)); +} + +void gpio_irq_enable(gpio_irq_t *obj) { + NVIC_EnableIRQ(obj->irq_n); +} + +void gpio_irq_disable(gpio_irq_t *obj) { + NVIC_DisableIRQ(obj->irq_n); + obj->event = EDGE_NONE; +} diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L053R8/gpio_object.h b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L053R8/gpio_object.h new file mode 100644 index 0000000000..46fdf92515 --- /dev/null +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L053R8/gpio_object.h @@ -0,0 +1,66 @@ +/* mbed Microcontroller Library + ******************************************************************************* + * Copyright (c) 2014, STMicroelectronics + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ******************************************************************************* + */ +#ifndef MBED_GPIO_OBJECT_H +#define MBED_GPIO_OBJECT_H + +#include "cmsis.h" +#include "PortNames.h" +#include "PeripheralNames.h" +#include "PinNames.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef struct { + PinName pin; + uint32_t mask; + __IO uint16_t *reg_in; + __IO uint32_t *reg_set; + __IO uint16_t *reg_clr; +} gpio_t; + +static inline void gpio_write(gpio_t *obj, int value) { + if (value) { + *obj->reg_set = obj->mask; + } else { + *obj->reg_clr = obj->mask; + } +} + +static inline int gpio_read(gpio_t *obj) { + return ((*obj->reg_in & obj->mask) ? 1 : 0); +} + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L053R8/i2c_api.c b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L053R8/i2c_api.c new file mode 100644 index 0000000000..c0e58d0d9b --- /dev/null +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L053R8/i2c_api.c @@ -0,0 +1,383 @@ +/* mbed Microcontroller Library + ******************************************************************************* + * Copyright (c) 2014, STMicroelectronics + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ******************************************************************************* + */ +#include "i2c_api.h" + +#if DEVICE_I2C + +#include "cmsis.h" +#include "pinmap.h" +#include "error.h" + +/* Timeout values for flags and events waiting loops. These timeouts are + not based on accurate values, they just guarantee that the application will + not remain stuck if the I2C communication is corrupted. */ +#define FLAG_TIMEOUT ((int)0x1000) +#define LONG_TIMEOUT ((int)0x8000) + +static const PinMap PinMap_I2C_SDA[] = { + {PB_7, I2C_1, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF1_I2C1)}, + {PB_9, I2C_1, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C1)}, + {PB_11, I2C_2, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF6_I2C2)}, + {PB_14, I2C_2, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF5_I2C2)}, + {NC, NC, 0} +}; + +static const PinMap PinMap_I2C_SCL[] = { + {PB_6, I2C_1, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF1_I2C1)}, + {PB_8, I2C_1, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF4_I2C1)}, + {PB_10, I2C_2, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF6_I2C2)}, + {PB_13, I2C_2, STM_PIN_DATA(STM_MODE_AF_OD, GPIO_NOPULL, GPIO_AF5_I2C2)}, + {NC, NC, 0} +}; + +I2C_HandleTypeDef I2cHandle; + +void i2c_init(i2c_t *obj, PinName sda, PinName scl) { + // Determine the I2C to use + I2CName i2c_sda = (I2CName)pinmap_peripheral(sda, PinMap_I2C_SDA); + I2CName i2c_scl = (I2CName)pinmap_peripheral(scl, PinMap_I2C_SCL); + + obj->i2c = (I2CName)pinmap_merge(i2c_sda, i2c_scl); + + if (obj->i2c == (I2CName)NC) { + error("I2C error: pinout mapping failed."); + } + + // Enable I2C clock + if (obj->i2c == I2C_1) { + __HAL_RCC_I2C1_CONFIG(RCC_I2C1CLKSOURCE_SYSCLK); + __I2C1_CLK_ENABLE(); + } + if (obj->i2c == I2C_2) { + __I2C2_CLK_ENABLE(); + } + + // Configure I2C pins + pinmap_pinout(sda, PinMap_I2C_SDA); + pinmap_pinout(scl, PinMap_I2C_SCL); + pin_mode(sda, OpenDrain); + pin_mode(scl, OpenDrain); + + // Reset to clear pending flags if any + i2c_reset(obj); + + // I2C configuration + i2c_frequency(obj, 100000); // 100 kHz per default +} + +void i2c_frequency(i2c_t *obj, int hz) { + I2cHandle.Instance = (I2C_TypeDef *)(obj->i2c); + + // Common settings: I2C clock = 32 MHz, Analog filter = ON, Digital filter coefficient = 0 + switch (hz) { + case 100000: + I2cHandle.Init.Timing = 0x20602938; // Standard mode with Rise Time = 400ns and Fall Time = 100ns + break; + case 400000: + I2cHandle.Init.Timing = 0x00B0122A; // Fast mode with Rise Time = 250ns and Fall Time = 100ns + break; + case 1000000: + I2cHandle.Init.Timing = 0x0030040E; // Fast mode Plus with Rise Time = 60ns and Fall Time = 100ns + break; + default: + error("Only 100kHz, 400kHz and 1MHz I2C frequencies are supported."); + break; + } + + // I2C configuration + I2cHandle.Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT; + I2cHandle.Init.DualAddressMode = I2C_DUALADDRESS_DISABLED; + I2cHandle.Init.GeneralCallMode = I2C_GENERALCALL_DISABLED; + I2cHandle.Init.NoStretchMode = I2C_NOSTRETCH_DISABLED; + I2cHandle.Init.OwnAddress1 = 0; + I2cHandle.Init.OwnAddress2 = 0; + I2cHandle.Init.OwnAddress2Masks = I2C_OA2_NOMASK; + HAL_I2C_Init(&I2cHandle); +} + +inline int i2c_start(i2c_t *obj) { + I2C_TypeDef *i2c = (I2C_TypeDef *)(obj->i2c); + int timeout; + + I2cHandle.Instance = (I2C_TypeDef *)(obj->i2c); + + // Clear Acknowledge failure flag + __HAL_I2C_CLEAR_FLAG(&I2cHandle, I2C_FLAG_AF); + + // Generate the START condition + i2c->CR2 |= I2C_CR2_START; + + // Wait the START condition has been correctly sent + timeout = FLAG_TIMEOUT; + while (__HAL_I2C_GET_FLAG(&I2cHandle, I2C_FLAG_BUSY) == RESET) { + if ((timeout--) == 0) { + return 1; + } + } + + return 0; +} + +inline int i2c_stop(i2c_t *obj) { + I2C_TypeDef *i2c = (I2C_TypeDef *)(obj->i2c); + + // Generate the STOP condition + i2c->CR2 |= I2C_CR2_STOP; + + return 0; +} + +int i2c_read(i2c_t *obj, int address, char *data, int length, int stop) { + I2C_TypeDef *i2c = (I2C_TypeDef *)(obj->i2c); + I2cHandle.Instance = (I2C_TypeDef *)(obj->i2c); + int timeout; + int count; + int value; + + if (length == 0) return 0; + + /* update CR2 register */ + i2c->CR2 = (i2c->CR2 & (uint32_t)~((uint32_t)(I2C_CR2_SADD | I2C_CR2_NBYTES | I2C_CR2_RELOAD | I2C_CR2_AUTOEND | I2C_CR2_RD_WRN | I2C_CR2_START | I2C_CR2_STOP))) + | (uint32_t)(((uint32_t)address & I2C_CR2_SADD) | (((uint32_t)length << 16) & I2C_CR2_NBYTES) | (uint32_t)I2C_SOFTEND_MODE | (uint32_t)I2C_GENERATE_START_READ); + + // Read all bytes + for (count = 0; count < length; count++) { + value = i2c_byte_read(obj, 0); + data[count] = (char)value; + } + + // Wait transfer complete + timeout = FLAG_TIMEOUT; + while (__HAL_I2C_GET_FLAG(&I2cHandle, I2C_FLAG_TC) == RESET) { + timeout--; + if (timeout == 0) { + return 0; + } + } + + __HAL_I2C_CLEAR_FLAG(&I2cHandle, I2C_FLAG_TC); + + // If not repeated start, send stop. + if (stop) { + i2c_stop(obj); + /* Wait until STOPF flag is set */ + timeout = FLAG_TIMEOUT; + while (__HAL_I2C_GET_FLAG(&I2cHandle, I2C_FLAG_STOPF) == RESET) { + timeout--; + if (timeout == 0) { + return 0; + } + } + /* Clear STOP Flag */ + __HAL_I2C_CLEAR_FLAG(&I2cHandle, I2C_FLAG_STOPF); + } + + return length; +} + +int i2c_write(i2c_t *obj, int address, const char *data, int length, int stop) { + I2C_TypeDef *i2c = (I2C_TypeDef *)(obj->i2c); + I2cHandle.Instance = (I2C_TypeDef *)(obj->i2c); + int timeout; + int count; + + if (length == 0) return 0; + + /* update CR2 register */ + i2c->CR2 = (i2c->CR2 & (uint32_t)~((uint32_t)(I2C_CR2_SADD | I2C_CR2_NBYTES | I2C_CR2_RELOAD | I2C_CR2_AUTOEND | I2C_CR2_RD_WRN | I2C_CR2_START | I2C_CR2_STOP))) + | (uint32_t)(((uint32_t)address & I2C_CR2_SADD) | (((uint32_t)length << 16) & I2C_CR2_NBYTES) | (uint32_t)I2C_SOFTEND_MODE | (uint32_t)I2C_GENERATE_START_WRITE); + + for (count = 0; count < length; count++) { + i2c_byte_write(obj, data[count]); + } + + // Wait transfer complete + timeout = FLAG_TIMEOUT; + while (__HAL_I2C_GET_FLAG(&I2cHandle, I2C_FLAG_TC) == RESET) { + timeout--; + if (timeout == 0) { + return 0; + } + } + + __HAL_I2C_CLEAR_FLAG(&I2cHandle, I2C_FLAG_TC); + + // If not repeated start, send stop. + if (stop) { + i2c_stop(obj); + /* Wait until STOPF flag is set */ + timeout = FLAG_TIMEOUT; + while (__HAL_I2C_GET_FLAG(&I2cHandle, I2C_FLAG_STOPF) == RESET) { + timeout--; + if (timeout == 0) { + return 0; + } + } + /* Clear STOP Flag */ + __HAL_I2C_CLEAR_FLAG(&I2cHandle, I2C_FLAG_STOPF); + } + + return count; +} + +int i2c_byte_read(i2c_t *obj, int last) { + I2C_TypeDef *i2c = (I2C_TypeDef *)(obj->i2c); + int timeout; + + // Wait until the byte is received + timeout = FLAG_TIMEOUT; + while (__HAL_I2C_GET_FLAG(&I2cHandle, I2C_FLAG_RXNE) == RESET) { + if ((timeout--) == 0) { + return 0; + } + } + + return (int)i2c->RXDR; +} + +int i2c_byte_write(i2c_t *obj, int data) { + I2C_TypeDef *i2c = (I2C_TypeDef *)(obj->i2c); + int timeout; + + // Wait until the previous byte is transmitted + timeout = FLAG_TIMEOUT; + while (__HAL_I2C_GET_FLAG(&I2cHandle, I2C_FLAG_TXIS) == RESET) { + if ((timeout--) == 0) { + return 0; + } + } + + i2c->TXDR = (uint8_t)data; + + return 1; +} + +void i2c_reset(i2c_t *obj) { + if (obj->i2c == I2C_1) { + __I2C1_FORCE_RESET(); + __I2C1_RELEASE_RESET(); + } + if (obj->i2c == I2C_2) { + __I2C2_FORCE_RESET(); + __I2C2_RELEASE_RESET(); + } +} + +#if DEVICE_I2CSLAVE + +void i2c_slave_address(i2c_t *obj, int idx, uint32_t address, uint32_t mask) { + I2C_TypeDef *i2c = (I2C_TypeDef *)(obj->i2c); + uint16_t tmpreg; + + // disable + i2c->OAR1 &= (uint32_t)(~I2C_OAR1_OA1EN); + // Get the old register value + tmpreg = i2c->OAR1; + // Reset address bits + tmpreg &= 0xFC00; + // Set new address + tmpreg |= (uint16_t)((uint16_t)address & (uint16_t)0x00FE); // 7-bits + // Store the new register value + i2c->OAR1 = tmpreg; + // enable + i2c->OAR1 |= I2C_OAR1_OA1EN; +} + +void i2c_slave_mode(i2c_t *obj, int enable_slave) { + + I2C_TypeDef *i2c = (I2C_TypeDef *)(obj->i2c); + uint16_t tmpreg; + + // Get the old register value + tmpreg = i2c->OAR1; + + // Enable / disable slave + if (enable_slave == 1) { + tmpreg |= I2C_OAR1_OA1EN; + } else { + tmpreg &= (uint32_t)(~I2C_OAR1_OA1EN); + } + + // Set new mode + i2c->OAR1 = tmpreg; + +} + +// See I2CSlave.h +#define NoData 0 // the slave has not been addressed +#define ReadAddressed 1 // the master has requested a read from this slave (slave = transmitter) +#define WriteGeneral 2 // the master is writing to all slave +#define WriteAddressed 3 // the master is writing to this slave (slave = receiver) + +int i2c_slave_receive(i2c_t *obj) { + I2cHandle.Instance = (I2C_TypeDef *)(obj->i2c); + int retValue = NoData; + + if (__HAL_I2C_GET_FLAG(&I2cHandle, I2C_FLAG_BUSY) == 1) { + if (__HAL_I2C_GET_FLAG(&I2cHandle, I2C_FLAG_ADDR) == 1) { + if (__HAL_I2C_GET_FLAG(&I2cHandle, I2C_FLAG_DIR) == 1) + retValue = ReadAddressed; + else + retValue = WriteAddressed; + __HAL_I2C_CLEAR_FLAG(&I2cHandle, I2C_FLAG_ADDR); + } + } + + return (retValue); +} + +int i2c_slave_read(i2c_t *obj, char *data, int length) { + char size = 0; + + if (length == 0) return 0; + + while (size < length) data[size++] = (char)i2c_byte_read(obj, 0); + + return size; +} + +int i2c_slave_write(i2c_t *obj, const char *data, int length) { + char size = 0; + I2cHandle.Instance = (I2C_TypeDef *)(obj->i2c); + + if (length == 0) return 0; + + do { + i2c_byte_write(obj, data[size]); + size++; + } while (size < length); + + return size; +} + + +#endif // DEVICE_I2CSLAVE + +#endif // DEVICE_I2C diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L053R8/mbed_overrides.c b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L053R8/mbed_overrides.c new file mode 100644 index 0000000000..60d7941d83 --- /dev/null +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L053R8/mbed_overrides.c @@ -0,0 +1,34 @@ +/* mbed Microcontroller Library + * Copyright (c) 2014, STMicroelectronics + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +#include "cmsis.h" + +// This function is called after RAM initialization and before main. +void mbed_sdk_init() { + // Update the SystemCoreClock variable. + SystemCoreClockUpdate(); +} diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L053R8/objects.h b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L053R8/objects.h new file mode 100644 index 0000000000..b5065b6066 --- /dev/null +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L053R8/objects.h @@ -0,0 +1,109 @@ +/* mbed Microcontroller Library + ******************************************************************************* + * Copyright (c) 2014, STMicroelectronics + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ******************************************************************************* + */ +#ifndef MBED_OBJECTS_H +#define MBED_OBJECTS_H + +#include "cmsis.h" +#include "PortNames.h" +#include "PeripheralNames.h" +#include "PinNames.h" + +#ifdef __cplusplus +extern "C" { +#endif + +struct gpio_irq_s { + IRQn_Type irq_n; + uint32_t irq_index; + uint32_t event; + PinName pin; +}; + +struct port_s { + PortName port; + uint32_t mask; + PinDirection direction; + __IO uint16_t *reg_in; + __IO uint16_t *reg_out; +}; + +struct analogin_s { + ADCName adc; + PinName pin; +}; + +struct dac_s { + DACName dac; + PinName pin; +}; + +struct serial_s { + UARTName uart; + int index; // Used by irq + uint32_t baudrate; + uint32_t databits; + uint32_t stopbits; + uint32_t parity; + PinName pin_tx; + PinName pin_rx; +}; + +struct spi_s { + SPIName spi; + uint32_t bits; + uint32_t cpol; + uint32_t cpha; + uint32_t mode; + uint32_t nss; + uint32_t br_presc; + PinName pin_miso; + PinName pin_mosi; + PinName pin_sclk; + PinName pin_ssel; +}; + +struct i2c_s { + I2CName i2c; +}; + +struct pwmout_s { + PWMName pwm; + PinName pin; + uint32_t period; + uint32_t pulse; +}; + +#include "gpio_object.h" + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L053R8/pinmap.c b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L053R8/pinmap.c new file mode 100644 index 0000000000..5024f4ba7a --- /dev/null +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L053R8/pinmap.c @@ -0,0 +1,137 @@ +/* mbed Microcontroller Library + ******************************************************************************* + * Copyright (c) 2014, STMicroelectronics + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ******************************************************************************* + */ +#include "pinmap.h" +#include "PortNames.h" +#include "error.h" + +// GPIO mode look-up table +static const uint32_t gpio_mode[12] = { + 0x00000000, // 0 = GPIO_MODE_INPUT + 0x00000001, // 1 = GPIO_MODE_OUTPUT_PP + 0x00000011, // 2 = GPIO_MODE_OUTPUT_OD + 0x00000002, // 3 = GPIO_MODE_AF_PP + 0x00000012, // 4 = GPIO_MODE_AF_OD + 0x00000003, // 5 = GPIO_MODE_ANALOG + 0x10110000, // 6 = GPIO_MODE_IT_RISING + 0x10210000, // 7 = GPIO_MODE_IT_FALLING + 0x10310000, // 8 = GPIO_MODE_IT_RISING_FALLING + 0x10120000, // 9 = GPIO_MODE_EVT_RISING + 0x10220000, // 10 = GPIO_MODE_EVT_FALLING + 0x10320000 // 11 = GPIO_MODE_EVT_RISING_FALLING +}; + +// Enable GPIO clock and return GPIO base address +uint32_t Set_GPIO_Clock(uint32_t port_idx) { + uint32_t gpio_add = 0; + switch (port_idx) { + case PortA: + gpio_add = GPIOA_BASE; + __GPIOA_CLK_ENABLE(); + break; + case PortB: + gpio_add = GPIOB_BASE; + __GPIOB_CLK_ENABLE(); + break; + case PortC: + gpio_add = GPIOC_BASE; + __GPIOC_CLK_ENABLE(); + break; + case PortD: + gpio_add = GPIOD_BASE; + __GPIOD_CLK_ENABLE(); + break; + case PortH: + gpio_add = GPIOH_BASE; + __GPIOH_CLK_ENABLE(); + break; + default: + error("Pinmap error: wrong port number."); + break; + } + return gpio_add; +} + +/** + * Configure pin (mode, speed, output type and pull-up/pull-down) + */ +void pin_function(PinName pin, int data) { + if (pin == NC) return; + + // Get the pin informations + uint32_t mode = STM_PIN_MODE(data); + uint32_t pupd = STM_PIN_PUPD(data); + uint32_t afnum = STM_PIN_AFNUM(data); + + uint32_t port_index = STM_PORT(pin); + uint32_t pin_index = STM_PIN(pin); + + // Enable GPIO clock + uint32_t gpio_add = Set_GPIO_Clock(port_index); + GPIO_TypeDef *gpio = (GPIO_TypeDef *)gpio_add; + + // Configure GPIO + GPIO_InitTypeDef GPIO_InitStructure; + GPIO_InitStructure.Pin = (uint32_t)(1 << pin_index); + GPIO_InitStructure.Mode = gpio_mode[mode]; + GPIO_InitStructure.Pull = pupd; + GPIO_InitStructure.Speed = GPIO_SPEED_HIGH; + GPIO_InitStructure.Alternate = afnum; + HAL_GPIO_Init(gpio, &GPIO_InitStructure); + + // [TODO] Disconnect JTAG-DP + SW-DP signals. + // Warning: Need to reconnect under reset + //if ((pin == PA_13) || (pin == PA_14)) { + // + //} + //if ((pin == PA_15) || (pin == PB_3) || (pin == PB_4)) { + // + //} +} + +/** + * Configure pin pull-up/pull-down + */ +void pin_mode(PinName pin, PinMode mode) { + if (pin == NC) return; + + uint32_t port_index = STM_PORT(pin); + uint32_t pin_index = STM_PIN(pin); + + // Enable GPIO clock + uint32_t gpio_add = Set_GPIO_Clock(port_index); + GPIO_TypeDef *gpio = (GPIO_TypeDef *)gpio_add; + + // Configure pull-up/pull-down resistors + uint32_t pupd = (uint32_t)mode; + if (pupd > 2) pupd = 0; // Open-drain = No pull-up/No pull-down + gpio->PUPDR &= (uint32_t)(~(GPIO_PUPDR_PUPD0 << (pin_index * 2))); + gpio->PUPDR |= (uint32_t)(pupd << (pin_index * 2)); + +} diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L053R8/port_api.c b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L053R8/port_api.c new file mode 100644 index 0000000000..9a6ad5e5f4 --- /dev/null +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L053R8/port_api.c @@ -0,0 +1,97 @@ +/* mbed Microcontroller Library + ******************************************************************************* + * Copyright (c) 2014, STMicroelectronics + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ******************************************************************************* + */ +#include "port_api.h" +#include "pinmap.h" +#include "gpio_api.h" +#include "error.h" + +#if DEVICE_PORTIN || DEVICE_PORTOUT + +extern uint32_t Set_GPIO_Clock(uint32_t port_idx); + +// high nibble = port number (0=A, 1=B, 2=C, 3=D, 4=E, 5=F, ...) +// low nibble = pin number +PinName port_pin(PortName port, int pin_n) { + return (PinName)(pin_n + (port << 4)); +} + +void port_init(port_t *obj, PortName port, int mask, PinDirection dir) { + uint32_t port_index = (uint32_t)port; + + // Enable GPIO clock + uint32_t gpio_add = Set_GPIO_Clock(port_index); + GPIO_TypeDef *gpio = (GPIO_TypeDef *)gpio_add; + + // Fill PORT object structure for future use + obj->port = port; + obj->mask = mask; + obj->direction = dir; + obj->reg_in = &gpio->IDR; + obj->reg_out = &gpio->ODR; + + port_dir(obj, dir); +} + +void port_dir(port_t *obj, PinDirection dir) { + uint32_t i; + obj->direction = dir; + for (i = 0; i < 16; i++) { // Process all pins + if (obj->mask & (1 << i)) { // If the pin is used + if (dir == PIN_OUTPUT) { + pin_function(port_pin(obj->port, i), STM_PIN_DATA(STM_MODE_OUTPUT_PP, GPIO_NOPULL, 0)); + } else { // PIN_INPUT + pin_function(port_pin(obj->port, i), STM_PIN_DATA(STM_MODE_INPUT, GPIO_NOPULL, 0)); + } + } + } +} + +void port_mode(port_t *obj, PinMode mode) { + uint32_t i; + for (i = 0; i < 16; i++) { // Process all pins + if (obj->mask & (1 << i)) { // If the pin is used + pin_mode(port_pin(obj->port, i), mode); + } + } +} + +void port_write(port_t *obj, int value) { + *obj->reg_out = (*obj->reg_out & ~obj->mask) | (value & obj->mask); +} + +int port_read(port_t *obj) { + if (obj->direction == PIN_OUTPUT) { + return (*obj->reg_out & obj->mask); + } else { // PIN_INPUT + return (*obj->reg_in & obj->mask); + } +} + +#endif diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L053R8/pwmout_api.c b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L053R8/pwmout_api.c new file mode 100644 index 0000000000..202d61dec3 --- /dev/null +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L053R8/pwmout_api.c @@ -0,0 +1,203 @@ +/* mbed Microcontroller Library + ******************************************************************************* + * Copyright (c) 2014, STMicroelectronics + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ******************************************************************************* + */ +#include "pwmout_api.h" + +#if DEVICE_PWMOUT + +#include "cmsis.h" +#include "pinmap.h" +#include "error.h" + +// TIM21 cannot be used because already used by the us_ticker +static const PinMap PinMap_PWM[] = { + {PA_0, PWM_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM2)}, // TIM2_CH1 + {PA_1, PWM_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM2)}, // TIM2_CH2 +// {PA_2, PWM_21, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_TIM21)}, // TIM21_CH1 +// {PA_2, PWM_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM2)}, // TIM2_CH3 - used by STDIO TX +// {PA_3, PWM_21, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_TIM21)}, // TIM21_CH2 +// {PA_3, PWM_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM2)}, // TIM2_CH4 - used by STDIO RX + {PA_5, PWM_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_TIM2)}, // TIM2_CH1 - used also to drive the LED + {PA_6, PWM_22, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_TIM22)}, // TIM22_CH1 + {PA_7, PWM_22, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_TIM22)}, // TIM22_CH2 + {PA_15, PWM_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_TIM2)}, // TIM2_CH1 + {PB_3, PWM_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM2)}, // TIM2_CH2 + {PB_4, PWM_22, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF4_TIM22)}, // TIM22_CH1 + {PB_5, PWM_22, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF4_TIM22)}, // TIM22_CH2 + {PB_10, PWM_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM2)}, // TIM2_CH3 + {PB_11, PWM_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_TIM2)}, // TIM2_CH4 +// {PB_13, PWM_21, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_TIM21)}, // TIM21_CH1 +// {PB_14, PWM_21, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF6_TIM21)}, // TIM21_CH2 + {PC_6, PWM_22, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_TIM22)}, // TIM22_CH1 + {PC_7, PWM_22, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_TIM22)}, // TIM22_CH2 + {NC, NC, 0} +}; + +static TIM_HandleTypeDef TimHandle; + +void pwmout_init(pwmout_t* obj, PinName pin) { + // Get the peripheral name from the pin and assign it to the object + obj->pwm = (PWMName)pinmap_peripheral(pin, PinMap_PWM); + + if (obj->pwm == (PWMName)NC) { + error("PWM error: pinout mapping failed."); + } + + // Enable TIM clock + if (obj->pwm == PWM_2) __TIM2_CLK_ENABLE(); + if (obj->pwm == PWM_21) __TIM21_CLK_ENABLE(); + if (obj->pwm == PWM_22) __TIM22_CLK_ENABLE(); + + // Configure GPIO + pinmap_pinout(pin, PinMap_PWM); + + obj->pin = pin; + obj->period = 0; + obj->pulse = 0; + + pwmout_period_us(obj, 20000); // 20 ms per default +} + +void pwmout_free(pwmout_t* obj) { + // Configure GPIO + pin_function(obj->pin, STM_PIN_DATA(STM_MODE_INPUT, GPIO_NOPULL, 0)); +} + +void pwmout_write(pwmout_t* obj, float value) { + TIM_OC_InitTypeDef sConfig; + int channel = 0; + + TimHandle.Instance = (TIM_TypeDef *)(obj->pwm); + + if (value < (float)0.0) { + value = 0.0; + } else if (value > (float)1.0) { + value = 1.0; + } + + obj->pulse = (uint32_t)((float)obj->period * value); + + // Configure channels + sConfig.OCMode = TIM_OCMODE_PWM1; + sConfig.Pulse = obj->pulse; + sConfig.OCPolarity = TIM_OCPOLARITY_HIGH; + sConfig.OCFastMode = TIM_OCFAST_ENABLE; + + switch (obj->pin) { + // Channels 1 + case PA_0: +// case PA_2: + case PA_5: + case PA_6: + case PA_15: + case PB_4: +// case PB_13: + case PC_6: + channel = TIM_CHANNEL_1; + break; + // Channels 2 + case PA_1: +// case PA_3: + case PA_7: + case PB_3: + case PB_5: +// case PB_14: + case PC_7: + channel = TIM_CHANNEL_2; + break; + // Channels 3 + case PA_2: + case PB_10: + channel = TIM_CHANNEL_3; + break; + // Channels 4 + case PA_3: + case PB_11: + channel = TIM_CHANNEL_4; + break; + default: + return; + } + + HAL_TIM_PWM_ConfigChannel(&TimHandle, &sConfig, channel); + HAL_TIM_PWM_Start(&TimHandle, channel); +} + +float pwmout_read(pwmout_t* obj) { + float value = 0; + if (obj->period > 0) { + value = (float)(obj->pulse) / (float)(obj->period); + } + return ((value > (float)1.0) ? (float)(1.0) : (value)); +} + +void pwmout_period(pwmout_t* obj, float seconds) { + pwmout_period_us(obj, seconds * 1000000.0f); +} + +void pwmout_period_ms(pwmout_t* obj, int ms) { + pwmout_period_us(obj, ms * 1000); +} + +void pwmout_period_us(pwmout_t* obj, int us) { + TimHandle.Instance = (TIM_TypeDef *)(obj->pwm); + + float dc = pwmout_read(obj); + + __HAL_TIM_DISABLE(&TimHandle); + + TimHandle.Init.Period = us - 1; + TimHandle.Init.Prescaler = (uint16_t)(SystemCoreClock / 1000000) - 1; // 1 µs tick + TimHandle.Init.ClockDivision = 0; + TimHandle.Init.CounterMode = TIM_COUNTERMODE_UP; + HAL_TIM_PWM_Init(&TimHandle); + + // Set duty cycle again + pwmout_write(obj, dc); + + // Save for future use + obj->period = us; + + __HAL_TIM_ENABLE(&TimHandle); +} + +void pwmout_pulsewidth(pwmout_t* obj, float seconds) { + pwmout_pulsewidth_us(obj, seconds * 1000000.0f); +} + +void pwmout_pulsewidth_ms(pwmout_t* obj, int ms) { + pwmout_pulsewidth_us(obj, ms * 1000); +} + +void pwmout_pulsewidth_us(pwmout_t* obj, int us) { + float value = (float)us / (float)obj->period; + pwmout_write(obj, value); +} + +#endif diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L053R8/rtc_api.c b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L053R8/rtc_api.c new file mode 100644 index 0000000000..ee7e84242a --- /dev/null +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L053R8/rtc_api.c @@ -0,0 +1,198 @@ +/* mbed Microcontroller Library + ******************************************************************************* + * Copyright (c) 2014, STMicroelectronics + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ******************************************************************************* + */ +#include "rtc_api.h" + +#if DEVICE_RTC + +#include "error.h" + +static int rtc_inited = 0; + +static RTC_HandleTypeDef RtcHandle; + +void rtc_init(void) { + RCC_OscInitTypeDef RCC_OscInitStruct; + uint32_t rtc_freq = 0; + + if (rtc_inited) return; + rtc_inited = 1; + + RtcHandle.Instance = RTC; + + // Enable Power clock + __PWR_CLK_ENABLE(); + + // Enable access to Backup domain + HAL_PWR_EnableBkUpAccess(); + + // Reset Backup domain + __HAL_RCC_BACKUPRESET_FORCE(); + __HAL_RCC_BACKUPRESET_RELEASE(); + + // Enable LSE Oscillator + RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSE; + RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE; /* Mandatory, otherwise the PLL is reconfigured! */ + RCC_OscInitStruct.LSEState = RCC_LSE_ON; /* External 32.768 kHz clock on OSC_IN/OSC_OUT */ + if (HAL_RCC_OscConfig(&RCC_OscInitStruct) == HAL_OK) { + // Connect LSE to RTC + __HAL_RCC_RTC_CLKPRESCALER(RCC_RTCCLKSOURCE_LSE); + __HAL_RCC_RTC_CONFIG(RCC_RTCCLKSOURCE_LSE); + rtc_freq = LSE_VALUE; + } else { + // Enable LSI clock + RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSI | RCC_OSCILLATORTYPE_LSE; + RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE; // Mandatory, otherwise the PLL is reconfigured! + RCC_OscInitStruct.LSEState = RCC_LSE_OFF; + RCC_OscInitStruct.LSIState = RCC_LSI_ON; + if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { + error("RTC error: LSI clock initialization failed."); + } + // Connect LSI to RTC + __HAL_RCC_RTC_CLKPRESCALER(RCC_RTCCLKSOURCE_LSI); + __HAL_RCC_RTC_CONFIG(RCC_RTCCLKSOURCE_LSI); + // [TODO] This value is LSI typical value. To be measured precisely using a timer input capture + rtc_freq = 32000; + } + + // Enable RTC + __HAL_RCC_RTC_ENABLE(); + + RtcHandle.Init.HourFormat = RTC_HOURFORMAT_24; + RtcHandle.Init.AsynchPrediv = 127; + RtcHandle.Init.SynchPrediv = (rtc_freq / 128) - 1; + RtcHandle.Init.OutPut = RTC_OUTPUT_DISABLE; + RtcHandle.Init.OutPutPolarity = RTC_OUTPUT_POLARITY_HIGH; + RtcHandle.Init.OutPutType = RTC_OUTPUT_TYPE_OPENDRAIN; + + if (HAL_RTC_Init(&RtcHandle) != HAL_OK) { + error("RTC error: RTC initialization failed."); + } +} + +void rtc_free(void) { + // Enable Power clock + __PWR_CLK_ENABLE(); + + // Enable access to Backup domain + HAL_PWR_EnableBkUpAccess(); + + // Reset Backup domain + __HAL_RCC_BACKUPRESET_FORCE(); + __HAL_RCC_BACKUPRESET_RELEASE(); + + // Disable access to Backup domain + HAL_PWR_DisableBkUpAccess(); + + // Disable LSI and LSE clocks + RCC_OscInitTypeDef RCC_OscInitStruct; + RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSI | RCC_OSCILLATORTYPE_LSE; + RCC_OscInitStruct.PLL.PLLState = RCC_PLL_NONE; + RCC_OscInitStruct.LSIState = RCC_LSI_OFF; + RCC_OscInitStruct.LSEState = RCC_LSE_OFF; + HAL_RCC_OscConfig(&RCC_OscInitStruct); + + rtc_inited = 0; +} + +int rtc_isenabled(void) { + return rtc_inited; +} + +/* + RTC Registers + RTC_WeekDay 1=monday, 2=tuesday, ..., 7=sunday + RTC_Month 1=january, 2=february, ..., 12=december + RTC_Date day of the month 1-31 + RTC_Year year 0-99 + struct tm + tm_sec seconds after the minute 0-61 + tm_min minutes after the hour 0-59 + tm_hour hours since midnight 0-23 + tm_mday day of the month 1-31 + tm_mon months since January 0-11 + tm_year years since 1900 + tm_wday days since Sunday 0-6 + tm_yday days since January 1 0-365 + tm_isdst Daylight Saving Time flag +*/ +time_t rtc_read(void) { + RTC_DateTypeDef dateStruct; + RTC_TimeTypeDef timeStruct; + struct tm timeinfo; + + RtcHandle.Instance = RTC; + + // Read actual date and time + // Warning: the time must be read first! + HAL_RTC_GetTime(&RtcHandle, &timeStruct, FORMAT_BIN); + HAL_RTC_GetDate(&RtcHandle, &dateStruct, FORMAT_BIN); + + // Setup a tm structure based on the RTC + timeinfo.tm_wday = dateStruct.WeekDay; + timeinfo.tm_mon = dateStruct.Month - 1; + timeinfo.tm_mday = dateStruct.Date; + timeinfo.tm_year = dateStruct.Year + 100; + timeinfo.tm_hour = timeStruct.Hours; + timeinfo.tm_min = timeStruct.Minutes; + timeinfo.tm_sec = timeStruct.Seconds; + + // Convert to timestamp + time_t t = mktime(&timeinfo); + + return t; +} + +void rtc_write(time_t t) { + RTC_DateTypeDef dateStruct; + RTC_TimeTypeDef timeStruct; + + RtcHandle.Instance = RTC; + + // Convert the time into a tm + struct tm *timeinfo = localtime(&t); + + // Fill RTC structures + dateStruct.WeekDay = timeinfo->tm_wday; + dateStruct.Month = timeinfo->tm_mon + 1; + dateStruct.Date = timeinfo->tm_mday; + dateStruct.Year = timeinfo->tm_year - 100; + timeStruct.Hours = timeinfo->tm_hour; + timeStruct.Minutes = timeinfo->tm_min; + timeStruct.Seconds = timeinfo->tm_sec; + timeStruct.TimeFormat = RTC_HOURFORMAT12_PM; + timeStruct.DayLightSaving = RTC_DAYLIGHTSAVING_NONE; + timeStruct.StoreOperation = RTC_STOREOPERATION_RESET; + + // Change the RTC current date/time + HAL_RTC_SetDate(&RtcHandle, &dateStruct, FORMAT_BIN); + HAL_RTC_SetTime(&RtcHandle, &timeStruct, FORMAT_BIN); +} + +#endif diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L053R8/serial_api.c b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L053R8/serial_api.c new file mode 100644 index 0000000000..7d1a9d4594 --- /dev/null +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L053R8/serial_api.c @@ -0,0 +1,346 @@ +/* mbed Microcontroller Library + ******************************************************************************* + * Copyright (c) 2014, STMicroelectronics + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ******************************************************************************* + */ +#include "serial_api.h" + +#if DEVICE_SERIAL + +#include "cmsis.h" +#include "pinmap.h" +#include "error.h" +#include + +static const PinMap PinMap_UART_TX[] = { + {PA_2, UART_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF4_USART2)}, + {PA_9, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF4_USART1)}, + {PA_14, UART_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF4_USART2)}, // Warning: this pin is used by SWCLK + {PB_6, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_USART1)}, + {PB_10, LPUART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF4_LPUART1)}, + {PC_4, LPUART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_LPUART1)}, + {PC_10, LPUART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_LPUART1)}, + {NC, NC, 0} +}; + +static const PinMap PinMap_UART_RX[] = { + {PA_3, UART_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF4_USART2)}, + {PA_10, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF4_USART1)}, + {PA_15, UART_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF4_USART2)}, + {PB_7, UART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_USART1)}, + {PB_11, LPUART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF4_LPUART1)}, + {PC_5, LPUART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_LPUART1)}, + {PC_11, LPUART_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_LPUART1)}, + {NC, NC, 0} +}; + +#define UART_NUM (3) + +static uint32_t serial_irq_ids[UART_NUM] = {0, 0, 0}; + +static uart_irq_handler irq_handler; + +UART_HandleTypeDef UartHandle; + +int stdio_uart_inited = 0; +serial_t stdio_uart; + +static void init_uart(serial_t *obj) { + UartHandle.Instance = (USART_TypeDef *)(obj->uart); + + // [TODO] Workaround to be removed after HAL driver is corrected + if (obj->uart == LPUART_1) { + UartHandle.Init.BaudRate = obj->baudrate >> 1; + } else { + UartHandle.Init.BaudRate = obj->baudrate; + } + UartHandle.Init.WordLength = obj->databits; + UartHandle.Init.StopBits = obj->stopbits; + UartHandle.Init.Parity = obj->parity; + UartHandle.Init.HwFlowCtl = UART_HWCONTROL_NONE; + + if (obj->pin_rx == NC) { + UartHandle.Init.Mode = UART_MODE_TX; + } else if (obj->pin_tx == NC) { + UartHandle.Init.Mode = UART_MODE_RX; + } else { + UartHandle.Init.Mode = UART_MODE_TX_RX; + } + + HAL_UART_Init(&UartHandle); +} + +void serial_init(serial_t *obj, PinName tx, PinName rx) { + // Determine the UART to use (UART_1, UART_2, ...) + UARTName uart_tx = (UARTName)pinmap_peripheral(tx, PinMap_UART_TX); + UARTName uart_rx = (UARTName)pinmap_peripheral(rx, PinMap_UART_RX); + + // Get the peripheral name (UART_1, UART_2, ...) from the pin and assign it to the object + obj->uart = (UARTName)pinmap_merge(uart_tx, uart_rx); + + if (obj->uart == (UARTName)NC) { + error("Serial error: pinout mapping failed."); + } + + // Enable UART clock + if (obj->uart == UART_1) { + __USART1_CLK_ENABLE(); + obj->index = 0; + } + + if (obj->uart == UART_2) { + __USART2_CLK_ENABLE(); + obj->index = 1; + } + + if (obj->uart == LPUART_1) { + __LPUART1_CLK_ENABLE(); + obj->index = 2; + } + + // Configure the UART pins + pinmap_pinout(tx, PinMap_UART_TX); + pinmap_pinout(rx, PinMap_UART_RX); + pin_mode(tx, PullUp); + pin_mode(rx, PullUp); + + // Configure UART + obj->baudrate = 9600; + obj->databits = UART_WORDLENGTH_8B; + obj->stopbits = UART_STOPBITS_1; + obj->parity = UART_PARITY_NONE; + obj->pin_tx = tx; + obj->pin_rx = rx; + + init_uart(obj); + + // For stdio management + if (obj->uart == STDIO_UART) { + stdio_uart_inited = 1; + memcpy(&stdio_uart, obj, sizeof(serial_t)); + } +} + +void serial_free(serial_t *obj) { + // Reset UART and disable clock + if (obj->uart == UART_1) { + __USART1_FORCE_RESET(); + __USART1_RELEASE_RESET(); + __USART1_CLK_DISABLE(); + } + + if (obj->uart == UART_2) { + __USART2_FORCE_RESET(); + __USART2_RELEASE_RESET(); + __USART2_CLK_DISABLE(); + } + + if (obj->uart == LPUART_1) { + __LPUART1_FORCE_RESET(); + __LPUART1_RELEASE_RESET(); + __LPUART1_CLK_DISABLE(); + } + + // Configure GPIOs + pin_function(obj->pin_tx, STM_PIN_DATA(STM_MODE_INPUT, GPIO_NOPULL, 0)); + pin_function(obj->pin_rx, STM_PIN_DATA(STM_MODE_INPUT, GPIO_NOPULL, 0)); + + serial_irq_ids[obj->index] = 0; +} + +void serial_baud(serial_t *obj, int baudrate) { + obj->baudrate = baudrate; + init_uart(obj); +} + +void serial_format(serial_t *obj, int data_bits, SerialParity parity, int stop_bits) { + if (data_bits == 8) { + obj->databits = UART_WORDLENGTH_8B; + } else { + obj->databits = UART_WORDLENGTH_9B; + } + + switch (parity) { + case ParityOdd: + case ParityForced0: + obj->parity = UART_PARITY_ODD; + break; + case ParityEven: + case ParityForced1: + obj->parity = UART_PARITY_EVEN; + break; + default: // ParityNone + obj->parity = UART_PARITY_NONE; + break; + } + + if (stop_bits == 2) { + obj->stopbits = UART_STOPBITS_2; + } else { + obj->stopbits = UART_STOPBITS_1; + } + + init_uart(obj); +} + +/****************************************************************************** + * INTERRUPTS HANDLING + ******************************************************************************/ + +static void uart_irq(UARTName name, int id) { + UartHandle.Instance = (USART_TypeDef *)name; + if (serial_irq_ids[id] != 0) { + if (__HAL_UART_GET_FLAG(&UartHandle, UART_FLAG_TC) != RESET) { + irq_handler(serial_irq_ids[id], TxIrq); + __HAL_UART_CLEAR_IT(&UartHandle, UART_CLEAR_TCF); + } + if (__HAL_UART_GET_FLAG(&UartHandle, UART_FLAG_RXNE) != RESET) { + irq_handler(serial_irq_ids[id], RxIrq); + __HAL_UART_SEND_REQ(&UartHandle, UART_RXDATA_FLUSH_REQUEST); + } + } +} + +static void uart1_irq(void) { + uart_irq(UART_1, 0); +} + +static void uart2_irq(void) { + uart_irq(UART_2, 1); +} + +static void lpuart1_irq(void) { + uart_irq(LPUART_1, 2); +} + +void serial_irq_handler(serial_t *obj, uart_irq_handler handler, uint32_t id) { + irq_handler = handler; + serial_irq_ids[obj->index] = id; +} + +void serial_irq_set(serial_t *obj, SerialIrq irq, uint32_t enable) { + IRQn_Type irq_n = (IRQn_Type)0; + uint32_t vector = 0; + + UartHandle.Instance = (USART_TypeDef *)(obj->uart); + + if (obj->uart == UART_1) { + irq_n = USART1_IRQn; + vector = (uint32_t)&uart1_irq; + } + + if (obj->uart == UART_2) { + irq_n = USART2_IRQn; + vector = (uint32_t)&uart2_irq; + } + + if (obj->uart == LPUART_1) { + irq_n = RNG_LPUART1_IRQn; + vector = (uint32_t)&lpuart1_irq; + } + + if (enable) { + + if (irq == RxIrq) { + __HAL_UART_ENABLE_IT(&UartHandle, UART_IT_RXNE); + } else { // TxIrq + __HAL_UART_ENABLE_IT(&UartHandle, UART_IT_TC); + } + + NVIC_SetVector(irq_n, vector); + NVIC_EnableIRQ(irq_n); + + } else { // disable + + int all_disabled = 0; + + if (irq == RxIrq) { + __HAL_UART_DISABLE_IT(&UartHandle, UART_IT_RXNE); + // Check if TxIrq is disabled too + if ((UartHandle.Instance->CR1 & USART_CR1_TXEIE) == 0) all_disabled = 1; + } else { // TxIrq + __HAL_UART_DISABLE_IT(&UartHandle, UART_IT_TXE); + // Check if RxIrq is disabled too + if ((UartHandle.Instance->CR1 & USART_CR1_RXNEIE) == 0) all_disabled = 1; + } + + if (all_disabled) NVIC_DisableIRQ(irq_n); + + } +} + +/****************************************************************************** + * READ/WRITE + ******************************************************************************/ + +int serial_getc(serial_t *obj) { + USART_TypeDef *uart = (USART_TypeDef *)(obj->uart); + while (!serial_readable(obj)); + return (int)(uart->RDR & 0xFF); +} + +void serial_putc(serial_t *obj, int c) { + USART_TypeDef *uart = (USART_TypeDef *)(obj->uart); + while (!serial_writable(obj)); + uart->TDR = (uint32_t)(c & 0xFF); +} + +int serial_readable(serial_t *obj) { + int status; + UartHandle.Instance = (USART_TypeDef *)(obj->uart); + // Check if data is received + status = ((__HAL_UART_GET_FLAG(&UartHandle, UART_FLAG_RXNE) != RESET) ? 1 : 0); + return status; +} + +int serial_writable(serial_t *obj) { + int status; + UartHandle.Instance = (USART_TypeDef *)(obj->uart); + // Check if data is transmitted + status = ((__HAL_UART_GET_FLAG(&UartHandle, UART_FLAG_TXE) != RESET) ? 1 : 0); + return status; +} + +void serial_clear(serial_t *obj) { + UartHandle.Instance = (USART_TypeDef *)(obj->uart); + __HAL_UART_CLEAR_IT(&UartHandle, UART_CLEAR_TCF); + __HAL_UART_SEND_REQ(&UartHandle, UART_RXDATA_FLUSH_REQUEST); +} + +void serial_pinout_tx(PinName tx) { + pinmap_pinout(tx, PinMap_UART_TX); +} + +void serial_break_set(serial_t *obj) { + UartHandle.Instance = (USART_TypeDef *)(obj->uart); + __HAL_UART_SEND_REQ(&UartHandle, UART_SENDBREAK_REQUEST); +} + +void serial_break_clear(serial_t *obj) { +} + +#endif diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L053R8/sleep.c b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L053R8/sleep.c new file mode 100644 index 0000000000..c8696bcca5 --- /dev/null +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L053R8/sleep.c @@ -0,0 +1,65 @@ +/* mbed Microcontroller Library + ******************************************************************************* + * Copyright (c) 2014, STMicroelectronics + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ******************************************************************************* + */ +#include "sleep_api.h" + +#if DEVICE_SLEEP + +#include "cmsis.h" + +static TIM_HandleTypeDef TimMasterHandle; + +void sleep(void) { + // Disable us_ticker update interrupt + TimMasterHandle.Instance = TIM21; + __HAL_TIM_DISABLE_IT(&TimMasterHandle, TIM_IT_UPDATE); + + // Request to enter SLEEP mode + HAL_PWR_EnterSLEEPMode(PWR_MAINREGULATOR_ON, PWR_SLEEPENTRY_WFI); + + // Re-enable us_ticker update interrupt + __HAL_TIM_ENABLE_IT(&TimMasterHandle, TIM_IT_UPDATE); +} + +void deepsleep(void) { + // Disable us_ticker update interrupt + TimMasterHandle.Instance = TIM21; + __HAL_TIM_DISABLE_IT(&TimMasterHandle, TIM_IT_UPDATE); + + // Request to enter STOP mode with regulator in low power mode + HAL_PWR_EnterSTOPMode(PWR_LOWPOWERREGULATOR_ON, PWR_STOPENTRY_WFI); + + // After wake-up from STOP reconfigure the PLL + SetSysClock(); + + // Re-enable us_ticker update interrupt + __HAL_TIM_ENABLE_IT(&TimMasterHandle, TIM_IT_UPDATE); +} + +#endif diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L053R8/spi_api.c b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L053R8/spi_api.c new file mode 100644 index 0000000000..2ee90a054f --- /dev/null +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L053R8/spi_api.c @@ -0,0 +1,290 @@ +/* mbed Microcontroller Library + ******************************************************************************* + * Copyright (c) 2014, STMicroelectronics + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + ******************************************************************************* + */ +#include "spi_api.h" + +#if DEVICE_SPI + +#include +#include "cmsis.h" +#include "pinmap.h" +#include "error.h" + +static const PinMap PinMap_SPI_MOSI[] = { + {PA_7, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_SPI1)}, + {PA_12, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_SPI1)}, + {PB_5, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_SPI1)}, + {PB_15, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_SPI2)}, + {PC_3, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_SPI2)}, + {NC, NC, 0} +}; + +static const PinMap PinMap_SPI_MISO[] = { + {PA_6, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_SPI1)}, + {PA_11, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_SPI1)}, + {PB_4, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_SPI1)}, + {PB_14, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_SPI2)}, + {PC_2, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF2_SPI2)}, + {NC, NC, 0} +}; + +static const PinMap PinMap_SPI_SCLK[] = { + {PA_5, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_SPI1)}, + {PB_3, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_SPI1)}, + {PB_10, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI2)}, + {PB_13, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_SPI2)}, + {NC, NC, 0} +}; + +static const PinMap PinMap_SPI_SSEL[] = { + {PA_4, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_SPI1)}, + {PA_15, SPI_1, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_SPI1)}, + {PB_9, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF5_SPI2)}, + {PB_12, SPI_2, STM_PIN_DATA(STM_MODE_AF_PP, GPIO_PULLUP, GPIO_AF0_SPI2)}, + {NC, NC, 0} +}; + +static SPI_HandleTypeDef SpiHandle; + +static void init_spi(spi_t *obj) { + SpiHandle.Instance = (SPI_TypeDef *)(obj->spi); + + __HAL_SPI_DISABLE(&SpiHandle); + + SpiHandle.Init.Mode = obj->mode; + SpiHandle.Init.BaudRatePrescaler = obj->br_presc; + SpiHandle.Init.Direction = SPI_DIRECTION_2LINES; + SpiHandle.Init.CLKPhase = obj->cpha; + SpiHandle.Init.CLKPolarity = obj->cpol; + SpiHandle.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLED; + SpiHandle.Init.CRCPolynomial = 7; + SpiHandle.Init.DataSize = obj->bits; + SpiHandle.Init.FirstBit = SPI_FIRSTBIT_MSB; + SpiHandle.Init.NSS = obj->nss; + SpiHandle.Init.TIMode = SPI_TIMODE_DISABLED; + + HAL_SPI_Init(&SpiHandle); + + __HAL_SPI_ENABLE(&SpiHandle); +} + +void spi_init(spi_t *obj, PinName mosi, PinName miso, PinName sclk, PinName ssel) { + // Determine the SPI to use + SPIName spi_mosi = (SPIName)pinmap_peripheral(mosi, PinMap_SPI_MOSI); + SPIName spi_miso = (SPIName)pinmap_peripheral(miso, PinMap_SPI_MISO); + SPIName spi_sclk = (SPIName)pinmap_peripheral(sclk, PinMap_SPI_SCLK); + SPIName spi_ssel = (SPIName)pinmap_peripheral(ssel, PinMap_SPI_SSEL); + + SPIName spi_data = (SPIName)pinmap_merge(spi_mosi, spi_miso); + SPIName spi_cntl = (SPIName)pinmap_merge(spi_sclk, spi_ssel); + + obj->spi = (SPIName)pinmap_merge(spi_data, spi_cntl); + + if (obj->spi == (SPIName)NC) { + error("SPI error: pinout mapping failed."); + } + + // Enable SPI clock + if (obj->spi == SPI_1) { + __SPI1_CLK_ENABLE(); + } + if (obj->spi == SPI_2) { + __SPI2_CLK_ENABLE(); + } + + // Configure the SPI pins + pinmap_pinout(mosi, PinMap_SPI_MOSI); + pinmap_pinout(miso, PinMap_SPI_MISO); + pinmap_pinout(sclk, PinMap_SPI_SCLK); + + // Save new values + obj->bits = SPI_DATASIZE_8BIT; + obj->cpol = SPI_POLARITY_LOW; + obj->cpha = SPI_PHASE_1EDGE; + obj->br_presc = SPI_BAUDRATEPRESCALER_256; + + obj->pin_miso = miso; + obj->pin_mosi = mosi; + obj->pin_sclk = sclk; + obj->pin_ssel = ssel; + + if (ssel == NC) { // SW NSS Master mode + obj->mode = SPI_MODE_MASTER; + obj->nss = SPI_NSS_SOFT; + } else { // Slave + pinmap_pinout(ssel, PinMap_SPI_SSEL); + obj->mode = SPI_MODE_SLAVE; + obj->nss = SPI_NSS_HARD_INPUT; + } + + init_spi(obj); +} + +void spi_free(spi_t *obj) { + // Reset SPI and disable clock + if (obj->spi == SPI_1) { + __SPI1_FORCE_RESET(); + __SPI1_RELEASE_RESET(); + __SPI1_CLK_DISABLE(); + } + + if (obj->spi == SPI_2) { + __SPI2_FORCE_RESET(); + __SPI2_RELEASE_RESET(); + __SPI2_CLK_DISABLE(); + } + + // Configure GPIO + pin_function(obj->pin_miso, STM_PIN_DATA(STM_MODE_INPUT, GPIO_NOPULL, 0)); + pin_function(obj->pin_mosi, STM_PIN_DATA(STM_MODE_INPUT, GPIO_NOPULL, 0)); + pin_function(obj->pin_sclk, STM_PIN_DATA(STM_MODE_INPUT, GPIO_NOPULL, 0)); + pin_function(obj->pin_ssel, STM_PIN_DATA(STM_MODE_INPUT, GPIO_NOPULL, 0)); +} + +void spi_format(spi_t *obj, int bits, int mode, int slave) { + // Save new values + if (bits == 8) { + obj->bits = SPI_DATASIZE_8BIT; + } else { + obj->bits = SPI_DATASIZE_16BIT; + } + + switch (mode) { + case 0: + obj->cpol = SPI_POLARITY_LOW; + obj->cpha = SPI_PHASE_1EDGE; + break; + case 1: + obj->cpol = SPI_POLARITY_LOW; + obj->cpha = SPI_PHASE_2EDGE; + break; + case 2: + obj->cpol = SPI_POLARITY_HIGH; + obj->cpha = SPI_PHASE_1EDGE; + break; + default: + obj->cpol = SPI_POLARITY_HIGH; + obj->cpha = SPI_PHASE_2EDGE; + break; + } + + if (slave == 0) { + obj->mode = SPI_MODE_MASTER; + obj->nss = SPI_NSS_SOFT; + } else { + obj->mode = SPI_MODE_SLAVE; + obj->nss = SPI_NSS_HARD_INPUT; + } + + init_spi(obj); +} + +void spi_frequency(spi_t *obj, int hz) { + // Note: The frequencies are obtained with SPI1 clock = 32 MHz (APB2 clock) + if (hz < 250000) { + obj->br_presc = SPI_BAUDRATEPRESCALER_256; // 125 kHz + } else if ((hz >= 250000) && (hz < 500000)) { + obj->br_presc = SPI_BAUDRATEPRESCALER_128; // 250 kHz + } else if ((hz >= 500000) && (hz < 1000000)) { + obj->br_presc = SPI_BAUDRATEPRESCALER_64; // 500 kHz + } else if ((hz >= 1000000) && (hz < 2000000)) { + obj->br_presc = SPI_BAUDRATEPRESCALER_32; // 1 MHz + } else if ((hz >= 2000000) && (hz < 4000000)) { + obj->br_presc = SPI_BAUDRATEPRESCALER_16; // 2 MHz + } else if ((hz >= 4000000) && (hz < 8000000)) { + obj->br_presc = SPI_BAUDRATEPRESCALER_8; // 4 MHz + } else if ((hz >= 8000000) && (hz < 16000000)) { + obj->br_presc = SPI_BAUDRATEPRESCALER_4; // 8 MHz + } else { // >= 16000000 + obj->br_presc = SPI_BAUDRATEPRESCALER_2; // 16 MHz + } + init_spi(obj); +} + +static inline int ssp_readable(spi_t *obj) { + int status; + SpiHandle.Instance = (SPI_TypeDef *)(obj->spi); + // Check if data is received + status = ((__HAL_SPI_GET_FLAG(&SpiHandle, SPI_FLAG_RXNE) != RESET) ? 1 : 0); + return status; +} + +static inline int ssp_writeable(spi_t *obj) { + int status; + SpiHandle.Instance = (SPI_TypeDef *)(obj->spi); + // Check if data is transmitted + status = ((__HAL_SPI_GET_FLAG(&SpiHandle, SPI_FLAG_TXE) != RESET) ? 1 : 0); + return status; +} + +static inline void ssp_write(spi_t *obj, int value) { + SPI_TypeDef *spi = (SPI_TypeDef *)(obj->spi); + while (!ssp_writeable(obj)); + spi->DR = (uint16_t)value; +} + +static inline int ssp_read(spi_t *obj) { + SPI_TypeDef *spi = (SPI_TypeDef *)(obj->spi); + while (!ssp_readable(obj)); + return (int)spi->DR; +} + +static inline int ssp_busy(spi_t *obj) { + int status; + SpiHandle.Instance = (SPI_TypeDef *)(obj->spi); + status = ((__HAL_SPI_GET_FLAG(&SpiHandle, SPI_FLAG_BSY) != RESET) ? 1 : 0); + return status; +} + +int spi_master_write(spi_t *obj, int value) { + ssp_write(obj, value); + return ssp_read(obj); +} + +int spi_slave_receive(spi_t *obj) { + return (ssp_readable(obj)) ? (1) : (0); +}; + +int spi_slave_read(spi_t *obj) { + SPI_TypeDef *spi = (SPI_TypeDef *)(obj->spi); + while (!ssp_readable(obj)); + return (int)spi->DR; +} + +void spi_slave_write(spi_t *obj, int value) { + SPI_TypeDef *spi = (SPI_TypeDef *)(obj->spi); + while (!ssp_writeable(obj)); + spi->DR = (uint16_t)value; +} + +int spi_busy(spi_t *obj) { + return ssp_busy(obj); +} + +#endif diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L053R8/us_ticker.c b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L053R8/us_ticker.c new file mode 100644 index 0000000000..ec0ec11ed9 --- /dev/null +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L053R8/us_ticker.c @@ -0,0 +1,151 @@ +/* mbed Microcontroller Library + * Copyright (c) 2014, STMicroelectronics + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * 3. Neither the name of STMicroelectronics nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, + * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ +#include +#include "us_ticker_api.h" +#include "PeripheralNames.h" + +// Timer selection: +#define TIM_MST TIM21 +#define TIM_MST_IRQ TIM21_IRQn +#define TIM_MST_RCC __TIM21_CLK_ENABLE() + +static TIM_HandleTypeDef TimMasterHandle; + +static int us_ticker_inited = 0; +static volatile uint32_t SlaveCounter = 0; +static volatile uint32_t oc_int_part = 0; +static volatile uint16_t oc_rem_part = 0; + +void set_compare(uint16_t count) { + // Set new output compare value + __HAL_TIM_SetCompare(&TimMasterHandle, TIM_CHANNEL_1, count); + // Enable IT + __HAL_TIM_ENABLE_IT(&TimMasterHandle, TIM_IT_CC1); +} + +static void tim_irq_handler(void) { + uint16_t cval = TIM_MST->CNT; + + if (__HAL_TIM_GET_ITSTATUS(&TimMasterHandle, TIM_IT_UPDATE) == SET) { + __HAL_TIM_CLEAR_IT(&TimMasterHandle, TIM_IT_UPDATE); + __HAL_TIM_SetCounter(&TimMasterHandle, 0); // Reset counter !!! + SlaveCounter++; + } + + // Clear interrupt flag + if (__HAL_TIM_GET_ITSTATUS(&TimMasterHandle, TIM_IT_CC1) == SET) { + __HAL_TIM_CLEAR_IT(&TimMasterHandle, TIM_IT_CC1); + if (oc_rem_part > 0) { + set_compare(oc_rem_part); // Finish the remaining time left + oc_rem_part = 0; + } else { + if (oc_int_part > 0) { + set_compare(0xFFFF); + oc_rem_part = cval; // To finish the counter loop the next time + oc_int_part--; + } else { + us_ticker_irq_handler(); + } + } + } +} + +void us_ticker_init(void) { + if (us_ticker_inited) return; + us_ticker_inited = 1; + + // Enable timer clock + TIM_MST_RCC; + + // Configure time base + TimMasterHandle.Instance = TIM_MST; + TimMasterHandle.Init.Period = 0xFFFF; + TimMasterHandle.Init.Prescaler = (uint32_t)(SystemCoreClock / 1000000) - 1; // 1 µs tick + TimMasterHandle.Init.ClockDivision = 0; + TimMasterHandle.Init.CounterMode = TIM_COUNTERMODE_UP; + HAL_TIM_Base_Init(&TimMasterHandle); + + // Configure interrupts + __HAL_TIM_ENABLE_IT(&TimMasterHandle, TIM_IT_UPDATE); + + // Update interrupt used for 32-bit counter + // Output compare interrupt used for timeout feature + NVIC_SetVector(TIM_MST_IRQ, (uint32_t)tim_irq_handler); + NVIC_EnableIRQ(TIM_MST_IRQ); + + // Enable timer + HAL_TIM_Base_Start(&TimMasterHandle); +} + +uint32_t us_ticker_read() { + uint32_t counter, counter2; + if (!us_ticker_inited) us_ticker_init(); + // A situation might appear when Master overflows right after Slave is read and before the + // new (overflowed) value of Master is read. Which would make the code below consider the + // previous (incorrect) value of Slave and the new value of Master, which would return a + // value in the past. Avoid this by computing consecutive values of the timer until they + // are properly ordered. + counter = (uint32_t)(SlaveCounter << 16); + counter += TIM_MST->CNT; + while (1) { + counter2 = (uint32_t)(SlaveCounter << 16); + counter2 += TIM_MST->CNT; + if (counter2 > counter) { + break; + } + counter = counter2; + } + return counter2; +} + +void us_ticker_set_interrupt(unsigned int timestamp) { + int delta = (int)(timestamp - us_ticker_read()); + uint16_t cval = TIM_MST->CNT; + + if (delta <= 0) { // This event was in the past + us_ticker_irq_handler(); + } else { + oc_int_part = (uint32_t)(delta >> 16); + oc_rem_part = (uint16_t)(delta & 0xFFFF); + if (oc_rem_part <= (0xFFFF - cval)) { + set_compare(cval + oc_rem_part); + oc_rem_part = 0; + } else { + set_compare(0xFFFF); + oc_rem_part = oc_rem_part - (0xFFFF - cval); + } + } +} + +void us_ticker_disable_interrupt(void) { + __HAL_TIM_DISABLE_IT(&TimMasterHandle, TIM_IT_CC1); +} + +void us_ticker_clear_interrupt(void) { + __HAL_TIM_CLEAR_IT(&TimMasterHandle, TIM_IT_CC1); +} diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L152RE/analogout_api.c b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L152RE/analogout_api.c index 7d579e6b59..16f5ef6746 100644 --- a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L152RE/analogout_api.c +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L152RE/analogout_api.c @@ -54,8 +54,8 @@ void analogout_init(dac_t *obj, PinName pin) { // Configure GPIO pinmap_pinout(pin, PinMap_DAC); - // Save the channel for the write and read functions - obj->channel = pin; + // Save the pin for future use + obj->pin = pin; // Enable DAC clock RCC_APB1PeriphClockCmd(RCC_APB1Periph_DAC, ENABLE); @@ -66,11 +66,11 @@ void analogout_init(dac_t *obj, PinName pin) { DAC_InitStructure.DAC_LFSRUnmask_TriangleAmplitude = DAC_LFSRUnmask_Bit0; DAC_InitStructure.DAC_OutputBuffer = DAC_OutputBuffer_Disable; - if (obj->channel == PA_4) { + if (obj->pin == PA_4) { DAC_Init(DAC_Channel_1, &DAC_InitStructure); DAC_Cmd(DAC_Channel_1, ENABLE); } - if (obj->channel == PA_5) { + if (obj->pin == PA_5) { DAC_Init(DAC_Channel_2, &DAC_InitStructure); DAC_Cmd(DAC_Channel_2, ENABLE); } @@ -79,22 +79,24 @@ void analogout_init(dac_t *obj, PinName pin) { } void analogout_free(dac_t *obj) { + // Configure GPIOs + pin_function(obj->pin, STM_PIN_DATA(GPIO_Mode_IN, 0, GPIO_PuPd_NOPULL, 0xFF)); } static inline void dac_write(dac_t *obj, uint16_t value) { - if (obj->channel == PA_4) { + if (obj->pin == PA_4) { DAC_SetChannel1Data(DAC_Align_12b_R, value); } - if (obj->channel == PA_5) { + if (obj->pin == PA_5) { DAC_SetChannel2Data(DAC_Align_12b_R, value); } } static inline int dac_read(dac_t *obj) { - if (obj->channel == PA_4) { + if (obj->pin == PA_4) { return (int)DAC_GetDataOutputValue(DAC_Channel_1); } - if (obj->channel == PA_5) { + if (obj->pin == PA_5) { return (int)DAC_GetDataOutputValue(DAC_Channel_2); } return 0; diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L152RE/device.h b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L152RE/device.h index d9fad1fedf..fd151e3566 100644 --- a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L152RE/device.h +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L152RE/device.h @@ -42,10 +42,10 @@ #define DEVICE_SERIAL 1 #define DEVICE_I2C 1 -#define DEVICE_I2CSLAVE 0 // Not yet supported +#define DEVICE_I2CSLAVE 1 #define DEVICE_SPI 1 -#define DEVICE_SPISLAVE 0 // Not yet supported +#define DEVICE_SPISLAVE 1 #define DEVICE_RTC 1 diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L152RE/i2c_api.c b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L152RE/i2c_api.c index aef949f047..da67f8f219 100644 --- a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L152RE/i2c_api.c +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L152RE/i2c_api.c @@ -313,7 +313,43 @@ void i2c_slave_mode(i2c_t *obj, int enable_slave) { #define WriteAddressed 3 // the master is writing to this slave (slave = receiver) int i2c_slave_receive(i2c_t *obj) { - return (0); + int retValue = NoData; + uint32_t event; + I2C_TypeDef *i2c = (I2C_TypeDef *)(obj->i2c); + + event = I2C_GetLastEvent(i2c); + if (event != 0) { + switch (event) { + case I2C_EVENT_SLAVE_RECEIVER_ADDRESS_MATCHED: + retValue = WriteAddressed; + break; + case I2C_EVENT_SLAVE_TRANSMITTER_ADDRESS_MATCHED: + retValue = ReadAddressed; + break; + case I2C_EVENT_SLAVE_GENERALCALLADDRESS_MATCHED: + retValue = WriteGeneral; + break; + default: + retValue = NoData; + break; + } + + // clear ADDR + if ((retValue == WriteAddressed) || (retValue == ReadAddressed)) { + i2c->SR1;// read status register 1 + i2c->SR2;// read status register 2 + } + // clear stopf + if (I2C_GetFlagStatus(i2c, I2C_FLAG_STOPF) == SET) { + i2c->SR1;// read status register 1 + I2C_Cmd(i2c, ENABLE); + } + // clear AF + if (I2C_GetFlagStatus(i2c, I2C_FLAG_AF) == SET) { + I2C_ClearFlag(i2c, I2C_FLAG_AF); + } + } + return (retValue); } int i2c_slave_read(i2c_t *obj, char *data, int length) { diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L152RE/objects.h b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L152RE/objects.h index 5b8c7ad918..48c09124c6 100644 --- a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L152RE/objects.h +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L152RE/objects.h @@ -60,7 +60,7 @@ struct analogin_s { struct dac_s { DACName dac; - PinName channel; + PinName pin; }; struct serial_s { @@ -70,6 +70,8 @@ struct serial_s { uint32_t databits; uint32_t stopbits; uint32_t parity; + PinName pin_tx; + PinName pin_rx; }; struct spi_s { @@ -80,6 +82,10 @@ struct spi_s { uint32_t mode; uint32_t nss; uint32_t br_presc; + PinName pin_miso; + PinName pin_mosi; + PinName pin_sclk; + PinName pin_ssel; }; struct i2c_s { diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L152RE/pwmout_api.c b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L152RE/pwmout_api.c index 5b8521e1cf..a9162ad572 100644 --- a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L152RE/pwmout_api.c +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L152RE/pwmout_api.c @@ -102,8 +102,8 @@ void pwmout_init(pwmout_t* obj, PinName pin) { } void pwmout_free(pwmout_t* obj) { - TIM_TypeDef *tim = (TIM_TypeDef *)(obj->pwm); - TIM_DeInit(tim); + // Configure GPIOs + pin_function(obj->pin, STM_PIN_DATA(GPIO_Mode_IN, 0, GPIO_PuPd_NOPULL, 0xFF)); } void pwmout_write(pwmout_t* obj, float value) { diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L152RE/rtc_api.c b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L152RE/rtc_api.c index 12712f5019..8813c246f6 100644 --- a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L152RE/rtc_api.c +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L152RE/rtc_api.c @@ -90,7 +90,16 @@ void rtc_init(void) { } void rtc_free(void) { - RCC_DeInit(); // Resets the RCC clock configuration to the default reset state + // Reset RTC + PWR_RTCAccessCmd(ENABLE); // Enable access to Backup Domain + RTC_DeInit(); + RCC_RTCResetCmd(ENABLE); + RCC_RTCResetCmd(DISABLE); + // Disable RTC, LSE and LSI clocks + RCC_RTCCLKCmd(DISABLE); + RCC_LSEConfig(RCC_LSE_OFF); + RCC_LSICmd(DISABLE); + rtc_inited = 0; } diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L152RE/serial_api.c b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L152RE/serial_api.c index d4b0661c29..dfa8bcc876 100644 --- a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L152RE/serial_api.c +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L152RE/serial_api.c @@ -99,18 +99,23 @@ void serial_init(serial_t *obj, PinName tx, PinName rx) { // Enable USART clock if (obj->uart == UART_1) { RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE); + obj->index = 0; } if (obj->uart == UART_2) { RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE); + obj->index = 1; } if (obj->uart == UART_3) { RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART3, ENABLE); + obj->index = 2; } if (obj->uart == UART_4) { RCC_APB1PeriphClockCmd(RCC_APB1Periph_UART4, ENABLE); + obj->index = 3; } if (obj->uart == UART_5) { RCC_APB1PeriphClockCmd(RCC_APB1Periph_UART5, ENABLE); + obj->index = 4; } // Configure the UART pins @@ -125,14 +130,10 @@ void serial_init(serial_t *obj, PinName tx, PinName rx) { obj->stopbits = USART_StopBits_1; obj->parity = USART_Parity_No; - init_usart(obj); + obj->pin_tx = tx; + obj->pin_rx = rx; - // The index is used by irq - if (obj->uart == UART_1) obj->index = 0; - if (obj->uart == UART_2) obj->index = 1; - if (obj->uart == UART_3) obj->index = 2; - if (obj->uart == UART_4) obj->index = 3; - if (obj->uart == UART_5) obj->index = 4; + init_usart(obj); // For stdio management if (obj->uart == STDIO_UART) { @@ -142,6 +143,37 @@ void serial_init(serial_t *obj, PinName tx, PinName rx) { } void serial_free(serial_t *obj) { + // Reset UART and disable clock + if (obj->uart == UART_1) { + RCC_APB2PeriphResetCmd(RCC_APB2Periph_USART1, ENABLE); + RCC_APB2PeriphResetCmd(RCC_APB2Periph_USART1, DISABLE); + RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, DISABLE); + } + if (obj->uart == UART_2) { + RCC_APB1PeriphResetCmd(RCC_APB1Periph_USART2, ENABLE); + RCC_APB1PeriphResetCmd(RCC_APB1Periph_USART2, DISABLE); + RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, DISABLE); + } + if (obj->uart == UART_3) { + RCC_APB1PeriphResetCmd(RCC_APB1Periph_USART3, ENABLE); + RCC_APB1PeriphResetCmd(RCC_APB1Periph_USART3, DISABLE); + RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART3, DISABLE); + } + if (obj->uart == UART_4) { + RCC_APB1PeriphResetCmd(RCC_APB1Periph_UART4, ENABLE); + RCC_APB1PeriphResetCmd(RCC_APB1Periph_UART4, DISABLE); + RCC_APB1PeriphClockCmd(RCC_APB1Periph_UART4, DISABLE); + } + if (obj->uart == UART_5) { + RCC_APB1PeriphResetCmd(RCC_APB1Periph_UART5, ENABLE); + RCC_APB1PeriphResetCmd(RCC_APB1Periph_UART5, DISABLE); + RCC_APB1PeriphClockCmd(RCC_APB1Periph_UART5, DISABLE); + } + + // Configure GPIOs + pin_function(obj->pin_tx, STM_PIN_DATA(GPIO_Mode_IN, 0, GPIO_PuPd_NOPULL, 0xFF)); + pin_function(obj->pin_rx, STM_PIN_DATA(GPIO_Mode_IN, 0, GPIO_PuPd_NOPULL, 0xFF)); + serial_irq_ids[obj->index] = 0; } diff --git a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L152RE/spi_api.c b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L152RE/spi_api.c index 560447b0b6..44cb74cfad 100644 --- a/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L152RE/spi_api.c +++ b/libraries/mbed/targets/hal/TARGET_STM/TARGET_NUCLEO_L152RE/spi_api.c @@ -132,21 +132,48 @@ void spi_init(spi_t *obj, PinName mosi, PinName miso, PinName sclk, PinName ssel obj->cpha = SPI_CPHA_1Edge; obj->br_presc = SPI_BaudRatePrescaler_256; + obj->pin_miso = miso; + obj->pin_mosi = mosi; + obj->pin_sclk = sclk; + obj->pin_ssel = ssel; + if (ssel == NC) { // Master obj->mode = SPI_Mode_Master; obj->nss = SPI_NSS_Soft; } else { // Slave pinmap_pinout(ssel, PinMap_SPI_SSEL); obj->mode = SPI_Mode_Slave; - obj->nss = SPI_NSS_Soft; + obj->nss = SPI_NSS_Hard; } init_spi(obj); } void spi_free(spi_t *obj) { - SPI_TypeDef *spi = (SPI_TypeDef *)(obj->spi); - SPI_I2S_DeInit(spi); + // Reset SPI and disable clock + if (obj->spi == SPI_1) { + RCC_APB2PeriphResetCmd(RCC_APB2Periph_SPI1, ENABLE); + RCC_APB2PeriphResetCmd(RCC_APB2Periph_SPI1, DISABLE); + RCC_APB2PeriphClockCmd(RCC_APB2Periph_SPI1, DISABLE); + } + + if (obj->spi == SPI_2) { + RCC_APB1PeriphResetCmd(RCC_APB1Periph_SPI2, ENABLE); + RCC_APB1PeriphResetCmd(RCC_APB1Periph_SPI2, DISABLE); + RCC_APB1PeriphClockCmd(RCC_APB1Periph_SPI2, DISABLE); + } + + if (obj->spi == SPI_3) { + RCC_APB1PeriphResetCmd(RCC_APB1Periph_SPI3, ENABLE); + RCC_APB1PeriphResetCmd(RCC_APB1Periph_SPI3, DISABLE); + RCC_APB1PeriphClockCmd(RCC_APB1Periph_SPI3, DISABLE); + } + + // Configure GPIOs + pin_function(obj->pin_miso, STM_PIN_DATA(GPIO_Mode_IN, 0, GPIO_PuPd_NOPULL, 0xFF)); + pin_function(obj->pin_mosi, STM_PIN_DATA(GPIO_Mode_IN, 0, GPIO_PuPd_NOPULL, 0xFF)); + pin_function(obj->pin_sclk, STM_PIN_DATA(GPIO_Mode_IN, 0, GPIO_PuPd_NOPULL, 0xFF)); + pin_function(obj->pin_ssel, STM_PIN_DATA(GPIO_Mode_IN, 0, GPIO_PuPd_NOPULL, 0xFF)); } void spi_format(spi_t *obj, int bits, int mode, int slave) { @@ -270,7 +297,8 @@ int spi_master_write(spi_t *obj, int value) { } int spi_slave_receive(spi_t *obj) { - return (ssp_readable(obj) && !ssp_busy(obj)) ? (1) : (0); + //return (ssp_readable(obj) && !ssp_busy(obj)) ? (1) : (0); // initial code + return (ssp_readable(obj)) ? (1) : (0); // works better like this }; int spi_slave_read(spi_t *obj) { diff --git a/libraries/net/cellular/CellularModem/ip/PPPIPInterface.cpp b/libraries/net/cellular/CellularModem/ip/PPPIPInterface.cpp index 1766868ff5..98614050ef 100644 --- a/libraries/net/cellular/CellularModem/ip/PPPIPInterface.cpp +++ b/libraries/net/cellular/CellularModem/ip/PPPIPInterface.cpp @@ -27,6 +27,7 @@ #include using std::sscanf; +using std::sprintf; #include "PPPIPInterface.h" diff --git a/libraries/net/cellular/CellularModem/sms/CDMASMSInterface.cpp b/libraries/net/cellular/CellularModem/sms/CDMASMSInterface.cpp index c1a87550b0..978b3e1e8b 100644 --- a/libraries/net/cellular/CellularModem/sms/CDMASMSInterface.cpp +++ b/libraries/net/cellular/CellularModem/sms/CDMASMSInterface.cpp @@ -29,6 +29,8 @@ #include #include +using std::sscanf; + #define DEFAULT_TIMEOUT 10000 CDMASMSInterface::CDMASMSInterface(ATCommandsInterface* pIf) : m_pIf(pIf), m_msg(NULL), m_maxMsgLength(0), m_msisdn(NULL) diff --git a/libraries/net/eth/lwip-eth/arch/TARGET_K64F/fsl_enet_driver.c b/libraries/net/eth/lwip-eth/arch/TARGET_K64F/fsl_enet_driver.c index f7fe320506..ea626f92b4 100644 --- a/libraries/net/eth/lwip-eth/arch/TARGET_K64F/fsl_enet_driver.c +++ b/libraries/net/eth/lwip-eth/arch/TARGET_K64F/fsl_enet_driver.c @@ -264,6 +264,13 @@ uint32_t enet_mac_configure_fifo_accel(enet_dev_if_t * enetIfPtr) { return kStatus_ENET_InvalidInput; } + + /* Initialize values that will not be initialized later on */ + rxFifo.rxEmpty = 0; + rxFifo.rxFull = 0; + txFifo.isStoreForwardEnabled = 0; + txFifo.txFifoWrite = 0; + txFifo.txEmpty = 0; /* Configure tx/rx accelerator*/ if (enetIfPtr->macCfgPtr->isRxAccelEnabled) @@ -290,6 +297,16 @@ uint32_t enet_mac_configure_fifo_accel(enet_dev_if_t * enetIfPtr) txFifo.isStoreForwardEnabled = 1; } + + /* Set TFWR value if STRFWD is not being used */ + if (txFifo.isStoreForwardEnabled == 1) + txFifo.txFifoWrite = 0; + else + /* TFWR value is a trade-off between transmit latency and risk of transmit FIFO underrun due to contention for the system bus + TFWR = 15 means transmission will begin once 960 bytes has been written to the Tx FIFO (for frames larger than 960 bytes) + See Section 45.4.18 - Transmit FIFO Watermark Register of the K64F Reference Manual for details */ + txFifo.txFifoWrite = 15; + /* Configure tx/rx FIFO with default value*/ rxFifo.rxAlmostEmpty = 4; rxFifo.rxAlmostFull = 4; diff --git a/libraries/net/eth/lwip-eth/arch/TARGET_K64F/k64f_emac.c b/libraries/net/eth/lwip-eth/arch/TARGET_K64F/k64f_emac.c index b4d252518b..76a7fe4f1a 100644 --- a/libraries/net/eth/lwip-eth/arch/TARGET_K64F/k64f_emac.c +++ b/libraries/net/eth/lwip-eth/arch/TARGET_K64F/k64f_emac.c @@ -110,7 +110,6 @@ static enet_phy_config_t g_enetPhyCfg[HW_ENET_INSTANCE_COUNT] = // K64F-specific macros #define RX_PBUF_AUTO_INDEX (-1) -#define TX_DESC_UPDATED_MASK (0x8000) /******************************************************************************** * Buffer management diff --git a/libraries/net/eth/lwip-eth/arch/TARGET_NXP/lpc17_emac.c b/libraries/net/eth/lwip-eth/arch/TARGET_NXP/lpc17_emac.c index aa6d19d470..ea68e24b0a 100644 --- a/libraries/net/eth/lwip-eth/arch/TARGET_NXP/lpc17_emac.c +++ b/libraries/net/eth/lwip-eth/arch/TARGET_NXP/lpc17_emac.c @@ -138,7 +138,7 @@ struct lpc_enetdata { # if defined (__ICCARM__) # define ETHMEM_SECTION # elif defined(TOOLCHAIN_GCC_CR) -# define ETHMEM_SECTION __attribute__((section(".data.$RamPeriph32"))) +# define ETHMEM_SECTION __attribute__((section(".data.$RamPeriph32"), aligned)) # else # define ETHMEM_SECTION __attribute__((section("AHBSRAM1"),aligned)) # endif diff --git a/libraries/rpc/parse_pins.cpp b/libraries/rpc/parse_pins.cpp index 1e69015c7a..d0779441f6 100644 --- a/libraries/rpc/parse_pins.cpp +++ b/libraries/rpc/parse_pins.cpp @@ -26,7 +26,7 @@ PinName parse_pins(const char *str) { static const PinName pin_names[] = {dp1, dp2, dp4, dp5, dp6, dp9, dp10, dp11 , dp13, dp14, dp15, dp16, dp17, dp18, dp23 , dp24, dp25, dp26, dp27, dp28}; -#elif defined(TARGET_LPC4088) +#elif defined(TARGET_LPC4088) static const PinName pin_names[] = {p5, p6, p7, p8, p9, p10, p11, p12, p13, p14 , p15, p16, p17, p18, p19, p20, NC, NC, p23 , p24, p25, p26, p27, p28, p29, p30, p31, p32 @@ -43,19 +43,19 @@ PinName parse_pins(const char *str) { } return port_pin((PortName)port, pin); -#elif defined(TARGET_KL25Z) || defined(TARGET_K64F) - if (str[0] == 'P' && str[1] == 'T') { // PTx_n - uint32_t port = str[2] - 'A'; - uint32_t pin = str[3] - '0'; // PTxn - uint32_t pin2 = str[4] - '0'; // PTxnn +#elif defined(TARGET_KL25Z) || defined(TARGET_KL05Z) || defined(TARGET_KL46Z) || defined(TARGET_K64F) + if (str[0] == 'P' && str[1] == 'T') { // PTxn + uint32_t port = str[2] - 'A'; + uint32_t pin = str[3] - '0'; // PTxn + uint32_t pin2 = str[4] - '0'; // PTxnn - if (pin2 <= 9) { - pin = pin * 10 + pin2; - } - return port_pin((PortName)port, pin); + if (pin2 <= 9) { + pin = pin * 10 + pin2; + } + return port_pin((PortName)port, pin); #endif -#if defined(TARGET_LPC1768) || defined(TARGET_LPC11U24) || defined(TARGET_LPC2368) +#if defined(TARGET_LPC1768) || defined(TARGET_LPC11U24) || defined(TARGET_LPC2368) } else if (str[0] == 'p') { // pn uint32_t pin = str[1] - '0'; // pn uint32_t pin2 = str[2] - '0'; // pnn @@ -66,7 +66,7 @@ PinName parse_pins(const char *str) { return NC; } return pin_names[pin - 5]; -#elif defined(TARGET_LPC4088) +#elif defined(TARGET_LPC4088) } else if (str[0] == 'p') { // pn uint32_t pin = str[1] - '0'; // pn uint32_t pin2 = str[2] - '0'; // pnn diff --git a/libraries/rtos/rtos/Mail.h b/libraries/rtos/rtos/Mail.h index d3e599fc8b..6ee3c29205 100644 --- a/libraries/rtos/rtos/Mail.h +++ b/libraries/rtos/rtos/Mail.h @@ -42,17 +42,17 @@ public: #ifdef CMSIS_OS_RTX memset(_mail_q, 0, sizeof(_mail_q)); _mail_p[0] = _mail_q; - + memset(_mail_m, 0, sizeof(_mail_m)); _mail_p[1] = _mail_m; - + _mail_def.pool = _mail_p; _mail_def.queue_sz = queue_sz; _mail_def.item_sz = sizeof(T); #endif _mail_id = osMailCreate(&_mail_def, NULL); } - + /** Allocate a memory block of type T @param millisec timeout value or 0 in case of no time-out. (default: 0). @return pointer to memory block that can be filled with mail or NULL in case error. @@ -60,23 +60,23 @@ public: T* alloc(uint32_t millisec=0) { return (T*)osMailAlloc(_mail_id, millisec); } - - /** Allocate a memory block of type T and set memory block to zero. + + /** Allocate a memory block of type T and set memory block to zero. @param millisec timeout value or 0 in case of no time-out. (default: 0). @return pointer to memory block that can be filled with mail or NULL in case error. */ T* calloc(uint32_t millisec=0) { return (T*)osMailCAlloc(_mail_id, millisec); } - + /** Put a mail in the queue. @param mptr memory block previously allocated with Mail::alloc or Mail::calloc. - @return status code that indicates the execution status of the function. + @return status code that indicates the execution status of the function. */ osStatus put(T *mptr) { return osMailPut(_mail_id, (void*)mptr); } - + /** Get a mail from a queue. @param millisec timeout value or 0 in case of no time-out. (default: osWaitForever). @return event that contains mail information or error code. @@ -84,9 +84,9 @@ public: osEvent get(uint32_t millisec=osWaitForever) { return osMailGet(_mail_id, millisec); } - + /** Free a memory block from a mail. - @param mptr pointer to the memory block that was obtained with Mail::get. + @param mptr pointer to the memory block that was obtained with Mail::get. @return status code that indicates the execution status of the function. */ osStatus free(T *mptr) { diff --git a/libraries/rtos/rtos/MemoryPool.h b/libraries/rtos/rtos/MemoryPool.h index db2829b502..d1b812611c 100644 --- a/libraries/rtos/rtos/MemoryPool.h +++ b/libraries/rtos/rtos/MemoryPool.h @@ -41,30 +41,30 @@ public: #ifdef CMSIS_OS_RTX memset(_pool_m, 0, sizeof(_pool_m)); _pool_def.pool = _pool_m; - + _pool_def.pool_sz = pool_sz; _pool_def.item_sz = sizeof(T); #endif _pool_id = osPoolCreate(&_pool_def); } - + /** Allocate a memory block of type T from a memory pool. @return address of the allocated memory block or NULL in case of no memory available. */ T* alloc(void) { return (T*)osPoolAlloc(_pool_id); } - + /** Allocate a memory block of type T from a memory pool and set memory block to zero. - @return address of the allocated memory block or NULL in case of no memory available. + @return address of the allocated memory block or NULL in case of no memory available. */ T* calloc(void) { return (T*)osPoolCAlloc(_pool_id); } - + /** Return an allocated memory block back to a specific memory pool. @param address of the allocated memory block that is returned to the memory pool. - @return status code that indicates the execution status of the function. + @return status code that indicates the execution status of the function. */ osStatus free(T *block) { return osPoolFree(_pool_id, (void*)block); diff --git a/libraries/rtos/rtos/Mutex.h b/libraries/rtos/rtos/Mutex.h index a897836af1..2a8a7fe4be 100644 --- a/libraries/rtos/rtos/Mutex.h +++ b/libraries/rtos/rtos/Mutex.h @@ -34,23 +34,23 @@ class Mutex { public: /** Create and Initialize a Mutex object */ Mutex(); - + /** Wait until a Mutex becomes available. @param millisec timeout value or 0 in case of no time-out. (default: osWaitForever) @return status code that indicates the execution status of the function. - */ + */ osStatus lock(uint32_t millisec=osWaitForever); - + /** Try to lock the mutex, and return immediately @return true if the mutex was acquired, false otherwise. */ bool trylock(); - + /** Unlock the mutex that has previously been locked by the same thread - @return status code that indicates the execution status of the function. + @return status code that indicates the execution status of the function. */ osStatus unlock(); - + ~Mutex(); private: diff --git a/libraries/rtos/rtos/Queue.h b/libraries/rtos/rtos/Queue.h index 6cf1222d3c..f4b316a9b2 100644 --- a/libraries/rtos/rtos/Queue.h +++ b/libraries/rtos/rtos/Queue.h @@ -51,16 +51,16 @@ public: error("Error initialising the queue object\n"); } } - + /** Put a message in a Queue. @param data message pointer. @param millisec timeout value or 0 in case of no time-out. (default: 0) - @return status code that indicates the execution status of the function. + @return status code that indicates the execution status of the function. */ osStatus put(T* data, uint32_t millisec=0) { return osMessagePut(_queue_id, (uint32_t)data, millisec); } - + /** Get a message or Wait for a message from a Queue. @param millisec timeout value or 0 in case of no time-out. (default: osWaitForever). @return event information that includes the message and the status code. diff --git a/libraries/rtos/rtos/RtosTimer.cpp b/libraries/rtos/rtos/RtosTimer.cpp index b68a94428b..2138d3311a 100644 --- a/libraries/rtos/rtos/RtosTimer.cpp +++ b/libraries/rtos/rtos/RtosTimer.cpp @@ -31,7 +31,7 @@ namespace rtos { RtosTimer::RtosTimer(void (*periodic_task)(void const *argument), os_timer_type type, void *argument) { #ifdef CMSIS_OS_RTX _timer.ptimer = periodic_task; - + memset(_timer_data, 0, sizeof(_timer_data)); _timer.timer = _timer_data; #endif diff --git a/libraries/rtos/rtos/RtosTimer.h b/libraries/rtos/rtos/RtosTimer.h index 927cdaec58..9e7004c84d 100644 --- a/libraries/rtos/rtos/RtosTimer.h +++ b/libraries/rtos/rtos/RtosTimer.h @@ -32,7 +32,7 @@ namespace rtos { periodic timers are possible. A timer can be started, restarted, or stopped. Timers are handled in the thread osTimerThread. - Callback functions run under control of this thread and may use CMSIS-RTOS API calls. + Callback functions run under control of this thread and may use CMSIS-RTOS API calls. */ class RtosTimer { public: @@ -44,18 +44,18 @@ public: RtosTimer(void (*task)(void const *argument), os_timer_type type=osTimerPeriodic, void *argument=NULL); - + /** Stop the timer. - @return status code that indicates the execution status of the function. + @return status code that indicates the execution status of the function. */ osStatus stop(void); - + /** start a timer. @param millisec time delay value of the timer. - @return status code that indicates the execution status of the function. + @return status code that indicates the execution status of the function. */ osStatus start(uint32_t millisec); - + ~RtosTimer(); private: diff --git a/libraries/rtos/rtos/Semaphore.h b/libraries/rtos/rtos/Semaphore.h index 253f0a3251..b4d294256a 100644 --- a/libraries/rtos/rtos/Semaphore.h +++ b/libraries/rtos/rtos/Semaphore.h @@ -30,22 +30,22 @@ namespace rtos { /** The Semaphore class is used to manage and protect access to a set of shared resources. */ class Semaphore { public: - /** Create and Initialize a Semaphore object used for managing resources. + /** Create and Initialize a Semaphore object used for managing resources. @param number of available resources; maximum index value is (count-1). */ Semaphore(int32_t count); - - /** Wait until a Semaphore resource becomes available. + + /** Wait until a Semaphore resource becomes available. @param millisec timeout value or 0 in case of no time-out. (default: osWaitForever). @return number of available tokens, or -1 in case of incorrect parameters */ int32_t wait(uint32_t millisec=osWaitForever); - + /** Release a Semaphore resource that was obtain with Semaphore::wait. - @return status code that indicates the execution status of the function. + @return status code that indicates the execution status of the function. */ osStatus release(void); - + ~Semaphore(); private: diff --git a/libraries/rtos/rtos/Thread.h b/libraries/rtos/rtos/Thread.h index 0d9007530e..a8911e966b 100644 --- a/libraries/rtos/rtos/Thread.h +++ b/libraries/rtos/rtos/Thread.h @@ -41,29 +41,29 @@ public: osPriority priority=osPriorityNormal, uint32_t stack_size=DEFAULT_STACK_SIZE, unsigned char *stack_pointer=NULL); - + /** Terminate execution of a thread and remove it from Active Threads @return status code that indicates the execution status of the function. */ osStatus terminate(); - + /** Set priority of an active thread @param priority new priority value for the thread function. @return status code that indicates the execution status of the function. */ osStatus set_priority(osPriority priority); - + /** Get priority of an active thread @return current priority value of the thread function. */ osPriority get_priority(); - + /** Set the specified Signal Flags of an active thread. @param signals specifies the signal flags of the thread that should be set. @return previous signal flags of the specified thread or 0x80000000 in case of incorrect parameters. */ int32_t signal_set(int32_t signals); - + /** State of the Thread */ enum State { Inactive, /**< Not created or terminated */ @@ -77,35 +77,35 @@ public: WaitingMailbox, /**< Waiting for a mailbox event to occur */ WaitingMutex, /**< Waiting for a mutex event to occur */ }; - + /** State of this Thread @return the State of this Thread */ State get_state(); - - /** Wait for one or more Signal Flags to become signaled for the current RUNNING thread. + + /** Wait for one or more Signal Flags to become signaled for the current RUNNING thread. @param signals wait until all specified signal flags set or 0 for any single signal flag. @param millisec timeout value or 0 in case of no time-out. (default: osWaitForever). @return event flag information or error code. */ static osEvent signal_wait(int32_t signals, uint32_t millisec=osWaitForever); - + /** Wait for a specified time period in millisec: @param millisec time delay value - @return status code that indicates the execution status of the function. + @return status code that indicates the execution status of the function. */ static osStatus wait(uint32_t millisec); - + /** Pass control to next thread that is in state READY. @return status code that indicates the execution status of the function. */ static osStatus yield(); - + /** Get the thread id of the current running thread. @return thread ID for reference by other functions or NULL in case of error. */ static osThreadId gettid(); - + virtual ~Thread(); private: diff --git a/libraries/rtos/rtx/HAL_CM.c b/libraries/rtos/rtx/HAL_CM.c index a5a2a9cff2..efbe04c68f 100644 --- a/libraries/rtos/rtx/HAL_CM.c +++ b/libraries/rtos/rtx/HAL_CM.c @@ -15,19 +15,19 @@ * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * - Neither the name of ARM nor the names of its contributors may be used - * to endorse or promote products derived from this software without + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without * specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *---------------------------------------------------------------------------*/ @@ -58,7 +58,7 @@ void rt_init_stack (P_TCB p_TCB, FUNCP task_body) { /* Prepare a complete interrupt frame for first task start */ size = p_TCB->priv_stack >> 2; - + /* Write to the top of stack. */ stk = &p_TCB->stack[size]; @@ -135,7 +135,7 @@ void rt_ret_val2(P_TCB p_TCB, U32 v0, U32 v1) { #ifdef DBG_MSG void dbg_init (void) { - if ((DEMCR & DEMCR_TRCENA) && + if ((DEMCR & DEMCR_TRCENA) && (ITM_CONTROL & ITM_ITMENA) && (ITM_ENABLE & (1UL << 31))) { dbg_msg = __TRUE; diff --git a/libraries/rtos/rtx/RTX_CM_lib.h b/libraries/rtos/rtx/RTX_CM_lib.h index 8c0e2815fc..f9c9904c49 100644 --- a/libraries/rtos/rtx/RTX_CM_lib.h +++ b/libraries/rtos/rtx/RTX_CM_lib.h @@ -152,7 +152,7 @@ osMessageQId osMessageQId_osTimerMessageQ; static uint32_t nr_mutex; /*--------------------------- _mutex_initialize -----------------------------*/ - + int _mutex_initialize (OS_ID *mutex) { /* Allocate and initialize a system mutex. */ @@ -223,6 +223,9 @@ osThreadDef_t os_thread_def_main = {(os_pthread)main, osPriorityNormal, 0, NULL} #elif defined(TARGET_KL46Z) #define INITIAL_SP (0x20006000UL) +#elif defined(TARGET_KL05Z) +#define INITIAL_SP (0x20000C00UL) + #elif defined(TARGET_LPC4088) #define INITIAL_SP (0x10010000UL) @@ -260,7 +263,7 @@ extern unsigned char __end__[]; void set_main_stack(void) { // That is the bottom of the main stack block: no collision detection os_thread_def_main.stack_pointer = HEAP_START; - + // Leave OS_SCHEDULERSTKSIZE words for the scheduler and interrupts os_thread_def_main.stacksize = (INITIAL_SP - (unsigned int)HEAP_START) - (OS_SCHEDULERSTKSIZE * 4); } @@ -279,7 +282,7 @@ void _main_init (void) { /* The single memory model is checking for stack collision at run time, verifing that the heap pointer is underneath the stack pointer. - + With the RTOS there is not only one stack above the heap, there are multiple stacks and some of them are underneath the heap pointer. */ @@ -400,7 +403,7 @@ extern void exit(int arg); __noreturn __stackless void __cmain(void) { int a; - + if (__low_level_init() != 0) { __iar_data_init3(); } diff --git a/libraries/rtos/rtx/RTX_Conf.h b/libraries/rtos/rtx/RTX_Conf.h index 9da2dfe3c6..0b0d4613cd 100644 --- a/libraries/rtos/rtx/RTX_Conf.h +++ b/libraries/rtos/rtx/RTX_Conf.h @@ -15,19 +15,19 @@ * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * - Neither the name of ARM nor the names of its contributors may be used - * to endorse or promote products derived from this software without + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without * specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *---------------------------------------------------------------------------*/ diff --git a/libraries/rtos/rtx/RTX_Conf_CM.c b/libraries/rtos/rtx/RTX_Conf_CM.c index 20ef627ef3..d9da204c5c 100644 --- a/libraries/rtos/rtx/RTX_Conf_CM.c +++ b/libraries/rtos/rtx/RTX_Conf_CM.c @@ -15,19 +15,19 @@ * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * - Neither the name of ARM nor the names of its contributors may be used - * to endorse or promote products derived from this software without + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without * specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *---------------------------------------------------------------------------*/ @@ -53,7 +53,7 @@ || defined(TARGET_KL46Z) || defined(TARGET_STM32F407) || defined(TARGET_F407VG) || defined(TARGET_STM32F303VC) || defined(TARGET_LPC1549) || defined(TARGET_LPC11U68) # define OS_TASKCNT 14 # elif defined(TARGET_LPC11U24) || defined(TARGET_LPC11U35_401) || defined(TARGET_LPC11U35_501) || defined(TARGET_LPC1114) \ - || defined(TARGET_LPC812) || defined(TARGET_KL25Z) || defined(TARGET_STM32F100RB) || defined(TARGET_STM32F051R8) + || defined(TARGET_LPC812) || defined(TARGET_KL25Z) || defined(TARGET_KL05Z) || defined(TARGET_STM32F100RB) || defined(TARGET_STM32F051R8) # define OS_TASKCNT 6 # else # error "no target defined" @@ -66,7 +66,7 @@ || defined(TARGET_KL46Z) || defined(TARGET_STM32F407) || defined(TARGET_F407VG) || defined(TARGET_STM32F303VC) || defined(TARGET_LPC1549) || defined(TARGET_LPC11U68) # define OS_SCHEDULERSTKSIZE 256 # elif defined(TARGET_LPC11U24) || defined(TARGET_LPC11U35_401) || defined(TARGET_LPC11U35_501) || defined(TARGET_LPC1114) \ - || defined(TARGET_LPC812) || defined(TARGET_KL25Z) || defined(TARGET_STM32F100RB) || defined(TARGET_STM32F051R8) + || defined(TARGET_LPC812) || defined(TARGET_KL25Z) || defined(TARGET_KL05Z) || defined(TARGET_STM32F100RB) || defined(TARGET_STM32F051R8) # define OS_SCHEDULERSTKSIZE 128 # else # error "no target defined" @@ -93,8 +93,8 @@ #define OS_STKCHECK 1 #endif -// Processor mode for thread execution -// <0=> Unprivileged mode +// Processor mode for thread execution +// <0=> Unprivileged mode // <1=> Privileged mode // Default: Privileged mode #ifndef OS_RUNPRIV @@ -115,7 +115,7 @@ # elif defined(TARGET_LPC1347) || defined(TARGET_STM32F303VC) || defined(TARGET_LPC1549) # define OS_CLOCK 72000000 -# elif defined(TARGET_LPC11U24) || defined(TARGET_LPC11U35_401) || defined(TARGET_LPC11U35_501) || defined(TARGET_LPC1114) || defined(TARGET_KL25Z) || defined(TARGET_KL46Z) || defined(TARGET_STM32F051R8) || defined(TARGET_LPC11U68) +# elif defined(TARGET_LPC11U24) || defined(TARGET_LPC11U35_401) || defined(TARGET_LPC11U35_501) || defined(TARGET_LPC1114) || defined(TARGET_KL25Z) || defined(TARGET_KL05Z) || defined(TARGET_KL46Z) || defined(TARGET_STM32F051R8) || defined(TARGET_LPC11U68) # define OS_CLOCK 48000000 # elif defined(TARGET_LPC812) @@ -211,7 +211,7 @@ // Standard library system mutexes // =============================== -// Define max. number system mutexes that are used to protect +// Define max. number system mutexes that are used to protect // the arm standard runtime library. For microlib they are not used. #ifndef OS_MUTEXCNT #define OS_MUTEXCNT 12 @@ -230,7 +230,7 @@ void os_idle_demon (void) { /* The idle demon is a system thread, running when no other thread is */ /* ready to run. */ - + /* Sleep: ideally, we should put the chip to sleep. Unfortunately, this usually requires disconnecting the interface chip (debugger). This can be done, but it would break the local file system. diff --git a/libraries/rtos/rtx/TARGET_M0/TOOLCHAIN_ARM/HAL_CM0.c b/libraries/rtos/rtx/TARGET_M0/TOOLCHAIN_ARM/HAL_CM0.c index 783e908b63..492e94a197 100644 --- a/libraries/rtos/rtx/TARGET_M0/TOOLCHAIN_ARM/HAL_CM0.c +++ b/libraries/rtos/rtx/TARGET_M0/TOOLCHAIN_ARM/HAL_CM0.c @@ -15,19 +15,19 @@ * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * - Neither the name of ARM nor the names of its contributors may be used - * to endorse or promote products derived from this software without + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without * specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *---------------------------------------------------------------------------*/ @@ -145,7 +145,7 @@ __asm void SVC_Handler (void) { LDMIA R0,{R0-R3,R4} ; Read R0-R3,R12 from stack MOV R12,R4 MOV R4,LR - BLX R12 ; Call SVC Function + BLX R12 ; Call SVC Function MRS R3,PSP ; Read PSP STMIA R3!,{R0-R2} ; Store return values @@ -161,14 +161,14 @@ __asm void SVC_Handler (void) { MRS R0,PSP ; Read PSP SUBS R0,R0,#32 ; Adjust Start Address - STR R0,[R1,#TCB_TSTACK] ; Update os_tsk.run->tsk_stack + STR R0,[R1,#TCB_TSTACK] ; Update os_tsk.run->tsk_stack STMIA R0!,{R4-R7} ; Save old context (R4-R7) MOV R4,R8 MOV R5,R9 MOV R6,R10 MOV R7,R11 STMIA R0!,{R4-R7} ; Save old context (R8-R11) - + PUSH {R2,R3} BL rt_stk_check ; Check for Stack overflow POP {R2,R3} @@ -243,7 +243,7 @@ Sys_Switch MOV R6,R10 MOV R7,R11 STMIA R0!,{R4-R7} ; Save old context (R8-R11) - + PUSH {R2,R3} BL rt_stk_check ; Check for Stack overflow POP {R2,R3} diff --git a/libraries/rtos/rtx/TARGET_M0P/TOOLCHAIN_ARM/HAL_CM0.c b/libraries/rtos/rtx/TARGET_M0P/TOOLCHAIN_ARM/HAL_CM0.c index 783e908b63..492e94a197 100644 --- a/libraries/rtos/rtx/TARGET_M0P/TOOLCHAIN_ARM/HAL_CM0.c +++ b/libraries/rtos/rtx/TARGET_M0P/TOOLCHAIN_ARM/HAL_CM0.c @@ -15,19 +15,19 @@ * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * - Neither the name of ARM nor the names of its contributors may be used - * to endorse or promote products derived from this software without + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without * specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *---------------------------------------------------------------------------*/ @@ -145,7 +145,7 @@ __asm void SVC_Handler (void) { LDMIA R0,{R0-R3,R4} ; Read R0-R3,R12 from stack MOV R12,R4 MOV R4,LR - BLX R12 ; Call SVC Function + BLX R12 ; Call SVC Function MRS R3,PSP ; Read PSP STMIA R3!,{R0-R2} ; Store return values @@ -161,14 +161,14 @@ __asm void SVC_Handler (void) { MRS R0,PSP ; Read PSP SUBS R0,R0,#32 ; Adjust Start Address - STR R0,[R1,#TCB_TSTACK] ; Update os_tsk.run->tsk_stack + STR R0,[R1,#TCB_TSTACK] ; Update os_tsk.run->tsk_stack STMIA R0!,{R4-R7} ; Save old context (R4-R7) MOV R4,R8 MOV R5,R9 MOV R6,R10 MOV R7,R11 STMIA R0!,{R4-R7} ; Save old context (R8-R11) - + PUSH {R2,R3} BL rt_stk_check ; Check for Stack overflow POP {R2,R3} @@ -243,7 +243,7 @@ Sys_Switch MOV R6,R10 MOV R7,R11 STMIA R0!,{R4-R7} ; Save old context (R8-R11) - + PUSH {R2,R3} BL rt_stk_check ; Check for Stack overflow POP {R2,R3} diff --git a/libraries/rtos/rtx/TARGET_M3/TOOLCHAIN_ARM/HAL_CM3.c b/libraries/rtos/rtx/TARGET_M3/TOOLCHAIN_ARM/HAL_CM3.c index 93764ba063..feb1457913 100644 --- a/libraries/rtos/rtx/TARGET_M3/TOOLCHAIN_ARM/HAL_CM3.c +++ b/libraries/rtos/rtx/TARGET_M3/TOOLCHAIN_ARM/HAL_CM3.c @@ -15,19 +15,19 @@ * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * - Neither the name of ARM nor the names of its contributors may be used - * to endorse or promote products derived from this software without + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without * specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *---------------------------------------------------------------------------*/ @@ -130,7 +130,7 @@ __asm void SVC_Handler (void) { CBNZ R1,SVC_User LDM R0,{R0-R3,R12} ; Read R0-R3,R12 from stack - BLX R12 ; Call SVC Function + BLX R12 ; Call SVC Function MRS R12,PSP ; Read PSP STM R12,{R0-R2} ; Store return values diff --git a/libraries/rtos/rtx/TARGET_M4/TOOLCHAIN_ARM/HAL_CM4.c b/libraries/rtos/rtx/TARGET_M4/TOOLCHAIN_ARM/HAL_CM4.c index 9c388c173a..32327d83d0 100644 --- a/libraries/rtos/rtx/TARGET_M4/TOOLCHAIN_ARM/HAL_CM4.c +++ b/libraries/rtos/rtx/TARGET_M4/TOOLCHAIN_ARM/HAL_CM4.c @@ -15,19 +15,19 @@ * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * - Neither the name of ARM nor the names of its contributors may be used - * to endorse or promote products derived from this software without + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without * specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *---------------------------------------------------------------------------*/ @@ -126,7 +126,7 @@ __asm void SVC_Handler (void) { #ifdef IFX_XMC4XXX EXPORT SVC_Handler_Veneer -SVC_Handler_Veneer +SVC_Handler_Veneer #endif MRS R0,PSP ; Read PSP @@ -136,7 +136,7 @@ SVC_Handler_Veneer LDM R0,{R0-R3,R12} ; Read R0-R3,R12 from stack PUSH {R4,LR} ; Save EXC_RETURN - BLX R12 ; Call SVC Function + BLX R12 ; Call SVC Function POP {R4,LR} ; Restore EXC_RETURN MRS R12,PSP ; Read PSP @@ -216,7 +216,7 @@ __asm void PendSV_Handler (void) { #ifdef IFX_XMC4XXX EXPORT PendSV_Handler_Veneer -PendSV_Handler_Veneer +PendSV_Handler_Veneer #endif PUSH {R4,LR} ; Save EXC_RETURN @@ -278,7 +278,7 @@ __asm void SysTick_Handler (void) { #ifdef IFX_XMC4XXX EXPORT SysTick_Handler_Veneer -SysTick_Handler_Veneer +SysTick_Handler_Veneer #endif PUSH {R4,LR} ; Save EXC_RETURN diff --git a/libraries/rtos/rtx/cmsis_os.h b/libraries/rtos/rtx/cmsis_os.h index 7890789506..f19a7239b8 100644 --- a/libraries/rtos/rtx/cmsis_os.h +++ b/libraries/rtos/rtx/cmsis_os.h @@ -1,14 +1,14 @@ -/* ---------------------------------------------------------------------- - * Copyright (C) 2012 ARM Limited. All rights reserved. - * +/* ---------------------------------------------------------------------- + * Copyright (C) 2012 ARM Limited. All rights reserved. + * * $Date: 5. June 2012 * $Revision: V1.01 - * + * * Project: CMSIS-RTOS API * Title: cmsis_os.h RTX header file - * + * * Version 0.02 - * Initial Proposal Phase + * Initial Proposal Phase * Version 0.03 * osKernelStart added, optional feature: main started as thread * osSemaphores have standard behavior @@ -16,11 +16,11 @@ * osThreadPass is renamed to osThreadYield * Version 1.01 * Support for C++ interface - * - const attribute removed from the osXxxxDef_t typedef's + * - const attribute removed from the osXxxxDef_t typedef's * - const attribute added to the osXxxxDef macros * Added: osTimerDelete, osMutexDelete, osSemaphoreDelete * Added: osKernelInitialize - * -------------------------------------------------------------------- */ + * -------------------------------------------------------------------- */ /** \page cmsis_os_h Header File Template: cmsis_os.h @@ -41,8 +41,8 @@ The file cmsis_os.h contains: All definitions are prefixed with \b os to give an unique name space for CMSIS-RTOS functions. Definitions that are prefixed \b os_ are not used in the application code but local to this header file. All definitions and functions that belong to a module are grouped and have a common prefix, i.e. \b osThread. - -Definitions that are marked with CAN BE CHANGED can be adapted towards the needs of the actual CMSIS-RTOS implementation. + +Definitions that are marked with CAN BE CHANGED can be adapted towards the needs of the actual CMSIS-RTOS implementation. These definitions can be specific to the underlying RTOS kernel. Definitions that are marked with MUST REMAIN UNCHANGED cannot be altered. Otherwise the CMSIS-RTOS implementation is no longer @@ -58,7 +58,7 @@ The following CMSIS-RTOS functions can be called from threads and interrupt serv - \ref osMessagePut, \ref osMessageGet - \ref osMailAlloc, \ref osMailCAlloc, \ref osMailGet, \ref osMailPut, \ref osMailFree -Functions that cannot be called from an ISR are verifying the interrupt status and return in case that they are called +Functions that cannot be called from an ISR are verifying the interrupt status and return in case that they are called from an ISR context the status code \b osErrorISR. In some implementations this condition might be caught using the HARD FAULT vector. Some CMSIS-RTOS implementations support CMSIS-RTOS function calls from multiple ISR at the same time. @@ -79,11 +79,11 @@ extern void thread_sample (void const *argument); // function protot osThreadDef (thread_sample, osPriorityBelowNormal, 1, 100); // Pool definition -osPoolDef(MyPool, 10, long); +osPoolDef(MyPool, 10, long); \endcode -This header file defines all objects when included in a C/C++ source file. When \#define osObjectsExternal is +This header file defines all objects when included in a C/C++ source file. When \#define osObjectsExternal is present before the header file, the objects are defined as external symbols. A single consistent header file can therefore be used throughout the whole project. @@ -98,7 +98,7 @@ used throughout the whole project. \endcode */ - + #ifndef _CMSIS_OS_H #define _CMSIS_OS_H @@ -159,7 +159,7 @@ typedef enum { osPriorityBelowNormal = -1, ///< priority: below normal osPriorityNormal = 0, ///< priority: normal (default) osPriorityAboveNormal = +1, ///< priority: above normal - osPriorityHigh = +2, ///< priority: high + osPriorityHigh = +2, ///< priority: high osPriorityRealtime = +3, ///< priority: realtime (highest) osPriorityError = 0x84 ///< system cannot determine priority or thread has illegal priority } osPriority; @@ -186,23 +186,23 @@ typedef enum { osErrorValue = 0x86, ///< value of a parameter is out of range. osErrorOS = 0xFF, ///< unspecified RTOS error: run-time error but no other error message fits. os_status_reserved = 0x7FFFFFFF ///< prevent from enum down-size compiler optimization. -} osStatus; +} osStatus; /// Timer type value for the timer definition. /// \note MUST REMAIN UNCHANGED: \b os_timer_type shall be consistent in every CMSIS-RTOS. typedef enum { - osTimerOnce = 0, ///< one-shot timer - osTimerPeriodic = 1 ///< repeating timer -} os_timer_type; + osTimerOnce = 0, ///< one-shot timer + osTimerPeriodic = 1 ///< repeating timer +} os_timer_type; /// Entry point of a thread. /// \note MUST REMAIN UNCHANGED: \b os_pthread shall be consistent in every CMSIS-RTOS. -typedef void (*os_pthread) (void const *argument); +typedef void (*os_pthread) (void const *argument); /// Entry point of a timer call back function. /// \note MUST REMAIN UNCHANGED: \b os_ptimer shall be consistent in every CMSIS-RTOS. -typedef void (*os_ptimer) (void const *argument); +typedef void (*os_ptimer) (void const *argument); // >>> the following data type definitions may shall adapted towards a specific RTOS @@ -268,7 +268,7 @@ typedef struct os_semaphore_def { /// \note CAN BE CHANGED: \b os_pool_def is implementation specific in every CMSIS-RTOS. typedef struct os_pool_def { uint32_t pool_sz; ///< number of items (elements) in the pool - uint32_t item_sz; ///< size of an item + uint32_t item_sz; ///< size of an item void *pool; ///< pointer to memory for pool } osPoolDef_t; @@ -283,23 +283,23 @@ typedef struct os_messageQ_def { /// \note CAN BE CHANGED: \b os_mailQ_def is implementation specific in every CMSIS-RTOS. typedef struct os_mailQ_def { uint32_t queue_sz; ///< number of elements in the queue - uint32_t item_sz; ///< size of an item + uint32_t item_sz; ///< size of an item void *pool; ///< memory array for mail } osMailQDef_t; -/// Event structure contains detailed information about an event. -/// \note MUST REMAIN UNCHANGED: \b os_event shall be consistent in every CMSIS-RTOS. +/// Event structure contains detailed information about an event. +/// \note MUST REMAIN UNCHANGED: \b os_event shall be consistent in every CMSIS-RTOS. /// However the struct may be extended at the end. typedef struct { osStatus status; ///< status code: event or error information union { - uint32_t v; ///< message as 32-bit value + uint32_t v; ///< message as 32-bit value void *p; ///< message or mail as void pointer - int32_t signals; ///< signal flags + int32_t signals; ///< signal flags } value; ///< event value union { - osMailQId mail_id; ///< mail id obtained by \ref osMailCreate - osMessageQId message_id; ///< message id obtained by \ref osMessageCreate + osMailQId mail_id; ///< mail id obtained by \ref osMailCreate + osMessageQId message_id; ///< message id obtained by \ref osMessageCreate } def; ///< event definition } osEvent; @@ -308,16 +308,16 @@ typedef struct { /// Initialize the RTOS Kernel for creating objects. /// \return status code that indicates the execution status of the function. -/// \note MUST REMAIN UNCHANGED: \b osKernelInitialize shall be consistent in every CMSIS-RTOS. +/// \note MUST REMAIN UNCHANGED: \b osKernelInitialize shall be consistent in every CMSIS-RTOS. osStatus osKernelInitialize (void); /// Start the RTOS Kernel. /// \return status code that indicates the execution status of the function. -/// \note MUST REMAIN UNCHANGED: \b osKernelStart shall be consistent in every CMSIS-RTOS. +/// \note MUST REMAIN UNCHANGED: \b osKernelStart shall be consistent in every CMSIS-RTOS. osStatus osKernelStart (void); /// Check if the RTOS kernel is already started. -/// \note MUST REMAIN UNCHANGED: \b osKernelRunning shall be consistent in every CMSIS-RTOS. +/// \note MUST REMAIN UNCHANGED: \b osKernelRunning shall be consistent in every CMSIS-RTOS. /// \return 0 RTOS is not started, 1 RTOS is started. int32_t osKernelRunning(void); @@ -328,7 +328,7 @@ int32_t osKernelRunning(void); /// \param name name of the thread function. /// \param priority initial priority of the thread function. /// \param stacksz stack size (in bytes) requirements for the thread function. -/// \note CAN BE CHANGED: The parameters to \b osThreadDef shall be consistent but the +/// \note CAN BE CHANGED: The parameters to \b osThreadDef shall be consistent but the /// macro body is implementation specific in every CMSIS-RTOS. #if defined (osObjectsExternal) // object is external #define osThreadDef(name, priority, stacksz) \ @@ -342,7 +342,7 @@ osThreadDef_t os_thread_def_##name = \ /// Access a Thread definition. /// \param name name of the thread definition object. -/// \note CAN BE CHANGED: The parameter to \b osThread shall be consistent but the +/// \note CAN BE CHANGED: The parameter to \b osThread shall be consistent but the /// macro body is implementation specific in every CMSIS-RTOS. #define osThread(name) \ &os_thread_def_##name @@ -370,7 +370,7 @@ osStatus osThreadTerminate (osThreadId thread_id); /// \note MUST REMAIN UNCHANGED: \b osThreadYield shall be consistent in every CMSIS-RTOS. osStatus osThreadYield (void); -/// Change priority of an active thread. +/// Change priority of an active thread. /// \param[in] thread_id thread ID obtained by \ref osThreadCreate or \ref osThreadGetId. /// \param[in] priority new priority value for the thread function. /// \return status code that indicates the execution status of the function. @@ -387,7 +387,7 @@ osPriority osThreadGetPriority (osThreadId thread_id); // ==== Generic Wait Functions ==== /// Wait for Timeout (Time Delay). -/// \param[in] millisec time delay value +/// \param[in] millisec time delay value /// \return status code that indicates the execution status of the function. osStatus osDelay (uint32_t millisec); @@ -406,7 +406,7 @@ os_InRegs osEvent osWait (uint32_t millisec); /// Define a Timer object. /// \param name name of the timer object. /// \param function name of the timer call back function. -/// \note CAN BE CHANGED: The parameter to \b osTimerDef shall be consistent but the +/// \note CAN BE CHANGED: The parameter to \b osTimerDef shall be consistent but the /// macro body is implementation specific in every CMSIS-RTOS. #if defined (osObjectsExternal) // object is external #define osTimerDef(name, function) \ @@ -420,7 +420,7 @@ osTimerDef_t os_timer_def_##name = \ /// Access a Timer definition. /// \param name name of the timer object. -/// \note CAN BE CHANGED: The parameter to \b osTimer shall be consistent but the +/// \note CAN BE CHANGED: The parameter to \b osTimer shall be consistent but the /// macro body is implementation specific in every CMSIS-RTOS. #define osTimer(name) \ &os_timer_def_##name @@ -487,7 +487,7 @@ os_InRegs osEvent osSignalWait (int32_t signals, uint32_t millisec); /// Define a Mutex. /// \param name name of the mutex object. -/// \note CAN BE CHANGED: The parameter to \b osMutexDef shall be consistent but the +/// \note CAN BE CHANGED: The parameter to \b osMutexDef shall be consistent but the /// macro body is implementation specific in every CMSIS-RTOS. #if defined (osObjectsExternal) // object is external #define osMutexDef(name) \ @@ -500,7 +500,7 @@ osMutexDef_t os_mutex_def_##name = { (os_mutex_cb_##name) } /// Access a Mutex definition. /// \param name name of the mutex object. -/// \note CAN BE CHANGED: The parameter to \b osMutex shall be consistent but the +/// \note CAN BE CHANGED: The parameter to \b osMutex shall be consistent but the /// macro body is implementation specific in every CMSIS-RTOS. #define osMutex(name) \ &os_mutex_def_##name @@ -537,7 +537,7 @@ osStatus osMutexDelete (osMutexId mutex_id); /// Define a Semaphore object. /// \param name name of the semaphore object. -/// \note CAN BE CHANGED: The parameter to \b osSemaphoreDef shall be consistent but the +/// \note CAN BE CHANGED: The parameter to \b osSemaphoreDef shall be consistent but the /// macro body is implementation specific in every CMSIS-RTOS. #if defined (osObjectsExternal) // object is external #define osSemaphoreDef(name) \ @@ -550,7 +550,7 @@ osSemaphoreDef_t os_semaphore_def_##name = { (os_semaphore_cb_##name) } /// Access a Semaphore definition. /// \param name name of the semaphore object. -/// \note CAN BE CHANGED: The parameter to \b osSemaphore shall be consistent but the +/// \note CAN BE CHANGED: The parameter to \b osSemaphore shall be consistent but the /// macro body is implementation specific in every CMSIS-RTOS. #define osSemaphore(name) \ &os_semaphore_def_##name @@ -583,7 +583,7 @@ osStatus osSemaphoreDelete (osSemaphoreId semaphore_id); #endif // Semaphore available - + // ==== Memory Pool Management Functions ==== #if (defined (osFeature_Pool) && (osFeature_Pool != 0)) // Memory Pool Management available @@ -592,7 +592,7 @@ osStatus osSemaphoreDelete (osSemaphoreId semaphore_id); /// \param name name of the memory pool. /// \param no maximum number of blocks (objects) in the memory pool. /// \param type data type of a single block (object). -/// \note CAN BE CHANGED: The parameter to \b osPoolDef shall be consistent but the +/// \note CAN BE CHANGED: The parameter to \b osPoolDef shall be consistent but the /// macro body is implementation specific in every CMSIS-RTOS. #if defined (osObjectsExternal) // object is external #define osPoolDef(name, no, type) \ @@ -606,7 +606,7 @@ osPoolDef_t os_pool_def_##name = \ /// \brief Access a Memory Pool definition. /// \param name name of the memory pool -/// \note CAN BE CHANGED: The parameter to \b osPool shall be consistent but the +/// \note CAN BE CHANGED: The parameter to \b osPool shall be consistent but the /// macro body is implementation specific in every CMSIS-RTOS. #define osPool(name) \ &os_pool_def_##name @@ -647,7 +647,7 @@ osStatus osPoolFree (osPoolId pool_id, void *block); /// \param name name of the queue. /// \param queue_sz maximum number of messages in the queue. /// \param type data type of a single message element (for debugger). -/// \note CAN BE CHANGED: The parameter to \b osMessageQDef shall be consistent but the +/// \note CAN BE CHANGED: The parameter to \b osMessageQDef shall be consistent but the /// macro body is implementation specific in every CMSIS-RTOS. #if defined (osObjectsExternal) // object is external #define osMessageQDef(name, queue_sz, type) \ @@ -661,7 +661,7 @@ osMessageQDef_t os_messageQ_def_##name = \ /// \brief Access a Message Queue Definition. /// \param name name of the queue -/// \note CAN BE CHANGED: The parameter to \b osMessageQ shall be consistent but the +/// \note CAN BE CHANGED: The parameter to \b osMessageQ shall be consistent but the /// macro body is implementation specific in every CMSIS-RTOS. #define osMessageQ(name) \ &os_messageQ_def_##name @@ -699,7 +699,7 @@ os_InRegs osEvent osMessageGet (osMessageQId queue_id, uint32_t millisec); /// \param name name of the queue /// \param queue_sz maximum number of messages in queue /// \param type data type of a single message element -/// \note CAN BE CHANGED: The parameter to \b osMailQDef shall be consistent but the +/// \note CAN BE CHANGED: The parameter to \b osMailQDef shall be consistent but the /// macro body is implementation specific in every CMSIS-RTOS. #if defined (osObjectsExternal) // object is external #define osMailQDef(name, queue_sz, type) \ @@ -712,10 +712,10 @@ void * os_mailQ_p_##name[2] = { (os_mailQ_q_##name), os_mailQ_m_##name }; \ osMailQDef_t os_mailQ_def_##name = \ { (queue_sz), sizeof(type), (os_mailQ_p_##name) } #endif - + /// \brief Access a Mail Queue Definition. /// \param name name of the queue -/// \note CAN BE CHANGED: The parameter to \b osMailQ shall be consistent but the +/// \note CAN BE CHANGED: The parameter to \b osMailQ shall be consistent but the /// macro body is implementation specific in every CMSIS-RTOS. #define osMailQ(name) \ &os_mailQ_def_##name @@ -761,7 +761,7 @@ os_InRegs osEvent osMailGet (osMailQId queue_id, uint32_t millisec); /// \return status code that indicates the execution status of the function. /// \note MUST REMAIN UNCHANGED: \b osMailFree shall be consistent in every CMSIS-RTOS. osStatus osMailFree (osMailQId queue_id, void *mail); - + #endif // Mail Queues available diff --git a/libraries/rtos/rtx/os_tcb.h b/libraries/rtos/rtx/os_tcb.h index 00b38beb46..9e18b285eb 100644 --- a/libraries/rtos/rtx/os_tcb.h +++ b/libraries/rtos/rtx/os_tcb.h @@ -36,13 +36,13 @@ typedef struct OS_TCB { U16 priv_stack; /* Private stack size in bytes */ U32 tsk_stack; /* Current task Stack pointer (R13) */ U32 *stack; /* Pointer to Task Stack memory block */ - + /* Library dependant part */ #if defined (__CC_ARM) && !defined (__MICROLIB) /* A memory space for arm standard library. */ U32 std_libspace[96/4]; #endif - + /* Task entry point used for uVision debugger */ FUNCP ptask; /* Task entry address */ } *P_TCB; diff --git a/libraries/rtos/rtx/rt_CMSIS.c b/libraries/rtos/rtx/rt_CMSIS.c index 4524e9df51..246f275280 100644 --- a/libraries/rtos/rtx/rt_CMSIS.c +++ b/libraries/rtos/rtx/rt_CMSIS.c @@ -15,19 +15,19 @@ * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * - Neither the name of ARM nor the names of its contributors may be used - * to endorse or promote products derived from this software without + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without * specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *---------------------------------------------------------------------------*/ @@ -131,9 +131,9 @@ static __inline t __##f (t1 a1, t2 a2, t3 a3, t4 a4) { \ return _##f(f,a1,a2,a3,a4); \ } -#define SVC_1_2 SVC_1_1 -#define SVC_1_3 SVC_1_1 -#define SVC_2_3 SVC_2_1 +#define SVC_1_2 SVC_1_1 +#define SVC_1_3 SVC_1_1 +#define SVC_2_3 SVC_2_1 #elif defined (__GNUC__) /* GNU Compiler */ @@ -257,9 +257,9 @@ static inline t __##f (t1 a1, t2 a2, t3 a3, t4 a4) { \ return (t) rv; \ } -#define SVC_1_2 SVC_1_1 -#define SVC_1_3 SVC_1_1 -#define SVC_2_3 SVC_2_1 +#define SVC_1_2 SVC_1_1 +#define SVC_1_3 SVC_1_1 +#define SVC_2_3 SVC_2_1 #elif defined (__ICCARM__) /* IAR Compiler */ @@ -405,7 +405,7 @@ static uint32_t rt_ms2tick (uint32_t millisec) { tick = ((1000 * millisec) + os_clockrate - 1) / os_clockrate; if (tick > 0xFFFE) return 0xFFFE; - + return tick; } @@ -517,12 +517,12 @@ osStatus osKernelInitialize (void) { /// Start the RTOS Kernel osStatus osKernelStart (void) { uint32_t stack[8]; - + if (__get_IPSR() != 0) return osErrorISR; // Not allowed in ISR switch (__get_CONTROL() & 0x03) { case 0x00: // Privileged Thread mode & MSP __set_PSP((uint32_t)(stack + 8)); // Initial PSP - if (os_flags & 1) { + if (os_flags & 1) { __set_CONTROL(0x02); // Set Privileged Thread mode & PSP } else { __set_CONTROL(0x03); // Set Unprivileged Thread mode & PSP @@ -576,20 +576,20 @@ extern void rt_init_context (P_TCB p_TCB, U8 priority, FUNCP task_body); /// Create a thread and add it to Active Threads and set it to state READY osThreadId svcThreadCreate (osThreadDef_t *thread_def, void *argument) { P_TCB ptcb; - + if ((thread_def == NULL) || (thread_def->pthread == NULL) || (thread_def->tpriority < osPriorityIdle) || (thread_def->tpriority > osPriorityRealtime) || (thread_def->stacksize == 0) || (thread_def->stack_pointer == NULL) ) { - sysThreadError(osErrorParameter); - return NULL; + sysThreadError(osErrorParameter); + return NULL; } - + U8 priority = thread_def->tpriority - osPriorityIdle + 1; P_TCB task_context = &thread_def->tcb; - + /* If "size != 0" use a private user provided stack. */ task_context->stack = (U32*)thread_def->stack_pointer; task_context->priv_stack = thread_def->stacksize; @@ -604,7 +604,7 @@ osThreadId svcThreadCreate (osThreadDef_t *thread_def, void *argument) { task_context->task_id = tsk; DBG_TASK_NOTIFY(task_context, __TRUE); rt_dispatch (task_context); - + ptcb = (P_TCB)os_active_TCB[tsk - 1]; // TCB pointer *((uint32_t *)ptcb->tsk_stack + 13) = (uint32_t)osThreadExit; @@ -625,14 +625,14 @@ osThreadId svcThreadGetId (void) { osStatus svcThreadTerminate (osThreadId thread_id) { OS_RESULT res; P_TCB ptcb; - + ptcb = rt_tid2ptcb(thread_id); // Get TCB pointer if (ptcb == NULL) return osErrorParameter; - + res = rt_tsk_delete(ptcb->task_id); // Delete task if (res == OS_R_NOK) return osErrorResource; // Delete task failed - + return osOK; } @@ -671,7 +671,7 @@ osPriority svcThreadGetPriority (osThreadId thread_id) { ptcb = rt_tid2ptcb(thread_id); // Get TCB pointer if (ptcb == NULL) return osPriorityError; - return (osPriority)(ptcb->prio - 1 + osPriorityIdle); + return (osPriority)(ptcb->prio - 1 + osPriorityIdle); } @@ -720,8 +720,8 @@ osPriority osThreadGetPriority (osThreadId thread_id) { /// INTERNAL - Not Public /// Auto Terminate Thread on exit (used implicitly when thread exists) -__NO_RETURN void osThreadExit (void) { - __svcThreadTerminate(__svcThreadGetId()); +__NO_RETURN void osThreadExit (void) { + __svcThreadTerminate(__svcThreadGetId()); for (;;); // Should never come here } @@ -794,7 +794,7 @@ os_InRegs osEvent osWait (uint32_t millisec) { #define osTimerStopped 1 #define osTimerRunning 2 -// Timer structures +// Timer structures typedef struct os_timer_cb_ { // Timer Control Block struct os_timer_cb_ *next; // Pointer to next active Timer @@ -802,7 +802,7 @@ typedef struct os_timer_cb_ { // Timer Control Block uint8_t type; // Timer Type (Periodic/One-shot) uint16_t reserved; // Reserved uint16_t tcnt; // Timer Delay Count - uint16_t icnt; // Timer Initial Count + uint16_t icnt; // Timer Initial Count void *arg; // Timer Function Argument osTimerDef_t *timer; // Pointer to Timer definition } os_timer_cb; @@ -933,7 +933,7 @@ osStatus svcTimerStart (osTimerId timer_id, uint32_t millisec) { default: return osErrorResource; } - + rt_timer_insert(pt, tcnt); return osOK; @@ -1054,8 +1054,8 @@ osStatus osTimerDelete (osTimerId timer_id) { /// INTERNAL - Not Public /// Get timer callback parameters (used by OS Timer Thread) -os_InRegs osCallback osTimerCall (osTimerId timer_id) { - return __svcTimerCall(timer_id); +os_InRegs osCallback osTimerCall (osTimerId timer_id) { + return __svcTimerCall(timer_id); } @@ -1183,7 +1183,7 @@ static __INLINE int32_t isrSignalSet (osThreadId thread_id, int32_t signals) { /// Set the specified Signal Flags of an active thread int32_t osSignalSet (osThreadId thread_id, int32_t signals) { if (__get_IPSR() != 0) { // in ISR - return isrSignalSet(thread_id, signals); + return isrSignalSet(thread_id, signals); } else { // in Thread return __svcSignalSet(thread_id, signals); } @@ -1367,7 +1367,7 @@ osSemaphoreId svcSemaphoreCreate (const osSemaphoreDef_t *semaphore_def, int32_t } rt_sem_init(sem, count); // Initialize Semaphore - + return sem; } @@ -1398,7 +1398,7 @@ osStatus svcSemaphoreRelease (osSemaphoreId semaphore_id) { if (((P_SCB)sem)->cb_type != SCB) return osErrorParameter; if (((P_SCB)sem)->tokens == osFeature_Semaphore) return osErrorResource; - + rt_sem_send(sem); // Release Semaphore return osOK; @@ -1532,7 +1532,7 @@ void *sysPoolAlloc (osPoolId pool_id, uint32_t clr) { /// Return an allocated memory block back to a specific memory pool osStatus sysPoolFree (osPoolId pool_id, void *block) { int32_t res; - + if (pool_id == NULL) return osErrorParameter; res = rt_free_box(pool_id, block); @@ -1601,7 +1601,7 @@ osMessageQId svcMessageCreate (osMessageQDef_t *queue_def, osThreadId thread_id) sysThreadError(osErrorParameter); return NULL; } - + if (((P_MCB)queue_def->pool)->cb_type != 0) { sysThreadError(osErrorParameter); return NULL; @@ -1645,7 +1645,7 @@ os_InRegs osEvent_type svcMessageGet (osMessageQId queue_id, uint32_t millisec) } res = rt_mbx_wait(queue_id, &ret.value.p, rt_ms2tick(millisec)); - + if (res == OS_R_TMO) { ret.status = millisec ? osEventTimeout : osOK; return osEvent_ret_value; @@ -1693,13 +1693,13 @@ static __INLINE os_InRegs osEvent isrMessageGet (osMessageQId queue_id, uint32_t } res = isr_mbx_receive(queue_id, &ret.value.p); - + if (res != OS_R_MBX) { ret.status = osOK; return ret; } - ret.status = osEventMessage; + ret.status = osEventMessage; return ret; } @@ -1812,7 +1812,7 @@ void *sysMailAlloc (osMailQId queue_id, uint32_t millisec, uint32_t isr, uint32_ rt_block(rt_ms2tick(millisec), WAIT_MBX); } - return mem; + return mem; } /// Free a memory block from a mail diff --git a/libraries/rtos/rtx/rt_Event.c b/libraries/rtos/rtx/rt_Event.c index d4322c6a25..acd8ccc205 100644 --- a/libraries/rtos/rtx/rt_Event.c +++ b/libraries/rtos/rtx/rt_Event.c @@ -15,19 +15,19 @@ * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * - Neither the name of ARM nor the names of its contributors may be used - * to endorse or promote products derived from this software without + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without * specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *---------------------------------------------------------------------------*/ @@ -108,7 +108,7 @@ wkup: p_tcb->events &= ~event_flags; rt_rmv_dly (p_tcb); p_tcb->state = READY; #ifdef __CMSIS_RTOS - rt_ret_val2(p_tcb, 0x08/*osEventSignal*/, p_tcb->waits); + rt_ret_val2(p_tcb, 0x08/*osEventSignal*/, p_tcb->waits); #else rt_ret_val (p_tcb, OS_R_EVT); #endif @@ -176,7 +176,7 @@ rdy: p_CB->events &= ~event_flags; rt_rmv_dly (p_CB); p_CB->state = READY; #ifdef __CMSIS_RTOS - rt_ret_val2(p_CB, 0x08/*osEventSignal*/, p_CB->waits); + rt_ret_val2(p_CB, 0x08/*osEventSignal*/, p_CB->waits); #else rt_ret_val (p_CB, OS_R_EVT); #endif diff --git a/libraries/rtos/rtx/rt_Event.h b/libraries/rtos/rtx/rt_Event.h index 7081f370c3..8b92f3c4c4 100644 --- a/libraries/rtos/rtx/rt_Event.h +++ b/libraries/rtos/rtx/rt_Event.h @@ -15,19 +15,19 @@ * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * - Neither the name of ARM nor the names of its contributors may be used - * to endorse or promote products derived from this software without + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without * specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *---------------------------------------------------------------------------*/ diff --git a/libraries/rtos/rtx/rt_HAL_CM.h b/libraries/rtos/rtx/rt_HAL_CM.h index 1c664fc1c7..2ab4b36cc7 100644 --- a/libraries/rtos/rtx/rt_HAL_CM.h +++ b/libraries/rtos/rtx/rt_HAL_CM.h @@ -15,19 +15,19 @@ * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * - Neither the name of ARM nor the names of its contributors may be used - * to endorse or promote products derived from this software without + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without * specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *---------------------------------------------------------------------------*/ @@ -86,7 +86,7 @@ __attribute__((always_inline)) static inline U32 __disable_irq(void) __attribute__(( always_inline)) static inline U8 __clz(U32 value) { U8 result; - + __asm volatile ("clz %0, %1" : "=r" (result) : "r" (value)); return(result); } @@ -119,7 +119,7 @@ static inline void __enable_irq(void) static inline U32 __disable_irq(void) { U32 result; - + __asm volatile ("mrs %0, primask" : "=r" (result)); __asm volatile ("cpsid i"); return(result & 1); @@ -130,7 +130,7 @@ static inline U32 __disable_irq(void) static inline U8 __clz(U32 value) { U8 result; - + __asm volatile ("clz %0, %1" : "=r" (result) : "r" (value)); return(result); } @@ -214,7 +214,7 @@ __inline static U32 rt_inc_qi (U32 size, U8 *count, U8 *first) { *count = cnt+1; c2 = (cnt = *first) + 1; if (c2 == size) c2 = 0; - *first = c2; + *first = c2; } __enable_irq (); #endif diff --git a/libraries/rtos/rtx/rt_List.c b/libraries/rtos/rtx/rt_List.c index ab984f8750..2134d14b38 100644 --- a/libraries/rtos/rtx/rt_List.c +++ b/libraries/rtos/rtx/rt_List.c @@ -15,19 +15,19 @@ * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * - Neither the name of ARM nor the names of its contributors may be used - * to endorse or promote products derived from this software without + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without * specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *---------------------------------------------------------------------------*/ diff --git a/libraries/rtos/rtx/rt_List.h b/libraries/rtos/rtx/rt_List.h index c9cfe295ad..cb3008e713 100644 --- a/libraries/rtos/rtx/rt_List.h +++ b/libraries/rtos/rtx/rt_List.h @@ -15,19 +15,19 @@ * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * - Neither the name of ARM nor the names of its contributors may be used - * to endorse or promote products derived from this software without + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without * specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *---------------------------------------------------------------------------*/ diff --git a/libraries/rtos/rtx/rt_Mailbox.c b/libraries/rtos/rtx/rt_Mailbox.c index 4357d6a02d..ef28b7639c 100644 --- a/libraries/rtos/rtx/rt_Mailbox.c +++ b/libraries/rtos/rtx/rt_Mailbox.c @@ -15,19 +15,19 @@ * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * - Neither the name of ARM nor the names of its contributors may be used - * to endorse or promote products derived from this software without + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without * specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *---------------------------------------------------------------------------*/ @@ -100,7 +100,7 @@ OS_RESULT rt_mbx_send (OS_ID mailbox, void *p_msg, U16 timeout) { p_MCB->p_lnk = os_tsk.run; os_tsk.run->p_lnk = NULL; os_tsk.run->p_rlnk = (P_TCB)p_MCB; - /* Task is waiting to send a message */ + /* Task is waiting to send a message */ p_MCB->state = 2; } os_tsk.run->msg = p_msg; @@ -163,7 +163,7 @@ OS_RESULT rt_mbx_wait (OS_ID mailbox, void **message, U16 timeout) { p_MCB->p_lnk = os_tsk.run; os_tsk.run->p_lnk = NULL; os_tsk.run->p_rlnk = (P_TCB)p_MCB; - /* Task is waiting to receive a message */ + /* Task is waiting to receive a message */ p_MCB->state = 1; } rt_block(timeout, WAIT_MBX); diff --git a/libraries/rtos/rtx/rt_Mailbox.h b/libraries/rtos/rtx/rt_Mailbox.h index 06a20c0fca..0c8e2f39b2 100644 --- a/libraries/rtos/rtx/rt_Mailbox.h +++ b/libraries/rtos/rtx/rt_Mailbox.h @@ -15,19 +15,19 @@ * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * - Neither the name of ARM nor the names of its contributors may be used - * to endorse or promote products derived from this software without + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without * specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *---------------------------------------------------------------------------*/ diff --git a/libraries/rtos/rtx/rt_MemBox.c b/libraries/rtos/rtx/rt_MemBox.c index 3e20fa7a66..5b96ae0e65 100644 --- a/libraries/rtos/rtx/rt_MemBox.c +++ b/libraries/rtos/rtx/rt_MemBox.c @@ -15,19 +15,19 @@ * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * - Neither the name of ARM nor the names of its contributors may be used - * to endorse or promote products derived from this software without + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without * specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *---------------------------------------------------------------------------*/ @@ -54,7 +54,7 @@ int _init_box (void *box_mem, U32 box_size, U32 blk_size) { /* Create memory structure. */ if (blk_size & BOX_ALIGN_8) { - /* Memory blocks 8-byte aligned. */ + /* Memory blocks 8-byte aligned. */ blk_size = ((blk_size & ~BOX_ALIGN_8) + 7) & ~7; sizeof_bm = (sizeof (struct OS_BM) + 7) & ~7; } diff --git a/libraries/rtos/rtx/rt_MemBox.h b/libraries/rtos/rtx/rt_MemBox.h index 52f150f138..c10a1cbe70 100644 --- a/libraries/rtos/rtx/rt_MemBox.h +++ b/libraries/rtos/rtx/rt_MemBox.h @@ -15,19 +15,19 @@ * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * - Neither the name of ARM nor the names of its contributors may be used - * to endorse or promote products derived from this software without + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without * specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *---------------------------------------------------------------------------*/ diff --git a/libraries/rtos/rtx/rt_Mutex.c b/libraries/rtos/rtx/rt_Mutex.c index c8d1c42083..c7a996bb50 100644 --- a/libraries/rtos/rtx/rt_Mutex.c +++ b/libraries/rtos/rtx/rt_Mutex.c @@ -15,19 +15,19 @@ * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * - Neither the name of ARM nor the names of its contributors may be used - * to endorse or promote products derived from this software without + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without * specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *---------------------------------------------------------------------------*/ @@ -120,7 +120,7 @@ OS_RESULT rt_mut_release (OS_ID mutex) { #ifdef __CMSIS_RTOS rt_ret_val(p_TCB, 0/*osOK*/); #else - rt_ret_val(p_TCB, OS_R_MUT); + rt_ret_val(p_TCB, OS_R_MUT); #endif rt_rmv_dly (p_TCB); /* A waiting task becomes the owner of this mutex. */ diff --git a/libraries/rtos/rtx/rt_Mutex.h b/libraries/rtos/rtx/rt_Mutex.h index 4f6b0de8a0..bf15c4d56c 100644 --- a/libraries/rtos/rtx/rt_Mutex.h +++ b/libraries/rtos/rtx/rt_Mutex.h @@ -15,19 +15,19 @@ * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * - Neither the name of ARM nor the names of its contributors may be used - * to endorse or promote products derived from this software without + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without * specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *---------------------------------------------------------------------------*/ diff --git a/libraries/rtos/rtx/rt_Robin.c b/libraries/rtos/rtx/rt_Robin.c index 05f5a307f7..d693dc6524 100644 --- a/libraries/rtos/rtx/rt_Robin.c +++ b/libraries/rtos/rtx/rt_Robin.c @@ -15,19 +15,19 @@ * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * - Neither the name of ARM nor the names of its contributors may be used - * to endorse or promote products derived from this software without + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without * specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *---------------------------------------------------------------------------*/ diff --git a/libraries/rtos/rtx/rt_Robin.h b/libraries/rtos/rtx/rt_Robin.h index eb665ad6ef..3ccbffcffd 100644 --- a/libraries/rtos/rtx/rt_Robin.h +++ b/libraries/rtos/rtx/rt_Robin.h @@ -15,19 +15,19 @@ * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * - Neither the name of ARM nor the names of its contributors may be used - * to endorse or promote products derived from this software without + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without * specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *---------------------------------------------------------------------------*/ diff --git a/libraries/rtos/rtx/rt_Semaphore.c b/libraries/rtos/rtx/rt_Semaphore.c index 7cee8cdb3c..93ff2bf083 100644 --- a/libraries/rtos/rtx/rt_Semaphore.c +++ b/libraries/rtos/rtx/rt_Semaphore.c @@ -15,19 +15,19 @@ * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * - Neither the name of ARM nor the names of its contributors may be used - * to endorse or promote products derived from this software without + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without * specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *---------------------------------------------------------------------------*/ diff --git a/libraries/rtos/rtx/rt_Semaphore.h b/libraries/rtos/rtx/rt_Semaphore.h index 5b04480282..ec4548000b 100644 --- a/libraries/rtos/rtx/rt_Semaphore.h +++ b/libraries/rtos/rtx/rt_Semaphore.h @@ -15,19 +15,19 @@ * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * - Neither the name of ARM nor the names of its contributors may be used - * to endorse or promote products derived from this software without + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without * specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *---------------------------------------------------------------------------*/ diff --git a/libraries/rtos/rtx/rt_System.c b/libraries/rtos/rtx/rt_System.c index 3eef20f540..f48b67bc2b 100644 --- a/libraries/rtos/rtx/rt_System.c +++ b/libraries/rtos/rtx/rt_System.c @@ -15,19 +15,19 @@ * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * - Neither the name of ARM nor the names of its contributors may be used - * to endorse or promote products derived from this software without + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without * specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *---------------------------------------------------------------------------*/ @@ -77,9 +77,9 @@ __RL_RTX_VER EQU 0x450 U32 rt_suspend (void) { /* Suspend OS scheduler */ U32 delta = 0xFFFF; - + rt_tsk_lock(); - + if (os_dly.p_dlnk) { delta = os_dly.delta_time; } @@ -88,7 +88,7 @@ U32 rt_suspend (void) { if (os_tmr.tcnt < delta) delta = os_tmr.tcnt; } #endif - + return (delta); } @@ -124,7 +124,7 @@ void rt_resume (U32 sleep_time) { } else { os_time += sleep_time; } - + #ifndef __CMSIS_RTOS /* Check the user timers. */ if (os_tmr.next) { @@ -274,7 +274,7 @@ void rt_systick (void) { #else rt_tmr_tick (); #endif - + /* Switch back to highest ready task */ next = rt_get_first (&os_rdy); rt_switch_req (next); diff --git a/libraries/rtos/rtx/rt_System.h b/libraries/rtos/rtx/rt_System.h index aff9aa662d..91db6487e0 100644 --- a/libraries/rtos/rtx/rt_System.h +++ b/libraries/rtos/rtx/rt_System.h @@ -15,19 +15,19 @@ * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * - Neither the name of ARM nor the names of its contributors may be used - * to endorse or promote products derived from this software without + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without * specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *---------------------------------------------------------------------------*/ diff --git a/libraries/rtos/rtx/rt_Task.c b/libraries/rtos/rtx/rt_Task.c index f5504e2db8..518f78fefb 100644 --- a/libraries/rtos/rtx/rt_Task.c +++ b/libraries/rtos/rtx/rt_Task.c @@ -15,19 +15,19 @@ * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * - Neither the name of ARM nor the names of its contributors may be used - * to endorse or promote products derived from this software without + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without * specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *---------------------------------------------------------------------------*/ @@ -232,7 +232,7 @@ OS_RESULT rt_tsk_delete (OS_TID task_id) { os_tsk.run->tsk_stack = rt_get_PSP (); rt_stk_check (); os_active_TCB[os_tsk.run->task_id-1] = NULL; - + os_tsk.run->stack = NULL; DBG_TASK_NOTIFY(os_tsk.run, __FALSE); os_tsk.run = NULL; @@ -249,7 +249,7 @@ OS_RESULT rt_tsk_delete (OS_TID task_id) { rt_rmv_list (task_context); rt_rmv_dly (task_context); os_active_TCB[task_id-1] = NULL; - + task_context->stack = NULL; DBG_TASK_NOTIFY(task_context, __FALSE); } @@ -273,7 +273,7 @@ void rt_sys_init (FUNCP first_task, U32 prio_stksz, void *stk) { for (i = 0; i < os_maxtaskrun; i++) { os_active_TCB[i] = NULL; } - + /* Set up TCB of idle demon */ os_idle_TCB.task_id = 255; os_idle_TCB.priv_stack = idle_task_stack_size; diff --git a/libraries/rtos/rtx/rt_Task.h b/libraries/rtos/rtx/rt_Task.h index edf3830387..9d3727b5a6 100644 --- a/libraries/rtos/rtx/rt_Task.h +++ b/libraries/rtos/rtx/rt_Task.h @@ -15,19 +15,19 @@ * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * - Neither the name of ARM nor the names of its contributors may be used - * to endorse or promote products derived from this software without + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without * specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *---------------------------------------------------------------------------*/ diff --git a/libraries/rtos/rtx/rt_Time.c b/libraries/rtos/rtx/rt_Time.c index e44e36e3a7..b02ccebbad 100644 --- a/libraries/rtos/rtx/rt_Time.c +++ b/libraries/rtos/rtx/rt_Time.c @@ -15,19 +15,19 @@ * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * - Neither the name of ARM nor the names of its contributors may be used - * to endorse or promote products derived from this software without + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without * specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *---------------------------------------------------------------------------*/ diff --git a/libraries/rtos/rtx/rt_Time.h b/libraries/rtos/rtx/rt_Time.h index e6bae1a6e2..27706373d5 100644 --- a/libraries/rtos/rtx/rt_Time.h +++ b/libraries/rtos/rtx/rt_Time.h @@ -15,19 +15,19 @@ * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * - Neither the name of ARM nor the names of its contributors may be used - * to endorse or promote products derived from this software without + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without * specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *---------------------------------------------------------------------------*/ diff --git a/libraries/rtos/rtx/rt_TypeDef.h b/libraries/rtos/rtx/rt_TypeDef.h index faa56f7f05..2adbe88cd8 100644 --- a/libraries/rtos/rtx/rt_TypeDef.h +++ b/libraries/rtos/rtx/rt_TypeDef.h @@ -15,19 +15,19 @@ * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * - Neither the name of ARM nor the names of its contributors may be used - * to endorse or promote products derived from this software without + * - Neither the name of ARM nor the names of its contributors may be used + * to endorse or promote products derived from this software without * specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. *---------------------------------------------------------------------------*/ diff --git a/libraries/tests/KL25Z/lptmr/main.cpp b/libraries/tests/KL25Z/lptmr/main.cpp index e7e1d84950..170fc46987 100644 --- a/libraries/tests/KL25Z/lptmr/main.cpp +++ b/libraries/tests/KL25Z/lptmr/main.cpp @@ -7,40 +7,40 @@ DigitalOut led(LED_BLUE); extern "C" void lptmr_isr(void) { // write 1 to TCF to clear the LPT timer compare flag LPTMR0->CSR |= LPTMR_CSR_TCF_MASK; - + ticks++; } int main() { /* Clock the timer */ SIM->SCGC5 |= SIM_SCGC5_LPTMR_MASK; - + /* Reset */ LPTMR0->CSR = 0; - + /* Compare value */ LPTMR0->CMR = 1000; - + /* Enable interrupt */ LPTMR0->CSR |= LPTMR_CSR_TIE_MASK; - + /* Set interrupt handler */ NVIC_SetVector(LPTimer_IRQn, (uint32_t)lptmr_isr); NVIC_EnableIRQ(LPTimer_IRQn); - + /* select LPO for RTC and LPTMR */ LPTMR0->PSR = LPTMR_PSR_PCS(3); // ERCLK32K -> 8MHz LPTMR0->PSR |= LPTMR_PSR_PRESCALE(2); // divide by 8 - + /* Start the timer */ LPTMR0->CSR |= LPTMR_CSR_TEN_MASK; - + led = 0; while (true) { wait(1); led = 1; printf("%d\n", ticks); - + wait(1); led = 0; printf("%d\n", ticks); diff --git a/libraries/tests/KL25Z/pit/main.cpp b/libraries/tests/KL25Z/pit/main.cpp index e4bbc7f639..3b13af2730 100644 --- a/libraries/tests/KL25Z/pit/main.cpp +++ b/libraries/tests/KL25Z/pit/main.cpp @@ -9,7 +9,7 @@ void SysTick_Handler(void) { void Delay(uint32_t dlyTicks) { uint32_t curTicks; - + curTicks = msTicks; while ((msTicks - curTicks) < dlyTicks); } @@ -17,32 +17,32 @@ void Delay(uint32_t dlyTicks) { int main() { SysTick_Config(SystemCoreClock / 1000); - + SIM->SCGC6 |= SIM_SCGC6_PIT_MASK; // Clock PIT PIT->MCR = 0; // Enable PIT - + // Timer 1 PIT->CHANNEL[1].LDVAL = 0xFFFFFFFF; PIT->CHANNEL[1].TCTRL = 0x0; // Disable Interrupts PIT->CHANNEL[1].TCTRL |= PIT_TCTRL_CHN_MASK; // Chain to timer 0 PIT->CHANNEL[1].TCTRL |= PIT_TCTRL_TEN_MASK; // Start timer 1 - + // Timer 2 PIT->CHANNEL[0].LDVAL = 0xFFFFFFFF; PIT->CHANNEL[0].TCTRL = PIT_TCTRL_TEN_MASK; // Start timer 0, disable interrupts - + DigitalOut led(LED_BLUE); while (true) { Delay(1000); led = !led; - + uint64_t ticks = (uint64_t)PIT->LTMR64H << 32; ticks |= (uint64_t)PIT->LTMR64L; printf("ticks: 0x%x%x\n", (uint32_t)(ticks>>32), (uint32_t)(ticks & 0xFFFFFFFF)); - + ticks = (~ticks) / 24; uint32_t us = (uint32_t)(0xFFFFFFFF & ticks); - + printf("us : 0x%x\n", us); } } diff --git a/libraries/tests/KL25Z/rtc/main.cpp b/libraries/tests/KL25Z/rtc/main.cpp index 393f5b42c5..31d7e64d26 100644 --- a/libraries/tests/KL25Z/rtc/main.cpp +++ b/libraries/tests/KL25Z/rtc/main.cpp @@ -23,21 +23,21 @@ void rtc_init(void) { // enable the clock to SRTC module register space SIM->SCGC6 |= SIM_SCGC6_RTC_MASK; SIM->SOPT1 = (SIM->SOPT1 & ~SIM_SOPT1_OSC32KSEL_MASK) | SIM_SOPT1_OSC32KSEL(0); - + // disable interrupts NVIC_DisableIRQ(RTC_Seconds_IRQn); NVIC_DisableIRQ(RTC_IRQn); - + // Reset - RTC->CR = RTC_CR_SWR_MASK; + RTC->CR = RTC_CR_SWR_MASK; RTC->CR &= ~RTC_CR_SWR_MASK; - + // Allow write RTC->CR = RTC_CR_UM_MASK | RTC_CR_SUP_MASK; - + NVIC_EnableIRQ(RTC_Seconds_IRQn); NVIC_EnableIRQ(RTC_Seconds_IRQn); - + printf("LR: 0x%x\n", RTC->LR); printf("CR: 0x%x\n", RTC->CR); wait(1); @@ -45,25 +45,25 @@ void rtc_init(void) { RTC->TSR = 0; } RTC->TCR = 0; - + // After setting this bit, wait the oscillator startup time before enabling // the time counter to allow the clock time to stabilize RTC->CR |= RTC_CR_OSCE_MASK; for (volatile int i=0; i<0x600000; i++); - + //enable seconds interrupts RTC->IER |= RTC_IER_TSIE_MASK; - + // enable time counter RTC->SR |= RTC_SR_TCE_MASK; - - + + } int main() { error_led = 1; rtc_init(); - + while (true) { wait(1); status_led = !status_led; diff --git a/libraries/tests/benchmarks/all/main.cpp b/libraries/tests/benchmarks/all/main.cpp index 4752c5e6cc..a3794f1005 100644 --- a/libraries/tests/benchmarks/all/main.cpp +++ b/libraries/tests/benchmarks/all/main.cpp @@ -11,7 +11,7 @@ volatile float w, x, y, z; int main() { while(1) { z = x * y / w; - printf("Hello World %d %f\n", out.read(), z); + printf("Hello World %d %f\n", out.read(), z); if(in > 0.5) { out = !out; } diff --git a/libraries/tests/ble/Health_Thermometer/main.cpp b/libraries/tests/ble/Health_Thermometer/main.cpp deleted file mode 100644 index 65aef50ab2..0000000000 --- a/libraries/tests/ble/Health_Thermometer/main.cpp +++ /dev/null @@ -1,159 +0,0 @@ -/* mbed Microcontroller Library - * Copyright (c) 2006-2014 ARM Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "mbed.h" -#include "TMP102.h" -#include "nRF51822n.h" - -nRF51822n nrf; /* BLE radio driver */ -TMP102 healthThemometer(p22, p20, 0x90); /* The TMP102 connected to our board */ - -/* LEDs for indication: */ -DigitalOut oneSecondLed(LED1); /* LED1 is toggled every second. */ -DigitalOut advertisingStateLed(LED2); /* LED2 is on when we are advertising, otherwise off. */ - - -/* Health Thermometer Service */ -uint8_t thermTempPayload[5] = { 0, 0, 0, 0, 0 }; -GattService thermService (GattService::UUID_HEALTH_THERMOMETER_SERVICE); -GattCharacteristic thermTemp (GattCharacteristic::UUID_TEMPERATURE_MEASUREMENT_CHAR, - 5, 5, GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_INDICATE); - -/* Battery Level Service */ -uint8_t batt = 100; /* Battery level */ -uint8_t read_batt = 0; /* Variable to hold battery level reads */ -GattService battService ( GattService::UUID_BATTERY_SERVICE ); -GattCharacteristic battLevel ( GattCharacteristic::UUID_BATTERY_LEVEL_CHAR, 1, 1, - GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY | - GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_READ); - - -/* Advertising data and parameters */ -GapAdvertisingData advData; -GapAdvertisingData scanResponse; -GapAdvertisingParams advParams ( GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED ); - -uint16_t uuid16_list[] = {GattService::UUID_HEALTH_THERMOMETER_SERVICE, - GattService::UUID_BATTERY_SERVICE}; - -uint32_t quick_ieee11073_from_float(float temperature); -void updateServiceValues(void); - -/**************************************************************************/ -/*! - @brief This custom class can be used to override any GapEvents - that you are interested in handling on an application level. -*/ -/**************************************************************************/ -class GapEventHandler : public GapEvents -{ - //virtual void onTimeout(void) {} - - virtual void onConnected(void) - { - advertisingStateLed = 0; - } - - /* When a client device disconnects we need to start advertising again. */ - virtual void onDisconnected(void) - { - nrf.getGap().startAdvertising(advParams); - advertisingStateLed = 1; - } -}; - -/**************************************************************************/ -/*! - @brief Program entry point -*/ -/**************************************************************************/ -int main(void) -{ - - /* Setup blinky led */ - oneSecondLed=1; - - /* Setup an event handler for GAP events i.e. Client/Server connection events. */ - nrf.getGap().setEventHandler(new GapEventHandler()); - - /* Initialise the nRF51822 */ - nrf.init(); - - /* Make sure we get a clean start */ - nrf.reset(); - - /* Add BLE-Only flag and complete service list to the advertising data */ - advData.addFlags(GapAdvertisingData::BREDR_NOT_SUPPORTED); - advData.addData(GapAdvertisingData::COMPLETE_LIST_16BIT_SERVICE_IDS, - (uint8_t*)uuid16_list, sizeof(uuid16_list)); - advData.addAppearance(GapAdvertisingData::GENERIC_THERMOMETER); - nrf.getGap().setAdvertisingData(advData, scanResponse); - - /* Health Thermometer Service */ - thermService.addCharacteristic(thermTemp); - nrf.getGattServer().addService(thermService); - - /* Add the Battery Level service */ - battService.addCharacteristic(battLevel); - nrf.getGattServer().addService(battService); - - /* Start advertising (make sure you've added all your data first) */ - nrf.getGap().startAdvertising(advParams); - advertisingStateLed = 1; - - for (;;) - { - /* Now that we're live, update the battery level & temperature characteristics */ - updateServiceValues(); - wait(1); - } -} - -/**************************************************************************/ -/*! - @brief Ticker callback to switch advertisingStateLed state -*/ -/**************************************************************************/ -void updateServiceValues(void) -{ - /* Toggle the one second LEDs */ - oneSecondLed = !oneSecondLed; - - /* Update battery level */ - nrf.getGattServer().updateValue(battLevel.handle, (uint8_t*)&batt, sizeof(batt)); - /* Decrement the battery level. */ - batt <=50 ? batt=100 : batt--;; - - /* Update the temperature. Note that we need to convert to an ieee11073 format float. */ - float temperature = healthThemometer.read(); - uint32_t temp_ieee11073 = quick_ieee11073_from_float(temperature); - memcpy(thermTempPayload+1, &temp_ieee11073, 4); - nrf.getGattServer().updateValue(thermTemp.handle, thermTempPayload, sizeof(thermTempPayload)); -} - -/** - * @brief A very quick conversion between a float temperature and 11073-20601 FLOAT-Type. - * @param temperature The temperature as a float. - * @return The temperature in 11073-20601 FLOAT-Type format. - */ -uint32_t quick_ieee11073_from_float(float temperature) -{ - uint8_t exponent = 0xFF; //exponent is -1 - uint32_t mantissa = (uint32_t)(temperature*10); - - return ( ((uint32_t)exponent) << 24) | mantissa; -} - diff --git a/libraries/tests/ble/HeartRate/main.cpp b/libraries/tests/ble/HeartRate/main.cpp deleted file mode 100644 index 3f64c94d67..0000000000 --- a/libraries/tests/ble/HeartRate/main.cpp +++ /dev/null @@ -1,243 +0,0 @@ -/* mbed Microcontroller Library - * Copyright (c) 2006-2013 ARM Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "mbed.h" -#include "nRF51822n.h" - -nRF51822n nrf; /* BLE radio driver */ - -DigitalOut led1(LED1); -DigitalOut led2(LED2); -Ticker flipper; -Serial pc(USBTX,USBRX); - -/* Battery Level Service */ -uint8_t batt = 72; /* Battery level */ -uint8_t read_batt = 0; /* Variable to hold battery level reads */ -GattService battService ( GattService::UUID_BATTERY_SERVICE ); -GattCharacteristic battLevel ( GattCharacteristic::UUID_BATTERY_LEVEL_CHAR, 1, 1, - GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY | - GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_READ); - -/* Heart Rate Service */ -/* Service: https://developer.bluetooth.org/gatt/services/Pages/ServiceViewer.aspx?u=org.bluetooth.service.heart_rate.xml */ -/* HRM Char: https://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.heart_rate_measurement.xml */ -/* Location: https://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.body_sensor_location.xml */ -GattService hrmService ( GattService::UUID_HEART_RATE_SERVICE ); -GattCharacteristic hrmRate ( GattCharacteristic::UUID_HEART_RATE_MEASUREMENT_CHAR, 2, 3, GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_NOTIFY ); -GattCharacteristic hrmLocation ( GattCharacteristic::UUID_BODY_SENSOR_LOCATION_CHAR, 1, 1, GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_READ ); - -/* Device Information service */ -uint8_t deviceName[4] = { 'm', 'b', 'e', 'd' }; -GattService deviceInformationService ( GattService::UUID_DEVICE_INFORMATION_SERVICE ); -GattCharacteristic deviceManufacturer ( GattCharacteristic::UUID_MANUFACTURER_NAME_STRING_CHAR, - sizeof(deviceName), sizeof(deviceName), - GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_READ); - -/* Health Thermometer Service */ -uint32_t temp_ieee11073 = 0xFF00016C; // 36.4C in IEEE-11073 32-bit float! -uint8_t thermTempPayload[5] = { 0, 0, 0, 0, 0 }; -GattService thermService (GattService::UUID_HEALTH_THERMOMETER_SERVICE); -GattCharacteristic thermTemp (GattCharacteristic::UUID_TEMPERATURE_MEASUREMENT_CHAR, - 5, 5, GattCharacteristic::BLE_GATT_CHAR_PROPERTIES_INDICATE); - -/* Advertising data and parameters */ -GapAdvertisingData advData; -GapAdvertisingData scanResponse; -GapAdvertisingParams advParams ( GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED ); -uint16_t uuid16_list[] = { GattService::UUID_BATTERY_SERVICE, - GattService::UUID_DEVICE_INFORMATION_SERVICE, - GattService::UUID_HEART_RATE_SERVICE, - GattService::UUID_HEALTH_THERMOMETER_SERVICE }; - -void tickerCallback(void); - -/**************************************************************************/ -/*! - @brief This custom class can be used to override any GapEvents - that you are interested in handling on an application level. -*/ -/**************************************************************************/ -class GapEventHandler : public GapEvents -{ - virtual void onTimeout(void) - { - pc.printf("Advertising Timeout!\n\r"); - // Restart the advertising process with a much slower interval, - // only start advertising again after a button press, etc. - } - - virtual void onConnected(void) - { - pc.printf("Connected!\n\r"); - } - - virtual void onDisconnected(void) - { - pc.printf("Disconnected!\n\r"); - pc.printf("Restarting the advertising process\n\r"); - nrf.getGap().startAdvertising(advParams); - } -}; - -/**************************************************************************/ -/*! - @brief This custom class can be used to override any GattServerEvents - that you are interested in handling on an application level. -*/ -/**************************************************************************/ -class GattServerEventHandler : public GattServerEvents -{ - //virtual void onDataSent(uint16_t charHandle) {} - //virtual void onDataWritten(uint16_t charHandle) {} - - virtual void onUpdatesEnabled(uint16_t charHandle) - { - if (charHandle == thermTemp.handle) - { - pc.printf("Temperature indication enabled\n\r"); - } - if (charHandle == hrmRate.handle) - { - pc.printf("Heart rate notify enabled\n\r"); - } - } - - virtual void onUpdatesDisabled(uint16_t charHandle) - { - if (charHandle == thermTemp.handle) - { - pc.printf("Temperature indication disabled\n\r"); - } - if (charHandle == hrmRate.handle) - { - pc.printf("Heart rate notify disabled\n\r"); - } - } - - virtual void onConfirmationReceived(uint16_t charHandle) - { - if (charHandle == thermTemp.handle) - { - pc.printf("Temperature indication received\n\r"); - } - } -}; - -/**************************************************************************/ -/*! - @brief Program entry point -*/ -/**************************************************************************/ -int main(void) -{ - *(uint32_t *)0x40000504 = 0xC007FFDF; - *(uint32_t *)0x40006C18 = 0x00008000; - - /* Setup blinky: led1 is toggled in main, led2 is toggled via Ticker */ - led1=1; - led2=1; - flipper.attach(&tickerCallback, 1.0); - - /* Setup the local GAP/GATT event handlers */ - nrf.getGap().setEventHandler(new GapEventHandler()); - nrf.getGattServer().setEventHandler(new GattServerEventHandler()); - - /* Initialise the nRF51822 */ - pc.printf("Initialising the nRF51822\n\r"); - nrf.init(); - - /* Make sure we get a clean start */ - nrf.reset(); - - /* Add BLE-Only flag and complete service list to the advertising data */ - advData.addFlags(GapAdvertisingData::BREDR_NOT_SUPPORTED); - advData.addData(GapAdvertisingData::COMPLETE_LIST_16BIT_SERVICE_IDS, - (uint8_t*)uuid16_list, sizeof(uuid16_list)); - advData.addAppearance(GapAdvertisingData::HEART_RATE_SENSOR_HEART_RATE_BELT); - nrf.getGap().setAdvertisingData(advData, scanResponse); - - /* Add the Battery Level service */ - battService.addCharacteristic(battLevel); - nrf.getGattServer().addService(battService); - - /* Add the Device Information service */ - deviceInformationService.addCharacteristic(deviceManufacturer); - nrf.getGattServer().addService(deviceInformationService); - - /* Add the Heart Rate service */ - hrmService.addCharacteristic(hrmRate); - hrmService.addCharacteristic(hrmLocation); - nrf.getGattServer().addService(hrmService); - - /* Health Thermometer Service */ - thermService.addCharacteristic(thermTemp); - nrf.getGattServer().addService(thermService); - - /* Start advertising (make sure you've added all your data first) */ - nrf.getGap().startAdvertising(advParams); - - /* Now that we're live, update the battery level characteristic, and */ - /* change the device manufacturer characteristic to 'mbed' */ - nrf.getGattServer().updateValue(battLevel.handle, (uint8_t*)&batt, sizeof(batt)); - nrf.getGattServer().updateValue(deviceManufacturer.handle, deviceName, sizeof(deviceName)); - nrf.getGattServer().updateValue(thermTemp.handle, thermTempPayload, sizeof(thermTempPayload)); - - /* Set the heart rate monitor location (one time only) */ - /* See --> https://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.body_sensor_location.xml */ - uint8_t location = 0x03; /* Finger */ - uint8_t hrmCounter = 100; - nrf.getGattServer().updateValue(hrmLocation.handle, (uint8_t*)&location, sizeof(location)); - - /* Do blinky on LED1 while we're waiting for BLE events */ - for (;;) - { - led1 = !led1; - wait(1); - - //nrf.getGattServer().readValue(battLevel.handle, (uint8_t*)&read_batt, sizeof(read_batt)); - //pc.printf("Battery Level = %d\n\r", read_batt); - - /* Update battery level */ - batt++; - if (batt > 100) batt = 72; - nrf.getGattServer().updateValue(battLevel.handle, (uint8_t*)&batt, sizeof(batt)); - - /* Update the HRM measurement */ - /* First byte = 8-bit values, no extra info, Second byte = uint8_t HRM value */ - /* See --> https://developer.bluetooth.org/gatt/characteristics/Pages/CharacteristicViewer.aspx?u=org.bluetooth.characteristic.heart_rate_measurement.xml */ - hrmCounter++; - if (hrmCounter == 175) hrmCounter = 100; - uint8_t bpm[2] = { 0x00, hrmCounter }; - nrf.getGattServer().updateValue(hrmRate.handle, bpm, sizeof(bpm)); - - /* Update the temperature */ - memcpy(thermTempPayload+1, &temp_ieee11073, 4); - nrf.getGattServer().updateValue(thermTemp.handle, thermTempPayload, sizeof(thermTempPayload)); - temp_ieee11073++; - if (temp_ieee11073 > 0xFF000200) temp_ieee11073 = 0xFF00016C; - } -} - -/**************************************************************************/ -/*! - @brief Ticker callback to switch led2 state -*/ -/**************************************************************************/ -void tickerCallback(void) -{ - led2 = !led2; -} diff --git a/libraries/tests/ble/iBeacon/main.cpp b/libraries/tests/ble/iBeacon/main.cpp deleted file mode 100644 index 3f71ea90a9..0000000000 --- a/libraries/tests/ble/iBeacon/main.cpp +++ /dev/null @@ -1,87 +0,0 @@ -/* mbed Microcontroller Library - * Copyright (c) 2006-2013 ARM Limited - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "mbed.h" -#include "nRF51822n.h" - -nRF51822n nrf; /* BLE radio driver */ - -DigitalOut led1(LED1); -DigitalOut led2(LED2); -Ticker flipper; -Serial pc(USBTX,USBRX); - -void tickerCallback(void); - -/**************************************************************************/ -/*! - @brief Program entry point -*/ -/**************************************************************************/ -int main(void) -{ - *(uint32_t *)0x40000504 = 0xC007FFDF; - *(uint32_t *)0x40006C18 = 0x00008000; - - /* Setup blinky: led1 is toggled in main, led2 is toggled via Ticker */ - led1=1; - led2=1; - flipper.attach(&tickerCallback, 1.0); - - /* Initialise the nRF51822 */ - pc.printf("Initialising the nRF51822\n\r"); - nrf.init(); - - GapAdvertisingParams advParams ( GapAdvertisingParams::ADV_NON_CONNECTABLE_UNDIRECTED ); - GapAdvertisingData advData; - GapAdvertisingData scanResponse; - - /* Define an iBeacon payload - -------------------------------------------------------------- - 128-Bit UUID = E2 0A 39 F4 73 F5 4B C4 A1 2F 17 D1 AD 07 A9 61 - Major/Minor = 0000 / 0000 - Tx Power = C8 - */ - uint8_t iBeaconPayload[25] = { 0x4C, 0x00, 0x02, 0x15, 0xE2, 0x0A, 0x39, 0xF4, 0x73, 0xF5, 0x4B, 0xC4, 0xA1, 0x2F, 0x17, 0xD1, 0xAD, 0x07, 0xA9, 0x61, 0x00, 0x00, 0x00, 0x00, 0xC8 }; - - /* Make sure we get a clean start */ - nrf.reset(); - - /* iBeacon includes the FLAG and MSD fields */ - advData.addFlags(GapAdvertisingData::BREDR_NOT_SUPPORTED); - advData.addData(GapAdvertisingData::MANUFACTURER_SPECIFIC_DATA, iBeaconPayload, sizeof(iBeaconPayload)); - - /* Start advertising! */ - nrf.getGap().setAdvertisingData(advData, scanResponse); - nrf.getGap().startAdvertising(advParams); - - /* Do blinky on LED1 while we're waiting for BLE events */ - for (;;) - { - led1 = !led1; - wait(1); - } -} - -/**************************************************************************/ -/*! - @brief Ticker callback to switch led2 state -*/ -/**************************************************************************/ -void tickerCallback(void) -{ - led2 = !led2; -} diff --git a/libraries/tests/dsp/cmsis/fir_f32/data.cpp b/libraries/tests/dsp/cmsis/fir_f32/data.cpp index e2e9ad658b..d946b36bc1 100644 --- a/libraries/tests/dsp/cmsis/fir_f32/data.cpp +++ b/libraries/tests/dsp/cmsis/fir_f32/data.cpp @@ -6,89 +6,89 @@ float32_t testInput_f32_1kHz_15kHz[320] = { -+0.0000000000f, +0.5924659585f, -0.0947343455f, +0.1913417162f, +1.0000000000f, +0.4174197128f, +0.3535533906f, +1.2552931065f, -+0.8660254038f, +0.4619397663f, +1.3194792169f, +1.1827865776f, +0.5000000000f, +1.1827865776f, +1.3194792169f, +0.4619397663f, -+0.8660254038f, +1.2552931065f, +0.3535533906f, +0.4174197128f, +1.0000000000f, +0.1913417162f, -0.0947343455f, +0.5924659585f, --0.0000000000f, -0.5924659585f, +0.0947343455f, -0.1913417162f, -1.0000000000f, -0.4174197128f, -0.3535533906f, -1.2552931065f, --0.8660254038f, -0.4619397663f, -1.3194792169f, -1.1827865776f, -0.5000000000f, -1.1827865776f, -1.3194792169f, -0.4619397663f, --0.8660254038f, -1.2552931065f, -0.3535533906f, -0.4174197128f, -1.0000000000f, -0.1913417162f, +0.0947343455f, -0.5924659585f, -+0.0000000000f, +0.5924659585f, -0.0947343455f, +0.1913417162f, +1.0000000000f, +0.4174197128f, +0.3535533906f, +1.2552931065f, -+0.8660254038f, +0.4619397663f, +1.3194792169f, +1.1827865776f, +0.5000000000f, +1.1827865776f, +1.3194792169f, +0.4619397663f, -+0.8660254038f, +1.2552931065f, +0.3535533906f, +0.4174197128f, +1.0000000000f, +0.1913417162f, -0.0947343455f, +0.5924659585f, -+0.0000000000f, -0.5924659585f, +0.0947343455f, -0.1913417162f, -1.0000000000f, -0.4174197128f, -0.3535533906f, -1.2552931065f, --0.8660254038f, -0.4619397663f, -1.3194792169f, -1.1827865776f, -0.5000000000f, -1.1827865776f, -1.3194792169f, -0.4619397663f, --0.8660254038f, -1.2552931065f, -0.3535533906f, -0.4174197128f, -1.0000000000f, -0.1913417162f, +0.0947343455f, -0.5924659585f, -+0.0000000000f, +0.5924659585f, -0.0947343455f, +0.1913417162f, +1.0000000000f, +0.4174197128f, +0.3535533906f, +1.2552931065f, -+0.8660254038f, +0.4619397663f, +1.3194792169f, +1.1827865776f, +0.5000000000f, +1.1827865776f, +1.3194792169f, +0.4619397663f, -+0.8660254038f, +1.2552931065f, +0.3535533906f, +0.4174197128f, +1.0000000000f, +0.1913417162f, -0.0947343455f, +0.5924659585f, -+0.0000000000f, -0.5924659585f, +0.0947343455f, -0.1913417162f, -1.0000000000f, -0.4174197128f, -0.3535533906f, -1.2552931065f, --0.8660254038f, -0.4619397663f, -1.3194792169f, -1.1827865776f, -0.5000000000f, -1.1827865776f, -1.3194792169f, -0.4619397663f, --0.8660254038f, -1.2552931065f, -0.3535533906f, -0.4174197128f, -1.0000000000f, -0.1913417162f, +0.0947343455f, -0.5924659585f, --0.0000000000f, +0.5924659585f, -0.0947343455f, +0.1913417162f, +1.0000000000f, +0.4174197128f, +0.3535533906f, +1.2552931065f, -+0.8660254038f, +0.4619397663f, +1.3194792169f, +1.1827865776f, +0.5000000000f, +1.1827865776f, +1.3194792169f, +0.4619397663f, -+0.8660254038f, +1.2552931065f, +0.3535533906f, +0.4174197128f, +1.0000000000f, +0.1913417162f, -0.0947343455f, +0.5924659585f, --0.0000000000f, -0.5924659585f, +0.0947343455f, -0.1913417162f, -1.0000000000f, -0.4174197128f, -0.3535533906f, -1.2552931065f, --0.8660254038f, -0.4619397663f, -1.3194792169f, -1.1827865776f, -0.5000000000f, -1.1827865776f, -1.3194792169f, -0.4619397663f, --0.8660254038f, -1.2552931065f, -0.3535533906f, -0.4174197128f, -1.0000000000f, -0.1913417162f, +0.0947343455f, -0.5924659585f, -+0.0000000000f, +0.5924659585f, -0.0947343455f, +0.1913417162f, +1.0000000000f, +0.4174197128f, +0.3535533906f, +1.2552931065f, -+0.8660254038f, +0.4619397663f, +1.3194792169f, +1.1827865776f, +0.5000000000f, +1.1827865776f, +1.3194792169f, +0.4619397663f, -+0.8660254038f, +1.2552931065f, +0.3535533906f, +0.4174197128f, +1.0000000000f, +0.1913417162f, -0.0947343455f, +0.5924659585f, -+0.0000000000f, -0.5924659585f, +0.0947343455f, -0.1913417162f, -1.0000000000f, -0.4174197128f, -0.3535533906f, -1.2552931065f, --0.8660254038f, -0.4619397663f, -1.3194792169f, -1.1827865776f, -0.5000000000f, -1.1827865776f, -1.3194792169f, -0.4619397663f, --0.8660254038f, -1.2552931065f, -0.3535533906f, -0.4174197128f, -1.0000000000f, -0.1913417162f, +0.0947343455f, -0.5924659585f, --0.0000000000f, +0.5924659585f, -0.0947343455f, +0.1913417162f, +1.0000000000f, +0.4174197128f, +0.3535533906f, +1.2552931065f, -+0.8660254038f, +0.4619397663f, +1.3194792169f, +1.1827865776f, +0.5000000000f, +1.1827865776f, +1.3194792169f, +0.4619397663f, -+0.8660254038f, +1.2552931065f, +0.3535533906f, +0.4174197128f, +1.0000000000f, +0.1913417162f, -0.0947343455f, +0.5924659585f, -+0.0000000000f, -0.5924659585f, +0.0947343455f, -0.1913417162f, -1.0000000000f, -0.4174197128f, -0.3535533906f, -1.2552931065f, --0.8660254038f, -0.4619397663f, -1.3194792169f, -1.1827865776f, -0.5000000000f, -1.1827865776f, -1.3194792169f, -0.4619397663f, --0.8660254038f, -1.2552931065f, -0.3535533906f, -0.4174197128f, -1.0000000000f, -0.1913417162f, +0.0947343455f, -0.5924659585f, --0.0000000000f, +0.5924659585f, -0.0947343455f, +0.1913417162f, +1.0000000000f, +0.4174197128f, +0.3535533906f, +1.2552931065f, -+0.8660254038f, +0.4619397663f, +1.3194792169f, +1.1827865776f, +0.5000000000f, +1.1827865776f, +1.3194792169f, +0.4619397663f, -+0.8660254038f, +1.2552931065f, +0.3535533906f, +0.4174197128f, +1.0000000000f, +0.1913417162f, -0.0947343455f, +0.5924659585f, -+0.0000000000f, -0.5924659585f, +0.0947343455f, -0.1913417162f, -1.0000000000f, -0.4174197128f, -0.3535533906f, -1.2552931065f, ++0.0000000000f, +0.5924659585f, -0.0947343455f, +0.1913417162f, +1.0000000000f, +0.4174197128f, +0.3535533906f, +1.2552931065f, ++0.8660254038f, +0.4619397663f, +1.3194792169f, +1.1827865776f, +0.5000000000f, +1.1827865776f, +1.3194792169f, +0.4619397663f, ++0.8660254038f, +1.2552931065f, +0.3535533906f, +0.4174197128f, +1.0000000000f, +0.1913417162f, -0.0947343455f, +0.5924659585f, +-0.0000000000f, -0.5924659585f, +0.0947343455f, -0.1913417162f, -1.0000000000f, -0.4174197128f, -0.3535533906f, -1.2552931065f, +-0.8660254038f, -0.4619397663f, -1.3194792169f, -1.1827865776f, -0.5000000000f, -1.1827865776f, -1.3194792169f, -0.4619397663f, +-0.8660254038f, -1.2552931065f, -0.3535533906f, -0.4174197128f, -1.0000000000f, -0.1913417162f, +0.0947343455f, -0.5924659585f, ++0.0000000000f, +0.5924659585f, -0.0947343455f, +0.1913417162f, +1.0000000000f, +0.4174197128f, +0.3535533906f, +1.2552931065f, ++0.8660254038f, +0.4619397663f, +1.3194792169f, +1.1827865776f, +0.5000000000f, +1.1827865776f, +1.3194792169f, +0.4619397663f, ++0.8660254038f, +1.2552931065f, +0.3535533906f, +0.4174197128f, +1.0000000000f, +0.1913417162f, -0.0947343455f, +0.5924659585f, ++0.0000000000f, -0.5924659585f, +0.0947343455f, -0.1913417162f, -1.0000000000f, -0.4174197128f, -0.3535533906f, -1.2552931065f, +-0.8660254038f, -0.4619397663f, -1.3194792169f, -1.1827865776f, -0.5000000000f, -1.1827865776f, -1.3194792169f, -0.4619397663f, +-0.8660254038f, -1.2552931065f, -0.3535533906f, -0.4174197128f, -1.0000000000f, -0.1913417162f, +0.0947343455f, -0.5924659585f, ++0.0000000000f, +0.5924659585f, -0.0947343455f, +0.1913417162f, +1.0000000000f, +0.4174197128f, +0.3535533906f, +1.2552931065f, ++0.8660254038f, +0.4619397663f, +1.3194792169f, +1.1827865776f, +0.5000000000f, +1.1827865776f, +1.3194792169f, +0.4619397663f, ++0.8660254038f, +1.2552931065f, +0.3535533906f, +0.4174197128f, +1.0000000000f, +0.1913417162f, -0.0947343455f, +0.5924659585f, ++0.0000000000f, -0.5924659585f, +0.0947343455f, -0.1913417162f, -1.0000000000f, -0.4174197128f, -0.3535533906f, -1.2552931065f, +-0.8660254038f, -0.4619397663f, -1.3194792169f, -1.1827865776f, -0.5000000000f, -1.1827865776f, -1.3194792169f, -0.4619397663f, +-0.8660254038f, -1.2552931065f, -0.3535533906f, -0.4174197128f, -1.0000000000f, -0.1913417162f, +0.0947343455f, -0.5924659585f, +-0.0000000000f, +0.5924659585f, -0.0947343455f, +0.1913417162f, +1.0000000000f, +0.4174197128f, +0.3535533906f, +1.2552931065f, ++0.8660254038f, +0.4619397663f, +1.3194792169f, +1.1827865776f, +0.5000000000f, +1.1827865776f, +1.3194792169f, +0.4619397663f, ++0.8660254038f, +1.2552931065f, +0.3535533906f, +0.4174197128f, +1.0000000000f, +0.1913417162f, -0.0947343455f, +0.5924659585f, +-0.0000000000f, -0.5924659585f, +0.0947343455f, -0.1913417162f, -1.0000000000f, -0.4174197128f, -0.3535533906f, -1.2552931065f, +-0.8660254038f, -0.4619397663f, -1.3194792169f, -1.1827865776f, -0.5000000000f, -1.1827865776f, -1.3194792169f, -0.4619397663f, +-0.8660254038f, -1.2552931065f, -0.3535533906f, -0.4174197128f, -1.0000000000f, -0.1913417162f, +0.0947343455f, -0.5924659585f, ++0.0000000000f, +0.5924659585f, -0.0947343455f, +0.1913417162f, +1.0000000000f, +0.4174197128f, +0.3535533906f, +1.2552931065f, ++0.8660254038f, +0.4619397663f, +1.3194792169f, +1.1827865776f, +0.5000000000f, +1.1827865776f, +1.3194792169f, +0.4619397663f, ++0.8660254038f, +1.2552931065f, +0.3535533906f, +0.4174197128f, +1.0000000000f, +0.1913417162f, -0.0947343455f, +0.5924659585f, ++0.0000000000f, -0.5924659585f, +0.0947343455f, -0.1913417162f, -1.0000000000f, -0.4174197128f, -0.3535533906f, -1.2552931065f, +-0.8660254038f, -0.4619397663f, -1.3194792169f, -1.1827865776f, -0.5000000000f, -1.1827865776f, -1.3194792169f, -0.4619397663f, +-0.8660254038f, -1.2552931065f, -0.3535533906f, -0.4174197128f, -1.0000000000f, -0.1913417162f, +0.0947343455f, -0.5924659585f, +-0.0000000000f, +0.5924659585f, -0.0947343455f, +0.1913417162f, +1.0000000000f, +0.4174197128f, +0.3535533906f, +1.2552931065f, ++0.8660254038f, +0.4619397663f, +1.3194792169f, +1.1827865776f, +0.5000000000f, +1.1827865776f, +1.3194792169f, +0.4619397663f, ++0.8660254038f, +1.2552931065f, +0.3535533906f, +0.4174197128f, +1.0000000000f, +0.1913417162f, -0.0947343455f, +0.5924659585f, ++0.0000000000f, -0.5924659585f, +0.0947343455f, -0.1913417162f, -1.0000000000f, -0.4174197128f, -0.3535533906f, -1.2552931065f, +-0.8660254038f, -0.4619397663f, -1.3194792169f, -1.1827865776f, -0.5000000000f, -1.1827865776f, -1.3194792169f, -0.4619397663f, +-0.8660254038f, -1.2552931065f, -0.3535533906f, -0.4174197128f, -1.0000000000f, -0.1913417162f, +0.0947343455f, -0.5924659585f, +-0.0000000000f, +0.5924659585f, -0.0947343455f, +0.1913417162f, +1.0000000000f, +0.4174197128f, +0.3535533906f, +1.2552931065f, ++0.8660254038f, +0.4619397663f, +1.3194792169f, +1.1827865776f, +0.5000000000f, +1.1827865776f, +1.3194792169f, +0.4619397663f, ++0.8660254038f, +1.2552931065f, +0.3535533906f, +0.4174197128f, +1.0000000000f, +0.1913417162f, -0.0947343455f, +0.5924659585f, ++0.0000000000f, -0.5924659585f, +0.0947343455f, -0.1913417162f, -1.0000000000f, -0.4174197128f, -0.3535533906f, -1.2552931065f, }; -float32_t refOutput[320] = +float32_t refOutput[320] = { -+0.0000000000f, -0.0010797829f, -0.0007681386f, -0.0001982932f, +0.0000644313f, +0.0020854271f, +0.0036891871f, +0.0015855941f, --0.0026280805f, -0.0075907658f, -0.0119390538f, -0.0086665968f, +0.0088981202f, +0.0430539279f, +0.0974468742f, +0.1740405600f, -+0.2681416601f, +0.3747720089f, +0.4893362230f, +0.6024154672f, +0.7058740791f, +0.7968348987f, +0.8715901940f, +0.9277881093f, -+0.9682182661f, +0.9934674267f, +1.0012052245f, +0.9925859371f, +0.9681538347f, +0.9257026822f, +0.8679010068f, +0.7952493046f, -+0.7085021596f, +0.6100062330f, +0.5012752767f, +0.3834386057f, +0.2592435399f, +0.1309866321f, -0.0000000000f, -0.1309866321f, --0.2592435399f, -0.3834386057f, -0.5012752767f, -0.6100062330f, -0.7085021596f, -0.7952493046f, -0.8679010068f, -0.9257026822f, --0.9681538347f, -0.9936657199f, -1.0019733630f, -0.9936657199f, -0.9681538347f, -0.9257026822f, -0.8679010068f, -0.7952493046f, --0.7085021596f, -0.6100062330f, -0.5012752767f, -0.3834386057f, -0.2592435399f, -0.1309866321f, +0.0000000000f, +0.1309866321f, -+0.2592435399f, +0.3834386057f, +0.5012752767f, +0.6100062330f, +0.7085021596f, +0.7952493046f, +0.8679010068f, +0.9257026822f, -+0.9681538347f, +0.9936657199f, +1.0019733630f, +0.9936657199f, +0.9681538347f, +0.9257026822f, +0.8679010068f, +0.7952493046f, -+0.7085021596f, +0.6100062330f, +0.5012752767f, +0.3834386057f, +0.2592435399f, +0.1309866321f, -0.0000000000f, -0.1309866321f, --0.2592435399f, -0.3834386057f, -0.5012752767f, -0.6100062330f, -0.7085021596f, -0.7952493046f, -0.8679010068f, -0.9257026822f, --0.9681538347f, -0.9936657199f, -1.0019733630f, -0.9936657199f, -0.9681538347f, -0.9257026822f, -0.8679010068f, -0.7952493046f, --0.7085021596f, -0.6100062330f, -0.5012752767f, -0.3834386057f, -0.2592435399f, -0.1309866321f, +0.0000000000f, +0.1309866321f, -+0.2592435399f, +0.3834386057f, +0.5012752767f, +0.6100062330f, +0.7085021596f, +0.7952493046f, +0.8679010068f, +0.9257026822f, -+0.9681538347f, +0.9936657199f, +1.0019733630f, +0.9936657199f, +0.9681538347f, +0.9257026822f, +0.8679010068f, +0.7952493046f, -+0.7085021596f, +0.6100062330f, +0.5012752767f, +0.3834386057f, +0.2592435399f, +0.1309866321f, -0.0000000000f, -0.1309866321f, --0.2592435399f, -0.3834386057f, -0.5012752767f, -0.6100062330f, -0.7085021596f, -0.7952493046f, -0.8679010068f, -0.9257026822f, --0.9681538347f, -0.9936657199f, -1.0019733630f, -0.9936657199f, -0.9681538347f, -0.9257026822f, -0.8679010068f, -0.7952493046f, --0.7085021596f, -0.6100062330f, -0.5012752767f, -0.3834386057f, -0.2592435399f, -0.1309866321f, +0.0000000000f, +0.1309866321f, -+0.2592435399f, +0.3834386057f, +0.5012752767f, +0.6100062330f, +0.7085021596f, +0.7952493046f, +0.8679010068f, +0.9257026822f, -+0.9681538347f, +0.9936657199f, +1.0019733630f, +0.9936657199f, +0.9681538347f, +0.9257026822f, +0.8679010068f, +0.7952493046f, -+0.7085021596f, +0.6100062330f, +0.5012752767f, +0.3834386057f, +0.2592435399f, +0.1309866321f, +0.0000000000f, -0.1309866321f, --0.2592435399f, -0.3834386057f, -0.5012752767f, -0.6100062330f, -0.7085021596f, -0.7952493046f, -0.8679010068f, -0.9257026822f, --0.9681538347f, -0.9936657199f, -1.0019733630f, -0.9936657199f, -0.9681538347f, -0.9257026822f, -0.8679010068f, -0.7952493046f, --0.7085021596f, -0.6100062330f, -0.5012752767f, -0.3834386057f, -0.2592435399f, -0.1309866321f, +0.0000000000f, +0.1309866321f, -+0.2592435399f, +0.3834386057f, +0.5012752767f, +0.6100062330f, +0.7085021596f, +0.7952493046f, +0.8679010068f, +0.9257026822f, -+0.9681538347f, +0.9936657199f, +1.0019733630f, +0.9936657199f, +0.9681538347f, +0.9257026822f, +0.8679010068f, +0.7952493046f, -+0.7085021596f, +0.6100062330f, +0.5012752767f, +0.3834386057f, +0.2592435399f, +0.1309866321f, +0.0000000000f, -0.1309866321f, --0.2592435399f, -0.3834386057f, -0.5012752767f, -0.6100062330f, -0.7085021596f, -0.7952493046f, -0.8679010068f, -0.9257026822f, --0.9681538347f, -0.9936657199f, -1.0019733630f, -0.9936657199f, -0.9681538347f, -0.9257026822f, -0.8679010068f, -0.7952493046f, --0.7085021596f, -0.6100062330f, -0.5012752767f, -0.3834386057f, -0.2592435399f, -0.1309866321f, -0.0000000000f, +0.1309866321f, -+0.2592435399f, +0.3834386057f, +0.5012752767f, +0.6100062330f, +0.7085021596f, +0.7952493046f, +0.8679010068f, +0.9257026822f, -+0.9681538347f, +0.9936657199f, +1.0019733630f, +0.9936657199f, +0.9681538347f, +0.9257026822f, +0.8679010068f, +0.7952493046f, -+0.7085021596f, +0.6100062330f, +0.5012752767f, +0.3834386057f, +0.2592435399f, +0.1309866321f, +0.0000000000f, -0.1309866321f, --0.2592435399f, -0.3834386057f, -0.5012752767f, -0.6100062330f, -0.7085021596f, -0.7952493046f, -0.8679010068f, -0.9257026822f, --0.9681538347f, -0.9936657199f, -1.0019733630f, -0.9936657199f, -0.9681538347f, -0.9257026822f, -0.8679010068f, -0.7952493046f, --0.7085021596f, -0.6100062330f, -0.5012752767f, -0.3834386057f, -0.2592435399f, -0.1309866321f, +0.0000000000f, +0.1309866321f, -+0.2592435399f, +0.3834386057f, +0.5012752767f, +0.6100062330f, +0.7085021596f, +0.7952493046f, +0.8679010068f, +0.9257026822f, -+0.9681538347f, +0.9936657199f, +1.0019733630f, +0.9936657199f, +0.9681538347f, +0.9257026822f, +0.8679010068f, +0.7952493046f ++0.0000000000f, -0.0010797829f, -0.0007681386f, -0.0001982932f, +0.0000644313f, +0.0020854271f, +0.0036891871f, +0.0015855941f, +-0.0026280805f, -0.0075907658f, -0.0119390538f, -0.0086665968f, +0.0088981202f, +0.0430539279f, +0.0974468742f, +0.1740405600f, ++0.2681416601f, +0.3747720089f, +0.4893362230f, +0.6024154672f, +0.7058740791f, +0.7968348987f, +0.8715901940f, +0.9277881093f, ++0.9682182661f, +0.9934674267f, +1.0012052245f, +0.9925859371f, +0.9681538347f, +0.9257026822f, +0.8679010068f, +0.7952493046f, ++0.7085021596f, +0.6100062330f, +0.5012752767f, +0.3834386057f, +0.2592435399f, +0.1309866321f, -0.0000000000f, -0.1309866321f, +-0.2592435399f, -0.3834386057f, -0.5012752767f, -0.6100062330f, -0.7085021596f, -0.7952493046f, -0.8679010068f, -0.9257026822f, +-0.9681538347f, -0.9936657199f, -1.0019733630f, -0.9936657199f, -0.9681538347f, -0.9257026822f, -0.8679010068f, -0.7952493046f, +-0.7085021596f, -0.6100062330f, -0.5012752767f, -0.3834386057f, -0.2592435399f, -0.1309866321f, +0.0000000000f, +0.1309866321f, ++0.2592435399f, +0.3834386057f, +0.5012752767f, +0.6100062330f, +0.7085021596f, +0.7952493046f, +0.8679010068f, +0.9257026822f, ++0.9681538347f, +0.9936657199f, +1.0019733630f, +0.9936657199f, +0.9681538347f, +0.9257026822f, +0.8679010068f, +0.7952493046f, ++0.7085021596f, +0.6100062330f, +0.5012752767f, +0.3834386057f, +0.2592435399f, +0.1309866321f, -0.0000000000f, -0.1309866321f, +-0.2592435399f, -0.3834386057f, -0.5012752767f, -0.6100062330f, -0.7085021596f, -0.7952493046f, -0.8679010068f, -0.9257026822f, +-0.9681538347f, -0.9936657199f, -1.0019733630f, -0.9936657199f, -0.9681538347f, -0.9257026822f, -0.8679010068f, -0.7952493046f, +-0.7085021596f, -0.6100062330f, -0.5012752767f, -0.3834386057f, -0.2592435399f, -0.1309866321f, +0.0000000000f, +0.1309866321f, ++0.2592435399f, +0.3834386057f, +0.5012752767f, +0.6100062330f, +0.7085021596f, +0.7952493046f, +0.8679010068f, +0.9257026822f, ++0.9681538347f, +0.9936657199f, +1.0019733630f, +0.9936657199f, +0.9681538347f, +0.9257026822f, +0.8679010068f, +0.7952493046f, ++0.7085021596f, +0.6100062330f, +0.5012752767f, +0.3834386057f, +0.2592435399f, +0.1309866321f, -0.0000000000f, -0.1309866321f, +-0.2592435399f, -0.3834386057f, -0.5012752767f, -0.6100062330f, -0.7085021596f, -0.7952493046f, -0.8679010068f, -0.9257026822f, +-0.9681538347f, -0.9936657199f, -1.0019733630f, -0.9936657199f, -0.9681538347f, -0.9257026822f, -0.8679010068f, -0.7952493046f, +-0.7085021596f, -0.6100062330f, -0.5012752767f, -0.3834386057f, -0.2592435399f, -0.1309866321f, +0.0000000000f, +0.1309866321f, ++0.2592435399f, +0.3834386057f, +0.5012752767f, +0.6100062330f, +0.7085021596f, +0.7952493046f, +0.8679010068f, +0.9257026822f, ++0.9681538347f, +0.9936657199f, +1.0019733630f, +0.9936657199f, +0.9681538347f, +0.9257026822f, +0.8679010068f, +0.7952493046f, ++0.7085021596f, +0.6100062330f, +0.5012752767f, +0.3834386057f, +0.2592435399f, +0.1309866321f, +0.0000000000f, -0.1309866321f, +-0.2592435399f, -0.3834386057f, -0.5012752767f, -0.6100062330f, -0.7085021596f, -0.7952493046f, -0.8679010068f, -0.9257026822f, +-0.9681538347f, -0.9936657199f, -1.0019733630f, -0.9936657199f, -0.9681538347f, -0.9257026822f, -0.8679010068f, -0.7952493046f, +-0.7085021596f, -0.6100062330f, -0.5012752767f, -0.3834386057f, -0.2592435399f, -0.1309866321f, +0.0000000000f, +0.1309866321f, ++0.2592435399f, +0.3834386057f, +0.5012752767f, +0.6100062330f, +0.7085021596f, +0.7952493046f, +0.8679010068f, +0.9257026822f, ++0.9681538347f, +0.9936657199f, +1.0019733630f, +0.9936657199f, +0.9681538347f, +0.9257026822f, +0.8679010068f, +0.7952493046f, ++0.7085021596f, +0.6100062330f, +0.5012752767f, +0.3834386057f, +0.2592435399f, +0.1309866321f, +0.0000000000f, -0.1309866321f, +-0.2592435399f, -0.3834386057f, -0.5012752767f, -0.6100062330f, -0.7085021596f, -0.7952493046f, -0.8679010068f, -0.9257026822f, +-0.9681538347f, -0.9936657199f, -1.0019733630f, -0.9936657199f, -0.9681538347f, -0.9257026822f, -0.8679010068f, -0.7952493046f, +-0.7085021596f, -0.6100062330f, -0.5012752767f, -0.3834386057f, -0.2592435399f, -0.1309866321f, -0.0000000000f, +0.1309866321f, ++0.2592435399f, +0.3834386057f, +0.5012752767f, +0.6100062330f, +0.7085021596f, +0.7952493046f, +0.8679010068f, +0.9257026822f, ++0.9681538347f, +0.9936657199f, +1.0019733630f, +0.9936657199f, +0.9681538347f, +0.9257026822f, +0.8679010068f, +0.7952493046f, ++0.7085021596f, +0.6100062330f, +0.5012752767f, +0.3834386057f, +0.2592435399f, +0.1309866321f, +0.0000000000f, -0.1309866321f, +-0.2592435399f, -0.3834386057f, -0.5012752767f, -0.6100062330f, -0.7085021596f, -0.7952493046f, -0.8679010068f, -0.9257026822f, +-0.9681538347f, -0.9936657199f, -1.0019733630f, -0.9936657199f, -0.9681538347f, -0.9257026822f, -0.8679010068f, -0.7952493046f, +-0.7085021596f, -0.6100062330f, -0.5012752767f, -0.3834386057f, -0.2592435399f, -0.1309866321f, +0.0000000000f, +0.1309866321f, ++0.2592435399f, +0.3834386057f, +0.5012752767f, +0.6100062330f, +0.7085021596f, +0.7952493046f, +0.8679010068f, +0.9257026822f, ++0.9681538347f, +0.9936657199f, +1.0019733630f, +0.9936657199f, +0.9681538347f, +0.9257026822f, +0.8679010068f, +0.7952493046f }; diff --git a/libraries/tests/dsp/cmsis/fir_f32/main.cpp b/libraries/tests/dsp/cmsis/fir_f32/main.cpp index 092a25de28..f6bdb4b7ce 100644 --- a/libraries/tests/dsp/cmsis/fir_f32/main.cpp +++ b/libraries/tests/dsp/cmsis/fir_f32/main.cpp @@ -1,5 +1,5 @@ -#include "arm_math.h" -#include "math_helper.h" +#include "arm_math.h" +#include "math_helper.h" #include #define BLOCK_SIZE 32 @@ -14,19 +14,19 @@ * The input signal and reference output (computed with MATLAB) * are defined externally in arm_fir_lpf_data.c. * ------------------------------------------------------------------- */ -extern float32_t testInput_f32_1kHz_15kHz[TEST_LENGTH_SAMPLES]; -extern float32_t refOutput[TEST_LENGTH_SAMPLES]; +extern float32_t testInput_f32_1kHz_15kHz[TEST_LENGTH_SAMPLES]; +extern float32_t refOutput[TEST_LENGTH_SAMPLES]; -/* ------------------------------------------------------------------- +/* ------------------------------------------------------------------- * Declare State buffer of size (numTaps + blockSize - 1) * ------------------------------------------------------------------- */ -static float32_t firStateF32[BLOCK_SIZE + NUM_TAPS - 1]; +static float32_t firStateF32[BLOCK_SIZE + NUM_TAPS - 1]; -/* ---------------------------------------------------------------------- - * FIR Coefficients buffer generated using fir1() MATLAB function. +/* ---------------------------------------------------------------------- + * FIR Coefficients buffer generated using fir1() MATLAB function. * fir1(28, 6/24) - * ------------------------------------------------------------------- */ -const float32_t firCoeffs32[NUM_TAPS] = { + * ------------------------------------------------------------------- */ +const float32_t firCoeffs32[NUM_TAPS] = { -0.0018225230f, -0.0015879294f, +0.0000000000f, +0.0036977508f, +0.0080754303f, +0.0085302217f, -0.0000000000f, -0.0173976984f, -0.0341458607f, -0.0333591565f, +0.0000000000f, +0.0676308395f, +0.1522061835f, +0.2229246956f, +0.2504960933f, @@ -35,23 +35,23 @@ const float32_t firCoeffs32[NUM_TAPS] = { +0.0036977508f, +0.0000000000f, -0.0015879294f, -0.0018225230f }; -/* ---------------------------------------------------------------------- - * FIR LPF Example +/* ---------------------------------------------------------------------- + * FIR LPF Example * ------------------------------------------------------------------- */ -int main(void) { +int main(void) { /* Call FIR init function to initialize the instance structure. */ arm_fir_instance_f32 S; - arm_fir_init_f32(&S, NUM_TAPS, (float32_t *)&firCoeffs32[0], &firStateF32[0], BLOCK_SIZE); - - /* ---------------------------------------------------------------------- - * Call the FIR process function for every blockSize samples - * ------------------------------------------------------------------- */ + arm_fir_init_f32(&S, NUM_TAPS, (float32_t *)&firCoeffs32[0], &firStateF32[0], BLOCK_SIZE); + + /* ---------------------------------------------------------------------- + * Call the FIR process function for every blockSize samples + * ------------------------------------------------------------------- */ for (uint32_t i=0; i < NUM_BLOCKS; i++) { float32_t* signal = testInput_f32_1kHz_15kHz + (i * BLOCK_SIZE); arm_fir_f32(&S, signal, signal, BLOCK_SIZE); - } - - /* ---------------------------------------------------------------------- + } + + /* ---------------------------------------------------------------------- * Compare the generated output against the reference output computed * in MATLAB. * ------------------------------------------------------------------- */ @@ -62,4 +62,4 @@ int main(void) { } else { printf("Success\n\r"); } -} +} diff --git a/libraries/tests/dsp/mbed/fir_f32/main.cpp b/libraries/tests/dsp/mbed/fir_f32/main.cpp index c7c9e4c0cd..d5e98d58ee 100644 --- a/libraries/tests/dsp/mbed/fir_f32/main.cpp +++ b/libraries/tests/dsp/mbed/fir_f32/main.cpp @@ -14,7 +14,7 @@ float32_t output[TEST_LENGTH_SAMPLES]; /* FIR Coefficients buffer generated using fir1() MATLAB function: fir1(28, 6/24) */ #define NUM_TAPS 29 -const float32_t firCoeffs32[NUM_TAPS] = { +const float32_t firCoeffs32[NUM_TAPS] = { -0.0018225230f, -0.0015879294f, +0.0000000000f, +0.0036977508f, +0.0080754303f, +0.0085302217f, -0.0000000000f, -0.0173976984f, -0.0341458607f, -0.0333591565f, +0.0000000000f, +0.0676308395f, +0.1522061835f, +0.2229246956f, +0.2504960933f, @@ -29,7 +29,7 @@ int main() { Sine_f32 sine_1KHz( 1000, SAMPLE_RATE, 1.0); Sine_f32 sine_15KHz(15000, SAMPLE_RATE, 0.5); FIR_f32 fir(firCoeffs32); - + float32_t buffer_a[BLOCK_SIZE]; float32_t buffer_b[BLOCK_SIZE]; for (float32_t *sgn=output; sgn<(output+TEST_LENGTH_SAMPLES); sgn += BLOCK_SIZE) { @@ -37,12 +37,12 @@ int main() { sine_15KHz.process(buffer_a, buffer_b); // Add a 15KHz sine wave fir.process(buffer_b, sgn); // FIR low pass filter: 6KHz cutoff } - + sine_1KHz.reset(); for (float32_t *sgn=expected_output; sgn<(expected_output+TEST_LENGTH_SAMPLES); sgn += BLOCK_SIZE) { sine_1KHz.generate(sgn); // Generate a 1KHz sine wave } - + float snr = arm_snr_f32(&expected_output[DELAY-1], &output[WARMUP-1], TEST_LENGTH_SAMPLES-WARMUP); printf("snr: %f\n\r", snr); if (snr < SNR_THRESHOLD_F32) { diff --git a/libraries/tests/export/mcb1700/main.cpp b/libraries/tests/export/mcb1700/main.cpp index 395eac0f48..bc1d2c6748 100644 --- a/libraries/tests/export/mcb1700/main.cpp +++ b/libraries/tests/export/mcb1700/main.cpp @@ -7,7 +7,7 @@ int main() { while (true) { float value = 8.0 * in.read(); printf("analog in: %f\n\r", value); - + int led_mask = 0; if (value > 0.5) led_mask |= 1 << 0; if (value > 1.5) led_mask |= 1 << 1; @@ -18,7 +18,7 @@ int main() { if (value > 6.5) led_mask |= 1 << 6; if (value > 7.5) led_mask |= 1 << 7; leds = led_mask; - + wait(1); } } diff --git a/libraries/tests/libs/SPIHalfDuplex/SPIHalfDuplex.h b/libraries/tests/libs/SPIHalfDuplex/SPIHalfDuplex.h index ff5555e19f..14633b8555 100644 --- a/libraries/tests/libs/SPIHalfDuplex/SPIHalfDuplex.h +++ b/libraries/tests/libs/SPIHalfDuplex/SPIHalfDuplex.h @@ -30,7 +30,7 @@ namespace mbed { * // Send a byte to a SPI half-duplex slave, and record the response * * #include "mbed.h" - * + * * SPIHalfDuplex device(p5, p6, p7) // mosi, miso, sclk * * int main() { @@ -42,7 +42,7 @@ namespace mbed { class SPIHalfDuplex : public SPI { public: - + /** Create a SPI half-duplex master connected to the specified pins * * Pin Options: @@ -65,7 +65,7 @@ public: * Response from the SPI slave */ virtual int write(int value); - + /** Set the number of databits expected from the slave, from 4-16 * * @param sbits Number of expected bits in the slave response diff --git a/libraries/tests/libs/SerialHalfDuplex/SerialHalfDuplex.cpp b/libraries/tests/libs/SerialHalfDuplex/SerialHalfDuplex.cpp index f6e54a99d6..7594e40473 100644 --- a/libraries/tests/libs/SerialHalfDuplex/SerialHalfDuplex.cpp +++ b/libraries/tests/libs/SerialHalfDuplex/SerialHalfDuplex.cpp @@ -12,7 +12,7 @@ namespace mbed { SerialHalfDuplex::SerialHalfDuplex(PinName tx, PinName rx) : Serial(tx, rx) { - + gpio_init(&gpio, tx, PIN_INPUT); gpio_mode(&gpio, PullNone); // no pull } @@ -27,19 +27,19 @@ SerialHalfDuplex::SerialHalfDuplex(PinName tx, PinName rx) // 6. Re-enable interrupts int SerialHalfDuplex::_putc(int c) { int retc; - + // TODO: We should not disable all interrupts __disable_irq(); - + serial_pinout_tx(gpio.pin); - + Serial::_putc(c); retc = Serial::getc(); // reading also clears any interrupt - + pin_function(gpio.pin, 0); - + __enable_irq(); - + return retc; } diff --git a/libraries/tests/libs/SerialHalfDuplex/SerialHalfDuplex.h b/libraries/tests/libs/SerialHalfDuplex/SerialHalfDuplex.h index 744e261b2f..0ba13d38e5 100644 --- a/libraries/tests/libs/SerialHalfDuplex/SerialHalfDuplex.h +++ b/libraries/tests/libs/SerialHalfDuplex/SerialHalfDuplex.h @@ -13,13 +13,13 @@ namespace mbed { -/** A serial port (UART) for communication with other devices using +/** A serial port (UART) for communication with other devices using * Half-Duplex, allowing transmit and receive on a single - * shared transmit and receive line. Only one end should be transmitting + * shared transmit and receive line. Only one end should be transmitting * at a time. - * - * Both the tx and rx pin should be defined, and wired together. - * This is in addition to them being wired to the other serial + * + * Both the tx and rx pin should be defined, and wired together. + * This is in addition to them being wired to the other serial * device to allow both read and write functions to operate. * * For Simplex and Full-Duplex Serial communication, see Serial() @@ -27,9 +27,9 @@ namespace mbed { * Example: * @code * // Send a byte to a second HalfDuplex device, and read the response - * + * * #include "mbed.h" - * + * * // p9 and p10 should be wired together to form "a" * // p28 and p27 should be wired together to form "b" * // p9/p10 should be wired to p28/p27 as the Half Duplex connection @@ -40,7 +40,7 @@ namespace mbed { * void b_rx() { // second device response * b.putc(b.getc() + 4); * } - * + * * int main() { * b.attach(&b_rx); * for (int c = 'A'; c < 'Z'; c++) { diff --git a/libraries/tests/mbed/analog_in/main.cpp b/libraries/tests/mbed/analog_in/main.cpp index 4be49f849a..157885df36 100644 --- a/libraries/tests/mbed/analog_in/main.cpp +++ b/libraries/tests/mbed/analog_in/main.cpp @@ -6,12 +6,12 @@ * Connect 'control' to pin 21 of an mbed LPC1768 * Connect 'analogInput' to pin 18 of an mbed LPC1768 * Connect 'TX/RX' to pins 27 and 28 of an mbed LPC1768 - * - * Upload: + * + * Upload: */ #include "test_env.h" -#define ERROR_TOLERANCE 0.05 +#define ERROR_TOLERANCE 0.05 #if defined(TARGET_LPC1114) diff --git a/libraries/tests/mbed/can/main.cpp b/libraries/tests/mbed/can/main.cpp index 4a51923f8b..f6fd7d15d4 100644 --- a/libraries/tests/mbed/can/main.cpp +++ b/libraries/tests/mbed/can/main.cpp @@ -10,14 +10,14 @@ CAN can2(p34, p33); CAN can2(p30, p29); #endif char counter = 0; - -void printmsg(char *title, CANMessage *msg) { + +void printmsg(char *title, CANMessage *msg) { printf("%s [%03X]", title, msg->id); for(char i = 0; i < msg->len; i++) { printf(" %02X", msg->data[i]); } printf("\n"); -} +} void send() { printf("send()\n"); @@ -25,7 +25,7 @@ void send() { if(can1.write(msg)) { printmsg("Tx message:", &msg); counter++; - } + } led1 = !led1; } diff --git a/libraries/tests/mbed/can_interrupt/main.cpp b/libraries/tests/mbed/can_interrupt/main.cpp index 979e7ac3d9..468ee4e0d2 100644 --- a/libraries/tests/mbed/can_interrupt/main.cpp +++ b/libraries/tests/mbed/can_interrupt/main.cpp @@ -10,14 +10,14 @@ CAN can2(p34, p33); CAN can2(p30, p29); #endif char counter = 0; - -void printmsg(char *title, CANMessage *msg) { + +void printmsg(char *title, CANMessage *msg) { printf("%s [%03X]", title, msg->id); for(char i = 0; i < msg->len; i++) { printf(" %02X", msg->data[i]); } printf("\n"); -} +} void send() { printf("send()\n"); @@ -25,7 +25,7 @@ void send() { if(can1.write(msg)) { printmsg("Tx message:", &msg); counter++; - } + } led1 = !led1; } @@ -37,7 +37,7 @@ void read() { led2 = !led2; } } - + int main() { printf("main()\n"); ticker.attach(&send, 1); diff --git a/libraries/tests/mbed/digitalin_digitalout/main.cpp b/libraries/tests/mbed/digitalin_digitalout/main.cpp index fe9a4f627e..15848c320f 100644 --- a/libraries/tests/mbed/digitalin_digitalout/main.cpp +++ b/libraries/tests/mbed/digitalin_digitalout/main.cpp @@ -1,10 +1,6 @@ #include "test_env.h" -#if defined(TARGET_FF_ARDUINO) -DigitalOut out(D0); -DigitalIn in(D7); - -#elif defined(TARGET_LPC1114) +#if defined(TARGET_LPC1114) DigitalOut out(dp1); DigitalIn in(dp2); @@ -12,6 +8,10 @@ DigitalIn in(dp2); DigitalOut out(PC_6); DigitalIn in(PB_8); +#elif defined(TARGET_FF_ARDUINO) +DigitalOut out(D7); +DigitalIn in(D0); + #else DigitalOut out(p5); DigitalIn in(p25); diff --git a/libraries/tests/mbed/digitalinout/main.cpp b/libraries/tests/mbed/digitalinout/main.cpp index 30c5f5bd6b..2ba498e4ef 100644 --- a/libraries/tests/mbed/digitalinout/main.cpp +++ b/libraries/tests/mbed/digitalinout/main.cpp @@ -1,10 +1,6 @@ #include "test_env.h" -#if defined(TARGET_FF_ARDUINO) -DigitalInOut d1(D0); -DigitalInOut d2(D7); - -#elif defined(TARGET_LPC1114) +#if defined(TARGET_LPC1114) DigitalInOut d1(dp1); DigitalInOut d2(dp2); @@ -12,6 +8,10 @@ DigitalInOut d2(dp2); DigitalInOut d1(PC_6); DigitalInOut d2(PB_8); +#elif defined(TARGET_FF_ARDUINO) +DigitalInOut d1(D0); +DigitalInOut d2(D7); + #else DigitalInOut d1(p5); DigitalInOut d2(p25); diff --git a/libraries/tests/mbed/dir/main.cpp b/libraries/tests/mbed/dir/main.cpp index dc642cd640..feb3241057 100644 --- a/libraries/tests/mbed/dir/main.cpp +++ b/libraries/tests/mbed/dir/main.cpp @@ -14,7 +14,7 @@ void notify_completion(bool success) { } else { printf("{failure}\n"); } - + printf("{end}\n"); led_blink(success ? LED1 : LED4); } @@ -28,7 +28,7 @@ FILE* test_open(char* path, const char* mode) { printf("Error opening file\n"); notify_completion(false); } - + return f; } @@ -50,12 +50,12 @@ void test_close(FILE* f) { int main() { LocalFileSystem local("local"); - + FILE *f; char* str = TEST_STRING; char* buffer = (char*) malloc(sizeof(unsigned char)*strlen(TEST_STRING)); int str_len = strlen(TEST_STRING); - + printf("Write files\n"); char filename[32]; for (int i=0; i<10; i++) { @@ -65,7 +65,7 @@ int main() { test_write(f, str); test_close(f); } - + printf("List files:\n"); DIR *d = opendir("/local"); struct dirent *p; @@ -73,6 +73,6 @@ int main() { printf("%s\n", p->d_name); } closedir(d); - + notify_completion(true); } diff --git a/libraries/tests/mbed/dir_sd/main.cpp b/libraries/tests/mbed/dir_sd/main.cpp index 286ae47b8a..ee3b8b1394 100644 --- a/libraries/tests/mbed/dir_sd/main.cpp +++ b/libraries/tests/mbed/dir_sd/main.cpp @@ -1,48 +1,56 @@ #include "mbed.h" #include "SDFileSystem.h" -void led_blink(PinName led) { +void led_blink(PinName led) +{ DigitalOut myled(led); + while (1) { myled = !myled; wait(1.0); } } -void notify_completion(bool success) { - if (success) { +void notify_completion(bool success) +{ + if (success) printf("{success}\n"); - } else { + else printf("{failure}\n"); - } - + printf("{end}\n"); led_blink(success ? LED1 : LED4); } #define TEST_STRING "Hello World!" -FILE* test_open(char* path, const char* mode) { +FILE *test_open(char *path, const char *mode) +{ FILE *f; + f = fopen(path, mode); if (f == NULL) { printf("Error opening file\n"); notify_completion(false); } - + return f; } -void test_write(FILE* f, const char* str) { +void test_write(FILE *f, const char *str) +{ int n = fprintf(f, str); + if (n != strlen(str)) { printf("Error writing file\n"); notify_completion(false); } } -void test_close(FILE* f) { +void test_close(FILE *f) +{ int rc = fclose(f); + if (rc != 0) { printf("Error closing file\n"); notify_completion(false); @@ -51,45 +59,52 @@ void test_close(FILE* f) { DigitalOut led2(LED2); -int main() { +int main() +{ #if defined(TARGET_KL25Z) SDFileSystem sd(PTD2, PTD3, PTD1, PTD0, "sd"); #elif defined(TARGET_nRF51822) //SDFileSystem sd(p20, p22, p25, p24, "sd"); -SDFileSystem sd(p12, p13, p15, p14, "sd"); + SDFileSystem sd(p12, p13, p15, p14, "sd"); +#elif defined(TARGET_NUCLEO_F103RB) || \ + defined(TARGET_NUCLEO_L152RE) || \ + defined(TARGET_NUCLEO_F302R8) || \ + defined(TARGET_NUCLEO_F030R8) || \ + defined(TARGET_NUCLEO_F401RE) || \ + defined(TARGET_NUCLEO_L053R8) + SDFileSystem sd(D11, D12, D13, D10, "sd"); #else SDFileSystem sd(p11, p12, p13, p14, "sd"); #endif - led2=1; - wait(0.5); + led2 = 1; + wait(0.5); FILE *f; - char* str = TEST_STRING; - char* buffer = (char*) malloc(sizeof(unsigned char)*strlen(TEST_STRING)); + char *str = TEST_STRING; + char *buffer = (char *)malloc(sizeof(unsigned char) * strlen(TEST_STRING)); int str_len = strlen(TEST_STRING); - + printf("Write files\n"); char filename[32]; - for (int i=0; i<10; i++) { + for (int i = 0; i < 10; i++) { sprintf(filename, "/sd/test_%d.txt", i); printf("Creating file: %s\n", filename); f = test_open(filename, "w"); - led2=0; + led2 = 0; test_write(f, str); test_close(f); } - + printf("List files:\n"); DIR *d = opendir("/sd"); if (d == NULL) { printf("Error opening directory\n"); notify_completion(false); } - + struct dirent *p; - while((p = readdir(d)) != NULL) { + while ((p = readdir(d)) != NULL) printf("%s\n", p->d_name); - } closedir(d); - + notify_completion(true); } diff --git a/libraries/tests/mbed/echo/main.cpp b/libraries/tests/mbed/echo/main.cpp index 583e9d884d..a0e6087d33 100644 --- a/libraries/tests/mbed/echo/main.cpp +++ b/libraries/tests/mbed/echo/main.cpp @@ -1,6 +1,11 @@ #include "mbed.h" -#if defined(TARGET_NUCLEO_F103RB) || defined(TARGET_NUCLEO_L152RE) || defined(TARGET_NUCLEO_F401RE) || defined(TARGET_NUCLEO_F030R8) +#if defined(TARGET_NUCLEO_F103RB) || \ + defined(TARGET_NUCLEO_L152RE) || \ + defined(TARGET_NUCLEO_F302R8) || \ + defined(TARGET_NUCLEO_F030R8) || \ + defined(TARGET_NUCLEO_F401RE) || \ + defined(TARGET_NUCLEO_L053R8) #define TXPIN STDIO_UART_TX #define RXPIN STDIO_UART_RX #else diff --git a/libraries/tests/mbed/echo_flow_control/main.cpp b/libraries/tests/mbed/echo_flow_control/main.cpp index d0b6c1b20b..327bca62d4 100644 --- a/libraries/tests/mbed/echo_flow_control/main.cpp +++ b/libraries/tests/mbed/echo_flow_control/main.cpp @@ -24,9 +24,9 @@ int main() { char buf[256]; pc.set_flow_control(Serial::RTSCTS, FLOW_CONTROL_RTS, FLOW_CONTROL_CTS); -#ifdef RTS_CHECK_PIN +#ifdef RTS_CHECK_PIN in.fall(checker); -#endif +#endif while (1) { pc.gets(buf, 256); pc.printf("%s", buf); diff --git a/libraries/tests/mbed/env/test_env.cpp b/libraries/tests/mbed/env/test_env.cpp index 1c86c03625..28a29f5353 100644 --- a/libraries/tests/mbed/env/test_env.cpp +++ b/libraries/tests/mbed/env/test_env.cpp @@ -17,7 +17,7 @@ void notify_completion(bool success) { } else { printf("{{failure}}" NL ); } - + printf("{{end}}" NL); #ifdef LED4 led_blink(success ? LED1 : LED4); diff --git a/libraries/tests/mbed/freopen/TextDisplay.cpp b/libraries/tests/mbed/freopen/TextDisplay.cpp index 4076addae6..0eb30f56cd 100644 --- a/libraries/tests/mbed/freopen/TextDisplay.cpp +++ b/libraries/tests/mbed/freopen/TextDisplay.cpp @@ -2,14 +2,14 @@ * Copyright (c) 2007-2009 sford * Released under the MIT License: http://mbed.org/license/mit */ - + #include "TextDisplay.h" TextDisplay::TextDisplay(const char *name) : Stream(name) { _row = 0; _column = 0; } - + int TextDisplay::_putc(int value) { if(value == '\n') { _column = 0; @@ -47,7 +47,7 @@ void TextDisplay::locate(int column, int row) { int TextDisplay::_getc() { return -1; } - + void TextDisplay::foreground(int colour) { _foreground = colour; } diff --git a/libraries/tests/mbed/freopen/TextDisplay.h b/libraries/tests/mbed/freopen/TextDisplay.h index a9d6de3cf2..51694ab1be 100644 --- a/libraries/tests/mbed/freopen/TextDisplay.h +++ b/libraries/tests/mbed/freopen/TextDisplay.h @@ -9,7 +9,7 @@ * Everything else (locate, printf, putc, cls) will come for free * * The model is the display will wrap at the right and bottom, so you can - * keep writing and will always get valid characters. The location is + * keep writing and will always get valid characters. The location is * maintained internally to the class to make this easy */ @@ -26,7 +26,7 @@ public: virtual void character(int column, int row, int c) = 0; virtual int rows() = 0; virtual int columns() = 0; - + // functions that come for free, but can be overwritten virtual void cls(); virtual void locate(int column, int row); @@ -34,7 +34,7 @@ public: virtual void background(int colour); // putc (from Stream) // printf (from Stream) - + protected: virtual int _putc(int value); diff --git a/libraries/tests/mbed/freopen/TextLCD.cpp b/libraries/tests/mbed/freopen/TextLCD.cpp index 00e386a5cc..8e70c3c299 100644 --- a/libraries/tests/mbed/freopen/TextLCD.cpp +++ b/libraries/tests/mbed/freopen/TextLCD.cpp @@ -2,7 +2,7 @@ * Copyright (c) 2007-2009 sford * Released under the MIT License: http://mbed.org/license/mit */ - + #include "TextLCD.h" #include "mbed.h" @@ -15,7 +15,7 @@ * After attaching the supply voltage/after a reset, the display needs to be brought in to a defined state * * - wait approximately 15 ms so the display is ready to execute commands - * - Execute the command 0x30 ("Display Settings") three times (wait 1,64ms after each command, the busy flag cannot be queried now). + * - Execute the command 0x30 ("Display Settings") three times (wait 1,64ms after each command, the busy flag cannot be queried now). * - The display is in 8 bit mode, so if you have only connected 4 data pins you should only transmit the higher nibble of each command. * - If you want to use the 4 bit mode, now you can execute the command to switch over to this mode now. * - Execute the "clear display" command @@ -23,19 +23,19 @@ * Timing * ====== * - * Nearly all commands transmitted to the display need 40us for execution. - * Exceptions are the commands "Clear Display and Reset" and "Set Cursor to Start Position" - * These commands need 1.64ms for execution. These timings are valid for all displays working with an - * internal clock of 250kHz. But I do not know any displays that use other frequencies. Any time you + * Nearly all commands transmitted to the display need 40us for execution. + * Exceptions are the commands "Clear Display and Reset" and "Set Cursor to Start Position" + * These commands need 1.64ms for execution. These timings are valid for all displays working with an + * internal clock of 250kHz. But I do not know any displays that use other frequencies. Any time you * can use the busy flag to test if the display is ready to accept the next command. - * + * * _e is kept high apart from calling clock * _rw is kept 0 (write) apart from actions that uyse it differently * _rs is set by the data/command writes */ -TextLCD::TextLCD(PinName rs, PinName rw, PinName e, PinName d0, PinName d1, - PinName d2, PinName d3, const char *name) : TextDisplay(name), _rw(rw), _rs(rs), +TextLCD::TextLCD(PinName rs, PinName rw, PinName e, PinName d0, PinName d1, + PinName d2, PinName d3, const char *name) : TextDisplay(name), _rw(rw), _rs(rs), _e(e), _d(d0, d1, d2, d3) { _rw = 0; @@ -45,46 +45,46 @@ TextLCD::TextLCD(PinName rs, PinName rw, PinName e, PinName d0, PinName d1, // Should theoretically wait 15ms, but most things will be powered up pre-reset // so i'll disable that for the minute. If implemented, could wait 15ms post reset // instead - // wait(0.015); - + // wait(0.015); + // send "Display Settings" 3 times (Only top nibble of 0x30 as we've got 4-bit bus) for(int i=0; i<3; i++) { writeByte(0x3); wait(0.00164); // this command takes 1.64ms, so wait for it } writeByte(0x2); // 4-bit mode - - writeCommand(0x28); // Function set 001 BW N F - - + + writeCommand(0x28); // Function set 001 BW N F - - writeCommand(0x0C); - writeCommand(0x6); // Cursor Direction and Display Shift : 0000 01 CD S (CD 0-left, 1-right S(hift) 0-no, 1-yes + writeCommand(0x6); // Cursor Direction and Display Shift : 0000 01 CD S (CD 0-left, 1-right S(hift) 0-no, 1-yes cls(); } void TextLCD::character(int column, int row, int c) { int address = 0x80 + (row * 40) + column; // memory starts at 0x80, and is 40 chars long per row - writeCommand(address); - writeData(c); + writeCommand(address); + writeData(c); } int TextLCD::columns() { return 16; } -int TextLCD::rows() { - return 2; +int TextLCD::rows() { + return 2; } void TextLCD::writeByte(int value) { _d = value >> 4; wait(0.000040f); // most instructions take 40us _e = 0; - wait(0.000040f); - _e = 1; + wait(0.000040f); + _e = 1; _d = value >> 0; wait(0.000040f); _e = 0; wait(0.000040f); // most instructions take 40us - _e = 1; + _e = 1; } void TextLCD::writeCommand(int command) { diff --git a/libraries/tests/mbed/freopen/TextLCD.h b/libraries/tests/mbed/freopen/TextLCD.h index 22f986f6eb..9a29792183 100644 --- a/libraries/tests/mbed/freopen/TextLCD.h +++ b/libraries/tests/mbed/freopen/TextLCD.h @@ -12,11 +12,11 @@ public: TextLCD(PinName rs, PinName rw, PinName e, PinName d0, PinName d1, PinName d2, PinName d3, const char *name = NULL); virtual void character(int column, int row, int c); - virtual int rows(); - virtual int columns(); + virtual int rows(); + virtual int columns(); // locate, cls, putc, printf come from derived class - + protected: void writeByte(int value); diff --git a/libraries/tests/mbed/freopen/main.cpp b/libraries/tests/mbed/freopen/main.cpp index 795fad6f23..145a684a7e 100644 --- a/libraries/tests/mbed/freopen/main.cpp +++ b/libraries/tests/mbed/freopen/main.cpp @@ -3,25 +3,25 @@ int main() { printf("printf to stdout\n"); - + // printf to specific peripherals Serial pc(USBTX, USBRX); pc.printf("Serial(USBTX, USBRX).printf\n"); - + TextLCD lcd(p14, p15, p16, p17, p18, p19, p20, "lcd"); // rs, rw, e, d0-d3, name lcd.printf("TextLCD.printf\n"); - + // change stdout to file LocalFileSystem local("local"); freopen("/local/output.txt", "w", stdout); printf("printf redirected to LocalFileSystem\n"); fclose(stdout); - + // change stdout to LCD freopen("/lcd", "w", stdout); printf("printf redirected to TextLCD\n"); fclose(stdout); - + DigitalOut led(LED1); while (true) { led = !led; diff --git a/libraries/tests/mbed/fs/main.cpp b/libraries/tests/mbed/fs/main.cpp index 3948f60b6c..2dc525cd08 100644 --- a/libraries/tests/mbed/fs/main.cpp +++ b/libraries/tests/mbed/fs/main.cpp @@ -1,9 +1,9 @@ #include "mbed.h" #include "rtos.h" #include "SDFileSystem.h" - + #define FILE_LOC "/sd/test.txt" - + Serial pc(USBTX, USBRX); Serial gps(p28, p27); Serial test(p9,p10); @@ -12,7 +12,7 @@ SDFileSystem sd(p11, p12, p13, p14, "sd"); DigitalOut myled(LED1); DigitalOut sdled(LED2); - + void sd_thread(void const *argument) { while (true) { sdled = !sdled; diff --git a/libraries/tests/mbed/heap_and_stack/main.cpp b/libraries/tests/mbed/heap_and_stack/main.cpp index 4bd61dbf1c..a127efedb4 100644 --- a/libraries/tests/mbed/heap_and_stack/main.cpp +++ b/libraries/tests/mbed/heap_and_stack/main.cpp @@ -9,10 +9,10 @@ static unsigned int iterations = 0; void report_iterations(void) { unsigned int tot = (0x100 * iterations)*2; printf("\nAllocated (%d)Kb in (%u) iterations\n", tot/1024, iterations); -#if !defined(TOOLCHAIN_GCC_CR) +#if !defined(TOOLCHAIN_GCC_CR) // EA: This causes a crash when compiling with GCC_CR??? printf("%.2f\n", ((float)(tot)/(float)(initial_stack_p - initial_heap_p))*100.); -#endif +#endif #ifdef TOOLCHAIN_ARM #ifndef __MICROLIB __heapvalid((__heapprt) fprintf, stdout, 1); @@ -23,12 +23,12 @@ void report_iterations(void) { void stack_test(char *latest_heap_pointer) { char stack_line[256]; iterations++; - + sprintf(stack_line, "\nstack pointer: %p", &stack_line[255]); puts(stack_line); - + char *heap_pointer = (char*)malloc(0x100); - + if (heap_pointer == NULL) { int diff = (&stack_line[255] - latest_heap_pointer); if (diff > 0x200) { @@ -45,7 +45,7 @@ void stack_test(char *latest_heap_pointer) { sprintf(line, "heap pointer: %p", heap_pointer); puts(line); } - + if ((&stack_line[255]) > heap_pointer) { stack_test(heap_pointer); } else { @@ -58,19 +58,19 @@ void stack_test(char *latest_heap_pointer) { int main (void) { char c; initial_stack_p = &c; - + initial_heap_p = (char*)malloc(1); if (initial_heap_p == NULL) { printf("Unable to malloc a single byte\n"); notify_completion(false); } - + printf("Initial stack/heap geometry:\n"); printf(" stack pointer:V %p\n", initial_stack_p); printf(" heap pointer :^ %p\n", initial_heap_p); - + initial_heap_p++; stack_test(initial_heap_p); - + notify_completion(true); } diff --git a/libraries/tests/mbed/i2c_TMP102/main.cpp b/libraries/tests/mbed/i2c_TMP102/main.cpp index 6453e8ecb0..682ff98f2c 100644 --- a/libraries/tests/mbed/i2c_TMP102/main.cpp +++ b/libraries/tests/mbed/i2c_TMP102/main.cpp @@ -10,19 +10,20 @@ TMP102 temperature(D10, D11, 0x90); #elif defined(TARGET_LPC4088) TMP102 temperature(p9, p10, 0x90); +#elif defined(TARGET_LPC2368) +TMP102 temperature(p28, p27, 0x90); + #else TMP102 temperature(p28, p27, 0x90); #endif -int main() { +int main() +{ float t = temperature.read(); - printf("Temperature: %f\n\r", t); - + + printf("TMP102: Temperature: %f\n\r", t); // In our test environment (ARM office) we should get a temperature within // the range ]15, 30[C - if ((t > 15.0) && (t < 30.0)) { - notify_completion(true); - } else { - notify_completion(false); - } + bool result = (t > 15.0) && (t < 30.0); + notify_completion(result); } diff --git a/libraries/tests/mbed/i2c_eeprom/main.cpp b/libraries/tests/mbed/i2c_eeprom/main.cpp index af391b853f..0b49b54dd9 100644 --- a/libraries/tests/mbed/i2c_eeprom/main.cpp +++ b/libraries/tests/mbed/i2c_eeprom/main.cpp @@ -33,12 +33,20 @@ I2C i2c(P0_10, P0_11); #elif defined(TARGET_LPC1549) I2C i2c(P0_23, P0_22); -#elif defined(TARGET_NUCLEO_F103RB) +#elif defined(TARGET_NUCLEO_F103RB) || \ + defined(TARGET_NUCLEO_L152RE) || \ + defined(TARGET_NUCLEO_F302R8) || \ + defined(TARGET_NUCLEO_F030R8) || \ + defined(TARGET_NUCLEO_F401RE) || \ + defined(TARGET_NUCLEO_L053R8) I2C i2c(I2C_SDA, I2C_SCL); #elif defined(TARGET_K64F) I2C i2c(PTE25, PTE24); +#elif defined(TARGET_LPC11U68) +I2C i2c(SDA, SCL); + #else I2C i2c(p28, p27); #endif diff --git a/libraries/tests/mbed/i2c_eeprom_line/main.cpp b/libraries/tests/mbed/i2c_eeprom_line/main.cpp index 91a6693d5f..c487079643 100644 --- a/libraries/tests/mbed/i2c_eeprom_line/main.cpp +++ b/libraries/tests/mbed/i2c_eeprom_line/main.cpp @@ -42,7 +42,15 @@ I2C i2c(P0_10, P0_11); #elif defined(TARGET_LPC1549) I2C i2c(P0_23, P0_22); -#elif defined(TARGET_NUCLEO_F103RB) +#elif defined(TARGET_LPC11U68) +I2C i2c(SDA, SCL); + +#elif defined(TARGET_NUCLEO_F103RB) || \ + defined(TARGET_NUCLEO_L152RE) || \ + defined(TARGET_NUCLEO_F302R8) || \ + defined(TARGET_NUCLEO_F030R8) || \ + defined(TARGET_NUCLEO_F401RE) || \ + defined(TARGET_NUCLEO_L053R8) I2C i2c(I2C_SDA, I2C_SCL); #elif defined(TARGET_K64F) @@ -106,8 +114,8 @@ int main() } printf("[%s]\r\n", read_errors ? "FAIL" : "OK"); - printf("I2C: Read errors: %d ... [%s]\r\n", read_errors, read_errors ? "FAIL" : "OK"); - printf("EEPROM: Pattern match errors: %d ... [%s]\r\n", pattern_errors, pattern_errors ? "FAIL" : "OK"); + printf("I2C: Read errors: %d/%d ... [%s]\r\n", read_errors, ntests, read_errors ? "FAIL" : "OK"); + printf("EEPROM: Pattern match errors: %d/%d ... [%s]\r\n", pattern_errors, ntests, pattern_errors ? "FAIL" : "OK"); result = write_errors == 0 && read_errors == 0; notify_completion(result); diff --git a/libraries/tests/mbed/i2c_master_slave/main.cpp b/libraries/tests/mbed/i2c_master_slave/main.cpp index 7f7d00f6b7..f94b59f3db 100644 --- a/libraries/tests/mbed/i2c_master_slave/main.cpp +++ b/libraries/tests/mbed/i2c_master_slave/main.cpp @@ -8,7 +8,7 @@ // ******************************************************** // This tests data transfer between two I2C interfaces on // the same chip, one configured as master, the other as -// slave. Works on the LPC1768 mbed. +// slave. Works on the LPC1768 mbed. // // Wiring: // p28 <-> p9 @@ -35,7 +35,7 @@ int main() { notify_completion(false); return 1; - } + } slave.read(&received, 1); if(sent != received) { diff --git a/libraries/tests/mbed/i2c_slave/main.cpp b/libraries/tests/mbed/i2c_slave/main.cpp index 66831d0bc4..1b24b3cd4b 100644 --- a/libraries/tests/mbed/i2c_slave/main.cpp +++ b/libraries/tests/mbed/i2c_slave/main.cpp @@ -22,13 +22,13 @@ I2CSlave slave(p28, p27); switch (i) { case I2CSlave::ReadAddressed: slave.write(buf, SIZE); - for(int i = 0; i < SIZE; i++){ + for(int i = 0; i < SIZE; i++){ } break; case I2CSlave::WriteAddressed: slave.read(buf, SIZE); for(int i = 0; i < SIZE; i++){ - buf[i]++; + buf[i]++; } break; } diff --git a/libraries/tests/mbed/interruptin/main.cpp b/libraries/tests/mbed/interruptin/main.cpp index 4a8e336f9f..530e2fbdab 100644 --- a/libraries/tests/mbed/interruptin/main.cpp +++ b/libraries/tests/mbed/interruptin/main.cpp @@ -29,9 +29,18 @@ void in_handler() { #define PIN_IN (p11) #define PIN_OUT (p12) -#elif defined(TARGET_NUCLEO_F103RB) || defined(TARGET_NUCLEO_L152RE) || defined(TARGET_NUCLEO_F401RE) || defined(TARGET_NUCLEO_F030R8) -#define PIN_IN (PB_8) -#define PIN_OUT (PC_6) +#elif defined(TARGET_NUCLEO_F103RB) || \ + defined(TARGET_NUCLEO_L152RE) || \ + defined(TARGET_NUCLEO_F302R8) || \ + defined(TARGET_NUCLEO_F030R8) || \ + defined(TARGET_NUCLEO_F401RE) || \ + defined(TARGET_NUCLEO_L053R8) +#define PIN_IN PB_8 +#define PIN_OUT PC_6 + +#elif defined(TARGET_FF_ARDUINO) +#define PIN_OUT D0 +#define PIN_IN D7 #else #define PIN_IN (p5) diff --git a/libraries/tests/mbed/interruptin_2/main.cpp b/libraries/tests/mbed/interruptin_2/main.cpp index 7768f77b0b..0f12f6e976 100644 --- a/libraries/tests/mbed/interruptin_2/main.cpp +++ b/libraries/tests/mbed/interruptin_2/main.cpp @@ -28,7 +28,7 @@ InterruptIn button9(p15); DigitalOut led(LED1); DigitalOut flash(LED2); -#else +#else InterruptIn button(p30); InterruptIn button1(p29); InterruptIn button2(p28); @@ -42,11 +42,11 @@ InterruptIn button9(p21); DigitalOut led(LED1); DigitalOut flash(LED4); #endif - + void flip() { led = !led; } - + int main() { flash = 0; led = 0; diff --git a/libraries/tests/mbed/modserial/main.cpp b/libraries/tests/mbed/modserial/main.cpp index a16abcf811..7db8c6876d 100644 --- a/libraries/tests/mbed/modserial/main.cpp +++ b/libraries/tests/mbed/modserial/main.cpp @@ -48,35 +48,35 @@ void rxCallback(MODSERIAL_IRQ_INFO *q) { int main() { int c = 'A'; - + // Ensure the baud rate for the PC "USB" serial is much // higher than "uart" baud rate below. (default: 9600) // pc.baud(9600); - + // Use a deliberatly slow baud to fill up the TX buffer uart.baud(1200); - + uart.attach(&txCallback, MODSERIAL::ModTxIrq); uart.attach(&rxCallback, MODSERIAL::ModRxIrq); uart.attach(&txEmpty, MODSERIAL::ModTxEmpty); - + // Loop sending characters. We send 512 // which is twice the default TX/RX buffer size. - + led1 = 1; // Show start of sending with LED1. - + for (int loop = 0; loop < 512; loop++) { - uart.printf("%c", c); + uart.printf("%c", c); c++; if (c > 'Z') c = 'A'; } - + led1 = 0; // Show the end of sending by switching off LED1. - + // End program. Flash LED4. Notice how LED 2 and 3 continue - // to flash for a short period while the interrupt system + // to flash for a short period while the interrupt system // continues to send the characters left in the TX buffer. - + while(1) { led4 = !led4; wait(0.25); @@ -97,7 +97,7 @@ int main() { * * Of interest is that last "R" character after the system has said "Done." * This comes from the fact that the TxEmpty callback is made when the TX buffer - * becomes empty. MODSERIAL makes use of the fact that the Uarts built into the + * becomes empty. MODSERIAL makes use of the fact that the Uarts built into the * LPC17xx device use a 16 byte FIFO on both RX and TX channels. This means that * when the TxEmpty callback is made, the TX buffer is empty, but that just means * the "last few characters" were written to the TX FIFO. So although the TX @@ -110,6 +110,6 @@ int main() { * In a similar way, when characters are received into the RX FIFO, the entire * FIFO contents is moved to the RX buffer, assuming there is room left in the * RX buffer. If there is not, any remaining characters are left in the RX FIFO - * and will be moved to the RX buffer on the next interrupt or when the running + * and will be moved to the RX buffer on the next interrupt or when the running * program removes a character(s) from the RX buffer with the getc() method. */ diff --git a/libraries/tests/mbed/portinout/main.cpp b/libraries/tests/mbed/portinout/main.cpp index e1babdfc03..06345d3174 100644 --- a/libraries/tests/mbed/portinout/main.cpp +++ b/libraries/tests/mbed/portinout/main.cpp @@ -1,6 +1,15 @@ #include "test_env.h" -#if defined(TARGET_LPC11U24) +#if defined(TARGET_K64F) +#define P1_1 (1 << 16) +#define P1_2 (1 << 17) +#define PORT_1 PortC + +#define P2_1 (1 << 2) +#define P2_2 (1 << 3) +#define PORT_2 PortC + +#elif defined(TARGET_LPC11U24) #define P1_1 (1 << 9) // p0.9 #define P1_2 (1 << 8) // p0.8 #define PORT_1 Port0 @@ -72,24 +81,24 @@ PortInOut port2(PORT_2, MASK_2); int main() { bool check = true; - + port1.output(); port2.input(); - + port1 = MASK_1; wait(0.1); if (port2 != MASK_2) check = false; - + port1 = 0; wait(0.1); if (port2 != 0) check = false; - + port1.input(); port2.output(); - + port2 = MASK_2; wait(0.1); if (port1 != MASK_1) check = false; - + port2 = 0; wait(0.1); if (port1 != 0) check = false; - + notify_completion(check); } diff --git a/libraries/tests/mbed/portout/main.cpp b/libraries/tests/mbed/portout/main.cpp index d6e04353cd..b15383bad0 100644 --- a/libraries/tests/mbed/portout/main.cpp +++ b/libraries/tests/mbed/portout/main.cpp @@ -7,7 +7,7 @@ # define LED4 (1 << 23) // P1.23 # elif defined(TARGET_LPC11U24) || defined(TARGET_LPC1114) # define LED1 (1 << 8) // P1.8 -# define LED2 (1 << 9) // P1.9 +# define LED2 (1 << 9) // P1.9 # define LED3 (1 << 10) // P1.10 # define LED4 (1 << 11) // P1.11 # endif diff --git a/libraries/tests/mbed/portout_portin/main.cpp b/libraries/tests/mbed/portout_portin/main.cpp index 1c4310b0a8..6a178eebbb 100644 --- a/libraries/tests/mbed/portout_portin/main.cpp +++ b/libraries/tests/mbed/portout_portin/main.cpp @@ -1,6 +1,6 @@ #include "test_env.h" -#if defined(TARGET_K64F) +#if defined(TARGET_K64F) || defined(TARGET_KL05Z) #define P1_1 (1 << 16) #define P1_2 (1 << 17) #define PORT_1 PortC @@ -87,7 +87,7 @@ int main() { printf("[Test high] expected (0x%x) received (0x%x)\n", MASK_2, value); notify_completion(false); } - + port_out = 0; wait(0.1); value = port_in.read(); @@ -95,6 +95,6 @@ int main() { printf("[Test low] expected (0x%x) received (0x%x)\n", 0, value); notify_completion(false); } - + notify_completion(true); } diff --git a/libraries/tests/mbed/pwm/main.cpp b/libraries/tests/mbed/pwm/main.cpp index 4d049e6858..fd99c96457 100644 --- a/libraries/tests/mbed/pwm/main.cpp +++ b/libraries/tests/mbed/pwm/main.cpp @@ -13,7 +13,7 @@ CT32B0/MR0 p25 (P1_24) CT32B0/MR1 p26 (P1_25) and USBTX (P0_19) CT32B0/MR2 p10 (P1_26) */ - + float value = 0.75; int main() { @@ -59,7 +59,7 @@ int main() { printf("Initialize PWM on pin 25 with duty cycle: %.2f\n", pwm_p25.read()); #elif defined(TARGET_DISCO_F100RB) - PwmOut pwm_1(PB_3); + PwmOut pwm_1(PB_3); PwmOut pwm_2(PB_4); pwm_1.write(0.75); @@ -68,7 +68,7 @@ int main() { printf("Initialize PWM on pin PB_3 with duty cycle: %.2f\n", pwm_1.read()); printf("Initialize PWM on pin PB_4 with duty cycle: %.2f\n", pwm_2.read()); #elif defined(TARGET_DISCO_F051R8) - PwmOut pwm_1(PA_7); + PwmOut pwm_1(PA_7); PwmOut pwm_2(PC_7); pwm_1.write(0.75); @@ -77,7 +77,7 @@ int main() { printf("Initialize PWM on pin PA_7 with duty cycle: %.2f\n", pwm_1.read()); printf("Initialize PWM on pin PC_7 with duty cycle: %.2f\n", pwm_2.read()); #elif defined(TARGET_DISCO_F303VC) - PwmOut pwm_1(PA_8); + PwmOut pwm_1(PA_8); PwmOut pwm_2(PA_9); pwm_1.write(0.75); diff --git a/libraries/tests/mbed/reset/main.cpp b/libraries/tests/mbed/reset/main.cpp index be2817bfbd..b38218e706 100644 --- a/libraries/tests/mbed/reset/main.cpp +++ b/libraries/tests/mbed/reset/main.cpp @@ -7,7 +7,7 @@ extern "C" void mbed_reset(); int main() { pc.printf("start\n"); wait(1); - + unsigned int counter = 0; while(1) { pc.printf("%u\n",counter++); diff --git a/libraries/tests/mbed/rpc/main.cpp b/libraries/tests/mbed/rpc/main.cpp index a8336c3ed0..9912c671b6 100644 --- a/libraries/tests/mbed/rpc/main.cpp +++ b/libraries/tests/mbed/rpc/main.cpp @@ -34,7 +34,11 @@ int main() { // Function RPCFunction rpc_foo(&foo, "foo"); +#if defined(TOOLCHAIN_ARM_MICRO) + RPC_TEST("/foo/run 1", "3.299999952316284"); +#else RPC_TEST("/foo/run 1", "3.2999999523162842"); +#endif // Class RPC::add_rpc_class(); diff --git a/libraries/tests/mbed/sd/main.cpp b/libraries/tests/mbed/sd/main.cpp index 54bccab7b5..612cf4f344 100644 --- a/libraries/tests/mbed/sd/main.cpp +++ b/libraries/tests/mbed/sd/main.cpp @@ -11,12 +11,23 @@ SDFileSystem sd(PTD6, PTD7, PTD5, PTD4, "sd"); #elif defined(TARGET_nRF51822) SDFileSystem sd(p12, p13, p15, p14, "sd"); -#elif defined(TARGET_NUCLEO_F103RB) +#elif defined(TARGET_NUCLEO_F103RB) || \ + defined(TARGET_NUCLEO_L152RE) || \ + defined(TARGET_NUCLEO_F302R8) || \ + defined(TARGET_NUCLEO_F030R8) || \ + defined(TARGET_NUCLEO_F401RE) || \ + defined(TARGET_NUCLEO_L053R8) SDFileSystem sd(D11, D12, D13, D10, "sd"); #elif defined(TARGET_DISCO_F051R8) SDFileSystem sd(SPI_MOSI, SPI_MISO, SPI_SCK, SPI_CS, "sd"); +#elif defined(TARGET_LPC2368) +SDFileSystem sd(p11, p12, p13, p14, "sd"); + +#elif defined(TARGET_LPC11U68) +SDFileSystem sd(D11, D12, D13, D10, "sd"); + #else SDFileSystem sd(p11, p12, p13, p14, "sd"); #endif diff --git a/libraries/tests/mbed/serial_interrupt/main.cpp b/libraries/tests/mbed/serial_interrupt/main.cpp index 2818422395..5174b308bf 100644 --- a/libraries/tests/mbed/serial_interrupt/main.cpp +++ b/libraries/tests/mbed/serial_interrupt/main.cpp @@ -1,5 +1,5 @@ #include "mbed.h" - + DigitalOut led1(LED1); DigitalOut led2(LED2); @@ -13,13 +13,13 @@ Serial computer(SERIAL_TX, SERIAL_RX); void txCallback() { led1 = !led1; } - + // This function is called when a character goes into the RX buffer. void rxCallback() { led2 = !led2; computer.putc(computer.getc()); } - + int main() { printf("start test\n"); computer.attach(&txCallback, Serial::TxIrq); diff --git a/libraries/tests/mbed/serial_interrupt_2/main.cpp b/libraries/tests/mbed/serial_interrupt_2/main.cpp index 00b199ed01..744116045e 100644 --- a/libraries/tests/mbed/serial_interrupt_2/main.cpp +++ b/libraries/tests/mbed/serial_interrupt_2/main.cpp @@ -22,17 +22,17 @@ int main() { // Use a deliberatly slow baud to fill up the TX buffer uart.baud(1200); uart.attach(&rxCallback, Serial::RxIrq); - + printf("Starting test loop:\n"); wait(1); - + int c = 'A'; for (int loop = 0; loop < 512; loop++) { uart.printf("%c", c); c++; if (c > 'Z') c = 'A'; } - + while (true) { led2 = !led2; wait(1); diff --git a/libraries/tests/mbed/sleep/main.cpp b/libraries/tests/mbed/sleep/main.cpp index ee26d4f694..6922b1ea4d 100644 --- a/libraries/tests/mbed/sleep/main.cpp +++ b/libraries/tests/mbed/sleep/main.cpp @@ -12,7 +12,7 @@ void flip() { int main() { wkp.rise(&flip); - + while (true) { // sleep(); deepsleep(); diff --git a/libraries/tests/mbed/spi/main.cpp b/libraries/tests/mbed/spi/main.cpp index 070469ee8d..ce571cf1d9 100644 --- a/libraries/tests/mbed/spi/main.cpp +++ b/libraries/tests/mbed/spi/main.cpp @@ -6,7 +6,7 @@ DigitalOut latchpin(p10); int main() { spi.format(8, 0); spi.frequency(16 * 1000 * 1000); - + latchpin = 0; while (1) { latchpin = 1; diff --git a/libraries/tests/mbed/spi_ADXL345/main.cpp b/libraries/tests/mbed/spi_ADXL345/main.cpp index 3eaa59b701..11055ebfa1 100644 --- a/libraries/tests/mbed/spi_ADXL345/main.cpp +++ b/libraries/tests/mbed/spi_ADXL345/main.cpp @@ -24,32 +24,32 @@ void check_X_Y(int v) { int main() { int readings[3] = {0, 0, 0}; - + printf("Starting ADXL345 test...\n"); printf("Device ID is: 0x%02x\n", accelerometer.getDevId()); - + //Go into standby mode to configure the device. accelerometer.setPowerControl(0x00); - + //Full resolution, +/-16g, 4mg/LSB. accelerometer.setDataFormatControl(0x0B); - + //3.2kHz data rate. accelerometer.setDataRate(ADXL345_3200HZ); - + //Measurement mode. accelerometer.setPowerControl(0x08); - + for (int i=0; i<3; i++) { wait(0.1); - + //13-bit, sign extended values. accelerometer.getOutput(readings); - + // X and Y check_X_Y(readings[0]); check_X_Y(readings[1]); - + // Z int16_t z = (int16_t)readings[2]; if ((z < MIN_Z) || (z > MAX_Z)) { @@ -57,6 +57,6 @@ int main() { notify_completion(false); } } - + notify_completion(true); } diff --git a/libraries/tests/mbed/spi_slave/main.cpp b/libraries/tests/mbed/spi_slave/main.cpp index ebc4a085c4..c9c58feb15 100644 --- a/libraries/tests/mbed/spi_slave/main.cpp +++ b/libraries/tests/mbed/spi_slave/main.cpp @@ -15,7 +15,7 @@ int main() { uint8_t resp = 0; device.reply(resp); // Prime SPI with first reply - + while(1) { if(device.receive()) { resp = device.read(); // Read byte from master and add 1 diff --git a/libraries/tests/mbed/spifi1/main.cpp b/libraries/tests/mbed/spifi1/main.cpp index 7f64f6d23d..97e6469b71 100644 --- a/libraries/tests/mbed/spifi1/main.cpp +++ b/libraries/tests/mbed/spifi1/main.cpp @@ -26,19 +26,19 @@ const unsigned char cube_image_ref[] = { int cube_image_ref_sz = sizeof(cube_image_ref); -/* +/* * The SPIFI_ROM_PTR (0x1FFF1FF8) points to an area where the pointers to * different drivers in ROM are stored. */ typedef struct { - /*const*/ unsigned p_usbd; // USBROMD + /*const*/ unsigned p_usbd; // USBROMD /*const*/ unsigned p_clib; /*const*/ unsigned p_cand; /*const*/ unsigned p_pwrd; // PWRROMD /*const*/ unsigned p_promd; // DIVROMD /*const*/ SPIFI_RTNS *pSPIFID; // SPIFIROMD /*const*/ unsigned p_dev3; - /*const*/ unsigned p_dev4; + /*const*/ unsigned p_dev4; } ROM; #define ROM_DRIVERS_PTR ((ROM *)(*((unsigned int *)SPIFI_ROM_PTR))) @@ -52,7 +52,7 @@ static void initialize_spifi(void) // Failed to allocate memory for ROM data notify_completion(false); } - + // Turn on SPIFI block as it is disabled on reset LPC_SC->PCONP |= 0x00010000; @@ -63,7 +63,7 @@ static void initialize_spifi(void) LPC_IOCON->P0_16 = 5; /* SPIFI_IO3 @ P0.16 */ LPC_IOCON->P0_17 = 5; /* SPIFI_IO1 @ P0.17 */ LPC_IOCON->P0_18 = 5; /* SPIFI_IO0 @ P0.18 */ - + uint32_t spifi_clk_div = (*((volatile uint32_t*)0x400FC1B4)) & 0x1f; uint32_t spifi_clk_mhz = (SystemCoreClock / spifi_clk_div) / 1000000; @@ -80,17 +80,17 @@ static void initialize_spifi(void) int main() { initialize_spifi(); - + // Make sure that cube_image is placed in SPIFI if (!IS_ADDR_IN_SPIFI(cube_image)) { notify_completion(false); } - + // Make sure that cube_image_ref is in IFLASH if (IS_ADDR_IN_SPIFI(cube_image_ref)) { notify_completion(false); } - + // Compare content if (cube_image_sz != cube_image_ref_sz) { notify_completion(false); @@ -102,6 +102,6 @@ int main() { } } } - + notify_completion(true); } diff --git a/libraries/tests/mbed/spifi1/spifi_rom_api.h b/libraries/tests/mbed/spifi1/spifi_rom_api.h index 69b752f196..baacb38209 100644 --- a/libraries/tests/mbed/spifi1/spifi_rom_api.h +++ b/libraries/tests/mbed/spifi1/spifi_rom_api.h @@ -3,9 +3,9 @@ written by CAM start 4/16/10 first testing 5/12/10 OK with first SST & Winbond devices 6/8/10 - OK with Gigadevice, Numonyx, Atmel, + OK with Gigadevice, Numonyx, Atmel, some Macronyx 7/13/10 - consensus with BK, performance optimized 8/24/10 + consensus with BK, performance optimized 8/24/10 this file is largely platform-independent */ #ifndef SPIFI_ROM_API_H @@ -14,7 +14,7 @@ #define SPIFI_MEM_BASE 0x28000000 /* allocated size of the SPIFI memory area on this device */ -#define MEM_AREA_SIZE 0x00001000 +#define MEM_AREA_SIZE 0x00001000 #define SPIFI_ROM_PTR 0x1FFF1FF8 /* define the symbol TESTING in the environment if test output desired */ @@ -61,7 +61,7 @@ typedef struct { } SPIFIopers; -/* bits in options operands (MODE3, RCVCLK, and FULLCLK +/* bits in options operands (MODE3, RCVCLK, and FULLCLK have the same relationship as in the Control register) */ #define S_MODE3 1 #define S_MODE0 0 @@ -87,7 +87,7 @@ typedef struct { /* interface to ROM API */ typedef struct { - int (*spifi_init) (SPIFIobj *obj, unsigned csHigh, unsigned options, + int (*spifi_init) (SPIFIobj *obj, unsigned csHigh, unsigned options, unsigned mhz); int (*spifi_program) (SPIFIobj *obj, char *source, SPIFIopers *opers); int (*spifi_erase) (SPIFIobj *obj, SPIFIopers *opers); @@ -97,19 +97,19 @@ typedef struct { /* mid level functions */ int (*checkAd) (SPIFIobj *obj, SPIFIopers *opers); - int (*setProt) (SPIFIobj *obj, SPIFIopers *opers, char *change, + int (*setProt) (SPIFIobj *obj, SPIFIopers *opers, char *change, char *saveProt); - int (*check_block) (SPIFIobj *obj, char *source, SPIFIopers *opers, + int (*check_block) (SPIFIobj *obj, char *source, SPIFIopers *opers, unsigned check_program); int (*send_erase_cmd) (SPIFIobj *obj, unsigned char op, unsigned addr); unsigned (*ck_erase) (SPIFIobj *obj, unsigned *addr, unsigned length); - int (*prog_block) (SPIFIobj *obj, char *source, SPIFIopers *opers, + int (*prog_block) (SPIFIobj *obj, char *source, SPIFIopers *opers, unsigned *left_in_page); unsigned (*ck_prog) (SPIFIobj *obj, char *source, char *dest, unsigned length); /* low level functions */ void(*setSize) (SPIFIobj *obj, int value); - int (*setDev) (SPIFIobj *obj, unsigned opts, unsigned mem_cmd, + int (*setDev) (SPIFIobj *obj, unsigned opts, unsigned mem_cmd, unsigned prog_cmd); unsigned (*cmd) (uint8_t op, uint8_t addrLen, uint8_t intLen, unsigned short len); unsigned (*readAd) (SPIFIobj *obj, unsigned cmd, unsigned addr); diff --git a/libraries/tests/mbed/spifi2/main.cpp b/libraries/tests/mbed/spifi2/main.cpp index cabfd29851..aac2a00d91 100644 --- a/libraries/tests/mbed/spifi2/main.cpp +++ b/libraries/tests/mbed/spifi2/main.cpp @@ -18,19 +18,19 @@ extern const unsigned char splash_image13[]; extern int splash_image13_sz; extern const unsigned char splash_image14[]; extern int splash_image14_sz; extern const unsigned char splash_image15[]; extern int splash_image15_sz; -/* +/* * The SPIFI_ROM_PTR (0x1FFF1FF8) points to an area where the pointers to * different drivers in ROM are stored. */ typedef struct { - /*const*/ unsigned p_usbd; // USBROMD + /*const*/ unsigned p_usbd; // USBROMD /*const*/ unsigned p_clib; /*const*/ unsigned p_cand; /*const*/ unsigned p_pwrd; // PWRROMD /*const*/ unsigned p_promd; // DIVROMD /*const*/ SPIFI_RTNS *pSPIFID; // SPIFIROMD /*const*/ unsigned p_dev3; - /*const*/ unsigned p_dev4; + /*const*/ unsigned p_dev4; } ROM; #define ROM_DRIVERS_PTR ((ROM *)(*((unsigned int *)SPIFI_ROM_PTR))) @@ -44,7 +44,7 @@ static void initialize_spifi(void) // Failed to allocate memory for ROM data notify_completion(false); } - + // Turn on SPIFI block as it is disabled on reset LPC_SC->PCONP |= 0x00010000; @@ -55,7 +55,7 @@ static void initialize_spifi(void) LPC_IOCON->P0_16 = 5; /* SPIFI_IO3 @ P0.16 */ LPC_IOCON->P0_17 = 5; /* SPIFI_IO1 @ P0.17 */ LPC_IOCON->P0_18 = 5; /* SPIFI_IO0 @ P0.18 */ - + uint32_t spifi_clk_div = (*((volatile uint32_t*)0x400FC1B4)) & 0x1f; uint32_t spifi_clk_mhz = (SystemCoreClock / spifi_clk_div) / 1000000; @@ -74,27 +74,27 @@ int main() { initialize_spifi(); // Make sure that most files are placed in IFLASH - if (IS_ADDR_IN_SPIFI(splash_image1) || - IS_ADDR_IN_SPIFI(splash_image2) || - IS_ADDR_IN_SPIFI(splash_image3) || - IS_ADDR_IN_SPIFI(splash_image4) || - IS_ADDR_IN_SPIFI(splash_image5) || - IS_ADDR_IN_SPIFI(splash_image6) || - IS_ADDR_IN_SPIFI(splash_image7) || - IS_ADDR_IN_SPIFI(splash_image8) || - IS_ADDR_IN_SPIFI(splash_image9) || - IS_ADDR_IN_SPIFI(splash_image10) || - IS_ADDR_IN_SPIFI(splash_image11) || - IS_ADDR_IN_SPIFI(splash_image12) || + if (IS_ADDR_IN_SPIFI(splash_image1) || + IS_ADDR_IN_SPIFI(splash_image2) || + IS_ADDR_IN_SPIFI(splash_image3) || + IS_ADDR_IN_SPIFI(splash_image4) || + IS_ADDR_IN_SPIFI(splash_image5) || + IS_ADDR_IN_SPIFI(splash_image6) || + IS_ADDR_IN_SPIFI(splash_image7) || + IS_ADDR_IN_SPIFI(splash_image8) || + IS_ADDR_IN_SPIFI(splash_image9) || + IS_ADDR_IN_SPIFI(splash_image10) || + IS_ADDR_IN_SPIFI(splash_image11) || + IS_ADDR_IN_SPIFI(splash_image12) || IS_ADDR_IN_SPIFI(splash_image13) || IS_ADDR_IN_SPIFI(splash_image14)) { notify_completion(false); } - + // Make sure that splash_image15 is placed in SPIFI if (!IS_ADDR_IN_SPIFI(splash_image15)) { notify_completion(false); } - + notify_completion(true); } diff --git a/libraries/tests/mbed/spifi2/spifi_rom_api.h b/libraries/tests/mbed/spifi2/spifi_rom_api.h index 69b752f196..baacb38209 100644 --- a/libraries/tests/mbed/spifi2/spifi_rom_api.h +++ b/libraries/tests/mbed/spifi2/spifi_rom_api.h @@ -3,9 +3,9 @@ written by CAM start 4/16/10 first testing 5/12/10 OK with first SST & Winbond devices 6/8/10 - OK with Gigadevice, Numonyx, Atmel, + OK with Gigadevice, Numonyx, Atmel, some Macronyx 7/13/10 - consensus with BK, performance optimized 8/24/10 + consensus with BK, performance optimized 8/24/10 this file is largely platform-independent */ #ifndef SPIFI_ROM_API_H @@ -14,7 +14,7 @@ #define SPIFI_MEM_BASE 0x28000000 /* allocated size of the SPIFI memory area on this device */ -#define MEM_AREA_SIZE 0x00001000 +#define MEM_AREA_SIZE 0x00001000 #define SPIFI_ROM_PTR 0x1FFF1FF8 /* define the symbol TESTING in the environment if test output desired */ @@ -61,7 +61,7 @@ typedef struct { } SPIFIopers; -/* bits in options operands (MODE3, RCVCLK, and FULLCLK +/* bits in options operands (MODE3, RCVCLK, and FULLCLK have the same relationship as in the Control register) */ #define S_MODE3 1 #define S_MODE0 0 @@ -87,7 +87,7 @@ typedef struct { /* interface to ROM API */ typedef struct { - int (*spifi_init) (SPIFIobj *obj, unsigned csHigh, unsigned options, + int (*spifi_init) (SPIFIobj *obj, unsigned csHigh, unsigned options, unsigned mhz); int (*spifi_program) (SPIFIobj *obj, char *source, SPIFIopers *opers); int (*spifi_erase) (SPIFIobj *obj, SPIFIopers *opers); @@ -97,19 +97,19 @@ typedef struct { /* mid level functions */ int (*checkAd) (SPIFIobj *obj, SPIFIopers *opers); - int (*setProt) (SPIFIobj *obj, SPIFIopers *opers, char *change, + int (*setProt) (SPIFIobj *obj, SPIFIopers *opers, char *change, char *saveProt); - int (*check_block) (SPIFIobj *obj, char *source, SPIFIopers *opers, + int (*check_block) (SPIFIobj *obj, char *source, SPIFIopers *opers, unsigned check_program); int (*send_erase_cmd) (SPIFIobj *obj, unsigned char op, unsigned addr); unsigned (*ck_erase) (SPIFIobj *obj, unsigned *addr, unsigned length); - int (*prog_block) (SPIFIobj *obj, char *source, SPIFIopers *opers, + int (*prog_block) (SPIFIobj *obj, char *source, SPIFIopers *opers, unsigned *left_in_page); unsigned (*ck_prog) (SPIFIobj *obj, char *source, char *dest, unsigned length); /* low level functions */ void(*setSize) (SPIFIobj *obj, int value); - int (*setDev) (SPIFIobj *obj, unsigned opts, unsigned mem_cmd, + int (*setDev) (SPIFIobj *obj, unsigned opts, unsigned mem_cmd, unsigned prog_cmd); unsigned (*cmd) (uint8_t op, uint8_t addrLen, uint8_t intLen, unsigned short len); unsigned (*readAd) (SPIFIobj *obj, unsigned cmd, unsigned addr); diff --git a/libraries/tests/mbed/stdio/main.cpp b/libraries/tests/mbed/stdio/main.cpp index ab32d6110e..5ebe100c0a 100644 --- a/libraries/tests/mbed/stdio/main.cpp +++ b/libraries/tests/mbed/stdio/main.cpp @@ -11,14 +11,14 @@ fprintf(stderr, "Test 4: fprintf(stderr, ...) test\r\n"); fscanf(stdin, "%d", &Value); fprintf(stdout, "Test 3: fprintf(stdout, ...) test\r\n"); - + fprintf(stderr, "Test 4: fprintf(stderr, ...) test\r\n"); - + printf("Test 5: fscanf(stdin, ...) test\r\n"); printf(" Type number and press Enter: \n"); fscanf(stdin, "%d", &Value); printf("\n Your value was: %d\r\n", Value); - + printf("Test complete\r\n"); */ diff --git a/libraries/tests/mbed/stdio_benchmark/main.cpp b/libraries/tests/mbed/stdio_benchmark/main.cpp index 748107fb6a..b9179815dc 100644 --- a/libraries/tests/mbed/stdio_benchmark/main.cpp +++ b/libraries/tests/mbed/stdio_benchmark/main.cpp @@ -4,20 +4,20 @@ int main() { printf("\r\n\r\n*** Start of memory write test (2K bytes) ***\r\n"); - + // dummy data char buf[2048]; int index = 0; for (index = 0; index < 2048; index++) { buf[index] = ~index & 0xFF; } - + // Run the timed write test float starttime, duration; Timer t; t.start(); starttime = t.read(); - + #if TEST_STDIO LocalFileSystem local("local"); FILE *fp = fopen("/local/test.dat", "w"); @@ -29,7 +29,7 @@ int main() { lfh.write(buf, sizeof(buf)); lfh.close(); #endif - + duration = t.read() - starttime; printf("Write completed in %.2f seconds. Average throughput = %.0f bytes/second.\r\n", duration, 2048/duration); } diff --git a/libraries/tests/mbed/stl/main.cpp b/libraries/tests/mbed/stl/main.cpp index 37e11e90b2..221f62f566 100644 --- a/libraries/tests/mbed/stl/main.cpp +++ b/libraries/tests/mbed/stl/main.cpp @@ -23,32 +23,32 @@ int main() { queueObject.push("one"); queueObject.push("two"); queueObject.push("three"); - + while (!queueObject.empty()) { string& s = queueObject.front(); printf("%s"NL, s.c_str()); queueObject.pop(); } - + map m; map::iterator it; - + m["a1"] = "50"; m["b2"] = "100"; m["c3"] = "150"; m["d4"] = "200"; - + it = m.find("b2"); if (it == m.end()) { printf("lookup error"NL); } - + m.erase(it); m.erase(m.find("d4")); - + printf("elements in the map:"NL); printf("a1 => %s"NL, m.find("a1")->second.c_str()); printf("c3 => %s"NL, m.find("c3")->second.c_str()); - + notify_completion(true); } diff --git a/libraries/tests/mbed/ticker_2/main.cpp b/libraries/tests/mbed/ticker_2/main.cpp index 6c58ee0c7a..f180e7e662 100644 --- a/libraries/tests/mbed/ticker_2/main.cpp +++ b/libraries/tests/mbed/ticker_2/main.cpp @@ -17,6 +17,17 @@ DigitalOut out(PTA1); #elif defined(TARGET_K64F) DigitalOut out(PTA1); +#elif defined(TARGET_NUCLEO_F103RB) || \ + defined(TARGET_NUCLEO_L152RE) || \ + defined(TARGET_NUCLEO_F302R8) || \ + defined(TARGET_NUCLEO_F030R8) || \ + defined(TARGET_NUCLEO_F401RE) || \ + defined(TARGET_NUCLEO_L053R8) +DigitalOut out(PA_3); + +#elif defined(TARGET_LPC11U68) +DigitalOut out(LED2); + #else DigitalOut out(p5); #endif @@ -31,8 +42,10 @@ void print_char(char c = '*') fflush(stdout); } -void togglePin (void) { +void togglePin(void) +{ static int ticker_count = 0; + if (ticker_count == MS_INTERVALS) { print_char(); ticker_count = 0; @@ -42,9 +55,9 @@ void togglePin (void) { ticker_count++; } -int main() { +int main() +{ tick.attach_us(togglePin, 1000); - while (true) { + while (true) wait(1); - } } diff --git a/libraries/tests/mbed/time_us/main.cpp b/libraries/tests/mbed/time_us/main.cpp index 67475ff505..b9504c38ee 100644 --- a/libraries/tests/mbed/time_us/main.cpp +++ b/libraries/tests/mbed/time_us/main.cpp @@ -15,6 +15,17 @@ DigitalOut out(PTA1); #elif defined(TARGET_LPC812) DigitalOut out(D10); +#elif defined(TARGET_NUCLEO_F103RB) || \ + defined(TARGET_NUCLEO_L152RE) || \ + defined(TARGET_NUCLEO_F302R8) || \ + defined(TARGET_NUCLEO_F030R8) || \ + defined(TARGET_NUCLEO_F401RE) || \ + defined(TARGET_NUCLEO_L053R8) +DigitalOut out(LED2); + +#elif defined(TARGET_LPC11U68) +DigitalOut out(LED2); + #else DigitalOut out(p5); #endif @@ -29,10 +40,10 @@ void print_char(char c = '*') fflush(stdout); } -int main() { +int main() +{ while (true) { - for (int i = 0; i < MS_INTERVALS; i++) - { + for (int i = 0; i < MS_INTERVALS; i++) { wait_us(1000); out = !out; } diff --git a/libraries/tests/mbed/timeout/main.cpp b/libraries/tests/mbed/timeout/main.cpp index be089b17ff..b8e9d19c49 100644 --- a/libraries/tests/mbed/timeout/main.cpp +++ b/libraries/tests/mbed/timeout/main.cpp @@ -20,6 +20,17 @@ DigitalOut out(LED2); #elif defined(TARGET_K64F) DigitalOut out(LED1); +#elif defined(TARGET_NUCLEO_F103RB) || \ + defined(TARGET_NUCLEO_L152RE) || \ + defined(TARGET_NUCLEO_F302R8) || \ + defined(TARGET_NUCLEO_F030R8) || \ + defined(TARGET_NUCLEO_F401RE) || \ + defined(TARGET_NUCLEO_L053R8) +DigitalOut out(LED1); + +#elif defined(TARGET_LPC11U68) +DigitalOut out(LED2); + #else DigitalOut out(p5); #endif @@ -34,10 +45,12 @@ void print_char(char c = '*') fflush(stdout); } -void toggleOff (void); +void toggleOff(void); -void toggleOn (void) { +void toggleOn(void) +{ static int toggle_counter = 0; + out = 1; led = 1; if (toggle_counter == MS_INTERVALS) { @@ -48,13 +61,15 @@ void toggleOn (void) { timer.attach_us(toggleOff, 500); } -void toggleOff(void) { +void toggleOff(void) +{ out = 0; led = 0; timer.attach_us(toggleOn, 500); } -int main() { +int main() +{ toggleOn(); - while(1); + while (1) ; } diff --git a/libraries/tests/net/cellular/http/common/HTTPClient/HTTPClient.cpp b/libraries/tests/net/cellular/http/common/HTTPClient/HTTPClient.cpp index ed4574ff75..ff367fb30a 100644 --- a/libraries/tests/net/cellular/http/common/HTTPClient/HTTPClient.cpp +++ b/libraries/tests/net/cellular/http/common/HTTPClient/HTTPClient.cpp @@ -21,15 +21,15 @@ #if 0 //Enable debug #include -#define DBG(x, ...) std::printf("[HTTPClient : DBG]"x"\r\n", ##__VA_ARGS__); -#define WARN(x, ...) std::printf("[HTTPClient : WARN]"x"\r\n", ##__VA_ARGS__); -#define ERR(x, ...) std::printf("[HTTPClient : ERR]"x"\r\n", ##__VA_ARGS__); +#define DBG(x, ...) std::printf("[HTTPClient : DBG]"x"\r\n", ##__VA_ARGS__); +#define WARN(x, ...) std::printf("[HTTPClient : WARN]"x"\r\n", ##__VA_ARGS__); +#define ERR(x, ...) std::printf("[HTTPClient : ERR]"x"\r\n", ##__VA_ARGS__); #else //Disable debug -#define DBG(x, ...) +#define DBG(x, ...) #define WARN(x, ...) -#define ERR(x, ...) +#define ERR(x, ...) #endif @@ -114,10 +114,10 @@ int HTTPClient::getHTTPResponseCode() } while(0) HTTPResult HTTPClient::connect(const char* url, HTTP_METH method, IHTTPDataOut* pDataOut, IHTTPDataIn* pDataIn, int timeout) //Execute request -{ +{ m_httpResponseCode = 0; //Invalidate code m_timeout = timeout; - + pDataIn->writeReset(); if( pDataOut ) { @@ -194,14 +194,14 @@ HTTPResult HTTPClient::connect(const char* url, HTTP_METH method, IHTTPDataOut* CHECK_CONN_ERR(ret); } } - + //Close headers DBG("Headers sent"); ret = send("\r\n"); CHECK_CONN_ERR(ret); size_t trfLen; - + //Send data (if available) if( pDataOut != NULL ) { @@ -249,7 +249,7 @@ HTTPResult HTTPClient::connect(const char* url, HTTP_METH method, IHTTPDataOut* } } - + //Receive response DBG("Receiving response"); ret = recv(buf, CHUNK_SIZE - 1, CHUNK_SIZE - 1, &trfLen); //Read n bytes @@ -276,7 +276,7 @@ HTTPResult HTTPClient::connect(const char* url, HTTP_METH method, IHTTPDataOut* if( (m_httpResponseCode < 200) || (m_httpResponseCode >= 300) ) { - //Did not return a 2xx code; TODO fetch headers/(&data?) anyway and implement a mean of writing/reading headers + //Did not return a 2xx code; TODO fetch headers/(&data?) anyway and implement a mean of writing/reading headers WARN("Response code %d", m_httpResponseCode); PRTCL_ERR(); } @@ -484,13 +484,13 @@ HTTPResult HTTPClient::recv(char* buf, size_t minLen, size_t maxLen, size_t* pRe { DBG("Trying to read between %d and %d bytes", minLen, maxLen); size_t readLen = 0; - + if(!m_sock.is_connected()) { WARN("Connection was closed by server"); - return HTTP_CLOSED; //Connection was closed by server + return HTTP_CLOSED; //Connection was closed by server } - + int ret; while(readLen < maxLen) { @@ -506,7 +506,7 @@ HTTPResult HTTPClient::recv(char* buf, size_t minLen, size_t maxLen, size_t* pRe m_sock.set_blocking(false, 0); ret = m_sock.receive(buf + readLen, maxLen - readLen); } - + if( ret > 0) { readLen += ret; @@ -525,10 +525,10 @@ HTTPResult HTTPClient::recv(char* buf, size_t minLen, size_t maxLen, size_t* pRe } else { - break; + break; } } - + if(!m_sock.is_connected()) { break; @@ -547,13 +547,13 @@ HTTPResult HTTPClient::send(char* buf, size_t len) //0 on success, err code on f } DBG("Trying to write %d bytes", len); size_t writtenLen = 0; - + if(!m_sock.is_connected()) { WARN("Connection was closed by server"); - return HTTP_CLOSED; //Connection was closed by server + return HTTP_CLOSED; //Connection was closed by server } - + m_sock.set_blocking(false, m_timeout); int ret = m_sock.send_all(buf, len); if(ret > 0) @@ -570,7 +570,7 @@ HTTPResult HTTPClient::send(char* buf, size_t len) //0 on success, err code on f ERR("Connection error (send returned %d)", ret); return HTTP_CONN; } - + DBG("Written %d bytes", writtenLen); return HTTP_OK; } diff --git a/libraries/tests/net/cellular/http/common/HTTPClient/HTTPClient.h b/libraries/tests/net/cellular/http/common/HTTPClient/HTTPClient.h index 25301c3649..7cb30b0337 100644 --- a/libraries/tests/net/cellular/http/common/HTTPClient/HTTPClient.h +++ b/libraries/tests/net/cellular/http/common/HTTPClient/HTTPClient.h @@ -60,7 +60,7 @@ public: ///Instantiate the HTTP client HTTPClient(); ~HTTPClient(); - + #if 0 //TODO add header handlers /** Provides a basic authentification feature (Base64 encoded username and password) @@ -70,7 +70,7 @@ public: */ void basicAuth(const char* user, const char* password); //Basic Authentification #endif - + //High Level setup functions /** Execute a GET request on the URL Blocks until completion @@ -80,7 +80,7 @@ public: @return 0 on success, HTTP error (<0) on failure */ HTTPResult get(const char* url, IHTTPDataIn* pDataIn, int timeout = HTTP_CLIENT_DEFAULT_TIMEOUT); //Blocking - + /** Execute a GET request on the URL Blocks until completion This is a helper to directly get a piece of text from a HTTP result @@ -101,7 +101,7 @@ public: @return 0 on success, HTTP error (<0) on failure */ HTTPResult post(const char* url, const IHTTPDataOut& dataOut, IHTTPDataIn* pDataIn, int timeout = HTTP_CLIENT_DEFAULT_TIMEOUT); //Blocking - + /** Execute a PUT request on the URL Blocks until completion @param url : url on which to execute the request @@ -111,7 +111,7 @@ public: @return 0 on success, HTTP error (<0) on failure */ HTTPResult put(const char* url, const IHTTPDataOut& dataOut, IHTTPDataIn* pDataIn, int timeout = HTTP_CLIENT_DEFAULT_TIMEOUT); //Blocking - + /** Execute a DELETE request on the URL Blocks until completion @param url : url on which to execute the request @@ -120,12 +120,12 @@ public: @return 0 on success, HTTP error (<0) on failure */ HTTPResult del(const char* url, IHTTPDataIn* pDataIn, int timeout = HTTP_CLIENT_DEFAULT_TIMEOUT); //Blocking - + /** Get last request's HTTP response code @return The HTTP response code of the last request */ int getHTTPResponseCode(); - + private: enum HTTP_METH { @@ -143,7 +143,7 @@ private: //Parameters TCPSocketConnection m_sock; - + int m_timeout; const char* m_basicAuthUser; diff --git a/libraries/tests/net/cellular/http/common/HTTPClient/IHTTPData.h b/libraries/tests/net/cellular/http/common/HTTPClient/IHTTPData.h index 6c8f4368f8..24f1337511 100644 --- a/libraries/tests/net/cellular/http/common/HTTPClient/IHTTPData.h +++ b/libraries/tests/net/cellular/http/common/HTTPClient/IHTTPData.h @@ -29,8 +29,8 @@ class IHTTPDataOut { protected: friend class HTTPClient; - - /** Reset stream to its beginning + + /** Reset stream to its beginning * Called by the HTTPClient on each new request */ virtual void readReset() = 0; @@ -41,17 +41,17 @@ protected: * @param pReadLen Pointer to the variable on which the actual copied data length will be stored */ virtual int read(char* buf, size_t len, size_t* pReadLen) = 0; - + /** Get MIME type * @param type Internet media type from Content-Type header */ virtual int getDataType(char* type, size_t maxTypeLen) = 0; //Internet media type for Content-Type header - + /** Determine whether the HTTP client should chunk the data * Used for Transfer-Encoding header */ virtual bool getIsChunked() = 0; - + /** If the data is not chunked, get its size * Used for Content-Length header */ @@ -65,7 +65,7 @@ class IHTTPDataIn protected: friend class HTTPClient; - /** Reset stream to its beginning + /** Reset stream to its beginning * Called by the HTTPClient on each new request */ virtual void writeReset() = 0; @@ -85,7 +85,7 @@ protected: * Recovered from Transfer-Encoding header */ virtual void setIsChunked(bool chunked) = 0; - + /** If the data is not chunked, set its size * From Content-Length header */ diff --git a/libraries/tests/net/cellular/http/common/HTTPClient/data/HTTPText.h b/libraries/tests/net/cellular/http/common/HTTPClient/data/HTTPText.h index f55ff762ae..cb76c6fdac 100644 --- a/libraries/tests/net/cellular/http/common/HTTPClient/data/HTTPText.h +++ b/libraries/tests/net/cellular/http/common/HTTPClient/data/HTTPText.h @@ -42,7 +42,7 @@ public: protected: //IHTTPDataIn virtual void readReset(); - + virtual int read(char* buf, size_t len, size_t* pReadLen); virtual int getDataType(char* type, size_t maxTypeLen); //Internet media type for Content-Type header @@ -53,7 +53,7 @@ protected: //IHTTPDataOut virtual void writeReset(); - + virtual int write(const char* buf, size_t len); virtual void setDataType(const char* type); //Internet media type from Content-Type header diff --git a/libraries/tests/net/cellular/http/common/httptest.cpp b/libraries/tests/net/cellular/http/common/httptest.cpp index 3bbc4673ea..e3db1c826a 100644 --- a/libraries/tests/net/cellular/http/common/httptest.cpp +++ b/libraries/tests/net/cellular/http/common/httptest.cpp @@ -4,9 +4,9 @@ #include "httptest.h" int httptest(CellularModem& modem, const char* apn, const char* username, const char* password) -{ +{ printf("Connecting...\n"); - + HTTPClient http; char str[512]; @@ -18,7 +18,7 @@ int httptest(CellularModem& modem, const char* apn, const char* username, const printf("Could not connect\n"); return false; } - + //GET data printf("Trying to fetch page...\n"); ret = http.get("http://mbed.org/media/uploads/donatien/hello.txt", str, 128); @@ -33,7 +33,7 @@ int httptest(CellularModem& modem, const char* apn, const char* username, const modem.disconnect(); return false; } - + //POST data HTTPMap map; HTTPText text(str, 512); @@ -52,7 +52,7 @@ int httptest(CellularModem& modem, const char* apn, const char* username, const modem.disconnect(); return false; } - + modem.disconnect(); return true; } diff --git a/libraries/tests/net/cellular/sms/common/smstest.cpp b/libraries/tests/net/cellular/sms/common/smstest.cpp index ca55e88543..5a6393590f 100644 --- a/libraries/tests/net/cellular/sms/common/smstest.cpp +++ b/libraries/tests/net/cellular/sms/common/smstest.cpp @@ -1,12 +1,12 @@ #include "CellularModem.h" #include "smstest.h" -void smstest(CellularModem& modem) +void smstest(CellularModem& modem) { modem.power(true); Thread::wait(1000); -#ifdef DESTINATION_NUMBER +#ifdef DESTINATION_NUMBER modem.sendSM(DESINATION_NUMBER, "Hello from mbed:)"); #endif @@ -32,7 +32,7 @@ void smstest(CellularModem& modem) Thread::wait(3000); continue; } - + printf("%s : %s\n", num, msg); } Thread::wait(3000); diff --git a/libraries/tests/net/echo/udp_link_layer/main.cpp b/libraries/tests/net/echo/udp_link_layer/main.cpp new file mode 100644 index 0000000000..35e613645e --- /dev/null +++ b/libraries/tests/net/echo/udp_link_layer/main.cpp @@ -0,0 +1,151 @@ +#include "mbed.h" +#include "rtos.h" +#include "EthernetInterface.h" +#include +#include + +/** +* How to use: +* make.py -m LPC1768 -t ARM -d E:\ -n NET_14 +* udp_link_layer_auto.py -p COM20 -d E:\ -t 10 +*/ + +// Evil globals +namespace { +Mutex cli_serv_mutex; +// cli_serv_mutex.lock(); // LOCK +// cli_serv_mutex.unlock(); // LOCK + +const int ECHO_SERVER_PORT = 7; +const int BUFFER_SIZE = 256; + +// Forwarding packet queue +std::list datagram_queue; + +// IP and port used to store HOST address info +char host_address[32] = { 0 }; +volatile int host_port = 0; + +// Statistics (mbed) +volatile int received_packets = 0; +volatile int forwarded_packets = 0; +volatile int max_queue_len = 0; +} + +void udp_server_task(void const *argument) +{ + DigitalOut indicator(LED1); + UDPSocket server; + + server.bind(ECHO_SERVER_PORT); + // printf("[udp_server_task] Start\r\n"); + + Endpoint client; + char buffer[BUFFER_SIZE] = { 0 }; + while (true) { + //printf("[udp_server_task] Wait for packet...\r\n"); + int n = server.receiveFrom(client, buffer, sizeof(buffer)); + if (n > 0) { + //printf("[udp_server_task] Received packet from: %s\r\n", client.get_address()); + const int buffer_string_end_index = n >= BUFFER_SIZE ? BUFFER_SIZE - 1 : n; + buffer[buffer_string_end_index] = '\0'; + //printf("[udp_server_task] Server received: %s\r\n", buffer); + if (host_port == 0) { + strcpy(host_address, client.get_address()); + host_port = ECHO_SERVER_PORT + 1; + //printf("[udp_server_task] Set host address and port: %s:%d\r\n", host_address, host_port); + } + // Dispatch data to client for sending to test HOST + cli_serv_mutex.lock(); // LOCK + // Push to datagram queue + datagram_queue.push_front(std::string(buffer)); + max_queue_len = datagram_queue.size() > max_queue_len ? datagram_queue.size() : max_queue_len; + received_packets++; + cli_serv_mutex.unlock(); // LOCK + indicator = !indicator; + } + } +} + +void udp_client_task(void const *argument) +{ + while (host_port == 0) { + // Waiting for HOST port notification + } + + DigitalOut indicator(LED2); + UDPSocket socket; + socket.init(); + + Endpoint echo_server; + echo_server.set_address(host_address, host_port); + //printf("[udp_client_task] Start: %s:%d\r\n", host_address, host_port); + + while (1) { + std::string datagram; + bool sent_datagram = false; + cli_serv_mutex.lock(); // LOCK + if (datagram_queue.size() > 0) { + // POP from datagram queue + datagram = datagram_queue.back(); + datagram_queue.pop_back(); + sent_datagram = true; + } + cli_serv_mutex.unlock(); // LOCK + if (sent_datagram) { + //printf("[udp_client_task] Forwarded datagram: %s\r\n", datagram.c_str()); + socket.sendTo(echo_server, (char *)datagram.c_str(), datagram.length()); + forwarded_packets++; + indicator = !indicator; + } + } +} + +int main(void) +{ + EthernetInterface eth; + + eth.init(); //Use DHCP + eth.connect(); + printf("Server IP Address is %s:%d\n", eth.getIPAddress(), ECHO_SERVER_PORT); + + Thread UdpServerTask(udp_server_task, NULL, osPriorityNormal, DEFAULT_STACK_SIZE * 2.25); + Thread UdpClientTask(udp_client_task, NULL, osPriorityNormal, DEFAULT_STACK_SIZE * 2.25); + + // Control TCP server to get mbed statistics + { + const int TELNET_SERVER_PORT = 23; + const int BUFFER_SIZE = 256; + TCPSocketServer server; + server.bind(TELNET_SERVER_PORT); + server.listen(); + + while (true) { + printf("Wait for new connection...\n"); + TCPSocketConnection client; + server.accept(client); + client.set_blocking(false, 1500); // Timeout after (1.5)s + printf("Connection from: %s\n", client.get_address()); + + char buffer[BUFFER_SIZE] = { 0 }; + while (true) { + int n = client.receive(buffer, sizeof(buffer)); + //if (n <= 0) break; + if (n > 0) { + printf("Recv %d chars\r\n", n); + const int buffer_string_end_index = n >= BUFFER_SIZE ? BUFFER_SIZE - 1 : n; + buffer[buffer_string_end_index] = '\0'; + // client.send_all(buffer, strlen(buffer)); + if (strncmp(buffer, "stat", 4) == 0) { + sprintf(buffer, "received_packets %d\nforwarded_packets %d\nmax_queue_len %d", + received_packets, forwarded_packets, max_queue_len); + client.send_all(buffer, strlen(buffer)); + // printf("%s", buffer); + } + } + //if (n <= 0) break; + } + client.close(); + } + } +} diff --git a/libraries/tests/net/echo/udp_server/main.cpp b/libraries/tests/net/echo/udp_server/main.cpp index ab53f554e4..6cd51ca372 100644 --- a/libraries/tests/net/echo/udp_server/main.cpp +++ b/libraries/tests/net/echo/udp_server/main.cpp @@ -11,10 +11,10 @@ int main (void) { eth.init(); //Use DHCP eth.connect(); printf("Server IP Address is %s:%d\n", eth.getIPAddress(), ECHO_SERVER_PORT); - + UDPSocket server; server.bind(ECHO_SERVER_PORT); - + Endpoint client; char buffer[BUFFER_SIZE] = {0}; while (true) { diff --git a/libraries/tests/net/helloworld/broadcast_receive/main.cpp b/libraries/tests/net/helloworld/broadcast_receive/main.cpp index c8d266f9e3..9cee345519 100644 --- a/libraries/tests/net/helloworld/broadcast_receive/main.cpp +++ b/libraries/tests/net/helloworld/broadcast_receive/main.cpp @@ -7,11 +7,11 @@ int main() { EthernetInterface eth; eth.init(); //Use DHCP eth.connect(); - + UDPSocket socket; socket.bind(BROADCAST_PORT); socket.set_broadcasting(); - + Endpoint broadcaster; char buffer[256]; while (true) { diff --git a/libraries/tests/net/helloworld/broadcast_send/main.cpp b/libraries/tests/net/helloworld/broadcast_send/main.cpp index 77b5b64d02..4632c63ff0 100644 --- a/libraries/tests/net/helloworld/broadcast_send/main.cpp +++ b/libraries/tests/net/helloworld/broadcast_send/main.cpp @@ -7,16 +7,16 @@ int main() { EthernetInterface eth; eth.init(); //Use DHCP eth.connect(); - + UDPSocket sock; sock.init(); sock.set_broadcasting(); - + Endpoint broadcast; broadcast.set_address("255.255.255.255", BROADCAST_PORT); - + char out_buffer[] = "very important data"; - + while (true) { printf("Broadcasting...\n"); sock.sendTo(broadcast, out_buffer, sizeof(out_buffer)); diff --git a/libraries/tests/net/helloworld/multicast_receive/main.cpp b/libraries/tests/net/helloworld/multicast_receive/main.cpp index eeb1527c63..0398bdd1fd 100644 --- a/libraries/tests/net/helloworld/multicast_receive/main.cpp +++ b/libraries/tests/net/helloworld/multicast_receive/main.cpp @@ -8,20 +8,20 @@ int main() { EthernetInterface eth; eth.init(); //Use DHCP eth.connect(); - + UDPSocket server; server.bind(MCAST_PORT); if (server.join_multicast_group(MCAST_GRP) != 0) { printf("Error joining the multicast group\n"); while (true) {} } - + Endpoint client; char buffer[256]; while (true) { printf("\nWait for packet...\n"); int n = server.receiveFrom(client, buffer, sizeof(buffer)); - + printf("Packet from \"%s\": %s\n", client.get_address(), buffer); } } diff --git a/libraries/tests/net/helloworld/multicast_send/main.cpp b/libraries/tests/net/helloworld/multicast_send/main.cpp index 773ea6105a..df41c6d80a 100644 --- a/libraries/tests/net/helloworld/multicast_send/main.cpp +++ b/libraries/tests/net/helloworld/multicast_send/main.cpp @@ -8,13 +8,13 @@ int main() { EthernetInterface eth; eth.init(); //Use DHCP eth.connect(); - + UDPSocket sock; sock.init(); - + Endpoint multicast_group; multicast_group.set_address(MCAST_GRP, MCAST_PORT); - + char out_buffer[] = "very important data"; while (true) { printf("Multicast to group: %s\n", MCAST_GRP); diff --git a/libraries/tests/net/protocols/HTTPClient_HelloWorld/HTTPClient/HTTPClient.cpp b/libraries/tests/net/protocols/HTTPClient_HelloWorld/HTTPClient/HTTPClient.cpp index 2d13aac113..baef0a36ad 100644 --- a/libraries/tests/net/protocols/HTTPClient_HelloWorld/HTTPClient/HTTPClient.cpp +++ b/libraries/tests/net/protocols/HTTPClient_HelloWorld/HTTPClient/HTTPClient.cpp @@ -21,16 +21,16 @@ #if 1 //Enable debug #include -//#define DBG(x, ...) std::printf("[HTTPClient : DBG]"x"\r\n", ##__VA_ARGS__); -#define DBG(x, ...) -#define WARN(x, ...) std::printf("[HTTPClient : WARN]"x"\r\n", ##__VA_ARGS__); -#define ERR(x, ...) std::printf("[HTTPClient : ERR]"x"\r\n", ##__VA_ARGS__); +//#define DBG(x, ...) std::printf("[HTTPClient : DBG]"x"\r\n", ##__VA_ARGS__); +#define DBG(x, ...) +#define WARN(x, ...) std::printf("[HTTPClient : WARN]"x"\r\n", ##__VA_ARGS__); +#define ERR(x, ...) std::printf("[HTTPClient : ERR]"x"\r\n", ##__VA_ARGS__); #else //Disable debug -#define DBG(x, ...) +#define DBG(x, ...) #define WARN(x, ...) -#define ERR(x, ...) +#define ERR(x, ...) #endif @@ -104,7 +104,7 @@ int HTTPClient::getHTTPResponseCode() } while(0) HTTPResult HTTPClient::connect(const char* url, HTTP_METH method, IHTTPDataOut* pDataOut, IHTTPDataIn* pDataIn, int timeout) //Execute request -{ +{ m_httpResponseCode = 0; //Invalidate code m_timeout = timeout; @@ -178,14 +178,14 @@ HTTPResult HTTPClient::connect(const char* url, HTTP_METH method, IHTTPDataOut* CHECK_CONN_ERR(ret); } } - + //Close headers DBG("Headers sent"); ret = send("\r\n"); CHECK_CONN_ERR(ret); size_t trfLen; - + //Send data (if POST) if( (method == HTTP_POST) && (pDataOut != NULL) ) { @@ -233,7 +233,7 @@ HTTPResult HTTPClient::connect(const char* url, HTTP_METH method, IHTTPDataOut* } } - + //Receive response DBG("Receiving response"); ret = recv(buf, CHUNK_SIZE - 1, CHUNK_SIZE - 1, &trfLen); //Read n bytes @@ -458,13 +458,13 @@ HTTPResult HTTPClient::recv(char* buf, size_t minLen, size_t maxLen, size_t* pRe { DBG("Trying to read between %d and %d bytes", minLen, maxLen); size_t readLen = 0; - + if(!m_sock.is_connected()) { WARN("Connection was closed by server"); - return HTTP_CLOSED; //Connection was closed by server + return HTTP_CLOSED; //Connection was closed by server } - + int ret; while(readLen < maxLen) { @@ -480,7 +480,7 @@ HTTPResult HTTPClient::recv(char* buf, size_t minLen, size_t maxLen, size_t* pRe m_sock.set_blocking(false, 0); ret = m_sock.receive(buf + readLen, maxLen - readLen); } - + if( ret > 0) { readLen += ret; @@ -499,10 +499,10 @@ HTTPResult HTTPClient::recv(char* buf, size_t minLen, size_t maxLen, size_t* pRe } else { - break; + break; } } - + if(!m_sock.is_connected()) { break; @@ -521,13 +521,13 @@ HTTPResult HTTPClient::send(char* buf, size_t len) //0 on success, err code on f } DBG("Trying to write %d bytes", len); size_t writtenLen = 0; - + if(!m_sock.is_connected()) { WARN("Connection was closed by server"); - return HTTP_CLOSED; //Connection was closed by server + return HTTP_CLOSED; //Connection was closed by server } - + m_sock.set_blocking(false, m_timeout); int ret = m_sock.send_all(buf, len); if(ret > 0) @@ -544,7 +544,7 @@ HTTPResult HTTPClient::send(char* buf, size_t len) //0 on success, err code on f ERR("Connection error (send returned %d)", ret); return HTTP_CONN; } - + DBG("Written %d bytes", writtenLen); return HTTP_OK; } diff --git a/libraries/tests/net/protocols/HTTPClient_HelloWorld/HTTPClient/HTTPClient.h b/libraries/tests/net/protocols/HTTPClient_HelloWorld/HTTPClient/HTTPClient.h index 8489d277cd..e9ac860cab 100644 --- a/libraries/tests/net/protocols/HTTPClient_HelloWorld/HTTPClient/HTTPClient.h +++ b/libraries/tests/net/protocols/HTTPClient_HelloWorld/HTTPClient/HTTPClient.h @@ -60,7 +60,7 @@ public: ///Instantiate the HTTP client HTTPClient(); ~HTTPClient(); - + #if 0 //TODO add header handlers /** Provides a basic authentification feature (Base64 encoded username and password) @@ -70,7 +70,7 @@ public: */ void basicAuth(const char* user, const char* password); //Basic Authentification #endif - + //High Level setup functions /** Execute a GET request on the url Blocks until completion @@ -80,7 +80,7 @@ public: @return 0 on success, HTTP error (<0) on failure */ HTTPResult get(const char* url, IHTTPDataIn* pDataIn, int timeout = HTTP_CLIENT_DEFAULT_TIMEOUT); //Blocking - + /** Execute a GET request on the url Blocks until completion This is a helper to directly get a piece of text from a HTTP result @@ -101,12 +101,12 @@ public: @return 0 on success, HTTP error (<0) on failure */ HTTPResult post(const char* url, const IHTTPDataOut& dataOut, IHTTPDataIn* pDataIn, int timeout = HTTP_CLIENT_DEFAULT_TIMEOUT); //Blocking - + /** Get last request's HTTP response code @return The HTTP response code of the last request */ int getHTTPResponseCode(); - + private: enum HTTP_METH { @@ -122,7 +122,7 @@ private: //Parameters TCPSocketConnection m_sock; - + int m_timeout; const char* m_basicAuthUser; diff --git a/libraries/tests/net/protocols/HTTPClient_HelloWorld/HTTPClient/IHTTPData.h b/libraries/tests/net/protocols/HTTPClient_HelloWorld/HTTPClient/IHTTPData.h index df06b06647..2eead464f1 100644 --- a/libraries/tests/net/protocols/HTTPClient_HelloWorld/HTTPClient/IHTTPData.h +++ b/libraries/tests/net/protocols/HTTPClient_HelloWorld/HTTPClient/IHTTPData.h @@ -36,17 +36,17 @@ protected: * @param pReadLen Pointer to the variable on which the actual copied data length will be stored */ virtual int read(char* buf, size_t len, size_t* pReadLen) = 0; - + /** Get MIME type * @param type Internet media type from Content-Type header */ virtual int getDataType(char* type, size_t maxTypeLen) = 0; //Internet media type for Content-Type header - + /** Determine whether the HTTP client should chunk the data * Used for Transfer-Encoding header */ virtual bool getIsChunked() = 0; - + /** If the data is not chunked, get its size * Used for Content-Length header */ @@ -75,7 +75,7 @@ protected: * Recovered from Transfer-Encoding header */ virtual void setIsChunked(bool chunked) = 0; - + /** If the data is not chunked, set its size * From Content-Length header */ diff --git a/libraries/tests/net/protocols/NTPClient_HelloWorld/NTPClient/NTPClient.cpp b/libraries/tests/net/protocols/NTPClient_HelloWorld/NTPClient/NTPClient.cpp index ba4ad1b222..b049d30036 100644 --- a/libraries/tests/net/protocols/NTPClient_HelloWorld/NTPClient/NTPClient.cpp +++ b/libraries/tests/net/protocols/NTPClient_HelloWorld/NTPClient/NTPClient.cpp @@ -22,15 +22,15 @@ //Enable debug #define __DEBUG__ #include -#define DBG(x, ...) std::printf("[NTPClient : DBG]"x"\r\n", ##__VA_ARGS__); -#define WARN(x, ...) std::printf("[NTPClient : WARN]"x"\r\n", ##__VA_ARGS__); -#define ERR(x, ...) std::printf("[NTPClient : ERR]"x"\r\n", ##__VA_ARGS__); +#define DBG(x, ...) std::printf("[NTPClient : DBG]"x"\r\n", ##__VA_ARGS__); +#define WARN(x, ...) std::printf("[NTPClient : WARN]"x"\r\n", ##__VA_ARGS__); +#define ERR(x, ...) std::printf("[NTPClient : ERR]"x"\r\n", ##__VA_ARGS__); #else //Disable debug -#define DBG(x, ...) +#define DBG(x, ...) #define WARN(x, ...) -#define ERR(x, ...) +#define ERR(x, ...) #endif @@ -61,7 +61,7 @@ NTPResult NTPClient::setTime(const char* host, uint16_t port, uint32_t timeout) //Create & bind socket DBG("Binding socket"); m_sock.bind(0); //Bind to a random port - + m_sock.set_blocking(false, timeout); //Set not blocking struct NTPPacket pkt; @@ -88,13 +88,13 @@ NTPResult NTPClient::setTime(const char* host, uint16_t port, uint32_t timeout) pkt.refTm_f = pkt.origTm_f = pkt.rxTm_f = pkt.txTm_f = 0; Endpoint outEndpoint; - + if( outEndpoint.set_address(host, port) < 0) { m_sock.close(); return NTP_DNS; } - + //Set timeout, non-blocking and wait using select int ret = m_sock.sendTo( outEndpoint, (char*)&pkt, sizeof(NTPPacket) ); if (ret < 0 ) diff --git a/libraries/tests/net/protocols/NTPClient_HelloWorld/NTPClient/NTPClient.h b/libraries/tests/net/protocols/NTPClient_HelloWorld/NTPClient/NTPClient.h index d66cb2de04..598bdc31c3 100644 --- a/libraries/tests/net/protocols/NTPClient_HelloWorld/NTPClient/NTPClient.h +++ b/libraries/tests/net/protocols/NTPClient_HelloWorld/NTPClient/NTPClient.h @@ -93,7 +93,7 @@ private: uint32_t txTm_s; uint32_t txTm_f; } __attribute__ ((packed)); - + UDPSocket m_sock; }; diff --git a/libraries/tests/peripherals/ADXL345/ADXL345.cpp b/libraries/tests/peripherals/ADXL345/ADXL345.cpp index bc8f97c46e..6f9c856826 100644 --- a/libraries/tests/peripherals/ADXL345/ADXL345.cpp +++ b/libraries/tests/peripherals/ADXL345/ADXL345.cpp @@ -1,6 +1,6 @@ /** * @author Aaron Berk - * + * * @section LICENSE * * Copyright (c) 2010 ARM Limited @@ -30,22 +30,22 @@ * Datasheet: * * http://www.analog.com/static/imported-files/data_sheets/ADXL345.pdf - */ - + */ + /** * Includes */ #include "ADXL345.h" -ADXL345::ADXL345(PinName mosi, - PinName miso, - PinName sck, +ADXL345::ADXL345(PinName mosi, + PinName miso, + PinName sck, PinName cs) : spi_(mosi, miso, sck), nCS_(cs) { //2MHz, allowing us to use the fastest data rates. spi_.frequency(2000000); spi_.format(8,3); - + nCS_ = 1; wait_us(500); @@ -316,9 +316,9 @@ void ADXL345::setDataRate(int rate) { void ADXL345::getOutput(int* readings){ char buffer[6]; - + multiByteRead(ADXL345_DATAX0_REG, buffer, 6); - + readings[0] = (int)buffer[1] << 8 | (int)buffer[0]; readings[1] = (int)buffer[3] << 8 | (int)buffer[2]; readings[2] = (int)buffer[5] << 8 | (int)buffer[4]; diff --git a/libraries/tests/peripherals/ADXL345/ADXL345.h b/libraries/tests/peripherals/ADXL345/ADXL345.h index c02c975bc2..af17c5f3e7 100644 --- a/libraries/tests/peripherals/ADXL345/ADXL345.h +++ b/libraries/tests/peripherals/ADXL345/ADXL345.h @@ -30,7 +30,7 @@ * Datasheet: * * http://www.analog.com/static/imported-files/data_sheets/ADXL345.pdf - */ + */ #ifndef ADXL345_H #define ADXL345_H @@ -254,7 +254,7 @@ public: * seconds. */ int getTimeInactivity(void); - + /** * Set the time required for inactivity to be declared. * @@ -265,7 +265,7 @@ public: * threshold inactivity. */ void setTimeInactivity(int timeInactivity); - + /** * Get the activity/inactivity control settings. * @@ -284,7 +284,7 @@ public: * @return The contents of the ACT_INACT_CTL register. */ int getActivityInactivityControl(void); - + /** * Set the activity/inactivity control settings. * @@ -303,7 +303,7 @@ public: * @param settings The control byte to write to the ACT_INACT_CTL register. */ void setActivityInactivityControl(int settings); - + /** * Get the threshold for free fall detection. * @@ -311,17 +311,17 @@ public: * with scale factor 62.5mg/LSB. */ int getFreefallThreshold(void); - + /** * Set the threshold for free fall detection. * * @return The threshold value for free-fall detection, as an 8-bit number, - * with scale factor 62.5mg/LSB. A value of 0 may result in + * with scale factor 62.5mg/LSB. A value of 0 may result in * undesirable behavior if the free-fall interrupt is enabled. * Values between 300 mg and 600 mg (0x05 to 0x09) are recommended. */ void setFreefallThreshold(int threshold); - + /** * Get the time required to generate a free fall interrupt. * @@ -330,18 +330,18 @@ public: * milliseconds. */ int getFreefallTime(void); - + /** * Set the time required to generate a free fall interrupt. * * @return The minimum time that the value of all axes must be less than * the freefall threshold to generate a free-fall interrupt, in * milliseconds. A value of 0 may result in undesirable behavior - * if the free-fall interrupt is enabled. Values between 100 ms + * if the free-fall interrupt is enabled. Values between 100 ms * and 350 ms (0x14 to 0x46) are recommended. */ void setFreefallTime(int freefallTime_ms); - + /** * Get the axis tap settings. * @@ -355,9 +355,9 @@ public: * See datasheet for more details. * * @return The contents of the TAP_AXES register. - */ + */ int getTapAxisControl(void); - + /** * Set the axis tap settings. * @@ -373,14 +373,14 @@ public: * @param The control byte to write to the TAP_AXES register. */ void setTapAxisControl(int settings); - + /** * Get the source of a tap. * * @return The contents of the ACT_TAP_STATUS register. */ int getTapSource(void); - + /** * Set the power mode. * @@ -388,14 +388,14 @@ public: * 1 -> Reduced power operation. */ void setPowerMode(char mode); - + /** * Set the data rate. * * @param rate The rate code (see #defines or datasheet). */ void setDataRate(int rate); - + /** * Get the power control settings. * @@ -404,7 +404,7 @@ public: * @return The contents of the POWER_CTL register. */ int getPowerControl(void); - + /** * Set the power control settings. * @@ -413,56 +413,56 @@ public: * @param The control byte to write to the POWER_CTL register. */ void setPowerControl(int settings); - + /** * Get the interrupt enable settings. * * @return The contents of the INT_ENABLE register. */ int getInterruptEnableControl(void); - + /** * Set the interrupt enable settings. * * @param settings The control byte to write to the INT_ENABLE register. */ void setInterruptEnableControl(int settings); - + /** * Get the interrupt mapping settings. * * @return The contents of the INT_MAP register. */ int getInterruptMappingControl(void); - + /** * Set the interrupt mapping settings. * * @param settings The control byte to write to the INT_MAP register. */ void setInterruptMappingControl(int settings); - + /** * Get the interrupt source. * * @return The contents of the INT_SOURCE register. */ int getInterruptSource(void); - + /** * Get the data format settings. * * @return The contents of the DATA_FORMAT register. */ int getDataFormatControl(void); - + /** * Set the data format settings. * * @param settings The control byte to write to the DATA_FORMAT register. */ void setDataFormatControl(int settings); - + /** * Get the output of all three axes. * @@ -470,28 +470,28 @@ public: * x-axis, y-axis and z-axis [in that order]. */ void getOutput(int* readings); - + /** * Get the FIFO control settings. * * @return The contents of the FIFO_CTL register. */ int getFifoControl(void); - + /** * Set the FIFO control settings. * * @param The control byte to write to the FIFO_CTL register. */ void setFifoControl(int settings); - + /** * Get FIFO status. * * @return The contents of the FIFO_STATUS register. */ int getFifoStatus(void); - + private: SPI spi_; diff --git a/libraries/tests/peripherals/AX12/AX12.h b/libraries/tests/peripherals/AX12/AX12.h index e686191a6e..d1b3b42aef 100644 --- a/libraries/tests/peripherals/AX12/AX12.h +++ b/libraries/tests/peripherals/AX12/AX12.h @@ -54,9 +54,9 @@ * @code * #include "mbed.h" * #include "AX12.h" - * + * * int main() { - * + * * AX12 myax12 (p9, p10, 1); * * while (1) { @@ -75,8 +75,8 @@ public: /** Create an AX12 servo object connected to the specified serial port, with the specified ID * * @param pin tx pin - * @param pin rx pin - * @param int ID, the Bus ID of the servo 1-255 + * @param pin rx pin + * @param int ID, the Bus ID of the servo 1-255 */ AX12(PinName tx, PinName rx, int ID, int baud=1000000); @@ -106,7 +106,7 @@ public: * * @param degrees 0-300 * @param flags, defaults to 0 - * flags[0] = blocking, return when goal position reached + * flags[0] = blocking, return when goal position reached * flags[1] = register, activate with a broadcast trigger * */ @@ -127,7 +127,7 @@ public: * @param degrees, 0-300 */ int SetCWLimit(int degrees); - + /** Set the counter-clockwise limit of the servo * * @param degrees, 0-300 @@ -165,7 +165,7 @@ public: /** Read the temperature of the servo * - * @returns float temperature + * @returns float temperature */ float GetTemp(void); diff --git a/libraries/tests/peripherals/SRF08/SRF08.cpp b/libraries/tests/peripherals/SRF08/SRF08.cpp index c66c8ffe6b..8e44a3ee23 100644 --- a/libraries/tests/peripherals/SRF08/SRF08.cpp +++ b/libraries/tests/peripherals/SRF08/SRF08.cpp @@ -26,7 +26,7 @@ THE SOFTWARE. SRF08::SRF08(PinName sda, PinName scl, int addr) : m_i2c(sda, scl), m_addr(addr) { char cmd[2]; - + // Set up SRF08 max range and receiver sensitivity over I2C bus cmd[0] = 0x02; // Range register cmd[1] = 0x1C; // Set max range about 100cm diff --git a/libraries/tests/peripherals/SRF08/SRF08.h b/libraries/tests/peripherals/SRF08/SRF08.h index 5edaa9ac98..a3606338b8 100644 --- a/libraries/tests/peripherals/SRF08/SRF08.h +++ b/libraries/tests/peripherals/SRF08/SRF08.h @@ -1,17 +1,17 @@ /* Copyright (c) 2010 Chris Styles (chris dot styles at mbed dot org) - + Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - + The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE @@ -39,18 +39,18 @@ public: SRF08 */ SRF08(PinName sda, PinName scl, int addr); - + /*! Destroys instance. - */ + */ ~SRF08(); - + //!Reads the current temperature. /*! Reads the temperature register of the TMP102 and converts it to a useable value. */ float read(); - + private: I2C m_i2c; int m_addr; diff --git a/libraries/tests/peripherals/TMP102/TMP102.cpp b/libraries/tests/peripherals/TMP102/TMP102.cpp index 8bc074e47d..934c690ed3 100644 --- a/libraries/tests/peripherals/TMP102/TMP102.cpp +++ b/libraries/tests/peripherals/TMP102/TMP102.cpp @@ -9,15 +9,15 @@ TMP102::~TMP102() { } float TMP102::read() { const char tempRegAddr = TEMP_REG_ADDR; - + m_i2c.write(m_addr, &tempRegAddr, 1); - + char reg[2] = {0,0}; m_i2c.read(m_addr, reg, 2); - + unsigned short res = (reg[0] << 4) | (reg[1] >> 4); - + float temp = (float) ((float)res * 0.0625); - + return temp; } diff --git a/libraries/tests/peripherals/TMP102/TMP102.h b/libraries/tests/peripherals/TMP102/TMP102.h index 8925b5ba54..ce7de83849 100644 --- a/libraries/tests/peripherals/TMP102/TMP102.h +++ b/libraries/tests/peripherals/TMP102/TMP102.h @@ -14,23 +14,23 @@ public: /*! Connect module at I2C address addr using I2C port pins sda and scl. TMP102 - \param addr
A0 pin connectionAddress
GND0x90
V+0x92
SDA0x94
SCL0x96
+ \param addr
A0 pin connectionAddress
GND0x90
V+0x92
SDA0x94
SCL0x96
*/ TMP102(PinName sda, PinName scl, int addr); - + /*! Destroys instance. - */ + */ ~TMP102(); - + //!Reads the current temperature. /*! Reads the temperature register of the TMP102 and converts it to a useable value. */ float read(); - + I2C m_i2c; - + private: int m_addr; diff --git a/libraries/tests/rtos/cmsis/basic/main.cpp b/libraries/tests/rtos/cmsis/basic/main.cpp index 65155b5518..d78a49fcf6 100644 --- a/libraries/tests/rtos/cmsis/basic/main.cpp +++ b/libraries/tests/rtos/cmsis/basic/main.cpp @@ -14,7 +14,7 @@ osThreadDef(led2_thread, osPriorityNormal, DEFAULT_STACK_SIZE); int main() { osThreadCreate(osThread(led2_thread), NULL); - + while (true) { led1 = !led1; osDelay(500); diff --git a/libraries/tests/rtos/cmsis/isr/main.cpp b/libraries/tests/rtos/cmsis/isr/main.cpp index 1df5871a2d..52c7da3d8c 100644 --- a/libraries/tests/rtos/cmsis/isr/main.cpp +++ b/libraries/tests/rtos/cmsis/isr/main.cpp @@ -19,10 +19,10 @@ void queue_thread(void const *argument) { int main (void) { Thread thread(queue_thread); - + Ticker ticker; ticker.attach(queue_isr, 1.0); - + while (true) { osEvent evt = queue.get(); if (evt.status != osEventMessage) { diff --git a/libraries/tests/rtos/cmsis/mail/main.cpp b/libraries/tests/rtos/cmsis/mail/main.cpp index 4eac5617f1..545fca34c7 100644 --- a/libraries/tests/rtos/cmsis/mail/main.cpp +++ b/libraries/tests/rtos/cmsis/mail/main.cpp @@ -15,7 +15,7 @@ void send_thread (void const *argument) { while (true) { i++; // fake data update mail_t *mail = (mail_t*)osMailAlloc(mail_box, osWaitForever); - mail->voltage = (i * 0.1) * 33; + mail->voltage = (i * 0.1) * 33; mail->current = (i * 0.1) * 11; mail->counter = i; osMailPut(mail_box, mail); @@ -28,7 +28,7 @@ osThreadDef(send_thread, osPriorityNormal, DEFAULT_STACK_SIZE); int main (void) { mail_box = osMailCreate(osMailQ(mail_box), NULL); osThreadCreate(osThread(send_thread), NULL); - + while (true) { osEvent evt = osMailGet(mail_box, osWaitForever); if (evt.status == osEventMail) { @@ -36,7 +36,7 @@ int main (void) { printf("\nVoltage: %.2f V\n\r" , mail->voltage); printf("Current: %.2f A\n\r" , mail->current); printf("Number of cycles: %u\n\r", mail->counter); - + osMailFree(mail_box, mail); } } diff --git a/libraries/tests/rtos/cmsis/mutex/main.cpp b/libraries/tests/rtos/cmsis/mutex/main.cpp index 3e4d92d655..ccd1a603ca 100644 --- a/libraries/tests/rtos/cmsis/mutex/main.cpp +++ b/libraries/tests/rtos/cmsis/mutex/main.cpp @@ -25,9 +25,9 @@ osThreadDef(t3, osPriorityNormal, DEFAULT_STACK_SIZE); int main() { stdio_mutex = osMutexCreate(osMutex(stdio_mutex)); - + osThreadCreate(osThread(t2), NULL); osThreadCreate(osThread(t3), NULL); - + test_thread((void *)"Th 1"); } diff --git a/libraries/tests/rtos/cmsis/queue/main.cpp b/libraries/tests/rtos/cmsis/queue/main.cpp index badce1a273..1c6eab2f39 100644 --- a/libraries/tests/rtos/cmsis/queue/main.cpp +++ b/libraries/tests/rtos/cmsis/queue/main.cpp @@ -18,7 +18,7 @@ void send_thread (void const *argument) { while (true) { i++; // fake data update message_t *message = (message_t*)osPoolAlloc(mpool); - message->voltage = (i * 0.1) * 33; + message->voltage = (i * 0.1) * 33; message->current = (i * 0.1) * 11; message->counter = i; osMessagePut(queue, (uint32_t)message, osWaitForever); @@ -31,9 +31,9 @@ osThreadDef(send_thread, osPriorityNormal, DEFAULT_STACK_SIZE); int main (void) { mpool = osPoolCreate(osPool(mpool)); queue = osMessageCreate(osMessageQ(queue), NULL); - + osThreadCreate(osThread(send_thread), NULL); - + while (true) { osEvent evt = osMessageGet(queue, osWaitForever); if (evt.status == osEventMessage) { @@ -41,7 +41,7 @@ int main (void) { printf("\nVoltage: %.2f V\n\r" , message->voltage); printf("Current: %.2f A\n\r" , message->current); printf("Number of cycles: %u\n\r", message->counter); - + osPoolFree(mpool, message); } } diff --git a/libraries/tests/rtos/cmsis/semaphore/main.cpp b/libraries/tests/rtos/cmsis/semaphore/main.cpp index 4d8d9b53c3..d4b473c187 100644 --- a/libraries/tests/rtos/cmsis/semaphore/main.cpp +++ b/libraries/tests/rtos/cmsis/semaphore/main.cpp @@ -21,9 +21,9 @@ osThreadDef(t3, osPriorityNormal, DEFAULT_STACK_SIZE); int main (void) { two_slots = osSemaphoreCreate(osSemaphore(two_slots), 2); - + osThreadCreate(osThread(t2), NULL); osThreadCreate(osThread(t3), NULL); - + test_thread((void *)"Th 1"); } diff --git a/libraries/tests/rtos/cmsis/signals/main.cpp b/libraries/tests/rtos/cmsis/signals/main.cpp index 190d21ea82..14ce05dadb 100644 --- a/libraries/tests/rtos/cmsis/signals/main.cpp +++ b/libraries/tests/rtos/cmsis/signals/main.cpp @@ -15,7 +15,7 @@ osThreadDef(led_thread, osPriorityNormal, DEFAULT_STACK_SIZE); int main (void) { osThreadId tid = osThreadCreate(osThread(led_thread), NULL); - + while (true) { osDelay(1000); osSignalSet(tid, 0x1); diff --git a/libraries/tests/rtos/cmsis/timer/main.cpp b/libraries/tests/rtos/cmsis/timer/main.cpp index 53888c122c..a0b093f946 100644 --- a/libraries/tests/rtos/cmsis/timer/main.cpp +++ b/libraries/tests/rtos/cmsis/timer/main.cpp @@ -19,11 +19,11 @@ int main(void) { osTimerId timer_1 = osTimerCreate(osTimer(blink_1), osTimerPeriodic, (void *)1); osTimerId timer_2 = osTimerCreate(osTimer(blink_2), osTimerPeriodic, (void *)2); osTimerId timer_3 = osTimerCreate(osTimer(blink_3), osTimerPeriodic, (void *)3); - + osTimerStart(timer_0, 2000); osTimerStart(timer_1, 1000); osTimerStart(timer_2, 500); osTimerStart(timer_3, 250); - + osDelay(osWaitForever); } diff --git a/libraries/tests/usb/device/basic/main.cpp b/libraries/tests/usb/device/basic/main.cpp index dcf6af52c0..9f786559fc 100644 --- a/libraries/tests/usb/device/basic/main.cpp +++ b/libraries/tests/usb/device/basic/main.cpp @@ -10,17 +10,17 @@ int main(void) { int y_center = (Y_MAX_ABS - Y_MIN_ABS)/2; int16_t x_screen = 0; int16_t y_screen = 0; - + int32_t x_origin = x_center; int32_t y_origin = y_center; int32_t radius = 5000; int32_t angle = 0; - + while (1) { x_screen = x_origin + cos((double)angle*3.14/180.0)*radius; y_screen = y_origin + sin((double)angle*3.14/180.0)*radius; printf("cos: %f, sin: %f\r\n", cos((double)angle*3.14/180.0)*radius, sin((double)angle)*radius); - + mouse.move(x_screen, y_screen); angle += 3; wait(0.01); diff --git a/workspace_tools/build.py b/workspace_tools/build.py index de0dd705b4..89534408cc 100755 --- a/workspace_tools/build.py +++ b/workspace_tools/build.py @@ -26,17 +26,19 @@ ROOT = abspath(join(dirname(__file__), "..")) sys.path.insert(0, ROOT) from workspace_tools.toolchains import TOOLCHAINS +from workspace_tools.toolchains import print_notify_verbose from workspace_tools.targets import TARGET_NAMES, TARGET_MAP from workspace_tools.options import get_default_options_parser from workspace_tools.build_api import build_mbed_libs, build_lib +from workspace_tools.build_api import mcu_toolchain_matrix if __name__ == '__main__': start = time() - + # Parse Options parser = get_default_options_parser() - + # Extra libraries parser.add_option("-r", "--rtos", action="store_true", dest="rtos", default=False, help="Compile the rtos") @@ -54,29 +56,42 @@ if __name__ == '__main__': default=False, help="Compile the u-blox library") parser.add_option("-D", "", action="append", dest="macros", help="Add a macro definition") + parser.add_option("-S", "--supported-toolchains", action="store_true", dest="supported_toolchains", + default=False, help="Displays supported matrix of MCUs and toolchains") + parser.add_option("-x", "--extra-verbose-notifications", action="store_true", dest="extra_verbose_notify", + default=False, help="Makes compiler more verbose, CI friendly.") (options, args) = parser.parse_args() - + + # Only prints matrix of supported toolchains + if options.supported_toolchains: + mcu_toolchain_matrix() + exit(0) + # Get target list if options.mcu: - if options.mcu not in TARGET_NAMES: - print "Given MCU '%s' not into the supported list:\n%s" % (options.mcu, TARGET_NAMES) - sys.exit(1) - targets = [options.mcu] + mcu_list = (options.mcu).split(",") + for mcu in mcu_list: + if mcu not in TARGET_NAMES: + print "Given MCU '%s' not into the supported list:\n%s" % (mcu, TARGET_NAMES) + sys.exit(1) + targets = mcu_list else: targets = TARGET_NAMES - + # Get toolchains list if options.tool: - if options.tool not in TOOLCHAINS: - print "Given toolchain '%s' not into the supported list:\n%s" % (options.tool, TOOLCHAINS) - sys.exit(1) - toolchains = [options.tool] + toolchain_list = (options.tool).split(",") + for tc in toolchain_list: + if tc not in TOOLCHAINS: + print "Given toolchain '%s' not into the supported list:\n%s" % (tc, TOOLCHAINS) + sys.exit(1) + toolchains = toolchain_list else: toolchains = TOOLCHAINS - + # Get libraries list libraries = [] - + # Additional Libraries if options.rtos: libraries.extend(["rtx", "rtos"]) @@ -90,7 +105,7 @@ if __name__ == '__main__': libraries.extend(["cmsis_dsp", "dsp"]) if options.ublox: libraries.extend(["rtx", "rtos", "usb_host", "ublox"]) - + # Build failures = [] successes = [] @@ -99,12 +114,14 @@ if __name__ == '__main__': id = "%s::%s" % (toolchain, target) try: mcu = TARGET_MAP[target] + notify = print_notify_verbose if options.extra_verbose_notify else None # Special notify for CI (more verbose) build_mbed_libs(mcu, toolchain, options=options.options, - verbose=options.verbose, clean=options.clean, + notify=notify, verbose=options.verbose, clean=options.clean, macros=options.macros) for lib_id in libraries: + notify = print_notify_verbose if options.extra_verbose_notify else None # Special notify for CI (more verbose) build_lib(lib_id, mcu, toolchain, options=options.options, - verbose=options.verbose, clean=options.clean, + notify=notify, verbose=options.verbose, clean=options.clean, macros=options.macros) successes.append(id) except Exception, e: @@ -112,17 +129,17 @@ if __name__ == '__main__': import sys, traceback traceback.print_exc(file=sys.stdout) sys.exit(1) - + failures.append(id) print e - + # Write summary of the builds print "\n\nCompleted in: (%.2f)s" % (time() - start) - + if successes: print "\n\nBuild successes:" print "\n".join([" * %s" % s for s in successes]) - + if failures: print "\n\nBuild failures:" print "\n".join([" * %s" % f for f in failures]) diff --git a/workspace_tools/build_api.py b/workspace_tools/build_api.py index 2340a7848f..1c56b3afec 100644 --- a/workspace_tools/build_api.py +++ b/workspace_tools/build_api.py @@ -22,6 +22,7 @@ from workspace_tools.utils import mkdir from workspace_tools.toolchains import TOOLCHAIN_CLASSES from workspace_tools.paths import MBED_TARGETS_PATH, MBED_LIBRARIES, MBED_API, MBED_HAL, MBED_COMMON from workspace_tools.libraries import Library +from workspace_tools.targets import TARGET_NAMES, TARGET_MAP def build_project(src_path, build_path, target, toolchain_name, @@ -36,7 +37,7 @@ def build_project(src_path, build_path, target, toolchain_name, if name is None: name = basename(src_paths[0]) toolchain.info("\n>>> BUILD PROJECT: %s (%s, %s)" % (name.upper(), target.name, toolchain_name)) - + # Scan src_path and libraries_paths for resources resources = toolchain.scan_resources(src_paths[0]) for path in src_paths[1:]: @@ -45,22 +46,22 @@ def build_project(src_path, build_path, target, toolchain_name, src_paths.extend(libraries_paths) for path in libraries_paths: resources.add(toolchain.scan_resources(path)) - + if linker_script is not None: resources.linker_script = linker_script - + # Build Directory if clean: if exists(build_path): rmtree(build_path) mkdir(build_path) - + # Compile Sources for path in src_paths: src = toolchain.scan_resources(path) objects = toolchain.compile_sources(src, build_path, resources.inc_dirs) resources.objects.extend(objects) - + # Link Program return toolchain.link_program(resources, build_path, name) @@ -79,99 +80,99 @@ def build_library(src_paths, build_path, target, toolchain_name, dependencies_paths=None, options=None, name=None, clean=False, notify=None, verbose=False, macros=None): if type(src_paths) != ListType: src_paths = [src_paths] - + for src_path in src_paths: if not exists(src_path): raise Exception("The library source folder does not exist: %s", src_path) - + # Toolchain instance - toolchain = TOOLCHAIN_CLASSES[toolchain_name](target, options, notify, macros) + toolchain = TOOLCHAIN_CLASSES[toolchain_name](target, options, macros=macros, notify=notify) toolchain.VERBOSE = verbose toolchain.build_all = clean - + # The first path will give the name to the library name = basename(src_paths[0]) toolchain.info("\n>>> BUILD LIBRARY %s (%s, %s)" % (name.upper(), target.name, toolchain_name)) - + # Scan Resources resources = [] for src_path in src_paths: resources.append(toolchain.scan_resources(src_path)) - + # Dependencies Include Paths dependencies_include_dir = [] if dependencies_paths is not None: for path in dependencies_paths: lib_resources = toolchain.scan_resources(path) dependencies_include_dir.extend(lib_resources.inc_dirs) - + # Create the desired build directory structure bin_path = join(build_path, toolchain.obj_path) mkdir(bin_path) tmp_path = join(build_path, '.temp', toolchain.obj_path) mkdir(tmp_path) - + # Copy Headers for resource in resources: toolchain.copy_files(resource.headers, build_path, rel_path=resource.base_path) dependencies_include_dir.extend(toolchain.scan_resources(build_path).inc_dirs) - + # Compile Sources objects = [] for resource in resources: objects.extend(toolchain.compile_sources(resource, tmp_path, dependencies_include_dir)) - + toolchain.build_library(objects, bin_path, name) -def build_lib(lib_id, target, toolchain, options=None, verbose=False, clean=False, macros=None): +def build_lib(lib_id, target, toolchain, options=None, verbose=False, clean=False, macros=None, notify=None): lib = Library(lib_id) if lib.is_supported(target, toolchain): build_library(lib.source_dir, lib.build_dir, target, toolchain, lib.dependencies, options, - verbose=verbose, clean=clean, macros=macros) + verbose=verbose, clean=clean, macros=macros, notify=notify) else: print '\n\nLibrary "%s" is not yet supported on target %s with toolchain %s' % (lib_id, target.name, toolchain) # We do have unique legacy conventions about how we build and package the mbed library -def build_mbed_libs(target, toolchain_name, options=None, verbose=False, clean=False, macros=None): +def build_mbed_libs(target, toolchain_name, options=None, verbose=False, clean=False, macros=None, notify=None): # Check toolchain support if toolchain_name not in target.supported_toolchains: print '\n%s target is not yet supported by toolchain %s' % (target.name, toolchain_name) return - + # Toolchain - toolchain = TOOLCHAIN_CLASSES[toolchain_name](target, options, macros=macros) + toolchain = TOOLCHAIN_CLASSES[toolchain_name](target, options, macros=macros, notify=notify) toolchain.VERBOSE = verbose toolchain.build_all = clean - + # Source and Build Paths BUILD_TARGET = join(MBED_LIBRARIES, "TARGET_" + target.name) BUILD_TOOLCHAIN = join(BUILD_TARGET, "TOOLCHAIN_" + toolchain.name) mkdir(BUILD_TOOLCHAIN) - + TMP_PATH = join(MBED_LIBRARIES, '.temp', toolchain.obj_path) mkdir(TMP_PATH) - + # CMSIS toolchain.info("\n>>> BUILD LIBRARY %s (%s, %s)" % ('CMSIS', target.name, toolchain_name)) cmsis_src = join(MBED_TARGETS_PATH, "cmsis") resources = toolchain.scan_resources(cmsis_src) - + toolchain.copy_files(resources.headers, BUILD_TARGET) toolchain.copy_files(resources.linker_script, BUILD_TOOLCHAIN) - + objects = toolchain.compile_sources(resources, TMP_PATH) toolchain.copy_files(objects, BUILD_TOOLCHAIN) - + # mbed toolchain.info("\n>>> BUILD LIBRARY %s (%s, %s)" % ('MBED', target.name, toolchain_name)) - + # Common Headers toolchain.copy_files(toolchain.scan_resources(MBED_API).headers, MBED_LIBRARIES) toolchain.copy_files(toolchain.scan_resources(MBED_HAL).headers, MBED_LIBRARIES) - + # Target specific sources HAL_SRC = join(MBED_TARGETS_PATH, "hal") hal_implementation = toolchain.scan_resources(HAL_SRC) @@ -199,3 +200,40 @@ def build_mbed_libs(target, toolchain_name, options=None, verbose=False, clean=F toolchain.build_library(objects, BUILD_TOOLCHAIN, "mbed") for o in separate_objects: toolchain.copy_files(o, BUILD_TOOLCHAIN) + + +def get_unique_supported_toolchains(): + """ Get list of all unique toolchains supported by targets """ + unique_supported_toolchains = [] + for target in TARGET_NAMES: + for toolchain in TARGET_MAP[target].supported_toolchains: + if toolchain not in unique_supported_toolchains: + unique_supported_toolchains.append(toolchain) + return unique_supported_toolchains + + +def mcu_toolchain_matrix(): + """ Shows target map using prettytable """ + unique_supported_toolchains = get_unique_supported_toolchains() + from prettytable import PrettyTable # Only use it in this function so building works without extra modules + + # All tests status table print + columns = ["Platform"] + unique_supported_toolchains + pt = PrettyTable(["Platform"] + unique_supported_toolchains) + # Align table + for col in columns: + pt.align[col] = "c" + pt.align["Platform"] = "l" + + perm_counter = 0; + for target in sorted(TARGET_NAMES): + row = [target] # First column is platform name + for unique_toolchain in unique_supported_toolchains: + text = "-" + if unique_toolchain in TARGET_MAP[target].supported_toolchains: + text = "Supported" + perm_counter += 1 + row.append(text); + pt.add_row(row) + print pt + print "Total permutations: %d"% (perm_counter) diff --git a/workspace_tools/build_release.py b/workspace_tools/build_release.py index 7e62c50fec..49dffc099c 100644 --- a/workspace_tools/build_release.py +++ b/workspace_tools/build_release.py @@ -17,6 +17,7 @@ limitations under the License. import sys from time import time from os.path import join, abspath, dirname +from optparse import OptionParser # Be sure that the tools directory is in the search path ROOT = abspath(join(dirname(__file__), "..")) @@ -37,43 +38,57 @@ OFFICIAL_MBED_LIBRARY_BUILD = ( ('LPC11U35_401', ('ARM', 'uARM','GCC_ARM','GCC_CR')), ('LPC11U35_501', ('ARM', 'uARM','GCC_ARM','GCC_CR')), ('LPC1549', ('uARM',)), - + ('KL05Z', ('ARM', 'uARM', 'GCC_ARM')), ('KL25Z', ('ARM', 'GCC_ARM')), ('KL46Z', ('ARM', 'GCC_ARM')), - ('K64F', ('ARM',)), - - ('NUCLEO_F103RB', ('ARM', 'uARM')), - ('NUCLEO_L152RE', ('ARM', 'uARM')), - ('NUCLEO_F401RE', ('ARM', 'uARM')), + ('K64F', ('ARM', 'GCC_ARM')), + ('NUCLEO_F030R8', ('ARM', 'uARM')), + ('NUCLEO_F072RB', ('ARM', 'uARM')), + ('NUCLEO_F103RB', ('ARM', 'uARM')), ('NUCLEO_F302R8', ('ARM', 'uARM')), - + ('NUCLEO_F401RE', ('ARM', 'uARM')), + ('NUCLEO_L053R8', ('ARM', 'uARM')), + ('NUCLEO_L152RE', ('ARM', 'uARM')), + ('NRF51822', ('ARM', )), + + ('LPC11U68', ('uARM',)), ) if __name__ == '__main__': + parser = OptionParser() + parser.add_option('-o', '--official', dest="official_only", default=False, action="store_true", + help="Build using only the official toolchain for each target") + parser.add_option("-v", "--verbose", action="store_true", dest="verbose", + default=False, help="Verbose diagnostic output") + options, args = parser.parse_args() start = time() failures = [] successes = [] - for target_name, toolchains in OFFICIAL_MBED_LIBRARY_BUILD: + for target_name, toolchain_list in OFFICIAL_MBED_LIBRARY_BUILD: + if options.official_only: + toolchains = (getattr(TARGET_MAP[target_name], 'ONLINE_TOOLCHAIN', 'ARM'),) + else: + toolchains = toolchain_list for toolchain in toolchains: id = "%s::%s" % (target_name, toolchain) try: - build_mbed_libs(TARGET_MAP[target_name], toolchain) + build_mbed_libs(TARGET_MAP[target_name], toolchain, verbose=options.verbose) successes.append(id) except Exception, e: failures.append(id) print e - + # Write summary of the builds print "\n\nCompleted in: (%.2f)s" % (time() - start) - + if successes: print "\n\nBuild successes:" print "\n".join([" * %s" % s for s in successes]) - + if failures: print "\n\nBuild failures:" print "\n".join([" * %s" % f for f in failures]) diff --git a/workspace_tools/data/rpc/class.cpp b/workspace_tools/data/rpc/class.cpp index 73f36a2371..f7831980c0 100644 --- a/workspace_tools/data/rpc/class.cpp +++ b/workspace_tools/data/rpc/class.cpp @@ -1,9 +1,9 @@ class Rpc{{name}} : public RPC { public: Rpc{{name}}({{cons_proto}}) : RPC(name), o({{cons_call}}) {} - + {{methods}} - + virtual const struct rpc_method *get_rpc_methods() { static const rpc_method rpc_methods[] = { {{rpc_methods}}, diff --git a/workspace_tools/data/support.py b/workspace_tools/data/support.py index ed65eb0ac0..b47380f4d9 100644 --- a/workspace_tools/data/support.py +++ b/workspace_tools/data/support.py @@ -21,7 +21,7 @@ CORTEX_ARM_SUPPORT = {} for target in TARGETS: DEFAULT_SUPPORT[target.name] = target.supported_toolchains - + if target.core.startswith('Cortex'): CORTEX_ARM_SUPPORT[target.name] = [t for t in target.supported_toolchains if (t=='ARM' or t=='uARM')] diff --git a/workspace_tools/dev/intel_hex_utils.py b/workspace_tools/dev/intel_hex_utils.py index da92d9d116..c60e9c4e74 100644 --- a/workspace_tools/dev/intel_hex_utils.py +++ b/workspace_tools/dev/intel_hex_utils.py @@ -8,13 +8,13 @@ def sections(h): if last_address is None: start, last_address = a, a continue - + if a > last_address + 1: yield (start, last_address) start = a - + last_address = a - + if start: yield (start, last_address) diff --git a/workspace_tools/dev/rpc_classes.py b/workspace_tools/dev/rpc_classes.py index 35d75ffc2d..f082f3b9da 100644 --- a/workspace_tools/dev/rpc_classes.py +++ b/workspace_tools/dev/rpc_classes.py @@ -153,38 +153,38 @@ for c in RPC_CLASSES: "cons_proto": get_args_proto(c_args, ["const char *name=NULL"]), "cons_call": get_args_call(c_args) } - + c_name = "Rpc" + c['name'] - + methods = [] rpc_methods = [] for r, m, a in c['methods']: ret_proto = r if r else "void" args_proto = "void" - + ret_defin = "return " if r else "" args_defin = "" - + if a: args_proto = get_args_proto(a) args_defin = get_args_call(a) - + proto = "%s %s(%s)" % (ret_proto, m, args_proto) defin = "{%so.%s(%s);}" % (ret_defin, m, args_defin) methods.append("%s %s" % (proto, defin)) - + rpc_method_type = [r] if r else [] rpc_method_type.append(c_name) rpc_method_type.extend(a) rpc_methods.append('{"%s", rpc_method_caller<%s, &%s::%s>}' % (m, ', '.join(rpc_method_type), c_name, m)) - + data['methods'] = "\n ".join(methods) data['rpc_methods'] = ",\n ".join(rpc_methods) - + class_decl = class_template.render(data) if 'required' in c: class_decl = "#if DEVICE_%s\n%s\n#endif" % (c['required'], class_decl) - + classes.append(class_decl) write_rpc_classes('\n\n'.join(classes)) diff --git a/workspace_tools/dev/syms.py b/workspace_tools/dev/syms.py index 63d90a2add..2fdbd2dfba 100644 --- a/workspace_tools/dev/syms.py +++ b/workspace_tools/dev/syms.py @@ -28,7 +28,7 @@ OBJ_EXT = ['.o', '.a', '.ar'] def find_sym_in_lib(sym, obj_path): contain_symbol = False - + out = Popen(["nm", "-C", obj_path], stdout=PIPE, stderr=PIPE).communicate()[0] for line in out.splitlines(): tokens = line.split() @@ -41,24 +41,24 @@ def find_sym_in_lib(sym, obj_path): sym_name = tokens[2] else: continue - + if sym_type == "U": # This object is using this symbol, not defining it continue - + if sym_name == sym: contain_symbol = True - + return contain_symbol def find_sym_in_path(sym, dir_path): for root, _, files in walk(dir_path): for file in files: - + _, ext = splitext(file) if ext not in OBJ_EXT: continue - + path = join(root, file) if find_sym_in_lib(sym, path): print path @@ -71,5 +71,5 @@ if __name__ == '__main__': parser.add_argument('-p', '--path', required=True, help='The path where to search') args = parser.parse_args() - + find_sym_in_path(args.sym, args.path) diff --git a/workspace_tools/export/README.md b/workspace_tools/export/README.md index fb64292979..a434c13b42 100644 --- a/workspace_tools/export/README.md +++ b/workspace_tools/export/README.md @@ -111,6 +111,16 @@ Exporter Toolchain/Platform Support ✓ ✓ + + + Freescale K64F + + + + + + + ✓ ST Nucleo F030R8 @@ -131,6 +141,16 @@ Exporter Toolchain/Platform Support ✓ + + + ST Nucleo F302R8 + + + + + + + ✓ ST Nucleo F401RE @@ -152,4 +172,14 @@ Exporter Toolchain/Platform Support ✓ + + Nordic NRF51822 + + + + + + + ✓ + diff --git a/workspace_tools/export/codered.py b/workspace_tools/export/codered.py index 8abb268e5e..93acd2bff2 100644 --- a/workspace_tools/export/codered.py +++ b/workspace_tools/export/codered.py @@ -21,21 +21,22 @@ from os.path import splitext, basename class CodeRed(Exporter): NAME = 'CodeRed' TOOLCHAIN = 'GCC_CR' - + TARGETS = [ 'LPC1768', 'LPC4088', 'LPC1114', 'LPC11U35_401', 'LPC11U35_501', + 'UBLOX_C027', ] - + def generate(self): libraries = [] for lib in self.resources.libraries: l, _ = splitext(basename(lib)) libraries.append(l[3:]) - + ctx = { 'name': self.program_name, 'include_paths': self.resources.inc_dirs, diff --git a/workspace_tools/export/codered_ublox_c027_cproject.tmpl b/workspace_tools/export/codered_ublox_c027_cproject.tmpl new file mode 100644 index 0000000000..e317bb125e --- /dev/null +++ b/workspace_tools/export/codered_ublox_c027_cproject.tmpl @@ -0,0 +1,1925 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + <?xml version="1.0" encoding="UTF-8"?> +<TargetConfig> +<Properties property_0="" property_1="" property_2="" property_3="NXP" property_4="LPC1768" property_count="5" version="1"/> +<infoList vendor="NXP"> +<info chip="LPC1768" match_id="0x00013f37,0x26013F37,0x26113F37" name="LPC1768" package="lpc17_lqfp100.xml"> +<chip> +<name>LPC1768</name> +<family>LPC17xx</family> +<vendor>NXP (formerly Philips)</vendor> +<reset board="None" core="Real" sys="Real"/> +<clock changeable="TRUE" freq="20MHz" is_accurate="TRUE"/> +<memory can_program="true" id="Flash" is_ro="true" type="Flash"/> +<memory id="RAM" type="RAM"/> +<memory id="Periph" is_volatile="true" type="Peripheral"/> +<memoryInstance derived_from="Flash" id="MFlash512" location="0x00000000" size="0x80000"/> +<memoryInstance derived_from="RAM" id="RamLoc32" location="0x10000000" size="0x8000"/> +<memoryInstance derived_from="RAM" id="RamAHB32" location="0x2007c000" size="0x8000"/> +<prog_flash blocksz="0x1000" location="0" maxprgbuff="0x1000" progwithcode="TRUE" size="0x10000"/> +<prog_flash blocksz="0x8000" location="0x10000" maxprgbuff="0x1000" progwithcode="TRUE" size="0x70000"/> +<peripheralInstance derived_from="LPC17_NVIC" determined="infoFile" id="NVIC" location="0xE000E000"/> +<peripheralInstance derived_from="TIMER" determined="infoFile" enable="SYSCTL.PCONP.PCTIM0&amp;0x1" id="TIMER0" location="0x40004000"/> +<peripheralInstance derived_from="TIMER" determined="infoFile" enable="SYSCTL.PCONP.PCTIM1&amp;0x1" id="TIMER1" location="0x40008000"/> +<peripheralInstance derived_from="TIMER" determined="infoFile" enable="SYSCTL.PCONP.PCTIM2&amp;0x1" id="TIMER2" location="0x40090000"/> +<peripheralInstance derived_from="TIMER" determined="infoFile" enable="SYSCTL.PCONP.PCTIM3&amp;0x1" id="TIMER3" location="0x40094000"/> +<peripheralInstance derived_from="LPC17_RIT" determined="infoFile" enable="SYSCTL.PCONP.PCRIT&amp;0x1" id="RIT" location="0x400B0000"/> +<peripheralInstance derived_from="FGPIO" determined="infoFile" enable="SYSCTL.PCONP.PCGPIO&amp;0x1" id="GPIO0" location="0x2009C000"/> +<peripheralInstance derived_from="FGPIO" determined="infoFile" enable="SYSCTL.PCONP.PCGPIO&amp;0x1" id="GPIO1" location="0x2009C020"/> +<peripheralInstance derived_from="FGPIO" determined="infoFile" enable="SYSCTL.PCONP.PCGPIO&amp;0x1" id="GPIO2" location="0x2009C040"/> +<peripheralInstance derived_from="FGPIO" determined="infoFile" enable="SYSCTL.PCONP.PCGPIO&amp;0x1" id="GPIO3" location="0x2009C060"/> +<peripheralInstance derived_from="FGPIO" determined="infoFile" enable="SYSCTL.PCONP.PCGPIO&amp;0x1" id="GPIO4" location="0x2009C080"/> +<peripheralInstance derived_from="LPC17_I2S" determined="infoFile" enable="SYSCTL.PCONP&amp;0x08000000" id="I2S" location="0x400A8000"/> +<peripheralInstance derived_from="LPC17_SYSCTL" determined="infoFile" id="SYSCTL" location="0x400FC000"/> +<peripheralInstance derived_from="LPC17_DAC" determined="infoFile" enable="PCB.PINSEL1.P0_26&amp;0x2=2" id="DAC" location="0x4008C000"/> +<peripheralInstance derived_from="LPC17xx_UART" determined="infoFile" enable="SYSCTL.PCONP.PCUART0&amp;0x1" id="UART0" location="0x4000C000"/> +<peripheralInstance derived_from="LPC17xx_UART_MODEM" determined="infoFile" enable="SYSCTL.PCONP.PCUART1&amp;0x1" id="UART1" location="0x40010000"/> +<peripheralInstance derived_from="LPC17xx_UART" determined="infoFile" enable="SYSCTL.PCONP.PCUART2&amp;0x1" id="UART2" location="0x40098000"/> +<peripheralInstance derived_from="LPC17xx_UART" determined="infoFile" enable="SYSCTL.PCONP.PCUART3&amp;0x1" id="UART3" location="0x4009C000"/> +<peripheralInstance derived_from="SPI" determined="infoFile" enable="SYSCTL.PCONP.PCSPI&amp;0x1" id="SPI" location="0x40020000"/> +<peripheralInstance derived_from="LPC17_SSP" determined="infoFile" enable="SYSCTL.PCONP.PCSSP0&amp;0x1" id="SSP0" location="0x40088000"/> +<peripheralInstance derived_from="LPC17_SSP" determined="infoFile" enable="SYSCTL.PCONP.PCSSP1&amp;0x1" id="SSP1" location="0x40030000"/> +<peripheralInstance derived_from="LPC17_ADC" determined="infoFile" enable="SYSCTL.PCONP.PCAD&amp;0x1" id="ADC" location="0x40034000"/> +<peripheralInstance derived_from="LPC17_USBINTST" determined="infoFile" enable="USBCLKCTL.USBClkCtrl&amp;0x12" id="USBINTSTAT" location="0x400fc1c0"/> +<peripheralInstance derived_from="LPC17_USB_CLK_CTL" determined="infoFile" id="USBCLKCTL" location="0x5000cff4"/> +<peripheralInstance derived_from="LPC17_USBDEV" determined="infoFile" enable="USBCLKCTL.USBClkSt&amp;0x12=0x12" id="USBDEV" location="0x5000C200"/> +<peripheralInstance derived_from="LPC17_PWM" determined="infoFile" enable="SYSCTL.PCONP.PWM1&amp;0x1" id="PWM" location="0x40018000"/> +<peripheralInstance derived_from="LPC17_I2C" determined="infoFile" enable="SYSCTL.PCONP.PCI2C0&amp;0x1" id="I2C0" location="0x4001C000"/> +<peripheralInstance derived_from="LPC17_I2C" determined="infoFile" enable="SYSCTL.PCONP.PCI2C1&amp;0x1" id="I2C1" location="0x4005C000"/> +<peripheralInstance derived_from="LPC17_I2C" determined="infoFile" enable="SYSCTL.PCONP.PCI2C2&amp;0x1" id="I2C2" location="0x400A0000"/> +<peripheralInstance derived_from="LPC17_DMA" determined="infoFile" enable="SYSCTL.PCONP.PCGPDMA&amp;0x1" id="DMA" location="0x50004000"/> +<peripheralInstance derived_from="LPC17_ENET" determined="infoFile" enable="SYSCTL.PCONP.PCENET&amp;0x1" id="ENET" location="0x50000000"/> +<peripheralInstance derived_from="CM3_DCR" determined="infoFile" id="DCR" location="0xE000EDF0"/> +<peripheralInstance derived_from="LPC17_PCB" determined="infoFile" id="PCB" location="0x4002c000"/> +<peripheralInstance derived_from="LPC17_QEI" determined="infoFile" enable="SYSCTL.PCONP.PCQEI&amp;0x1" id="QEI" location="0x400bc000"/> +<peripheralInstance derived_from="LPC17_USBHOST" determined="infoFile" enable="USBCLKCTL.USBClkSt&amp;0x11=0x11" id="USBHOST" location="0x5000C000"/> +<peripheralInstance derived_from="LPC17_USBOTG" determined="infoFile" enable="USBCLKCTL.USBClkSt&amp;0x1c=0x1c" id="USBOTG" location="0x5000C000"/> +<peripheralInstance derived_from="LPC17_RTC" determined="infoFile" enable="SYSCTL.PCONP.PCRTC&amp;0x1" id="RTC" location="0x40024000"/> +<peripheralInstance derived_from="MPU" determined="infoFile" id="MPU" location="0xE000ED90"/> +<peripheralInstance derived_from="LPC1x_WDT" determined="infoFile" id="WDT" location="0x40000000"/> +<peripheralInstance derived_from="LPC17_FLASHCFG" determined="infoFile" id="FLASHACCEL" location="0x400FC000"/> +<peripheralInstance derived_from="GPIO_INT" determined="infoFile" id="GPIOINTMAP" location="0x40028080"/> +<peripheralInstance derived_from="LPC17_CANAFR" determined="infoFile" enable="SYSCTL.PCONP.PCCAN1&amp;0x1|SYSCTL.PCONP.PCCAN2&amp;0x1" id="CANAFR" location="0x4003C000"/> +<peripheralInstance derived_from="LPC17_CANCEN" determined="infoFile" enable="SYSCTL.PCONP.PCCAN1&amp;0x1|SYSCTL.PCONP.PCCAN2&amp;0x1" id="CANCEN" location="0x40040000"/> +<peripheralInstance derived_from="LPC17_CANWAKESLEEP" determined="infoFile" id="CANWAKESLEEP" location="0x400FC110"/> +<peripheralInstance derived_from="LPC17_CANCON" determined="infoFile" enable="SYSCTL.PCONP.PCCAN1&amp;0x1" id="CANCON1" location="0x40044000"/> +<peripheralInstance derived_from="LPC17_CANCON" determined="infoFile" enable="SYSCTL.PCONP.PCCAN2&amp;0x1" id="CANCON2" location="0x40048000"/> +<peripheralInstance derived_from="LPC17_MCPWM" determined="infoFile" enable="SYSCTL.PCONP.PCMCPWM&amp;0x1" id="MCPWM" location="0x400B8000"/> +</chip> +<processor> +<name gcc_name="cortex-m3">Cortex-M3</name> +<family>Cortex-M</family> +</processor> +<link href="nxp_lpcxxxx_peripheral.xme" show="embed" type="simple"/> +</info> +</infoList> +</TargetConfig> + + + diff --git a/workspace_tools/export/codered_ublox_c027_project.tmpl b/workspace_tools/export/codered_ublox_c027_project.tmpl new file mode 100644 index 0000000000..42ef4384de --- /dev/null +++ b/workspace_tools/export/codered_ublox_c027_project.tmpl @@ -0,0 +1,84 @@ + + + {{name}} + This file was automagically generated by mbed.org. For more information, see http://mbed.org/handbook/Exporting-To-Code-Red + + + + + org.eclipse.cdt.managedbuilder.core.genmakebuilder + clean,full,incremental, + + + ?name? + + + + org.eclipse.cdt.make.core.append_environment + true + + + org.eclipse.cdt.make.core.autoBuildTarget + all + + + org.eclipse.cdt.make.core.buildArguments + + + + org.eclipse.cdt.make.core.buildCommand + make + + + org.eclipse.cdt.make.core.buildLocation + ${workspace_loc:/{{name}}/Debug} + + + org.eclipse.cdt.make.core.cleanBuildTarget + clean + + + org.eclipse.cdt.make.core.contents + org.eclipse.cdt.make.core.activeConfigSettings + + + org.eclipse.cdt.make.core.enableAutoBuild + false + + + org.eclipse.cdt.make.core.enableCleanBuild + true + + + org.eclipse.cdt.make.core.enableFullBuild + true + + + org.eclipse.cdt.make.core.fullBuildTarget + all + + + org.eclipse.cdt.make.core.stopOnError + true + + + org.eclipse.cdt.make.core.useDefaultBuildCmd + true + + + + + org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder + full,incremental, + + + + + + org.eclipse.cdt.core.cnature + org.eclipse.cdt.core.ccnature + org.eclipse.cdt.managedbuilder.core.managedBuildNature + org.eclipse.cdt.managedbuilder.core.ScannerConfigNature + + + diff --git a/workspace_tools/export/codesourcery.py b/workspace_tools/export/codesourcery.py index 2f470575ca..691cce809f 100644 --- a/workspace_tools/export/codesourcery.py +++ b/workspace_tools/export/codesourcery.py @@ -21,17 +21,18 @@ from os.path import splitext, basename class CodeSourcery(Exporter): NAME = 'CodeSourcery' TOOLCHAIN = 'GCC_CS' - + TARGETS = [ 'LPC1768', + 'UBLOX_C027', ] - + DOT_IN_RELATIVE_PATH = True - + def generate(self): # "make" wants Unix paths self.resources.win_to_unix() - + to_be_compiled = [] for r_type in ['s_sources', 'c_sources', 'cpp_sources']: r = getattr(self.resources, r_type) @@ -39,12 +40,12 @@ class CodeSourcery(Exporter): for source in r: base, ext = splitext(source) to_be_compiled.append(base + '.o') - + libraries = [] for lib in self.resources.libraries: l, _ = splitext(basename(lib)) libraries.append(l[3:]) - + ctx = { 'name': self.program_name, 'to_be_compiled': to_be_compiled, diff --git a/workspace_tools/export/codesourcery_ublox_c027.tmpl b/workspace_tools/export/codesourcery_ublox_c027.tmpl new file mode 100644 index 0000000000..0fa0fa6bd8 --- /dev/null +++ b/workspace_tools/export/codesourcery_ublox_c027.tmpl @@ -0,0 +1,56 @@ +# This file was automagically generated by mbed.org. For more information, +# see http://mbed.org/handbook/Exporting-to-CodeSourcery + +GCC_BIN = +PROJECT = {{name}} +OBJECTS = {% for f in to_be_compiled %}{{f}} {% endfor %} +SYS_OBJECTS = {% for f in object_files %}{{f}} {% endfor %} +INCLUDE_PATHS = {% for p in include_paths %}-I{{p}} {% endfor %} +LIBRARY_PATHS = {% for p in library_paths %}-L{{p}} {% endfor %} +LIBRARIES = {% for lib in libraries %}-l{{lib}} {% endfor %} +LINKER_SCRIPT = {{linker_script}} + +############################################################################### +CC = $(GCC_BIN)arm-none-eabi-gcc +CPP = $(GCC_BIN)arm-none-eabi-g++ +CC_FLAGS = -c -g -fno-common -fmessage-length=0 -Wall -fno-exceptions -mcpu=cortex-m3 -mthumb -ffunction-sections -fdata-sections +ONLY_C_FLAGS = -std=gnu99 +ONLY_CPP_FLAGS = -std=gnu++98 +CC_SYMBOLS = {% for s in symbols %}-D{{s}} {% endfor %} + + +AS = $(GCC_BIN)arm-none-eabi-as + +LD = $(GCC_BIN)arm-none-eabi-gcc +LD_FLAGS = -mcpu=cortex-m3 -mthumb -Wl,--gc-sections +LD_SYS_LIBS = -lstdc++ -lsupc++ -lm -lc -lgcc + +OBJCOPY = $(GCC_BIN)arm-none-eabi-objcopy + +ifeq ($(DEBUG), 1) + CC_FLAGS += -DDEBUG -O0 +else + CC_FLAGS += -DNDEBUG -Os +endif + +all: $(PROJECT).bin + +clean: + rm -f $(PROJECT).bin $(PROJECT).elf $(OBJECTS) + +.s.o: + $(AS) $(CC_FLAGS) $(CC_SYMBOLS) -o $@ $< + +.c.o: + $(CC) $(CC_FLAGS) $(CC_SYMBOLS) $(ONLY_C_FLAGS) $(INCLUDE_PATHS) -o $@ $< + +.cpp.o: + $(CPP) $(CC_FLAGS) $(CC_SYMBOLS) $(ONLY_CPP_FLAGS) $(INCLUDE_PATHS) -o $@ $< + + +$(PROJECT).elf: $(OBJECTS) $(SYS_OBJECTS) + $(LD) $(LD_FLAGS) -T$(LINKER_SCRIPT) $(LIBRARY_PATHS) -o $@ $^ $(LIBRARIES) $(LD_SYS_LIBS) $(LIBRARIES) $(LD_SYS_LIBS) + +$(PROJECT).bin: $(PROJECT).elf + $(OBJCOPY) -O binary $< $@ + diff --git a/workspace_tools/export/coide.py b/workspace_tools/export/coide.py index 4415d96400..4d88079e39 100644 --- a/workspace_tools/export/coide.py +++ b/workspace_tools/export/coide.py @@ -21,12 +21,12 @@ from os.path import splitext, basename class CoIDE(Exporter): NAME = 'CoIDE' TOOLCHAIN = 'GCC_ARM' - + TARGETS = [ 'KL25Z', 'KL05Z', ] - + # seems like CoIDE currently supports only one type FILE_TYPES = { 'c_sources':'1', diff --git a/workspace_tools/export/ds5_5.py b/workspace_tools/export/ds5_5.py index ec2a046711..6f304ebafe 100644 --- a/workspace_tools/export/ds5_5.py +++ b/workspace_tools/export/ds5_5.py @@ -20,17 +20,18 @@ from os.path import basename class DS5_5(Exporter): NAME = 'DS5' - + TARGETS = [ 'LPC1768', 'LPC11U24', 'LPC812', + 'UBLOX_C027', ] - + USING_MICROLIB = [ 'LPC812', ] - + FILE_TYPES = { 'c_sources':'1', 'cpp_sources':'8', @@ -39,7 +40,7 @@ class DS5_5(Exporter): def get_toolchain(self): return 'uARM' if (self.target in self.USING_MICROLIB) else 'ARM' - + def generate(self): source_files = [] for r_type, n in DS5_5.FILE_TYPES.iteritems(): @@ -47,7 +48,7 @@ class DS5_5(Exporter): source_files.append({ 'name': basename(file), 'type': n, 'path': file }) - + ctx = { 'name': self.program_name, 'include_paths': self.resources.inc_dirs, @@ -57,7 +58,7 @@ class DS5_5(Exporter): 'symbols': self.toolchain.get_symbols() } target = self.target.lower() - + # Project file self.gen_file('ds5_5_%s.project.tmpl' % target, ctx, '.project') self.gen_file('ds5_5_%s.cproject.tmpl' % target, ctx, '.cproject') diff --git a/workspace_tools/export/ds5_5_ublox_c027.cproject.tmpl b/workspace_tools/export/ds5_5_ublox_c027.cproject.tmpl new file mode 100644 index 0000000000..5a5fff4d49 --- /dev/null +++ b/workspace_tools/export/ds5_5_ublox_c027.cproject.tmpl @@ -0,0 +1,115 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/workspace_tools/export/ds5_5_ublox_c027.launch.tmpl b/workspace_tools/export/ds5_5_ublox_c027.launch.tmpl new file mode 100644 index 0000000000..74bc9649e7 --- /dev/null +++ b/workspace_tools/export/ds5_5_ublox_c027.launch.tmpl @@ -0,0 +1,111 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/workspace_tools/export/ds5_5_ublox_c027.project.tmpl b/workspace_tools/export/ds5_5_ublox_c027.project.tmpl new file mode 100644 index 0000000000..4f892f370b --- /dev/null +++ b/workspace_tools/export/ds5_5_ublox_c027.project.tmpl @@ -0,0 +1,83 @@ + + + {{name}}_ds5_lpc1768 + + + + + + org.eclipse.cdt.managedbuilder.core.genmakebuilder + clean,full,incremental, + + + ?name? + + + + org.eclipse.cdt.make.core.append_environment + true + + + org.eclipse.cdt.make.core.autoBuildTarget + all + + + org.eclipse.cdt.make.core.buildArguments + + + + org.eclipse.cdt.make.core.buildCommand + make + + + org.eclipse.cdt.make.core.buildLocation + ${workspace_loc:/ds5_lpc1768/Build} + + + org.eclipse.cdt.make.core.cleanBuildTarget + clean + + + org.eclipse.cdt.make.core.contents + org.eclipse.cdt.make.core.activeConfigSettings + + + org.eclipse.cdt.make.core.enableAutoBuild + false + + + org.eclipse.cdt.make.core.enableCleanBuild + true + + + org.eclipse.cdt.make.core.enableFullBuild + true + + + org.eclipse.cdt.make.core.fullBuildTarget + all + + + org.eclipse.cdt.make.core.stopOnError + true + + + org.eclipse.cdt.make.core.useDefaultBuildCmd + true + + + + + org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder + full,incremental, + + + + + + org.eclipse.cdt.core.cnature + org.eclipse.cdt.core.ccnature + org.eclipse.cdt.managedbuilder.core.managedBuildNature + org.eclipse.cdt.managedbuilder.core.ScannerConfigNature + + diff --git a/workspace_tools/export/exporters.py b/workspace_tools/export/exporters.py index 5fb5b91251..a5114c23fc 100644 --- a/workspace_tools/export/exporters.py +++ b/workspace_tools/export/exporters.py @@ -16,23 +16,23 @@ class OldLibrariesException(Exception): pass class Exporter(): TEMPLATE_DIR = dirname(__file__) DOT_IN_RELATIVE_PATH = False - + def __init__(self, target, inputDir, program_name, build_url_resolver): self.inputDir = inputDir self.target = target self.program_name = program_name self.toolchain = TOOLCHAIN_CLASSES[self.get_toolchain()](TARGET_MAP[target]) self.build_url_resolver = build_url_resolver - + def get_toolchain(self): return self.TOOLCHAIN - + def __scan_and_copy(self, src_path, trg_path): resources = self.toolchain.scan_resources(src_path) - + for r_type in ['headers', 's_sources', 'c_sources', 'cpp_sources', 'objects', 'libraries', 'linker_script', - 'lib_builds', 'lib_refs', 'repo_files']: + 'lib_builds', 'lib_refs', 'repo_files', 'hex_files']: r = getattr(resources, r_type) if r: self.toolchain.copy_files(r, trg_path, rel_path=src_path) @@ -40,7 +40,7 @@ class Exporter(): def __scan_all(self, path): resources = [] - + for root, dirs, files in walk(path): for d in copy(dirs): if d == '.' or d == '..': @@ -49,9 +49,9 @@ class Exporter(): for file in files: file_path = join(root, file) resources.append(file_path) - + return resources - + def scan_and_copy_resources(self, prj_path, trg_path): # Copy only the file for the required target and toolchain lib_builds = [] @@ -63,7 +63,7 @@ class Exporter(): for repo_dir in resources.repo_dirs: repo_files = self.__scan_all(repo_dir) self.toolchain.copy_files(repo_files, trg_path, rel_path=join(prj_path, src)) - + # The libraries builds for bld in lib_builds: build_url = open(bld).read().strip() @@ -90,7 +90,7 @@ class Exporter(): template_text = open(template_path).read() template = Template(template_text) target_text = template.render(data) - + target_path = join(self.inputDir, target_file) logging.debug("Generating: %s" % target_path) open(target_path, "w").write(target_text) @@ -99,7 +99,7 @@ class Exporter(): def zip_working_directory_and_clean_up(tempdirectory=None, destination=None, program_name=None, clean=True): uid = str(uuid.uuid4()) zipfilename = '%s.zip'%uid - + logging.debug("Zipping up %s to %s" % (tempdirectory, join(destination, zipfilename))) # make zip def zipdir(basedir, archivename): @@ -112,10 +112,10 @@ def zip_working_directory_and_clean_up(tempdirectory=None, destination=None, pro absfn = join(root, fn) zfn = fakeroot + '/' + absfn[len(basedir)+len(os.sep):] z.write(absfn, zfn) - + zipdir(tempdirectory, join(destination, zipfilename)) - + if clean: shutil.rmtree(tempdirectory) - + return join(destination, zipfilename) diff --git a/workspace_tools/export/gcc_arm_k64f.tmpl b/workspace_tools/export/gcc_arm_k64f.tmpl new file mode 100644 index 0000000000..037be828fb --- /dev/null +++ b/workspace_tools/export/gcc_arm_k64f.tmpl @@ -0,0 +1,52 @@ +# This file was automagically generated by mbed.org. For more information, +# see http://mbed.org/handbook/Exporting-to-GCC-ARM-Embedded + +GCC_BIN = +PROJECT = {{name}} +OBJECTS = {% for f in to_be_compiled %}{{f}} {% endfor %} +SYS_OBJECTS = {% for f in object_files %}{{f}} {% endfor %} +INCLUDE_PATHS = {% for p in include_paths %}-I{{p}} {% endfor %} +LIBRARY_PATHS = {% for p in library_paths %}-L{{p}} {% endfor %} +LIBRARIES = {% for lib in libraries %}-l{{lib}} {% endfor %} +LINKER_SCRIPT = {{linker_script}} + +############################################################################### +AS = $(GCC_BIN)arm-none-eabi-as +CC = $(GCC_BIN)arm-none-eabi-gcc +CPP = $(GCC_BIN)arm-none-eabi-g++ +LD = $(GCC_BIN)arm-none-eabi-gcc +OBJCOPY = $(GCC_BIN)arm-none-eabi-objcopy + +CPU = -mcpu=cortex-m4 -mthumb -mfpu=fpv4-sp-d16 -mfloat-abi=softfp +CC_FLAGS = $(CPU) -c -g -fno-common -fmessage-length=0 -Wall -fno-exceptions -ffunction-sections -fdata-sections +CC_SYMBOLS = {% for s in symbols %}-D{{s}} {% endfor %} + +LD_FLAGS = -mcpu=cortex-m4 -mthumb -Wl,--gc-sections --specs=nano.specs -u _printf_float -u _scanf_float +LD_SYS_LIBS = -lstdc++ -lsupc++ -lm -lc -lgcc -lnosys + +ifeq ($(DEBUG), 1) + CC_FLAGS += -DDEBUG -O0 +else + CC_FLAGS += -DNDEBUG -Os +endif + +all: $(PROJECT).bin + +clean: + rm -f $(PROJECT).bin $(PROJECT).elf $(OBJECTS) + +.s.o: + $(AS) $(CPU) -o $@ $< + +.c.o: + $(CC) $(CC_FLAGS) $(CC_SYMBOLS) -std=gnu99 $(INCLUDE_PATHS) -o $@ $< + +.cpp.o: + $(CPP) $(CC_FLAGS) $(CC_SYMBOLS) -std=gnu++98 $(INCLUDE_PATHS) -o $@ $< + + +$(PROJECT).elf: $(OBJECTS) $(SYS_OBJECTS) + $(LD) $(LD_FLAGS) -T$(LINKER_SCRIPT) $(LIBRARY_PATHS) -o $@ $^ $(LIBRARIES) $(LD_SYS_LIBS) $(LIBRARIES) $(LD_SYS_LIBS) + +$(PROJECT).bin: $(PROJECT).elf + $(OBJCOPY) -O binary $< $@ diff --git a/workspace_tools/export/gcc_arm_ublox_c027.tmpl b/workspace_tools/export/gcc_arm_ublox_c027.tmpl new file mode 100644 index 0000000000..aa3bfdab4b --- /dev/null +++ b/workspace_tools/export/gcc_arm_ublox_c027.tmpl @@ -0,0 +1,57 @@ +# This file was automagically generated by mbed.org. For more information, +# see http://mbed.org/handbook/Exporting-to-GCC-ARM-Embedded + +GCC_BIN = +PROJECT = {{name}} +OBJECTS = {% for f in to_be_compiled %}{{f}} {% endfor %} +SYS_OBJECTS = {% for f in object_files %}{{f}} {% endfor %} +INCLUDE_PATHS = {% for p in include_paths %}-I{{p}} {% endfor %} +LIBRARY_PATHS = {% for p in library_paths %}-L{{p}} {% endfor %} +LIBRARIES = {% for lib in libraries %}-l{{lib}} {% endfor %} +LINKER_SCRIPT = {{linker_script}} + +############################################################################### +AS = $(GCC_BIN)arm-none-eabi-as +CC = $(GCC_BIN)arm-none-eabi-gcc +CPP = $(GCC_BIN)arm-none-eabi-g++ +LD = $(GCC_BIN)arm-none-eabi-gcc +OBJCOPY = $(GCC_BIN)arm-none-eabi-objcopy + +CPU = -mcpu=cortex-m3 -mthumb +CC_FLAGS = $(CPU) -c -g -fno-common -fmessage-length=0 -Wall -fno-exceptions -ffunction-sections -fdata-sections +CC_FLAGS += -MMD -MP +CC_SYMBOLS = {% for s in symbols %}-D{{s}} {% endfor %} + +LD_FLAGS = -mcpu=cortex-m3 -mthumb -Wl,--gc-sections --specs=nano.specs -u _printf_float -u _scanf_float +LD_SYS_LIBS = -lstdc++ -lsupc++ -lm -lc -lgcc -lnosys + +ifeq ($(DEBUG), 1) + CC_FLAGS += -DDEBUG -O0 +else + CC_FLAGS += -DNDEBUG -Os +endif + +all: $(PROJECT).bin + +clean: + rm -f $(PROJECT).bin $(PROJECT).elf $(OBJECTS) $(DEPS) + +.s.o: + $(AS) $(CPU) -o $@ $< + +.c.o: + $(CC) $(CC_FLAGS) $(CC_SYMBOLS) -std=gnu99 $(INCLUDE_PATHS) -o $@ $< + +.cpp.o: + $(CPP) $(CC_FLAGS) $(CC_SYMBOLS) -std=gnu++98 $(INCLUDE_PATHS) -o $@ $< + + +$(PROJECT).elf: $(OBJECTS) $(SYS_OBJECTS) + $(LD) $(LD_FLAGS) -T$(LINKER_SCRIPT) $(LIBRARY_PATHS) -o $@ $^ $(LIBRARIES) $(LD_SYS_LIBS) $(LIBRARIES) $(LD_SYS_LIBS) + +$(PROJECT).bin: $(PROJECT).elf + $(OBJCOPY) -O binary $< $@ + +DEPS = $(OBJECTS:.o=.d) $(SYS_OBJECTS:.o=.d) +-include $(DEPS) + diff --git a/workspace_tools/export/gccarm.py b/workspace_tools/export/gccarm.py index 3f4243cbce..88039c7305 100644 --- a/workspace_tools/export/gccarm.py +++ b/workspace_tools/export/gccarm.py @@ -21,12 +21,13 @@ from os.path import splitext, basename class GccArm(Exporter): NAME = 'GccArm' TOOLCHAIN = 'GCC_ARM' - + TARGETS = [ 'LPC1768', 'KL05Z', 'KL25Z', 'KL46Z', + 'K64F', 'K20D5M', 'LPC4088', 'LPC11U24', @@ -38,14 +39,15 @@ class GccArm(Exporter): 'DISCO_F051R8', 'DISCO_F407VG', 'DISCO_F303VC', + 'UBLOX_C027', ] - + DOT_IN_RELATIVE_PATH = True - + def generate(self): # "make" wants Unix paths self.resources.win_to_unix() - + to_be_compiled = [] for r_type in ['s_sources', 'c_sources', 'cpp_sources']: r = getattr(self.resources, r_type) @@ -53,12 +55,12 @@ class GccArm(Exporter): for source in r: base, ext = splitext(source) to_be_compiled.append(base + '.o') - + libraries = [] for lib in self.resources.libraries: l, _ = splitext(basename(lib)) libraries.append(l[3:]) - + ctx = { 'name': self.program_name, 'to_be_compiled': to_be_compiled, diff --git a/workspace_tools/export/iar.py b/workspace_tools/export/iar.py index aa2487168e..637e045be6 100644 --- a/workspace_tools/export/iar.py +++ b/workspace_tools/export/iar.py @@ -20,11 +20,12 @@ from exporters import Exporter class IAREmbeddedWorkbench(Exporter): NAME = 'IAR' TOOLCHAIN = 'IAR' - + TARGETS = [ 'LPC1768', + 'UBLOX_C027', ] - + def generate(self): ctx = { 'name': self.program_name, diff --git a/workspace_tools/export/uvision4.py b/workspace_tools/export/uvision4.py index 0cb18ecdae..bd9dd31361 100644 --- a/workspace_tools/export/uvision4.py +++ b/workspace_tools/export/uvision4.py @@ -20,7 +20,7 @@ from os.path import basename class Uvision4(Exporter): NAME = 'uVision4' - + TARGETS = [ 'LPC1768', 'LPC11U24', @@ -34,14 +34,17 @@ class Uvision4(Exporter): 'LPC11C24', 'LPC4088', 'LPC812', - 'NUCLEO_F103RB', - 'NUCLEO_L152RE', 'NUCLEO_F030R8', - 'NUCLEO_F401RE', + 'NUCLEO_F072RB', + 'NUCLEO_F103RB', 'NUCLEO_F302R8', + 'NUCLEO_F401RE', + 'NUCLEO_L053R8', + 'NUCLEO_L152RE', 'UBLOX_C027', 'LPC1549', 'LPC11U35_501', + 'NRF51822', ] USING_MICROLIB = [ @@ -49,26 +52,37 @@ class Uvision4(Exporter): 'LPC1114', 'LPC11C24', 'LPC812', - 'NUCLEO_F103RB', - 'NUCLEO_L152RE', 'NUCLEO_F030R8', - 'NUCLEO_F401RE', + 'NUCLEO_F072RB', + 'NUCLEO_F103RB', 'NUCLEO_F302R8', + 'NUCLEO_F401RE', + 'NUCLEO_L053R8', + 'NUCLEO_L152RE', 'LPC1549', 'LPC11U35_501', + 'KL05Z', ] - + FILE_TYPES = { 'c_sources':'1', 'cpp_sources':'8', 's_sources':'2' } + + FLAGS = [ + "--gnu", + ] + # By convention uVision projects do not show header files in the editor: # 'headers':'5', - + def get_toolchain(self): return 'uARM' if (self.target in self.USING_MICROLIB) else 'ARM' - + + def get_flags(self): + return self.FLAGS + def generate(self): source_files = { 'mbed': [], @@ -91,10 +105,11 @@ class Uvision4(Exporter): 'scatter_file': self.resources.linker_script, 'object_files': self.resources.objects + self.resources.libraries, 'source_files': source_files.items(), - 'symbols': self.toolchain.get_symbols() + 'symbols': self.toolchain.get_symbols(), + 'hex_files' : self.resources.hex_files, + 'flags' : self.get_flags(), } target = self.target.lower() - # Project file self.gen_file('uvision4_%s.uvproj.tmpl' % target, ctx, '%s.uvproj' % self.program_name) self.gen_file('uvision4_%s.uvopt.tmpl' % target, ctx, '%s.uvopt' % self.program_name) diff --git a/workspace_tools/export/uvision4_k20d5m.uvproj.tmpl b/workspace_tools/export/uvision4_k20d5m.uvproj.tmpl index 3adb8921cc..5e5ff5a55d 100644 --- a/workspace_tools/export/uvision4_k20d5m.uvproj.tmpl +++ b/workspace_tools/export/uvision4_k20d5m.uvproj.tmpl @@ -346,7 +346,7 @@ 0 0 - --gnu + {% for flag in flags %}{{flag}} {% endfor %} {% for s in symbols %} {{s}}, {% endfor %} {% for path in include_paths %} {{path}}; {% endfor %} diff --git a/workspace_tools/export/uvision4_k64f.uvproj.tmpl b/workspace_tools/export/uvision4_k64f.uvproj.tmpl index 5bcf67f411..25923318b9 100644 --- a/workspace_tools/export/uvision4_k64f.uvproj.tmpl +++ b/workspace_tools/export/uvision4_k64f.uvproj.tmpl @@ -348,7 +348,7 @@ 0 0 - --gnu + {% for flag in flags %}{{flag}} {% endfor %} --pch --pch_dir=build {% for s in symbols %} {{s}}, {% endfor %} {% for path in include_paths %} {{path}}; {% endfor %} diff --git a/workspace_tools/export/uvision4_kl05z.uvproj.tmpl b/workspace_tools/export/uvision4_kl05z.uvproj.tmpl index f6faf306e3..d167d31fa5 100644 --- a/workspace_tools/export/uvision4_kl05z.uvproj.tmpl +++ b/workspace_tools/export/uvision4_kl05z.uvproj.tmpl @@ -346,7 +346,7 @@ 0 0 - --gnu + {% for flag in flags %}{{flag}} {% endfor %} {% for s in symbols %} {{s}}, {% endfor %} {% for path in include_paths %} {{path}}; {% endfor %} diff --git a/workspace_tools/export/uvision4_kl25z.uvproj.tmpl b/workspace_tools/export/uvision4_kl25z.uvproj.tmpl index ac92ccc25e..9aebfa0070 100644 --- a/workspace_tools/export/uvision4_kl25z.uvproj.tmpl +++ b/workspace_tools/export/uvision4_kl25z.uvproj.tmpl @@ -346,7 +346,7 @@ 0 0 - --gnu + {% for flag in flags %}{{flag}} {% endfor %} {% for s in symbols %} {{s}}, {% endfor %} {% for path in include_paths %} {{path}}; {% endfor %} diff --git a/workspace_tools/export/uvision4_kl46z.uvproj.tmpl b/workspace_tools/export/uvision4_kl46z.uvproj.tmpl index 1fd0b306a0..e0b055d92f 100644 --- a/workspace_tools/export/uvision4_kl46z.uvproj.tmpl +++ b/workspace_tools/export/uvision4_kl46z.uvproj.tmpl @@ -346,7 +346,7 @@ 0 0 - --gnu + {% for flag in flags %}{{flag}} {% endfor %} {% for s in symbols %} {{s}}, {% endfor %} {% for path in include_paths %} {{path}}; {% endfor %} diff --git a/workspace_tools/export/uvision4_lpc1114.uvproj.tmpl b/workspace_tools/export/uvision4_lpc1114.uvproj.tmpl index 58316ef123..be9df69956 100644 --- a/workspace_tools/export/uvision4_lpc1114.uvproj.tmpl +++ b/workspace_tools/export/uvision4_lpc1114.uvproj.tmpl @@ -348,7 +348,7 @@ 0 0 - + {% for flag in flags %}{{flag}} {% endfor %} {% for s in symbols %} {{s}}, {% endfor %} {% for path in include_paths %} {{path}}; {% endfor %} diff --git a/workspace_tools/export/uvision4_lpc11c24.uvproj.tmpl b/workspace_tools/export/uvision4_lpc11c24.uvproj.tmpl index a49f2c0090..9e6be2526f 100644 --- a/workspace_tools/export/uvision4_lpc11c24.uvproj.tmpl +++ b/workspace_tools/export/uvision4_lpc11c24.uvproj.tmpl @@ -348,7 +348,7 @@ 0 0 - + {% for flag in flags %}{{flag}} {% endfor %} {% for s in symbols %} {{s}}, {% endfor %} {% for path in include_paths %} {{path}}; {% endfor %} diff --git a/workspace_tools/export/uvision4_lpc11u24.uvproj.tmpl b/workspace_tools/export/uvision4_lpc11u24.uvproj.tmpl index 061eb2c5eb..b089827968 100644 --- a/workspace_tools/export/uvision4_lpc11u24.uvproj.tmpl +++ b/workspace_tools/export/uvision4_lpc11u24.uvproj.tmpl @@ -343,7 +343,7 @@ 0 0 - --gnu + {% for flag in flags %}{{flag}} {% endfor %} {% for s in symbols %} {{s}}, {% endfor %} {% for path in include_paths %} {{path}}; {% endfor %} diff --git a/workspace_tools/export/uvision4_lpc1347.uvproj.tmpl b/workspace_tools/export/uvision4_lpc1347.uvproj.tmpl index 171fc70c7e..75deb14fef 100644 --- a/workspace_tools/export/uvision4_lpc1347.uvproj.tmpl +++ b/workspace_tools/export/uvision4_lpc1347.uvproj.tmpl @@ -344,7 +344,7 @@ 0 0 - --gnu + {% for flag in flags %}{{flag}} {% endfor %} {% for s in symbols %} {{s}}, {% endfor %} {% for path in include_paths %} {{path}}; {% endfor %} diff --git a/workspace_tools/export/uvision4_lpc1549.uvproj.tmpl b/workspace_tools/export/uvision4_lpc1549.uvproj.tmpl index a3ea979c83..63e0882502 100644 --- a/workspace_tools/export/uvision4_lpc1549.uvproj.tmpl +++ b/workspace_tools/export/uvision4_lpc1549.uvproj.tmpl @@ -354,7 +354,7 @@ 0 0 - + {% for flag in flags %}{{flag}} {% endfor %} {% for s in symbols %} {{s}}, {% endfor %} {% for path in include_paths %} {{path}}; {% endfor %} diff --git a/workspace_tools/export/uvision4_lpc1768.uvproj.tmpl b/workspace_tools/export/uvision4_lpc1768.uvproj.tmpl index 8f16a02ba1..6fdbbe2419 100644 --- a/workspace_tools/export/uvision4_lpc1768.uvproj.tmpl +++ b/workspace_tools/export/uvision4_lpc1768.uvproj.tmpl @@ -345,7 +345,7 @@ 0 0 - --gnu + {% for flag in flags %}{{flag}} {% endfor %} {% for s in symbols %} {{s}}, {% endfor %} {% for path in include_paths %} {{path}}; {% endfor %} diff --git a/workspace_tools/export/uvision4_lpc4088.uvproj.tmpl b/workspace_tools/export/uvision4_lpc4088.uvproj.tmpl index 3d28824bb5..6a92907c1a 100644 --- a/workspace_tools/export/uvision4_lpc4088.uvproj.tmpl +++ b/workspace_tools/export/uvision4_lpc4088.uvproj.tmpl @@ -347,7 +347,7 @@ 0 0 - --gnu + {% for flag in flags %}{{flag}} {% endfor %} {% for s in symbols %} {{s}}, {% endfor %} {% for path in include_paths %} {{path}}; {% endfor %} diff --git a/workspace_tools/export/uvision4_lpc812.uvproj.tmpl b/workspace_tools/export/uvision4_lpc812.uvproj.tmpl index 84fd7f6af8..4f66e80339 100644 --- a/workspace_tools/export/uvision4_lpc812.uvproj.tmpl +++ b/workspace_tools/export/uvision4_lpc812.uvproj.tmpl @@ -348,7 +348,7 @@ 0 0 - --gnu + {% for flag in flags %}{{flag}} {% endfor %} {% for s in symbols %} {{s}}, {% endfor %} {% for path in include_paths %} {{path}}; {% endfor %} diff --git a/workspace_tools/export/uvision4_nrf51822.uvopt.tmpl b/workspace_tools/export/uvision4_nrf51822.uvopt.tmpl new file mode 100644 index 0000000000..1d3b463017 --- /dev/null +++ b/workspace_tools/export/uvision4_nrf51822.uvopt.tmpl @@ -0,0 +1,214 @@ + + + + 1.0 + +
### uVision Project, (C) Keil Software
+ + + *.c + *.s*; *.src; *.a* + *.obj + *.lib + *.txt; *.h; *.inc + *.plm + *.cpp + + + + 0 + 0 + + + + nRF51822AA + 0x4 + ARM-ADS + + 16000000 + + 1 + 1 + 1 + 0 + + + 1 + 65535 + 0 + 0 + 0 + + + 79 + 66 + 8 + .\build\ + + + 1 + 1 + 1 + 0 + 1 + 1 + 0 + 1 + 0 + 0 + 0 + 0 + + + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 0 + 0 + + + 1 + 0 + 1 + + 0 + + SARMCM3.DLL + + DARMCM1.DLL + -pCM0 + SARMCM3.DLL + + TARMCM1.DLL + -pCM0 + + + 0 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 0 + 1 + 0 + 1 + 1 + 0 + 0 + 12 + + + + + + + + + + + BIN\CMSIS_AGDI.dll + + + + 0 + JL2CM3 + -U480204337 -O78 -S0 -A0 -C0 -JU1 -JI127.0.0.1 -JP0 -RST0 -N00("ARM CoreSight SW-DP") -D00(0BB11477) -L00(0) -TO18 -TC10000000 -TP21 -TDS8004 -TDT0 -TDC1F -TIEFFFFFFFF -TIP8 -TB1 -TFE0 -FO31 -FD20000000 -FC800 -FN1 -FF0nrf51xxx.flm -FS00 -FL0200000 -FP0($$Device:nRF51822_xxAA$Flash\nrf51xxx.flm) + + + 0 + UL2CM3 + -S0 -C0 -P0 -FD20000000 -FC1000 -FN1 -FF0nrf51xxx -FS00 -FL0200000 -FP0($$Device:nRF51$Flash\nrf51xxx.flm)) + + + 0 + DLGTARM + (1010=-1,-1,-1,-1,0)(1007=-1,-1,-1,-1,0)(1008=-1,-1,-1,-1,0) + + + 0 + ARMDBGFLAGS + + + + 0 + DLGUARM + + + + 0 + ULP2CM3 + -O2510 -S0 -C0 -FO15 -FD20000000 -FC800 -FN1 -FF0MK_P128_48MHZ -FS00 -FL020000) + + + 0 + CMSIS_AGDI + -X"MBED CMSIS-DAP" -U107002011FE6E019E2180F91 -O718 -S0 -C0 -P00 -N00("ARM CoreSight SW-DP") -D00(0BB11477) -L00(0) -FO31 -FD20000000 -FC800 -FN1 -FF0nrf51xxx.flm -FS00 -FL0200000 -FP0($$Device:nRF51822_xxAA$Flash\nrf51xxx.flm) + + + + + 0 + 0 + 1 + 0 + 0 + 0 + 0 + 1 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + + + + + + + + src + 1 + 0 + 0 + + 1 + 1 + 8 + 0 + 0 + 0 + 0 + 1 + 2 + 0 + main.cpp + main.cpp + + + +
diff --git a/workspace_tools/export/uvision4_nrf51822.uvproj.tmpl b/workspace_tools/export/uvision4_nrf51822.uvproj.tmpl new file mode 100644 index 0000000000..b14d1afa35 --- /dev/null +++ b/workspace_tools/export/uvision4_nrf51822.uvproj.tmpl @@ -0,0 +1,431 @@ + + + + 1.1 + +
###This file was automagically generated by mbed.org. For more information, see http://mbed.org/handbook/Exporting-To-Uvision
+ + + + nRF51822AA + 0x4 + ARM-ADS + + + nRF51822_xxAA + Nordic Semiconductor + IROM(0x00000000,0x40000) IRAM(0x20000000,0x4000) CPUTYPE("Cortex-M0") CLOCK(16000000) ELITTLE + + + UL2CM3(-S0 -C0 -P0 -FD20000000 -FC1000 -FN1 -FF0nrf51xxx -FS00 -FL0200000 -FP0($$Device:nRF51822_xxAA$Flash\nrf51xxx.flm)) + 0 + $$Device:nRF51822_xxAA$Device\Include\nrf.h + + + + + + + + + + $$Device:nRF51822_xxAA$SVD\nrf51.xml + 0 + 0 + + + + + + + 0 + 0 + 0 + 0 + 1 + + .\build\ + {{name}} + 1 + 0 + 1 + 1 + 1 + .\build\ + 1 + 0 + 0 + + 0 + 0 + + + 0 + 0 + 0 + 0 + + + 0 + 0 + + + 0 + 0 + + + 1 + 0 + mergehex -m !H {% for hex in hex_files %} {{hex}} {% endfor %} -o $H@H.hex + + 0 + 0 + + 0 + + + + 0 + 0 + 0 + 0 + 0 + 1 + 0 + 0 + 0 + 0 + 3 + + + 1 + + + SARMCM3.DLL + + DARMCM1.DLL + -pCM0 + SARMCM3.DLL + + TARMCM1.DLL + -pCM0 + + + + 1 + 0 + 0 + 0 + 16 + + + 0 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 0 + + + 1 + 1 + 1 + 1 + 1 + 1 + 0 + 1 + + 0 + 1 + + + + + + + + + + + + + + BIN\UL2CM3.DLL + + + + + 1 + 0 + 0 + 0 + 1 + 4096 + + 1 + BIN\UL2CM3.DLL + "" () + + + + + 0 + + + + 0 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 0 + 1 + 1 + 0 + 1 + 1 + 0 + 0 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 0 + 0 + "Cortex-M0" + + 0 + 0 + 0 + 1 + 1 + 0 + 0 + 0 + 0 + 0 + 8 + 0 + 0 + 0 + 3 + 3 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 1 + 0 + 0 + 0 + 0 + 1 + 0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x20000000 + 0x4000 + + + 1 + 0x0 + 0x40000 + + + 0 + 0x0 + 0x0 + + + 1 + 0x0 + 0x0 + + + 1 + 0x0 + 0x0 + + + 1 + 0x0 + 0x0 + + + 1 + 0x0 + 0x40000 + + + 1 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x20000000 + 0x4000 + + + 0 + 0x0 + 0x0 + + + + + + 1 + 1 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + + {% for flag in flags %}{{flag}} {% endfor %} + {% for s in symbols %} {{s}}, {% endfor %} + + {% for path in include_paths %} {{path}}; {% endfor %} + + + + 1 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + + + + + + + + + 0 + 0 + 0 + 0 + 1 + 0 + 0x00000000 + 0x10000000 + + {{scatter_file}} + + + + {% for file in object_files %} + {{file}} + {% endfor %} + + + + + + + + {% for group,files in source_files %} + + {{group}} + + {% for file in files %} + + {{file.name}} + {{file.type}} + {{file.path}} + {%if file.type == "1" %} + + + + + --c99 + + + + + {% endif %} + + {% endfor %} + + + {% endfor %} + + + + +
diff --git a/workspace_tools/export/uvision4_nucleo_f030r8.uvproj.tmpl b/workspace_tools/export/uvision4_nucleo_f030r8.uvproj.tmpl index 373f47a1b1..400e2c2684 100644 --- a/workspace_tools/export/uvision4_nucleo_f030r8.uvproj.tmpl +++ b/workspace_tools/export/uvision4_nucleo_f030r8.uvproj.tmpl @@ -354,7 +354,7 @@ 0 0 - --gnu + {% for flag in flags %}{{flag}} {% endfor %} {% for s in symbols %} {{s}}, {% endfor %} {% for path in include_paths %} {{path}}; {% endfor %} @@ -399,7 +399,7 @@ - {% for group,files in source_files %} + {% for group,files in source_files %} {{group}} diff --git a/workspace_tools/export/uvision4_nucleo_f072rb.uvopt.tmpl b/workspace_tools/export/uvision4_nucleo_f072rb.uvopt.tmpl new file mode 100644 index 0000000000..37e8f8834d --- /dev/null +++ b/workspace_tools/export/uvision4_nucleo_f072rb.uvopt.tmpl @@ -0,0 +1,218 @@ + + + + 1.0 + +
### uVision Project, (C) Keil Software
+ + + *.c + *.s*; *.src; *.a* + *.obj + *.lib + *.txt; *.h; *.inc + *.plm + *.cpp + + + + 0 + 0 + + + + mbed NUCLEO_F072RB + 0x4 + ARM-ADS + + 48000000 + + 1 + 1 + 1 + 0 + + + 1 + 65535 + 0 + 0 + 0 + + + 79 + 66 + 8 + .\build\ + + + 1 + 1 + 1 + 0 + 1 + 1 + 0 + 1 + 0 + 0 + 0 + 0 + + + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 0 + 0 + + + 1 + 0 + 1 + + 255 + + SARMCM3.DLL + + DARMCM1.DLL + -pCM0 + SARMCM3.DLL + + TARMCM1.DLL + -pCM0 + + + 0 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 0 + 1 + 0 + 0 + 0 + 13 + + + + + + + + + + + STLink\ST-LINKIII-KEIL_SWO.dll + + + + 0 + DLGTARM + (1010=-1,-1,-1,-1,0)(1007=-1,-1,-1,-1,0)(1008=-1,-1,-1,-1,0) + + + 0 + ARMDBGFLAGS + + + + 0 + DLGUARM + (105=-1,-1,-1,-1,0) + + + 0 + ST-LINKIII-KEIL_SWO + -U-O207 -O207 -S0 -C0 -N00("ARM CoreSight SW-DP") -D00(0BB11477) -L00(0) -TO18 -TC10000000 -TP21 -TDS8007 -TDT0 -TDC1F -TIEFFFFFFFF -TIP8 -FO15 -FD20000000 -FC800 -FN1 -FF0STM32F05x_128 -FS08000000 -FL020000 + + + 0 + UL2CM3 + -O207 -S0 -C0 -FO7 -FD20000000 -FC800 -FN1 -FF0STM32F0xx_128 -FS08000000 -FL020000) + + + 0 + ULP2CM3 + -O2510 -S0 -C0 -FO15 -FN1 -FC800 -FD20000000 -FF0MK_P128_48MHZ -FL020000 -FS00 + + + 0 + CMSIS_AGDI + -X"MBED CMSIS-DAP" -UA000000001 -O462 -S0 -C0 -N00("ARM CoreSight SW-DP") -D00(0BC11477) -L00(0) -FO15 -FD20000000 -FC800 -FN1 -FF0MK_P128_48MHZ -FS00 -FL020000 + + + + + 0 + + + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + + + + + + + + src + 1 + 0 + 0 + 0 + + 1 + 1 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + main.cpp + main.cpp + 0 + 0 + + + +
diff --git a/workspace_tools/export/uvision4_nucleo_f072rb.uvproj.tmpl b/workspace_tools/export/uvision4_nucleo_f072rb.uvproj.tmpl new file mode 100644 index 0000000000..6b7adb144f --- /dev/null +++ b/workspace_tools/export/uvision4_nucleo_f072rb.uvproj.tmpl @@ -0,0 +1,438 @@ + + + + 1.1 + +
### uVision Project, (C) Keil Software
+ + + + mbed NUCLEO_F072RB + 0x4 + ARM-ADS + + + STM32F072RB + STMicroelectronics + IRAM(0x20000000-0x20003FFF) IROM(0x08000000-0x0801FFFF) CLOCK(8000000) CPUTYPE("Cortex-M0") + + "Startup\ST\STM32F0xx\startup_stm32f072.s" ("STM32F072 Startup Code") + UL2CM3(-O207 -S0 -C0 -FO7 -FD20000000 -FC800 -FN1 -FF0STM32F0xx_128 -FS08000000 -FL020000) + 7471 + stm32f0xx.h + + + + + + + + + + SFD\ST\STM32F0xx\STM32F072x.SFR + 0 + 0 + + + + + + + 0 + 0 + 0 + 0 + 1 + + .\build\ + {{name}} + 1 + 0 + 0 + 1 + 1 + .\build\ + 1 + 0 + 0 + + 0 + 0 + + + 0 + 0 + 0 + 0 + + + 0 + 0 + + + 0 + 0 + + + 1 + 0 + fromelf --bin -o build\{{name}}_NUCLEO_F072RB.bin build\{{name}}.axf + + 0 + 0 + + 0 + + + + 0 + 0 + 0 + 0 + 0 + 1 + 0 + 0 + 0 + 0 + 3 + + + 1 + + + SARMCM3.DLL + + DARMCM1.DLL + -pCM0 + SARMCM3.DLL + + TARMCM1.DLL + -pCM0 + + + + 1 + 0 + 0 + 0 + 16 + + + 0 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 0 + + + 1 + 1 + 1 + 1 + 1 + 1 + 0 + 1 + 0 + + 0 + 11 + + + + + + + + + + + + + + STLink\ST-LINKIII-KEIL_SWO.dll + + + + + 1 + 0 + 0 + 1 + 1 + 4096 + + 1 + STLink\ST-LINKIII-KEIL_SWO.dll + "" () + + + + + 0 + + + + 0 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 0 + 1 + 1 + 0 + 1 + 1 + 0 + 0 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 0 + 0 + "Cortex-M0" + + 0 + 0 + 0 + 1 + 1 + 0 + 0 + 0 + 0 + 0 + 8 + 1 + 0 + 0 + 3 + 3 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 1 + 0 + 0 + 0 + 0 + 1 + 0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x20000000 + 0x4000 + + + 1 + 0x8000000 + 0x20000 + + + 0 + 0x0 + 0x0 + + + 1 + 0x0 + 0x0 + + + 1 + 0x0 + 0x0 + + + 1 + 0x0 + 0x0 + + + 1 + 0x8000000 + 0x20000 + + + 1 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x20000000 + 0x4000 + + + 0 + 0x0 + 0x0 + + + + + + 1 + 1 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 2 + 0 + 0 + + {% for flag in flags %}{{flag}} {% endfor %} + {% for s in symbols %} {{s}}, {% endfor %} + + {% for path in include_paths %} {{path}}; {% endfor %} + + + + 1 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + + + + + + + + + 0 + 0 + 0 + 0 + 1 + 0 + 0x00000000 + 0x10000000 + {{scatter_file}} + + + + {% for file in object_files %} + {{file}} + {% endfor %} + + + + + + + + {% for group,files in source_files %} + + {{group}} + + {% for file in files %} + + {{file.name}} + {{file.type}} + {{file.path}} + + + 2 + 0 + 0 + 0 + 0 + 1 + 0 + 0 + 0 + 0 + 3 + + + + + + + {% endfor %} + + + {% endfor %} + + + + +
diff --git a/workspace_tools/export/uvision4_nucleo_f103rb.uvproj.tmpl b/workspace_tools/export/uvision4_nucleo_f103rb.uvproj.tmpl index 24ae31d86c..dcb6507b6a 100644 --- a/workspace_tools/export/uvision4_nucleo_f103rb.uvproj.tmpl +++ b/workspace_tools/export/uvision4_nucleo_f103rb.uvproj.tmpl @@ -354,7 +354,7 @@ 0 0 - --gnu + {% for flag in flags %}{{flag}} {% endfor %} {% for s in symbols %} {{s}}, {% endfor %} {% for path in include_paths %} {{path}}; {% endfor %} @@ -399,7 +399,7 @@ - {% for group,files in source_files %} + {% for group,files in source_files %} {{group}} diff --git a/workspace_tools/export/uvision4_nucleo_f302r8.uvproj.tmpl b/workspace_tools/export/uvision4_nucleo_f302r8.uvproj.tmpl index 32289ffb30..73961b05d4 100644 --- a/workspace_tools/export/uvision4_nucleo_f302r8.uvproj.tmpl +++ b/workspace_tools/export/uvision4_nucleo_f302r8.uvproj.tmpl @@ -354,7 +354,7 @@ 0 0 - --gnu + {% for flag in flags %}{{flag}} {% endfor %} {% for s in symbols %} {{s}}, {% endfor %} {% for path in include_paths %} {{path}}; {% endfor %} @@ -399,7 +399,7 @@ - {% for group,files in source_files %} + {% for group,files in source_files %} {{group}} diff --git a/workspace_tools/export/uvision4_nucleo_f401re.uvproj.tmpl b/workspace_tools/export/uvision4_nucleo_f401re.uvproj.tmpl index 5d3a335cff..f65b87e527 100644 --- a/workspace_tools/export/uvision4_nucleo_f401re.uvproj.tmpl +++ b/workspace_tools/export/uvision4_nucleo_f401re.uvproj.tmpl @@ -354,7 +354,7 @@ 0 0 - --gnu + {% for flag in flags %}{{flag}} {% endfor %} {% for s in symbols %} {{s}}, {% endfor %} {% for path in include_paths %} {{path}}; {% endfor %} @@ -399,7 +399,7 @@ - {% for group,files in source_files %} + {% for group,files in source_files %} {{group}} diff --git a/workspace_tools/export/uvision4_nucleo_l053r8.uvopt.tmpl b/workspace_tools/export/uvision4_nucleo_l053r8.uvopt.tmpl new file mode 100644 index 0000000000..6f58e6da83 --- /dev/null +++ b/workspace_tools/export/uvision4_nucleo_l053r8.uvopt.tmpl @@ -0,0 +1,208 @@ + + + + 1.0 + +
### uVision Project, (C) Keil Software
+ + + *.c + *.s*; *.src; *.a* + *.obj + *.lib + *.txt; *.h; *.inc + *.plm + *.cpp + + + + 0 + 0 + + + + mbed NUCLEO_L053R8 + 0x4 + ARM-ADS + + 8000000 + + 1 + 1 + 0 + 1 + + + 1 + 65535 + 0 + 0 + 0 + + + 79 + 66 + 8 + .\build\ + + + 1 + 1 + 1 + 0 + 1 + 1 + 0 + 1 + 0 + 0 + 0 + 0 + + + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 0 + 0 + + + 1 + 0 + 1 + + 0 + + SARMCM3.DLL + -MPU + DARMCM1.DLL + -pCM0+ + SARMCM3.DLL + -MPU + TARMCM1.DLL + -pCM0+ + + + 0 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 0 + 0 + 0 + 13 + + + + + + + + + + + STLink\ST-LINKIII-KEIL_SWO.dll + + + + 0 + DLGTARM + (1010=-1,-1,-1,-1,0)(1007=-1,-1,-1,-1,0)(1008=-1,-1,-1,-1,0)(1012=-1,-1,-1,-1,0)(1009=-1,-1,-1,-1,0) + + + 0 + ARMDBGFLAGS + + + + 0 + DLGUARM + (105=-1,-1,-1,-1,0) + + + 0 + ULP2CM3 + -O207 -S8 -C0 -FO7 -F2000 -FN1 -FD20000000 -FF0STM32L0xx_64 -FL020000 -FS08000000 + + + 0 + ST-LINKIII-KEIL_SWO + -U-O207 -O207 -S8 -C0 -N00("ARM CoreSight SW-DP") -D00(0BC11477) -L00(0) -TO18 -TC10000000 -TP21 -TDS8007 -TDT0 -TDC1F -TIEFFFFFFFF -TIP8 -FO15 -FD20000000 -FC800 -FN1 -FF0STM32L0x_64 -FS08000000 -FL010000 + + + + + 0 + + + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + + + + + + + + src + 1 + 0 + 0 + 0 + + 1 + 1 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + main.cpp + main.cpp + 0 + 0 + + + +
diff --git a/workspace_tools/export/uvision4_nucleo_l053r8.uvproj.tmpl b/workspace_tools/export/uvision4_nucleo_l053r8.uvproj.tmpl new file mode 100644 index 0000000000..b19b0feea8 --- /dev/null +++ b/workspace_tools/export/uvision4_nucleo_l053r8.uvproj.tmpl @@ -0,0 +1,438 @@ + + + + 1.1 + +
### uVision Project, (C) Keil Software
+ + + + mbed NUCLEO_L053R8 + 0x4 + ARM-ADS + + + STM32L053R8 + STMicroelectronics + IRAM(0x20000000-0x20001FFF) IROM(0x8000000-0x800FFFF) CLOCK(8000000) CPUTYPE("Cortex-M0+") + + + ULP2CM3(-O207 -S8 -C0 -FO7 -FD20000000 -F2000 -FN1 -FF0STM32L0xx_64 -FS08000000 -FL020000) + 0 + + + + + + + + + + + + 0 + 0 + + + + + + + 0 + 0 + 0 + 0 + 1 + + .\build\ + {{name}} + 1 + 0 + 0 + 1 + 1 + .\build\ + 1 + 0 + 0 + + 0 + 0 + + + 0 + 0 + 0 + 0 + + + 0 + 0 + + + 0 + 0 + + + 1 + 0 + fromelf --bin -o build\{{name}}_NUCLEO_L053R8.bin build\{{name}}.axf + + 0 + 0 + + 0 + + + + 0 + 0 + 0 + 0 + 0 + 1 + 0 + 0 + 0 + 0 + 3 + + + 1 + + + SARMCM3.DLL + -MPU + DARMCM1.DLL + -pCM0+ + SARMCM3.DLL + -MPU + TARMCM1.DLL + -pCM0+ + + + + 1 + 0 + 0 + 0 + 16 + + + 0 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 0 + + + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 0 + + 0 + 13 + + + + + + + + + + + + + + STLink\ST-LINKIII-KEIL_SWO.dll + + + + + 1 + 0 + 0 + 1 + 1 + 4100 + + 1 + BIN\ULP2CM3.DLL + + + + + + 0 + + + + 0 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 0 + 1 + 1 + 0 + 1 + 1 + 0 + 0 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 0 + 0 + "Cortex-M0+" + + 0 + 0 + 0 + 1 + 1 + 0 + 0 + 0 + 0 + 0 + 8 + 1 + 0 + 0 + 3 + 3 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 1 + 0 + 0 + 0 + 0 + 1 + 0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x20000000 + 0x2000 + + + 1 + 0x8000000 + 0x10000 + + + 0 + 0x0 + 0x0 + + + 1 + 0x0 + 0x0 + + + 1 + 0x0 + 0x0 + + + 1 + 0x0 + 0x0 + + + 1 + 0x8000000 + 0x10000 + + + 1 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x0 + 0x0 + + + 0 + 0x20000000 + 0x2000 + + + 0 + 0x0 + 0x0 + + + + + + 1 + 1 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + 2 + 0 + 0 + + {% for flag in flags %}{{flag}} {% endfor %} + {% for s in symbols %} {{s}}, {% endfor %} + + {% for path in include_paths %} {{path}}; {% endfor %} + + + + 1 + 0 + 0 + 0 + 0 + 0 + 0 + 0 + + + + + + + + + 0 + 0 + 0 + 0 + 1 + 0 + 0x08000000 + 0x20000000 + {{scatter_file}} + + + + {% for file in object_files %} + {{file}} + {% endfor %} + + + + + + + + {% for group,files in source_files %} + + {{group}} + + {% for file in files %} + + {{file.name}} + {{file.type}} + {{file.path}} + + + 2 + 0 + 0 + 0 + 0 + 1 + 0 + 0 + 0 + 0 + 3 + + + + + + + {% endfor %} + + + {% endfor %} + + + + +
diff --git a/workspace_tools/export/uvision4_nucleo_l152re.uvproj.tmpl b/workspace_tools/export/uvision4_nucleo_l152re.uvproj.tmpl index a2f7863467..48756bacc3 100644 --- a/workspace_tools/export/uvision4_nucleo_l152re.uvproj.tmpl +++ b/workspace_tools/export/uvision4_nucleo_l152re.uvproj.tmpl @@ -354,7 +354,7 @@ 0 0 - --gnu + {% for flag in flags %}{{flag}} {% endfor %} {% for s in symbols %} {{s}}, {% endfor %} {% for path in include_paths %} {{path}}; {% endfor %} @@ -399,7 +399,7 @@ - {% for group,files in source_files %} + {% for group,files in source_files %} {{group}} diff --git a/workspace_tools/export/uvision4_ublox_c027.uvproj.tmpl b/workspace_tools/export/uvision4_ublox_c027.uvproj.tmpl index 8f16a02ba1..6fdbbe2419 100644 --- a/workspace_tools/export/uvision4_ublox_c027.uvproj.tmpl +++ b/workspace_tools/export/uvision4_ublox_c027.uvproj.tmpl @@ -345,7 +345,7 @@ 0 0 - --gnu + {% for flag in flags %}{{flag}} {% endfor %} {% for s in symbols %} {{s}}, {% endfor %} {% for path in include_paths %} {{path}}; {% endfor %} diff --git a/workspace_tools/export_test.py b/workspace_tools/export_test.py index 3985fce34f..9271c3c27e 100644 --- a/workspace_tools/export_test.py +++ b/workspace_tools/export_test.py @@ -35,9 +35,9 @@ def setup_test_user_prj(): if exists(USER_PRJ): print 'Test user project already generated...' return - + setup_user_prj(USER_PRJ, join(TEST_DIR, "rtos", "mbed", "basic"), [join(LIB_DIR, "rtos")]) - + # FAKE BUILD URL open(join(USER_SRC, "mbed.bld"), 'w').write("http://mbed.org/users/mbed_official/code/mbed/builds/976df7c37ad5\n") @@ -54,9 +54,9 @@ def test_export(toolchain, target, expected_error=None): base_dir = join(EXPORT_TMP, toolchain, target) temp_dir = join(base_dir, "temp") mkdir(temp_dir) - + zip_path, report = export(USER_PRJ, USR_PRJ_NAME, toolchain, target, base_dir, temp_dir, False, fake_build_url_resolver) - + if report['success']: move(zip_path, join(EXPORT_DIR, "export_%s_%s.zip" % (toolchain, target))) print "[OK]" @@ -74,18 +74,25 @@ def test_export(toolchain, target, expected_error=None): if __name__ == '__main__': setup_test_user_prj() - + for toolchain, target in [ ('uvision', 'LPC1768'), ('uvision', 'LPC11U24'), ('uvision', 'KL25Z'), ('uvision', 'LPC1347'), ('uvision', 'LPC1114'), ('uvision', 'LPC4088'), - ('uvision', 'NUCLEO_F103RB'), ('uvision', 'NUCLEO_L152RE'), ('uvision', 'NUCLEO_F401RE'), ('uvision', 'NUCLEO_F030R8'), ('uvision', 'NUCLEO_F302R8'), - + + ('uvision', 'NUCLEO_F030R8'), + ('uvision', 'NUCLEO_F072RB'), + ('uvision', 'NUCLEO_F103RB'), + ('uvision', 'NUCLEO_F302R8'), + ('uvision', 'NUCLEO_F401RE'), + ('uvision', 'NUCLEO_L053R8'), + ('uvision', 'NUCLEO_L152RE'), + ('lpcxpresso', 'LPC1768'), ('lpcxpresso', 'LPC4088'),('lpcxpresso', 'LPC1114'), ('lpcxpresso', 'LPC11U35_401'), ('lpcxpresso', 'LPC11U35_501'), # Linux path: /home/emimon01/bin/gcc-cs/bin/ # Windows path: "C:/Program Files (x86)/CodeSourcery/Sourcery_CodeBench_Lite_for_ARM_EABI/bin/" ('codesourcery', 'LPC1768'), - + # Linux path: /home/emimon01/bin/gcc-arm/bin/ # Windows path: C:/arm-none-eabi-gcc-4_7/bin/ ('gcc_arm', 'LPC1768'), @@ -99,16 +106,16 @@ if __name__ == '__main__': ('gcc_arm', 'DISCO_F407VG'), ('gcc_arm', 'DISCO_F303VC'), - + ('ds5_5', 'LPC1768'), ('ds5_5', 'LPC11U24'), - + ('iar', 'LPC1768'), - + (None, None) ]: print '\n=== Exporting to "%s::%s" ===' % (toolchain, target) test_export(toolchain, target) - + print "\n=== Test error messages ===" test_export('lpcxpresso', 'LPC11U24', expected_error='lpcxpresso') diff --git a/workspace_tools/host_tests/echo.py b/workspace_tools/host_tests/echo.py index dd09701ac8..f5f8300ba6 100644 --- a/workspace_tools/host_tests/echo.py +++ b/workspace_tools/host_tests/echo.py @@ -22,7 +22,7 @@ class EchoTest(Test): Test.__init__(self) self.mbed.init_serial(115200) self.mbed.reset() - + def test(self): self.mbed.flush() self.notify("Starting the ECHO test") @@ -32,14 +32,14 @@ class EchoTest(Test): self.mbed.serial.write(TEST + "\n") l = self.mbed.serial.readline().strip() if not l: continue - + if l != TEST: check = False self.notify('"%s" != "%s"' % (l, TEST)) else: if (i % 10) == 0: self.notify('.') - + return check diff --git a/workspace_tools/host_tests/echo_flow_control.py b/workspace_tools/host_tests/echo_flow_control.py index b354d0b04c..7ea11e9736 100644 --- a/workspace_tools/host_tests/echo_flow_control.py +++ b/workspace_tools/host_tests/echo_flow_control.py @@ -23,7 +23,7 @@ class EchoTest(Test): self.mbed.init_serial() self.mbed.extra_serial.rtscts = True self.mbed.reset() - + def test(self): self.mbed.flush() self.notify("Starting the ECHO test") @@ -33,14 +33,14 @@ class EchoTest(Test): self.mbed.extra_serial.write(TEST + "\n") l = self.mbed.extra_serial.readline().strip() if not l: continue - + if l != TEST: check = False self.notify('"%s" != "%s"' % (l, TEST)) else: if (i % 10) == 0: self.notify('.') - + return check diff --git a/workspace_tools/host_tests/example/UDPEchoServer.py b/workspace_tools/host_tests/example/UDPEchoServer.py index 8dd511d570..38503489ee 100644 --- a/workspace_tools/host_tests/example/UDPEchoServer.py +++ b/workspace_tools/host_tests/example/UDPEchoServer.py @@ -15,7 +15,7 @@ See the License for the specific language governing permissions and limitations under the License. """ import socket - + ECHO_PORT = 7 sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) diff --git a/workspace_tools/host_tests/mbedrpc.py b/workspace_tools/host_tests/mbedrpc.py index 5789270921..3fbc2e6f0d 100644 --- a/workspace_tools/host_tests/mbedrpc.py +++ b/workspace_tools/host_tests/mbedrpc.py @@ -66,7 +66,7 @@ p30 = pin("p30") class mbed: def __init__(self): print("This will work as a demo but no transport mechanism has been selected") - + def rpc(self, name, method, args): print("Superclass method not overridden") @@ -84,18 +84,18 @@ class SerialRPC(mbed): print "Reset mbed" self.ser.sendBreak() time.sleep(2) - + def rpc(self, name, method, args): request = "/" + name + "/" + method + " " + " ".join(args) if self.debug: print "[RPC::TX] %s" % request self.ser.write(request + "\n") - + while True: response = self.ser.readline().strip() if self.debug: print "[RPC::RX] %s" % response - + # Ignore comments if not response.startswith('#'): break return response @@ -104,7 +104,7 @@ class SerialRPC(mbed): class HTTPRPC(mbed): def __init__(self, ip): self.host = "http://" + ip - + def rpc(self, name, method, args): response = urllib2.urlopen(self.host + "/rpc/" + name + "/" + method + "," + ",".join(args)) return response.read().strip() @@ -119,13 +119,13 @@ class DigitalOut(): self.name = mpin elif isinstance(mpin, pin): self.name = self.mbed.rpc("DigitalOut", "new", [mpin.name]) - + def __del__(self): r = self.mbed.rpc(self.name, "delete", []) - + def write(self, value): r = self.mbed.rpc(self.name, "write", [str(value)]) - + def read(self): r = self.mbed.rpc(self.name, "read", []) return int(r) @@ -138,14 +138,14 @@ class AnalogIn(): self.name = mpin elif isinstance(mpin, pin): self.name = self.mbed.rpc("AnalogIn", "new", [mpin.name]) - + def __del__(self): r = self.mbed.rpc(self.name, "delete", []) - + def read(self): r = self.mbed.rpc(self.name, "read", []) return float(r) - + def read_u16(self): r = self.mbed.rpc(self.name, "read_u16", []) return int(r) @@ -158,16 +158,16 @@ class AnalogOut(): self.name = mpin elif isinstance(mpin, pin): self.name = self.mbed.rpc("AnalogOut", "new", [mpin.name]) - + def __del__(self): r = self.mbed.rpc(self.name, "delete", []) - + def write(self, value): r = self.mbed.rpc(self.name, "write", [str(value)]) - + def write_u16(self, value): r = self.mbed.rpc(self.name, "write_u16", [str(value)]) - + def read(self): r = self.mbed.rpc(self.name, "read", []) return float(r) @@ -180,10 +180,10 @@ class DigitalIn(): self.name = mpin elif isinstance(mpin, pin): self.name = self.mbed.rpc("DigitalIn", "new", [mpin.name]) - + def __del__(self): r = self.mbed.rpc(self.name, "delete", []) - + def read(self): r = self.mbed.rpc(self.name, "read", []) return int(r) @@ -196,29 +196,29 @@ class PwmOut(): self.name = mpin elif isinstance(mpin, pin): self.name = self.mbed.rpc("PwmOut", "new", [mpin.name]) - + def __del__(self): r = self.mbed.rpc(self.name, "delete", []) - + def write(self, value): r = self.mbed.rpc(self.name, "write", [str(value)]) - + def read(self): r = self.mbed.rpc(self.name, "read", []) return float(r) - + def period(self, value): r = self.mbed.rpc(self.name, "period", [str(value)]) - + def period_ms(self, value): r = self.mbed.rpc(self.name, "period_ms", [str(value)]) - + def period_us(self, value): r = self.mbed.rpc(self.name, "period_us", [str(value)]) - + def puslewidth(self, value): r = self.mbed.rpc(self.name, "pulsewidth", [str(value)]) - + def puslewidth_ms(self, value): r = self.mbed.rpc(self.name, "pulsewidth_ms", [str(value)]) @@ -233,16 +233,16 @@ class Serial(): self.name = mpin elif isinstance(mpin, pin): self.name = self.mbed.rpc("Serial", "new", [tx.name, rx.name]) - + def __del__(self): r = self.mbed.rpc(self.name, "delete", []) - + def putc(self, value): r = self.mbed.rpc(self.name, "putc", [str(value)]) - + def puts(self, value): r = self.mbed.rpc(self.name, "puts", [ "\"" + str(value) + "\""]) - + def getc(self): r = self.mbed.rpc(self.name, "getc", []) return int(r) @@ -253,14 +253,14 @@ class RPCFunction(): self.mbed = this_mbed if isinstance(name, str): self.name = name - + def __del__(self): r = self.mbed.rpc(self.name, "delete", []) - + def read(self): r = self.mbed.rpc(self.name, "read", []) return int(r) - + def run(self, input): r = self.mbed.rpc(self.name, "run", [input]) return r @@ -271,13 +271,13 @@ class RPCVariable(): self.mbed = this_mbed if isinstance(name, str): self.name = name - + def __del__(self): r = self.mbed.rpc(self.name, "delete", []) - + def write(self, value): self.mbed.rpc(self.name, "write", [str(value)]) - + def read(self): r = self.mbed.rpc(self.name, "read", []) return r diff --git a/workspace_tools/host_tests/rpc.py b/workspace_tools/host_tests/rpc.py index 3e5c147638..84b85d2cc6 100644 --- a/workspace_tools/host_tests/rpc.py +++ b/workspace_tools/host_tests/rpc.py @@ -22,26 +22,26 @@ class RpcTest(Test): def test(self): self.notify("RPC Test") s = SerialRPC(self.mbed.port, debug=True) - + self.notify("Init remote objects") - + p_out = pin("p10") p_in = pin("p11") - + if hasattr(self.mbed.options, 'micro'): if self.mbed.options.micro == 'M0+': print "Freedom Board: PTA12 <-> PTC4" p_out = pin("PTA12") p_in = pin("PTC4") - + self.output = DigitalOut(s, p_out); self.input = DigitalIn(s, p_in); - + self.check = True self.write_read_test(1) self.write_read_test(0) return self.check - + def write_read_test(self, v): self.notify("Check %d" % v) self.output.write(v) diff --git a/workspace_tools/host_tests/tcpecho_client.py b/workspace_tools/host_tests/tcpecho_client.py index cff88e9606..303f002ab8 100644 --- a/workspace_tools/host_tests/tcpecho_client.py +++ b/workspace_tools/host_tests/tcpecho_client.py @@ -30,17 +30,17 @@ UPDATE_STEP = (N_PACKETS/10) class TCP_EchoClient: def __init__(self, host): - self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.s.connect((host, ECHO_PORT)) self.packet = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(LEN_PACKET)) - + def __packet(self): # Comment out the checks when measuring the throughput # self.packet = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(LEN_PACKET)) self.s.send(self.packet) data = self.s.recv(LEN_PACKET) # assert self.packet == data, "packet error:\n%s\n%s\n" % (self.packet, data) - + def test(self): start = time() for i in range(N_PACKETS): @@ -48,9 +48,9 @@ class TCP_EchoClient: self.__packet() t = time() - start print 'Throughput: (%.2f)Mbits/s' % ((TOT_BITS / t)/MEGA) - + def __del__(self): - self.s.close() + self.s.close() while True: e = TCP_EchoClient(SERVER_ADDRESS) diff --git a/workspace_tools/host_tests/tcpecho_server.py b/workspace_tools/host_tests/tcpecho_server.py index c85aab96ef..4a68bd9ee7 100644 --- a/workspace_tools/host_tests/tcpecho_server.py +++ b/workspace_tools/host_tests/tcpecho_server.py @@ -31,7 +31,7 @@ class TCP_EchoHandler(BaseRequestHandler): while True: data = self.request.recv(1024) if not data: break - + bytes += len(data) for n in map(ord, data): if n != index: @@ -39,7 +39,7 @@ class TCP_EchoHandler(BaseRequestHandler): index += 1 if index > MAX_INDEX: index = 0 - + self.request.sendall(data) t = time() - start b = float(bytes * 8) * 2 diff --git a/workspace_tools/host_tests/udp_link_layer_auto.py b/workspace_tools/host_tests/udp_link_layer_auto.py new file mode 100644 index 0000000000..23dbebd870 --- /dev/null +++ b/workspace_tools/host_tests/udp_link_layer_auto.py @@ -0,0 +1,158 @@ +""" +mbed SDK +Copyright (c) 2011-2013 ARM Limited + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +""" + +""" +How to use: +make.py -m LPC1768 -t ARM -d E:\ -n NET_14 +udp_link_layer_auto.py -p COM20 -d E:\ -t 10 +""" + +import thread +from SocketServer import BaseRequestHandler, UDPServer +# from socket import socket, AF_INET, SOCK_DGRAM +import socket +import re +from host_test import Test, DefaultTest +from time import time, sleep +from sys import stdout + + +# Received datagrams (with time) +dict_udp_recv_datagrams = dict() + +# Sent datagrams (with time) +dict_udp_sent_datagrams = dict() + + +class UDPEchoClient_Handler(BaseRequestHandler): + def handle(self): + """ One handle per connection """ + data, socket = self.request + # Process received datagram + data_str = repr(data)[1:-1] + dict_udp_recv_datagrams[data_str] = time() + # print "[UDP_COUNTER] [" + data_str + "]" + # print ".", + + + +def udp_packet_recv(threadName, server_ip, server_port): + """ This function will receive packet stream from mbed device """ + server = UDPServer((server_ip, server_port), UDPEchoClient_Handler) + print "[UDP_COUNTER] Listening for connections... %s:%d"%(server_ip, server_port) + server.serve_forever() + + +class UDPEchoServerTest(DefaultTest): + ECHO_SERVER_ADDRESS = "" # UDP IP of datagram bursts + ECHO_PORT = 0 # UDP port for datagram bursts + CONTROL_PORT = 23 # TCP port used to get stats from mbed device, e.g. counters + s = None # Socket + + TEST_PACKET_COUNT = 1000 # how many packets should be send + TEST_STRESS_FACTOR = 0.001 # stress factor: 10 ms + + pattern_server_ip = "^Server IP Address is (\d+).(\d+).(\d+).(\d+):(\d+)" + re_detect_server_ip = re.compile(pattern_server_ip) + + def print_result(self, result): + print "\n{%s}\n{end}" % result + + def get_control_data(self, command="stat\n"): + BUFFER_SIZE = 256 + s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + s.connect((self.ECHO_SERVER_ADDRESS, self.CONTROL_PORT)) + s.send(command) + data = s.recv(BUFFER_SIZE) + s.close() + return data + + def run(self): + ip_msg_timeout = self.mbed.options.timeout + serial_ip_msg = "" + start_serial_pool = time(); + while (time() - start_serial_pool) < ip_msg_timeout: + c = self.mbed.serial.read(512) + stdout.write(c) + stdout.flush() + serial_ip_msg += c + # Searching for IP address and port prompted by server + m = self.re_detect_server_ip.search(serial_ip_msg) + if m and len(m.groups()): + self.ECHO_SERVER_ADDRESS = ".".join(m.groups()[:4]) + self.ECHO_PORT = int(m.groups()[4]) # must be integer for socket.connect method + duration = time() - start_serial_pool + print "UDP Server found at: " + self.ECHO_SERVER_ADDRESS + ":" + str(self.ECHO_PORT) + " after " + "%.2f" % duration + " sec" + stdout.flush() + break + else: + print "Error: No IP and port information sent from server" + self.print_result('error') + exit(-2) + + # Open client socket to burst datagrams to UDP server in mbed + try: + self.s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + except Exception, e: + print "Error: %s" % e + self.print_result('error') + exit(-1) + + # UDP replied receiver works in background to get echoed datagrams + SERVER_IP = str(socket.gethostbyname(socket.getfqdn())) + SERVER_PORT = self.ECHO_PORT + 1 + thread.start_new_thread( udp_packet_recv, ("Thread-udp-recv", SERVER_IP, SERVER_PORT) ) + sleep(0.5) + + # Burst part + TEST_STRING = 'Hello, world !!!' + for no in range(self.TEST_PACKET_COUNT): + payload = str(no) + "__" + TEST_STRING + self.s.sendto(payload, (self.ECHO_SERVER_ADDRESS, self.ECHO_PORT)) + dict_udp_sent_datagrams[payload] = time() + sleep(self.TEST_STRESS_FACTOR) + self.s.close() + + # Wait 5 seconds for packets to come + print + print "Test Summary:" + for d in range(5): + sleep(1) + summary_datagram_success = (float(len(dict_udp_recv_datagrams)) / float(self.TEST_PACKET_COUNT)) * 100.0 + # print dict_udp_recv_datagrams + print "Datagrams recved after +%d sec: %.3f%% (%d / %d), stress=%.3f ms" % (d, summary_datagram_success, len(dict_udp_recv_datagrams), self.TEST_PACKET_COUNT, self.TEST_STRESS_FACTOR) + + # Getting control data from test + print + print "Mbed Summary:" + mbed_stats = self.get_control_data() + print mbed_stats + print + + # Receiving serial data from mbed + print + print "Remaining mbed serial port data:" + try: + while True: + c = self.mbed.serial.read(512) + stdout.write(c) + stdout.flush() + except KeyboardInterrupt, _: + print "\n[CTRL+c] exit" + +if __name__ == '__main__': + UDPEchoServerTest().run() diff --git a/workspace_tools/host_tests/udpecho_client.py b/workspace_tools/host_tests/udpecho_client.py index 753496cd5b..1ff833f175 100644 --- a/workspace_tools/host_tests/udpecho_client.py +++ b/workspace_tools/host_tests/udpecho_client.py @@ -30,18 +30,18 @@ UPDATE_STEP = (N_PACKETS/10) class UDP_EchoClient: s = socket(AF_INET, SOCK_DGRAM) - + def __init__(self, host): self.host = host self.packet = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(LEN_PACKET)) - + def __packet(self): # Comment out the checks when measuring the throughput # packet = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(LEN_PACKET)) UDP_EchoClient.s.sendto(packet, (self.host, ECHO_PORT)) data = UDP_EchoClient.s.recv(LEN_PACKET) # assert packet == data, "packet error:\n%s\n%s\n" % (packet, data) - + def test(self): start = time() for i in range(N_PACKETS): diff --git a/workspace_tools/libraries.py b/workspace_tools/libraries.py index 95040f7573..3af8e42243 100644 --- a/workspace_tools/libraries.py +++ b/workspace_tools/libraries.py @@ -32,7 +32,7 @@ LIBRARIES = [ "build_dir": RTOS_LIBRARIES, "dependencies": [MBED_LIBRARIES, MBED_RTX], }, - + # USB Device libraries { "id": "usb", @@ -40,7 +40,7 @@ LIBRARIES = [ "build_dir": USB_LIBRARIES, "dependencies": [MBED_LIBRARIES], }, - + # USB Host libraries { "id": "usb_host", @@ -48,7 +48,7 @@ LIBRARIES = [ "build_dir": USB_HOST_LIBRARIES, "dependencies": [MBED_LIBRARIES, FAT_FS, MBED_RTX, RTOS_ABSTRACTION], }, - + # DSP libraries { "id": "cmsis_dsp", @@ -62,7 +62,7 @@ LIBRARIES = [ "build_dir": DSP_LIBRARIES, "dependencies": [MBED_LIBRARIES, DSP_CMSIS], }, - + # Network libraries { "id": "eth", @@ -70,7 +70,7 @@ LIBRARIES = [ "build_dir": ETH_LIBRARY, "dependencies": [MBED_LIBRARIES, RTOS_LIBRARIES] }, - + { "id": "ublox", "source_dir": [UBLOX_SOURCES, CELLULAR_SOURCES, CELLULAR_USB_SOURCES, LWIP_SOURCES], @@ -92,7 +92,7 @@ class Library: def __init__(self, lib_id): self.__dict__.update(Library.DEFAULTS) self.__dict__.update(LIBRARY_MAP[lib_id]) - + def is_supported(self, target, toolchain): if not hasattr(self, 'supported'): return True diff --git a/workspace_tools/options.py b/workspace_tools/options.py index 8ba8aff9d6..bbd26f4dd3 100644 --- a/workspace_tools/options.py +++ b/workspace_tools/options.py @@ -22,19 +22,19 @@ from workspace_tools.targets import TARGET_NAMES def get_default_options_parser(): parser = OptionParser() - + parser.add_option("-m", "--mcu", help="build for the given MCU (%s)" % ', '.join(TARGET_NAMES), metavar="MCU") - + parser.add_option("-t", "--tool", help="build using the given TOOLCHAIN (%s)" % ', '.join(TOOLCHAINS), metavar="TOOLCHAIN") - + parser.add_option("-c", "--clean", action="store_true", default=False, help="clean the build directory") - + parser.add_option("-o", "--options", action="append", help='Add a build option ("save-asm": save the asm generated by the compiler, "debug-info": generate debugging information, "analyze": run static code analyzer")') - + return parser diff --git a/workspace_tools/patch.py b/workspace_tools/patch.py index e87b4ef05c..6fda63f3c3 100644 --- a/workspace_tools/patch.py +++ b/workspace_tools/patch.py @@ -31,7 +31,7 @@ def patch(bin_path): with open(bin_path, 'r+b') as bin: # Read entries 0 through 6 (Little Endian 32bits words) vector = [unpack(' (len(TESTS)-1)): message = "[ERROR] You have to specify one of the following tests:\n" message += '\n'.join(map(str, sorted(TEST_MAP.values()))) args_error(parser, message) test = Test(options.program) - + if not options.build: # Substitute the library builds with the sources # TODO: Substitute also the other library build paths if MBED_LIBRARIES in test.dependencies: test.dependencies.remove(MBED_LIBRARIES) test.dependencies.append(MBED_BASE) - + # Build the projectwith the same directory structure of the mbed online IDE project_dir = join(EXPORT_WORKSPACE, test.id) setup_user_prj(project_dir, test.source_dir, test.dependencies) - - # Export to selected toolchain + + # Export to selected toolchain tmp_path, report = export(project_dir, test.id, ide, mcu, EXPORT_WORKSPACE, EXPORT_TMP) if report['success']: zip_path = join(EXPORT_DIR, "%s_%s_%s.zip" % (test.id, ide, mcu)) diff --git a/workspace_tools/singletest.py b/workspace_tools/singletest.py index 8f003679ba..00a81ede64 100644 --- a/workspace_tools/singletest.py +++ b/workspace_tools/singletest.py @@ -1,3 +1,5 @@ +#!/usr/bin/env python + """ mbed SDK Copyright (c) 2011-2013 ARM Limited @@ -76,7 +78,7 @@ import re from prettytable import PrettyTable from serial import Serial -from os.path import join, abspath, dirname, exists +from os.path import join, abspath, dirname, exists, basename from shutil import copy from subprocess import call from time import sleep, time @@ -87,20 +89,23 @@ from Queue import Queue, Empty ROOT = abspath(join(dirname(__file__), "..")) sys.path.insert(0, ROOT) + # Imports related to mbed build pi -from workspace_tools.build_api import build_project, build_mbed_libs +from workspace_tools.build_api import build_project, build_mbed_libs, build_lib +from workspace_tools.build_api import mcu_toolchain_matrix from workspace_tools.paths import BUILD_DIR from workspace_tools.paths import HOST_TESTS from workspace_tools.targets import TARGET_MAP from workspace_tools.tests import TEST_MAP from workspace_tools.tests import TESTS +from workspace_tools.libraries import LIBRARIES # Be sure that the tools directory is in the search path ROOT = abspath(join(dirname(__file__), "..")) sys.path.insert(0, ROOT) # Imports related to mbed build pi -from workspace_tools.utils import delete_dir_files +from workspace_tools.utils import delete_dir_files, copy_file from workspace_tools.settings import MUTs @@ -227,11 +232,17 @@ class SingleTestRunner(object): return (test_result, target_name, toolchain_name, test_id, test_description, round(elapsed_time, 2), duration) - if not target_by_mcu.is_disk_virtual: - delete_dir_files(disk) + #if not target_by_mcu.is_disk_virtual: + # delete_dir_files(disk) # Program MUT with proper image file - copy(image_path, disk) + if not disk.endswith('/') and not disk.endswith('\\'): + disk += '/' + + cmd = ["cp", image_path.encode('ascii','ignore'), disk.encode('ascii','ignore') + basename(image_path).encode('ascii','ignore')] + # print cmd + call(cmd) + # copy(image_path, disk) # Copy Extra Files if not target_by_mcu.is_disk_virtual and test.extra_files: @@ -427,12 +438,12 @@ def get_result_summary_table(): pt.align['percent [%]'] = "r" percent_progress = round(100.0 * counter_automated / float(counter_all), 1) - str_progress = progress_bar(percent_progress, 75) + str_progress = progress_bar(percent_progress, 75) pt.add_row([counter_automated, counter_all, percent_progress, str_progress]) print "Automation coverage:" print pt print - + # Test automation coverage table print test_id_cols = ['id', 'automated', 'all', 'percent [%]', 'progress'] pt = PrettyTable(test_id_cols) @@ -509,6 +520,16 @@ if __name__ == '__main__': action="store_true", help='Test only peripheral declared for MUT and skip common tests') + parser.add_option('-n', '--test-by-names', + dest='test_by_names', + help='Runs only test enumerated it this switch') + + parser.add_option("-S", "--supported-toolchains", + action="store_true", + dest="supported_toolchains", + default=False, + help="Displays supported matrix of MCUs and toolchains") + parser.add_option('-v', '--verbose', dest='verbose', default=False, @@ -525,6 +546,11 @@ if __name__ == '__main__': get_result_summary_table() exit(0) + # Only prints matrix of supported toolchains + if opts.supported_toolchains: + mcu_toolchain_matrix() + exit(0) + # Open file with test specification # test_spec_filename tells script which targets and their toolchain(s) # should be covered by the test scenario @@ -561,6 +587,9 @@ if __name__ == '__main__': build_dir = join(BUILD_DIR, "test", target, toolchain) for test_id, test in TEST_MAP.iteritems(): + if opts.test_by_names and test_id not in opts.test_by_names.split(','): + continue + if test_ids and test_id not in test_ids: continue @@ -582,6 +611,18 @@ if __name__ == '__main__': } build_project_options = ["analyze"] if opts.goanna_for_tests else None + + # Detect which lib should be added to test + # Some libs have to compiled like RTOS or ETH + libraries = [] + for lib in LIBRARIES: + if lib['build_dir'] in test.dependencies: + libraries.append(lib['id']) + # Build libs for test + for lib_id in libraries: + build_lib(lib_id, T, toolchain, options=build_project_options, + verbose=opts.verbose, clean=clean) + path = build_project(test.source_dir, join(build_dir, test_id), T, toolchain, test.dependencies, options=build_project_options, clean=clean, verbose=opts.verbose) diff --git a/workspace_tools/size.py b/workspace_tools/size.py index 8ba897d43f..233cb96153 100644 --- a/workspace_tools/size.py +++ b/workspace_tools/size.py @@ -61,13 +61,13 @@ def benchmarks(): # CSV Data csv_data = csv.writer(open(BENCHMARK_DATA_PATH, 'wb')) csv_data.writerow(['Toolchain', "Target", "Benchmark", "code", "data", "bss", "flash"]) - + # Build for toolchain in ['ARM', 'uARM', 'GCC_CR', 'GCC_CS', 'GCC_ARM']: for mcu in ["LPC1768", "LPC11U24"]: # Build Libraries build_mbed_libs(mcu, toolchain) - + # Build benchmarks build_dir = join(BUILD_DIR, "benchmarks", mcu, toolchain) for test_id, title in BENCHMARKS: @@ -90,23 +90,23 @@ def compare(t1, t2, target): benchmarks() else: print "Loading: %s" % BENCHMARK_DATA_PATH - + data = csv.reader(open(BENCHMARK_DATA_PATH, 'rb')) - + benchmarks_data = defaultdict(dict) for (toolchain, mcu, name, code, data, bss, flash) in data: if target == mcu: for t in [t1, t2]: if toolchain == t: benchmarks_data[name][t] = map(int, (code, data, bss, flash)) - + print "%s vs %s for %s" % (t1, t2, target) for name, data in benchmarks_data.iteritems(): try: # Check Size code_a, data_a, bss_a, flash_a = data[t1] code_u, data_u, bss_u, flash_u = data[t2] - + print "\n=== %s ===" % name print_diff("code", code_a , code_u) print_diff("data", data_a , data_u) diff --git a/workspace_tools/synch.py b/workspace_tools/synch.py index 03cfb6776b..cfc17212d9 100644 --- a/workspace_tools/synch.py +++ b/workspace_tools/synch.py @@ -46,19 +46,19 @@ commit_msg = '' # Code that does have a mirror in the mbed SDK # Tuple data: (repo_name, list_of_code_dirs, [team]) # team is optional - if not specified, the code is published under mbed_official -OFFICIAL_CODE = ( +OFFICIAL_CODE = ( ("mbed-src" , "mbed"), ("mbed-rtos", "rtos"), ("mbed-dsp" , "dsp"), ("mbed-rpc" , "rpc"), - + ("lwip" , "net/lwip/lwip"), ("lwip-sys", "net/lwip/lwip-sys"), ("Socket" , "net/lwip/Socket"), - + ("lwip-eth" , "net/eth/lwip-eth"), ("EthernetInterface", "net/eth/EthernetInterface"), - + ("USBDevice", "USBDevice"), ("USBHost" , "USBHost"), @@ -67,9 +67,6 @@ OFFICIAL_CODE = ( ("UbloxUSBModem", "net/cellular/UbloxUSBModem"), ("UbloxModemHTTPClientTest", ["tests/net/cellular/http/common", "tests/net/cellular/http/ubloxusb"]), ("UbloxModemSMSTest", ["tests/net/cellular/sms/common", "tests/net/cellular/sms/ubloxusb"]), - - ("BLE_API", "ble/ble-api", "Bluetooth-Low-Energy"), - ("nRF51822", "ble/nRF51822", "Nordic-Semiconductor"), ) @@ -78,7 +75,7 @@ OFFICIAL_CODE = ( CODE_WITH_DEPENDENCIES = ( # Libraries "EthernetInterface", - + # RTOS Examples "rtos_basic", "rtos_isr", @@ -88,7 +85,7 @@ CODE_WITH_DEPENDENCIES = ( "rtos_semaphore", "rtos_signals", "rtos_timer", - + # Net Examples "TCPEchoClient", "TCPEchoServer", @@ -98,7 +95,7 @@ CODE_WITH_DEPENDENCIES = ( "UDPEchoServer", "BroadcastReceive", "BroadcastSend", - + # mbed sources "mbed-src-program", ) @@ -126,7 +123,7 @@ class MbedRepository: def run_and_print(command, cwd): stdout, _, _ = run_cmd(command, wd=cwd, redirect=True) print(stdout) - + def __init__(self, name, team = None): self.name = name self.path = join(MBED_ORG_PATH, name) @@ -138,14 +135,14 @@ class MbedRepository: # Checkout code if not exists(MBED_ORG_PATH): makedirs(MBED_ORG_PATH) - + self.run_and_print(['hg', 'clone', self.url % name], cwd=MBED_ORG_PATH) - + else: # Update self.run_and_print(['hg', 'pull'], cwd=self.path) self.run_and_print(['hg', 'update'], cwd=self.path) - + def publish(self): # The maintainer has to evaluate the changes first and explicitly accept them self.run_and_print(['hg', 'addremove'], cwd=self.path) @@ -208,7 +205,7 @@ def get_line_endings(f): return 'cr' # Copy file to destination, but preserve destination line endings if possible -# This prevents very annoying issues with huge diffs that appear because of +# This prevents very annoying issues with huge diffs that appear because of # differences in line endings def copy_with_line_endings(sdk_file, repo_file): if not isfile(repo_file): @@ -240,11 +237,11 @@ def visit_files(path, visit): if ignore_path(full, IGNORE_DIRS): print "Skipping '%s'" % full dirs.remove(d) - + for file in files: if ignore_path(file, IGNORE_FILES): continue - + visit(join(root, file)) @@ -253,15 +250,15 @@ def update_repo(repo_name, sdk_paths, team_name): # copy files from mbed SDK to mbed_official repository def visit_mbed_sdk(sdk_file): repo_file = join(repo.path, relpath(sdk_file, sdk_path)) - + repo_dir = dirname(repo_file) if not exists(repo_dir): makedirs(repo_dir) - + copy_with_line_endings(sdk_file, repo_file) for sdk_path in sdk_paths: visit_files(sdk_path, visit_mbed_sdk) - + # remove repository files that do not exist in the mbed SDK def visit_repo(repo_file): for sdk_path in sdk_paths: @@ -272,7 +269,7 @@ def update_repo(repo_name, sdk_paths, team_name): remove(repo_file) print "remove: %s" % repo_file visit_files(repo.path, visit_repo) - + if repo.publish(): changed.append(repo_name) @@ -297,7 +294,7 @@ def update_dependencies(repositories): for repo_name in repositories: print '\n=== Updating "%s" ===' % repo_name repo = MbedRepository(repo_name) - + # point to the latest libraries def visit_repo(repo_file): with open(repo_file, "r") as f: @@ -305,7 +302,7 @@ def update_dependencies(repositories): with open(repo_file, "w") as f: f.write(url[:(url.rindex('/')+1)]) visit_files(repo.path, visit_repo, None, MBED_REPO_EXT) - + if repo.publish(): changed.append(repo_name) @@ -320,13 +317,13 @@ def do_sync(options): quiet = options.quiet commit_msg = options.msg chnaged = [] - + if options.code: update_code(OFFICIAL_CODE) - + if options.dependencies: update_dependencies(CODE_WITH_DEPENDENCIES) - + if options.mbed: update_mbed() @@ -340,19 +337,19 @@ def do_sync(options): if __name__ == '__main__': parser = OptionParser() - + parser.add_option("-c", "--code", action="store_true", default=False, help="Update the mbed_official code") - + parser.add_option("-d", "--dependencies", action="store_true", default=False, help="Update the mbed_official code dependencies") - + parser.add_option("-m", "--mbed", action="store_true", default=False, help="Release a build of the mbed library") - + parser.add_option("-n", "--nopush", action="store_true", default=False, help="Commit the changes locally only, don't push them") @@ -364,12 +361,12 @@ if __name__ == '__main__': parser.add_option("-r", "--repository", action="store", type="string", default='', dest='repo', help="Synchronize only the given repository") - + parser.add_option("-q", "--quiet", action="store_true", default=False, help="Don't ask for confirmation before commiting or pushing") - + (options, args) = parser.parse_args() - + do_sync(options) diff --git a/workspace_tools/targets.py b/workspace_tools/targets.py index db07d197e8..918209de87 100644 --- a/workspace_tools/targets.py +++ b/workspace_tools/targets.py @@ -32,13 +32,13 @@ class Target: def __init__(self): # ARM Core self.core = None - + # Is the disk provided by the interface chip of this board virtual? self.is_disk_virtual = False - + # list of toolchains that are supported by the mbed SDK for this target self.supported_toolchains = None - + # list of extra specific labels self.extra_labels = [] @@ -46,13 +46,13 @@ class Target: self.macros = [] self.name = self.__class__.__name__ - + def program_cycle_s(self): return 4 if self.is_disk_virtual else 1.5 - + def get_labels(self): return [self.name, CORE_LABELS[self.core]] + self.extra_labels - + def init_hooks(self, hook, toolchain_name): pass @@ -60,22 +60,22 @@ class Target: class LPC2368(Target): def __init__(self): Target.__init__(self) - + self.core = "ARM7TDMI-S" - + self.extra_labels = ['NXP', 'LPC23XX'] - + self.supported_toolchains = ["ARM","GCC_ARM","GCC_CR"] class LPC1768(Target): def __init__(self): Target.__init__(self) - + self.core = "Cortex-M3" - + self.extra_labels = ['NXP', 'LPC176X', 'MBED_LPC1768'] - + self.supported_toolchains = ["ARM", "uARM", "GCC_ARM", "GCC_CS", "GCC_CR", "IAR"] @@ -84,22 +84,22 @@ class LPC11U24(Target): def __init__(self): Target.__init__(self) - + self.core = "Cortex-M0" - + self.extra_labels = ['NXP', 'LPC11UXX', 'LPC11U24_401'] - + self.supported_toolchains = ["ARM", "uARM", "GCC_ARM"] class LPC11U24_301(Target): def __init__(self): Target.__init__(self) - + self.core = "Cortex-M0" - + self.extra_labels = ['NXP', 'LPC11UXX'] - + self.supported_toolchains = ["ARM", "uARM", "GCC_ARM"] @@ -108,58 +108,58 @@ class KL05Z(Target): def __init__(self): Target.__init__(self) - + self.core = "Cortex-M0+" - + self.extra_labels = ['Freescale', 'KLXX'] - + self.supported_toolchains = ["ARM", "uARM", "GCC_ARM"] - + self.supported_form_factors = ["ARDUINO"] - + self.is_disk_virtual = True class KL25Z(Target): def __init__(self): Target.__init__(self) - + self.core = "Cortex-M0+" - + self.extra_labels = ['Freescale', 'KLXX'] - + self.supported_toolchains = ["ARM", "GCC_CW_EWL", "GCC_CW_NEWLIB", "GCC_ARM"] - + self.supported_form_factors = ["ARDUINO"] - + self.is_disk_virtual = True class KL46Z(Target): def __init__(self): Target.__init__(self) - + self.core = "Cortex-M0+" - + self.extra_labels = ['Freescale', 'KLXX'] - + self.supported_toolchains = ["GCC_ARM", "ARM"] - + self.supported_form_factors = ["ARDUINO"] - + self.is_disk_virtual = True class K20D5M(Target): def __init__(self): Target.__init__(self) - + self.core = "Cortex-M4" - + self.extra_labels = ['Freescale'] - + self.supported_toolchains = ["GCC_ARM", "ARM"] - + self.is_disk_virtual = True @@ -173,8 +173,8 @@ class K64F(Target): self.macros = ["CPU_MK64FN1M0VMD12", "FSL_RTOS_MBED"] - self.supported_toolchains = ["ARM"] - + self.supported_toolchains = ["ARM", "GCC_ARM"] + self.supported_form_factors = ["ARDUINO"] self.is_disk_virtual = True @@ -185,15 +185,15 @@ class LPC812(Target): def __init__(self): Target.__init__(self) - + self.core = "Cortex-M0+" - + self.extra_labels = ['NXP', 'LPC81X'] - + self.supported_toolchains = ["uARM"] - + self.supported_form_factors = ["ARDUINO"] - + self.is_disk_virtual = True @@ -202,32 +202,32 @@ class LPC810(Target): def __init__(self): Target.__init__(self) - + self.core = "Cortex-M0+" - + self.extra_labels = ['NXP', 'LPC81X'] - + self.supported_toolchains = ["uARM"] - + self.is_disk_virtual = True class LPC4088(Target): def __init__(self): Target.__init__(self) - + self.core = "Cortex-M4F" - + self.extra_labels = ['NXP', 'LPC408X'] - + self.supported_toolchains = ["ARM", "GCC_CR", "GCC_ARM"] - + self.is_disk_virtual = True - + def init_hooks(self, hook, toolchain_name): if toolchain_name in ['ARM_STD', 'ARM_MICRO']: hook.hook_add_binary("post", self.binary_hook) - + @staticmethod def binary_hook(t_self, resources, elf, binf): if not os.path.isdir(binf): @@ -260,108 +260,92 @@ class LPC4088(Target): class LPC4330_M4(Target): def __init__(self): Target.__init__(self) - + self.core = "Cortex-M4F" - + self.extra_labels = ['NXP', 'LPC43XX'] - + self.supported_toolchains = ["ARM", "GCC_CR", "IAR", "GCC_ARM"] class LPC4330_M0(Target): def __init__(self): Target.__init__(self) - + self.core = "Cortex-M0" - + self.extra_labels = ['NXP', 'LPC43XX'] - + self.supported_toolchains = ["ARM", "GCC_CR", "IAR"] class LPC1800(Target): def __init__(self): Target.__init__(self) - + self.core = "Cortex-M3" - + self.extra_labels = ['NXP', 'LPC43XX'] - + self.supported_toolchains = ["ARM", "GCC_CR", "IAR"] class STM32F407(Target): def __init__(self): Target.__init__(self) - + self.core = "Cortex-M4F" - + self.extra_labels = ['STM', 'STM32F4XX'] - + self.supported_toolchains = ["ARM", "GCC_ARM"] -class NUCLEO_F103RB(Target): - ONLINE_TOOLCHAIN = "uARM" - OUTPUT_NAMING = "8.3" - - def __init__(self): - Target.__init__(self) - - self.core = "Cortex-M3" - - self.extra_labels = ['STM', 'STM32F1', 'STM32F103RB'] - - self.supported_toolchains = ["ARM", "uARM"] - - self.supported_form_factors = ["ARDUINO", "MORPHO"] - - -class NUCLEO_L152RE(Target): - ONLINE_TOOLCHAIN = "uARM" - OUTPUT_NAMING = "8.3" - - def __init__(self): - Target.__init__(self) - - self.core = "Cortex-M3" - - self.extra_labels = ['STM', 'STM32L1', 'STM32L152RE'] - - self.supported_toolchains = ["ARM", "uARM"] - - self.supported_form_factors = ["ARDUINO", "MORPHO"] - - -class NUCLEO_F401RE(Target): - ONLINE_TOOLCHAIN = "uARM" - OUTPUT_NAMING = "8.3" - - def __init__(self): - Target.__init__(self) - - self.core = "Cortex-M4F" - - self.extra_labels = ['STM', 'STM32F4', 'STM32F401RE'] - - self.supported_toolchains = ["ARM", "uARM", "GCC_ARM"] - - self.supported_form_factors = ["ARDUINO", "MORPHO"] - - class NUCLEO_F030R8(Target): ONLINE_TOOLCHAIN = "uARM" OUTPUT_NAMING = "8.3" def __init__(self): Target.__init__(self) - + self.core = "Cortex-M0" - + self.extra_labels = ['STM', 'STM32F0', 'STM32F030R8'] - + self.supported_toolchains = ["ARM", "uARM"] - + + self.supported_form_factors = ["ARDUINO", "MORPHO"] + + +class NUCLEO_F072RB(Target): + ONLINE_TOOLCHAIN = "uARM" + OUTPUT_NAMING = "8.3" + + def __init__(self): + Target.__init__(self) + + self.core = "Cortex-M0" + + self.extra_labels = ['STM', 'STM32F0', 'STM32F072RB'] + + self.supported_toolchains = ["ARM", "uARM"] + + self.supported_form_factors = ["ARDUINO", "MORPHO"] + + +class NUCLEO_F103RB(Target): + ONLINE_TOOLCHAIN = "uARM" + OUTPUT_NAMING = "8.3" + + def __init__(self): + Target.__init__(self) + + self.core = "Cortex-M3" + + self.extra_labels = ['STM', 'STM32F1', 'STM32F103RB'] + + self.supported_toolchains = ["ARM", "uARM", "GCC_ARM"] + self.supported_form_factors = ["ARDUINO", "MORPHO"] @@ -371,39 +355,87 @@ class NUCLEO_F302R8(Target): def __init__(self): Target.__init__(self) - + self.core = "Cortex-M4F" - + self.extra_labels = ['STM', 'STM32F3', 'STM32F302R8'] - + self.supported_toolchains = ["ARM", "uARM"] - + self.supported_form_factors = ["ARDUINO", "MORPHO"] - + +class NUCLEO_F401RE(Target): + ONLINE_TOOLCHAIN = "uARM" + OUTPUT_NAMING = "8.3" + + def __init__(self): + Target.__init__(self) + + self.core = "Cortex-M4F" + + self.extra_labels = ['STM', 'STM32F4', 'STM32F401RE'] + + self.supported_toolchains = ["ARM", "uARM", "GCC_ARM"] + + self.supported_form_factors = ["ARDUINO", "MORPHO"] + + +class NUCLEO_L053R8(Target): + ONLINE_TOOLCHAIN = "uARM" + OUTPUT_NAMING = "8.3" + + def __init__(self): + Target.__init__(self) + + self.core = "Cortex-M0+" + + self.extra_labels = ['STM', 'STM32L0', 'STM32L053R8'] + + self.supported_toolchains = ["ARM", "uARM"] + + self.supported_form_factors = ["ARDUINO", "MORPHO"] + + +class NUCLEO_L152RE(Target): + ONLINE_TOOLCHAIN = "uARM" + OUTPUT_NAMING = "8.3" + + def __init__(self): + Target.__init__(self) + + self.core = "Cortex-M3" + + self.extra_labels = ['STM', 'STM32L1', 'STM32L152RE'] + + self.supported_toolchains = ["ARM", "uARM"] + + self.supported_form_factors = ["ARDUINO", "MORPHO"] + + class STM32F3XX(Target): ONLINE_TOOLCHAIN = "uARM" OUTPUT_NAMING = "8.3" def __init__(self): Target.__init__(self) - - self.core = "Cortex-M4" - - self.extra_labels = ['STM', 'STM32F3XX'] - - self.supported_toolchains = ["ARM", "uARM", "GCC_ARM"] - - + self.core = "Cortex-M4" + + self.extra_labels = ['STM', 'STM32F3XX'] + + self.supported_toolchains = ["ARM", "uARM", "GCC_ARM"] + + + class LPC1347(Target): def __init__(self): Target.__init__(self) - + self.core = "Cortex-M3" - + self.extra_labels = ['NXP', 'LPC13XX'] - + self.supported_toolchains = ["ARM", "GCC_ARM"] @@ -412,22 +444,22 @@ class LPC1114(Target): def __init__(self): Target.__init__(self) - + self.core = "Cortex-M0" - + self.extra_labels = ['NXP', 'LPC11XX_11CXX', 'LPC11XX'] - + self.supported_toolchains = ["ARM", "uARM", "GCC_ARM","GCC_CR"] class LPC11C24(Target): def __init__(self): Target.__init__(self) - + self.core = "Cortex-M0" - + self.extra_labels = ['NXP', 'LPC11XX_11CXX', 'LPC11CXX'] - + self.supported_toolchains = ["ARM", "uARM", "GCC_ARM"] @@ -436,11 +468,11 @@ class LPC11U35_401(Target): def __init__(self): Target.__init__(self) - + self.core = "Cortex-M0" - + self.extra_labels = ['NXP', 'LPC11UXX'] - + self.supported_toolchains = ["ARM", "uARM", "GCC_ARM","GCC_CR"] @@ -449,48 +481,50 @@ class LPC11U35_501(Target): def __init__(self): Target.__init__(self) - + self.core = "Cortex-M0" - + self.extra_labels = ['NXP', 'LPC11UXX'] - + self.supported_toolchains = ["ARM", "uARM","GCC_ARM","GCC_CR"] class UBLOX_C027(Target): def __init__(self): Target.__init__(self) - + self.core = "Cortex-M3" - + self.extra_labels = ['NXP', 'LPC176X'] - + self.supported_toolchains = ["ARM", "uARM", "GCC_ARM", "GCC_CS", "GCC_CR", "IAR"] - + + self.macros = ['TARGET_LPC1768'] + self.supported_form_factors = ["ARDUINO"] class NRF51822(Target): EXPECTED_SOFTDEVICE = 's110_nrf51822_6.0.0_softdevice.hex' OUTPUT_EXT = '.hex' - + APPCODE_OFFSET = 0x14000 - + def __init__(self): Target.__init__(self) - + self.core = "Cortex-M0" - + self.extra_labels = ["NORDIC"] - + self.supported_toolchains = ["ARM"] - + self.is_disk_virtual = True - + def init_hooks(self, hook, toolchain_name): if toolchain_name in ['ARM_STD', 'ARM_MICRO']: hook.hook_add_binary("post", self.binary_hook) - + @staticmethod def binary_hook(t_self, resources, elf, binf): for hexf in resources.hex_files: @@ -499,46 +533,48 @@ class NRF51822(Target): else: t_self.debug("Hex file not found. Aborting.") return - + # Merge user code with softdevice from intelhex import IntelHex binh = IntelHex() binh.loadbin(binf, offset = NRF51822.APPCODE_OFFSET) - + sdh = IntelHex(hexf) sdh.merge(binh) - + with open(binf.replace(".bin", ".hex"), "w") as f: sdh.tofile(f, format = 'hex') class LPC1549(Target): ONLINE_TOOLCHAIN = "uARM" - + def __init__(self): Target.__init__(self) - + self.core = "Cortex-M3" - + self.extra_labels = ['NXP', 'LPC15XX'] - + self.supported_toolchains = ["uARM"] - + self.supported_form_factors = ["ARDUINO"] class LPC11U68(Target): ONLINE_TOOLCHAIN = "uARM" - + def __init__(self): Target.__init__(self) - + self.core = "Cortex-M0+" - + self.extra_labels = ['NXP', 'LPC11U6X'] - + self.supported_toolchains = ["uARM"] + self.supported_form_factors = ["ARDUINO"] + class DISCO_F100RB(Target): ONLINE_TOOLCHAIN = "uARM" @@ -546,54 +582,62 @@ class DISCO_F100RB(Target): def __init__(self): Target.__init__(self) - + self.core = "Cortex-M3" - + self.extra_labels = ['STM', 'STM32F1', 'STM32F100RB'] - + self.supported_toolchains = ["GCC_ARM"] - + class DISCO_F051R8(Target): ONLINE_TOOLCHAIN = "uARM" OUTPUT_NAMING = "8.3" def __init__(self): Target.__init__(self) - + self.core = "Cortex-M0" - + self.extra_labels = ['STM', 'STM32F0', 'STM32F051','STM32F051R8'] - + self.supported_toolchains = ["GCC_ARM"] - + class DISCO_F407VG(Target): ONLINE_TOOLCHAIN = "uARM" OUTPUT_NAMING = "8.3" def __init__(self): Target.__init__(self) - + self.core = "Cortex-M4F" - + self.extra_labels = ['STM', 'STM32F4', 'STM32F407','STM32F407VG'] - + self.supported_toolchains = ["GCC_ARM"] + class DISCO_F303VC(Target): ONLINE_TOOLCHAIN = "uARM" OUTPUT_NAMING = "8.3" def __init__(self): Target.__init__(self) - + self.core = "Cortex-M4F" - + self.extra_labels = ['STM', 'STM32F3', 'STM32F303','STM32F303VC'] - + self.supported_toolchains = ["GCC_ARM"] - + +class XADOW_M0(LPC11U35_501): + def __init__(self): + LPC11U35_501.__init__(self) + +class ARCH_BLE(NRF51822): + def __init__(self): + NRF51822.__init__(self) # Get a single instance for each target TARGETS = [ @@ -610,12 +654,15 @@ TARGETS = [ LPC810(), LPC4088(), LPC4330_M4(), + STM32F3XX(), STM32F407(), - NUCLEO_F103RB(), - NUCLEO_L152RE(), - NUCLEO_F401RE(), NUCLEO_F030R8(), + NUCLEO_F072RB(), + NUCLEO_F103RB(), NUCLEO_F302R8(), + NUCLEO_F401RE(), + NUCLEO_L053R8(), + NUCLEO_L152RE(), LPC1347(), LPC1114(), LPC11C24(), @@ -625,11 +672,12 @@ TARGETS = [ UBLOX_C027(), LPC1549(), LPC11U68(), - DISCO_F100RB(), DISCO_F051R8(), + DISCO_F100RB(), + DISCO_F303VC(), DISCO_F407VG(), - STM32F3XX(), - DISCO_F303VC() + XADOW_M0(), + ARCH_BLE() ] # Map each target name to its unique instance diff --git a/workspace_tools/tests.py b/workspace_tools/tests.py index 2468850917..acc796897d 100644 --- a/workspace_tools/tests.py +++ b/workspace_tools/tests.py @@ -25,8 +25,6 @@ BENCHMARKS_DIR = join(TEST_DIR, "benchmarks") SD = join(TEST_DIR, "sd") TMP102 = join(PERIPHERALS, 'TMP102') -BLE_API = join(LIB_DIR, "ble", "ble-api") -BLE_NRF51822 = join(LIB_DIR, "ble", "nRF51822") """ Wiring: @@ -82,7 +80,7 @@ TESTS = [ "automated": True, }, { - "id": "MBED_A2", "description": "semihost file system", + "id": "MBED_A2", "description": "Semihost file system", "source_dir": join(TEST_DIR, "mbed", "file"), "dependencies": [MBED_LIBRARIES, TEST_MBED_LIB], "automated": True, @@ -212,7 +210,7 @@ TESTS = [ "id": "MBED_A21", "description": "Call function before main (mbed_main)", "source_dir": join(TEST_DIR, "mbed", "call_before_main"), "dependencies": [MBED_LIBRARIES, TEST_MBED_LIB], - "automated": True, + "automated": False, }, { "id": "MBED_A22", "description": "SPIFI for LPC4088 (test 1)", @@ -361,8 +359,8 @@ TESTS = [ "id": "MBED_15", "description": "RPC", "source_dir": join(TEST_DIR, "mbed", "rpc"), "dependencies": [MBED_LIBRARIES, join(LIB_DIR, "rpc"), TEST_MBED_LIB], - "mcu": ["LPC1768"], "automated": True, + "mcu": ["LPC1768"] }, { "id": "MBED_16", "description": "RTC", @@ -403,6 +401,7 @@ TESTS = [ "source_dir": join(TEST_DIR, "mbed", "semihost"), "dependencies": [MBED_LIBRARIES, TEST_MBED_LIB], "automated": True, + "mcu": ["LPC1768", "LPC2368", "LPC11U24", "KL05Z", "KL25Z", "KL46Z"] }, { "id": "MBED_23", "description": "Ticker Int us", @@ -521,7 +520,8 @@ TESTS = [ "dependencies": [MBED_LIBRARIES, RTOS_LIBRARIES], "duration": 15, "automated": True, - "host_test": "wait_us_auto" + "host_test": "wait_us_auto", + "mcu": ["LPC1768", "LPC11U24", "LPC812", "KL25Z", "KL05Z", "K64F", "KL46Z"], }, { "id": "RTOS_2", "description": "Mutex resource lock", @@ -529,6 +529,7 @@ TESTS = [ "dependencies": [MBED_LIBRARIES, RTOS_LIBRARIES, TEST_MBED_LIB], "duration": 20, "automated": True, + "mcu": ["LPC1768", "LPC11U24", "LPC812", "KL25Z", "KL05Z", "K64F", "KL46Z"], }, { "id": "RTOS_3", "description": "Semaphore resource lock", @@ -536,24 +537,28 @@ TESTS = [ "dependencies": [MBED_LIBRARIES, RTOS_LIBRARIES, TEST_MBED_LIB], "duration": 20, "automated": True, + "mcu": ["LPC1768", "LPC11U24", "LPC812", "KL25Z", "KL05Z", "K64F", "KL46Z"], }, { "id": "RTOS_4", "description": "Signals messaging", "source_dir": join(TEST_DIR, "rtos", "mbed", "signals"), "dependencies": [MBED_LIBRARIES, RTOS_LIBRARIES, TEST_MBED_LIB], "automated": True, + "mcu": ["LPC1768", "LPC11U24", "LPC812", "KL25Z", "KL05Z", "K64F", "KL46Z"], }, { "id": "RTOS_5", "description": "Queue messaging", "source_dir": join(TEST_DIR, "rtos", "mbed", "queue"), "dependencies": [MBED_LIBRARIES, RTOS_LIBRARIES, TEST_MBED_LIB], "automated": True, + "mcu": ["LPC1768", "LPC11U24", "LPC812", "KL25Z", "KL05Z", "K64F", "KL46Z"], }, { "id": "RTOS_6", "description": "Mail messaging", "source_dir": join(TEST_DIR, "rtos", "mbed", "mail"), "dependencies": [MBED_LIBRARIES, RTOS_LIBRARIES, TEST_MBED_LIB], "automated": True, + "mcu": ["LPC1768", "LPC11U24", "LPC812", "KL25Z", "KL05Z", "K64F", "KL46Z"], }, { "id": "RTOS_7", "description": "Timer", @@ -561,20 +566,23 @@ TESTS = [ "dependencies": [MBED_LIBRARIES, RTOS_LIBRARIES], "duration": 15, "automated": True, - "host_test": "wait_us_auto" + "host_test": "wait_us_auto", + "mcu": ["LPC1768", "LPC11U24", "LPC812", "KL25Z", "KL05Z", "K64F", "KL46Z"], }, { "id": "RTOS_8", "description": "ISR (Queue)", "source_dir": join(TEST_DIR, "rtos", "mbed", "isr"), "dependencies": [MBED_LIBRARIES, RTOS_LIBRARIES, TEST_MBED_LIB], "automated": True, + "mcu": ["LPC1768", "LPC11U24", "LPC812", "KL25Z", "KL05Z", "K64F", "KL46Z"], }, { "id": "RTOS_9", "description": "SD File write-read", "source_dir": join(TEST_DIR, "rtos", "mbed", "file"), "dependencies": [MBED_LIBRARIES, RTOS_LIBRARIES, TEST_MBED_LIB, SD_FS, FAT_FS], "automated": True, - "peripherals": ["SD"] + "peripherals": ["SD"], + "mcu": ["LPC1768", "LPC11U24", "LPC812", "KL25Z", "KL05Z", "K64F", "KL46Z"], }, # Networking Tests @@ -674,6 +682,15 @@ TESTS = [ "host_test": "tcpecho_client_auto", "peripherals": ["ethernet"], }, + { + "id": "NET_14", "description": "UDP PHY/Data link layer", + "source_dir": join(TEST_DIR, "net", "echo", "udp_link_layer"), + "dependencies": [MBED_LIBRARIES, RTOS_LIBRARIES, ETH_LIBRARY], + "automated": False, + "duration": 15, + "host_test": "udp_link_layer_auto.py", + "peripherals": ["ethernet"], + }, # u-blox tests { @@ -790,21 +807,6 @@ TESTS = [ "source_dir": join(TEST_DIR, "mbed", "fs"), "dependencies": [MBED_LIBRARIES, RTOS_LIBRARIES, TEST_MBED_LIB, SD_FS, FAT_FS], }, - { - "id": "NORDIC_1", "description": "BLE Health Thermometer", - "source_dir": join(TEST_DIR, "ble", "Health_Thermometer"), - "dependencies": [MBED_LIBRARIES, TMP102, BLE_API, BLE_NRF51822], - }, - { - "id": "NORDIC_2", "description": "BLE Heart Rate Monitor", - "source_dir": join(TEST_DIR, "ble", "HeartRate"), - "dependencies": [MBED_LIBRARIES, BLE_API, BLE_NRF51822], - }, - { - "id": "NORDIC_3", "description": "BLE iBeacon", - "source_dir": join(TEST_DIR, "ble", "iBeacon"), - "dependencies": [MBED_LIBRARIES, BLE_API, BLE_NRF51822], - }, ] # Group tests with the same goals into categories diff --git a/workspace_tools/toolchains/__init__.py b/workspace_tools/toolchains/__init__.py index 58d6a9bdad..ca5b9a24fb 100644 --- a/workspace_tools/toolchains/__init__.py +++ b/workspace_tools/toolchains/__init__.py @@ -33,66 +33,84 @@ def print_notify(event): # Default command line notification if event['type'] in ['info', 'debug']: print event['message'] - + elif event['type'] == 'cc': event['severity'] = event['severity'].title() event['file'] = basename(event['file']) print '[%(severity)s] %(file)s@%(line)s: %(message)s' % event - + elif event['type'] == 'progress': print '%s: %s' % (event['action'].title(), basename(event['file'])) +def print_notify_verbose(event): + """ Default command line notification with more verbose mode """ + if event['type'] in ['info', 'debug']: + print_notify(event) # standard handle + + elif event['type'] == 'cc': + event['severity'] = event['severity'].title() + event['file'] = basename(event['file']) + event['mcu_name'] = "None" + event['toolchain'] = "None" + event['target_name'] = event['target_name'].upper() if event['target_name'] else "Unknown" + event['toolchain_name'] = event['toolchain_name'].upper() if event['toolchain_name'] else "Unknown" + print '[%(severity)s] %(target_name)s::%(toolchain_name)s::%(file)s@%(line)s: %(message)s' % event + + elif event['type'] == 'progress': + print_notify(event) # standard handle + + class Resources: def __init__(self, base_path=None): self.base_path = base_path - + self.inc_dirs = [] self.headers = [] - + self.s_sources = [] self.c_sources = [] self.cpp_sources = [] - + self.lib_dirs = set([]) self.objects = [] self.libraries = [] - + # mbed special files self.lib_builds = [] self.lib_refs = [] - + self.repo_dirs = [] self.repo_files = [] - + self.linker_script = None # Other files self.hex_files = [] - + def add(self, resources): self.inc_dirs += resources.inc_dirs self.headers += resources.headers - + self.s_sources += resources.s_sources self.c_sources += resources.c_sources self.cpp_sources += resources.cpp_sources - + self.lib_dirs |= resources.lib_dirs self.objects += resources.objects self.libraries += resources.libraries - + self.lib_builds += resources.lib_builds self.lib_refs += resources.lib_refs - + self.repo_dirs += resources.repo_dirs self.repo_files += resources.repo_files - + if resources.linker_script is not None: self.linker_script = resources.linker_script self.hex_files += resources.hex_files - + def relative_to(self, base, dot=False): for field in ['inc_dirs', 'headers', 's_sources', 'c_sources', 'cpp_sources', 'lib_dirs', 'objects', 'libraries', @@ -101,7 +119,7 @@ class Resources: setattr(self, field, v) if self.linker_script is not None: self.linker_script = rel_path(self.linker_script, base, dot) - + def win_to_unix(self): for field in ['inc_dirs', 'headers', 's_sources', 'c_sources', 'cpp_sources', 'lib_dirs', 'objects', 'libraries', @@ -110,18 +128,18 @@ class Resources: setattr(self, field, v) if self.linker_script is not None: self.linker_script = self.linker_script.replace('\\', '/') - + def __str__(self): s = [] - + for (label, resources) in ( ('Include Directories', self.inc_dirs), ('Headers', self.headers), - + ('Assembly sources', self.s_sources), ('C sources', self.c_sources), ('C++ sources', self.cpp_sources), - + ('Library directories', self.lib_dirs), ('Objects', self.objects), ('Libraries', self.libraries), @@ -130,10 +148,10 @@ class Resources: ): if resources: s.append('%s:\n ' % label + '\n '.join(resources)) - + if self.linker_script: s.append('Linker Script: ' + self.linker_script) - + return '\n'.join(s) @@ -153,7 +171,7 @@ LEGACY_TOOLCHAIN_NAMES = { class mbedToolchain: VERBOSE = True - + CORTEX_SYMBOLS = { "Cortex-M3" : ["__CORTEX_M3", "ARM_MATH_CM3"], "Cortex-M0" : ["__CORTEX_M0", "ARM_MATH_CM0"], @@ -169,14 +187,14 @@ class mbedToolchain: self.target = target self.name = self.__class__.__name__ self.hook = hooks.Hook(target, self) - + self.legacy_ignore_dirs = LEGACY_IGNORE_DIRS - set([target.name, LEGACY_TOOLCHAIN_NAMES[self.name]]) - + if notify is not None: self.notify = notify else: self.notify = print_notify - + if options is None: self.options = [] else: @@ -185,13 +203,13 @@ class mbedToolchain: self.options.extend(BUILD_OPTIONS) if self.options: self.info("Build Options: %s" % (', '.join(self.options))) - + self.obj_path = join("TARGET_"+target.name, "TOOLCHAIN_"+self.name) - + self.symbols = None self.labels = None self.has_config = False - + self.build_all = False self.timestamp = time() @@ -200,18 +218,18 @@ class mbedToolchain: return self.GOANNA_DIAGNOSTIC_PATTERN.match(line) else: return None - + def get_symbols(self): if self.symbols is None: # Target and Toolchain symbols labels = self.get_labels() self.symbols = ["TARGET_%s" % t for t in labels['TARGET']] self.symbols.extend(["TOOLCHAIN_%s" % t for t in labels['TOOLCHAIN']]) - + # Config support if self.has_config: self.symbols.append('HAVE_MBED_CONFIG_H') - + # Cortex CPU symbols if self.target.core in mbedToolchain.CORTEX_SYMBOLS: self.symbols.extend(mbedToolchain.CORTEX_SYMBOLS[self.target.core]) @@ -220,7 +238,7 @@ class mbedToolchain: self.symbols.extend(['MBED_BUILD_TIMESTAMP=%s' % self.timestamp, '__MBED__=1']) if MBED_ORG_USER: self.symbols.append('MBED_USERNAME=' + MBED_ORG_USER) - + # Add target's symbols for macro in self.target.macros: self.symbols.append(macro) @@ -228,9 +246,9 @@ class mbedToolchain: # Form factor variables if hasattr(self.target, 'supported_form_factors'): self.symbols.extend(["TARGET_FF_%s" % t for t in self.target.supported_form_factors]) - + return self.symbols - + def get_labels(self): if self.labels is None: toolchain_labels = [c.__name__ for c in getmro(self.__class__)] @@ -240,33 +258,33 @@ class mbedToolchain: 'TOOLCHAIN': toolchain_labels } return self.labels - + def need_update(self, target, dependencies): if self.build_all: return True - + if not exists(target): return True - + target_mod_time = stat(target).st_mtime - + for d in dependencies: # Some objects are not provided with full path and here we do not have # information about the library paths. Safe option: assume an update if not d or not exists(d): return True - + if stat(d).st_mtime >= target_mod_time: return True - + return False - + def scan_resources(self, path): labels = self.get_labels() resources = Resources(path) self.has_config = False - + """ os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]]) When topdown is True, the caller can modify the dirnames list in-place (perhaps using del or slice assignment), and walk() will only recurse into @@ -289,36 +307,36 @@ class mbedToolchain: (d.startswith('TARGET_') and d[7:] not in labels['TARGET']) or (d.startswith('TOOLCHAIN_') and d[10:] not in labels['TOOLCHAIN'])): dirs.remove(d) - + # Add root to include paths resources.inc_dirs.append(root) - + for file in files: file_path = join(root, file) _, ext = splitext(file) ext = ext.lower() - + if ext == '.s': resources.s_sources.append(file_path) - + elif ext == '.c': resources.c_sources.append(file_path) - + elif ext == '.cpp': resources.cpp_sources.append(file_path) - + elif ext == '.h': if basename(file_path) == "mbed_config.h": self.has_config = True resources.headers.append(file_path) - + elif ext == '.o': resources.objects.append(file_path) - + elif ext == self.LIBRARY_EXT: resources.libraries.append(file_path) resources.lib_dirs.add(root) - + elif ext == self.LINKER_EXT: resources.linker_script = file_path @@ -338,17 +356,17 @@ class mbedToolchain: def scan_repository(self, path): resources = [] - + for root, dirs, files in walk(path): # Remove ignored directories for d in copy(dirs): if d == '.' or d == '..': dirs.remove(d) - + for file in files: file_path = join(root, file) resources.append(file_path) - + return resources def copy_files(self, files_paths, trg_path, rel_path=None): @@ -364,30 +382,30 @@ class mbedToolchain: relative_path = relpath(source, rel_path) else: _, relative_path = split(source) - + target = join(trg_path, relative_path) - + if (target != source) and (self.need_update(target, [source])): self.progress("copy", relative_path) mkdir(dirname(target)) copyfile(source, target) - + def relative_object_path(self, build_path, base_dir, source): source_dir, name, _ = split_path(source) obj_dir = join(build_path, relpath(source_dir, base_dir)) mkdir(obj_dir) return join(obj_dir, name + '.o') - + def compile_sources(self, resources, build_path, inc_dirs=None): # Web IDE progress bar for project build self.to_be_compiled = len(resources.s_sources) + len(resources.c_sources) + len(resources.cpp_sources) self.compiled = 0 - + objects = [] inc_paths = resources.inc_dirs if inc_dirs is not None: inc_paths.extend(inc_dirs) - + base_path = resources.base_path for source in resources.s_sources: self.compiled += 1 @@ -396,97 +414,97 @@ class mbedToolchain: self.progress("assemble", source, build_update=True) self.assemble(source, object, inc_paths) objects.append(object) - + # The dependency checking for C/C++ is delegated to the specific compiler for source in resources.c_sources: object = self.relative_object_path(build_path, base_path, source) self.compile_c(source, object, inc_paths) objects.append(object) - + for source in resources.cpp_sources: object = self.relative_object_path(build_path, base_path, source) self.compile_cpp(source, object, inc_paths) objects.append(object) - + return objects - + def compile(self, cc, source, object, includes): # Check dependencies base, _ = splitext(object) dep_path = base + '.d' - + self.compiled += 1 if (not exists(dep_path) or self.need_update(object, self.parse_dependencies(dep_path))): - + self.progress("compile", source, build_update=True) - + # Compile command = cc + ['-D%s' % s for s in self.get_symbols() + self.macros] + ["-I%s" % i for i in includes] + ["-o", object, source] if hasattr(self, "get_dep_opt"): command.extend(self.get_dep_opt(dep_path)) - + if hasattr(self, "cc_extra"): command.extend(self.cc_extra(base)) - + self.debug(command) _, stderr, rc = run_cmd(self.hook.get_cmdline_compiler(command), dirname(object)) - + # Parse output for Warnings and Errors self.parse_output(stderr) - + # Check return code if rc != 0: raise ToolException(stderr) - + def compile_c(self, source, object, includes): self.compile(self.cc, source, object, includes) - + def compile_cpp(self, source, object, includes): self.compile(self.cppc, source, object, includes) - + def build_library(self, objects, dir, name): lib = self.STD_LIB_NAME % name fout = join(dir, lib) if self.need_update(fout, objects): self.info("Library: %s" % lib) self.archive(objects, fout) - + def link_program(self, r, tmp_path, name): ext = 'bin' - + if hasattr(self.target, 'OUTPUT_NAMING'): self.var("binary_naming", self.target.OUTPUT_NAMING) if self.target.OUTPUT_NAMING == "8.3": name = name[0:8] ext = ext[0:3] - + filename = name+'.'+ext - + elf = join(tmp_path, name + '.elf') bin = join(tmp_path, filename) - + if self.need_update(elf, r.objects + r.libraries + [r.linker_script]): self.progress("link", name) self.link(elf, r.objects, r.libraries, r.lib_dirs, r.linker_script) - + if self.need_update(bin, [elf]): self.progress("elf2bin", name) - + self.binary(r, elf, bin) - + if self.target.name.startswith('LPC'): self.debug("LPC Patch %s" % filename) patch(bin) - + self.var("compile_succeded", True) self.var("binary", filename) if hasattr(self.target, 'OUTPUT_EXT'): bin = bin.replace('.bin', self.target.OUTPUT_EXT) - + return bin - + def default_cmd(self, command): self.debug(command) stdout, stderr, rc = run_cmd(command) @@ -495,29 +513,35 @@ class mbedToolchain: for line in stderr.splitlines(): self.tool_error(line) raise ToolException(stderr) - + ### NOTIFICATIONS ### def info(self, message): self.notify({'type': 'info', 'message': message}) - + def debug(self, message): if self.VERBOSE: if type(message) is ListType: message = ' '.join(message) self.notify({'type': 'debug', 'message': message}) - - def cc_info(self, severity, file, line, message): - self.notify({'type': 'cc', 'severity': severity, 'file': file, 'line': line, 'message': message}) - + + def cc_info(self, severity, file, line, message, target_name=None, toolchain_name=None): + self.notify({'type': 'cc', + 'severity': severity, + 'file': file, + 'line': line, + 'message': message, + 'target_name': target_name, + 'toolchain_name': toolchain_name}) + def progress(self, action, file, build_update=False): msg = {'type': 'progress', 'action': action, 'file': file} if build_update: msg['percent'] = 100. * float(self.compiled) / float(self.to_be_compiled) self.notify(msg) - + def tool_error(self, message): self.notify({'type': 'tool_error', 'message': message}) - + def var(self, key, value): self.notify({'type': 'var', 'key': key, 'val': value}) diff --git a/workspace_tools/toolchains/arm.py b/workspace_tools/toolchains/arm.py index 8f7e30c661..0b0f076a02 100644 --- a/workspace_tools/toolchains/arm.py +++ b/workspace_tools/toolchains/arm.py @@ -25,64 +25,67 @@ from workspace_tools.settings import GOANNA_PATH class ARM(mbedToolchain): LINKER_EXT = '.sct' LIBRARY_EXT = '.ar' - + STD_LIB_NAME = "%s.ar" DIAGNOSTIC_PATTERN = re.compile('"(?P[^"]+)", line (?P\d+): (?PWarning|Error): (?P.+)') DEP_PATTERN = re.compile('\S+:\s(?P.+)\n') - + def __init__(self, target, options=None, notify=None, macros=None): mbedToolchain.__init__(self, target, options, notify, macros) - - if target.core == "Cortex-M0+": + + if target.core == "Cortex-M0+": cpu = "Cortex-M0" elif target.core == "Cortex-M4F": cpu = "Cortex-M4.fp" else: cpu = target.core - + main_cc = join(ARM_BIN, "armcc") common = ["-c", "--cpu=%s" % cpu, "--gnu", - "-O3", "-Otime", "--split_sections", "--apcs=interwork", + "-Otime", "--split_sections", "--apcs=interwork", "--brief_diagnostics", "--restrict" ] - + if "save-asm" in self.options: common.extend(["--asm", "--interleave"]) if "debug-info" in self.options: common.append("-g") - + common.append("-O0") + else: + common.append("-O3") + common_c = [ "--md", "--no_depend_system_headers", '-I%s' % ARM_INC ] - + self.asm = [main_cc] + common + ['-I%s' % ARM_INC] if not "analyze" in self.options: self.cc = [main_cc] + common + common_c + ["--c99"] self.cppc = [main_cc] + common + common_c + ["--cpp", "--no_rtti"] else: self.cc = [join(GOANNA_PATH, "goannacc"), "--with-cc=" + main_cc.replace('\\', '/'), "--dialect=armcc", '--output-format="%s"' % self.GOANNA_FORMAT] + common + common_c + ["--c99"] - self.cppc= [join(GOANNA_PATH, "goannac++"), "--with-cxx=" + main_cc.replace('\\', '/'), "--dialect=armcc", '--output-format="%s"' % self.GOANNA_FORMAT] + common + common_c + ["--cpp", "--no_rtti"] - + self.cppc= [join(GOANNA_PATH, "goannac++"), "--with-cxx=" + main_cc.replace('\\', '/'), "--dialect=armcc", '--output-format="%s"' % self.GOANNA_FORMAT] + common + common_c + ["--cpp", "--no_rtti"] + self.ld = [join(ARM_BIN, "armlink")] self.sys_libs = [] - + self.ar = join(ARM_BIN, "armar") self.elf2bin = join(ARM_BIN, "fromelf") - + def remove_option(self, option): for tool in [self.asm, self.cc, self.cppc]: if option in tool: tool.remove(option) - + def assemble(self, source, object, includes): # Preprocess first, then assemble tempfile = object + '.E.s' self.default_cmd(self.asm + ['-D%s' % s for s in self.get_symbols() + self.macros] + ["-I%s" % i for i in includes] + ["-E", "-o", tempfile, source]) self.default_cmd(self.hook.get_cmdline_assembler(self.asm + ["-o", object, tempfile])) - + def parse_dependencies(self, dep_path): dependencies = [] for line in open(dep_path).readlines(): @@ -90,7 +93,7 @@ class ARM(mbedToolchain): if match is not None: dependencies.append(match.group('file')) return dependencies - + def parse_output(self, output): for line in output.splitlines(): match = ARM.DIAGNOSTIC_PATTERN.match(line) @@ -99,7 +102,9 @@ class ARM(mbedToolchain): match.group('severity').lower(), match.group('file'), match.group('line'), - match.group('message') + match.group('message'), + target_name=self.target.name, + toolchain_name=self.name ) match = self.goanna_parse_line(line) if match is not None: @@ -112,7 +117,7 @@ class ARM(mbedToolchain): def archive(self, objects, lib_path): self.default_cmd([self.ar, '-r', lib_path] + objects) - + def link(self, output, objects, libraries, lib_dirs, mem_map): if len(lib_dirs): args = ["-o", output, "--userlibpath", ",".join(lib_dirs), "--info=totals", "--list=.link_totals.txt"] @@ -126,14 +131,14 @@ class ARM(mbedToolchain): args = self.target.link_cmdline_hook(self.__class__.__name__, args) self.default_cmd(self.ld + args + objects + libraries + self.sys_libs) - + @hook_tool def binary(self, resources, elf, bin): args = [self.elf2bin, '--bin', '-o', bin, elf] - + if hasattr(self.target, "binary_cmdline_hook"): args = self.target.binary_cmdline_hook(self.__class__.__name__, args) - + self.default_cmd(args) class ARM_STD(ARM): @@ -144,29 +149,29 @@ class ARM_STD(ARM): class ARM_MICRO(ARM): PATCHED_LIBRARY = False - + def __init__(self, target, options=None, notify=None, macros=None): ARM.__init__(self, target, options, notify, macros) - + # Compiler self.asm += ["-D__MICROLIB"] self.cc += ["--library_type=microlib", "-D__MICROLIB"] self.cppc += ["--library_type=microlib", "-D__MICROLIB"] - + # Linker self.ld.append("--library_type=microlib") - + # We had to patch microlib to add C++ support # In later releases this patch should have entered mainline if ARM_MICRO.PATCHED_LIBRARY: self.ld.append("--noscanlib") - + # System Libraries self.sys_libs.extend([join(MY_ARM_CLIB, lib+".l") for lib in ["mc_p", "mf_p", "m_ps"]]) - + if target.core == "Cortex-M3": self.sys_libs.extend([join(ARM_CPPLIB, lib+".l") for lib in ["cpp_ws", "cpprt_w"]]) - + elif target.core in ["Cortex-M0", "Cortex-M0+"]: self.sys_libs.extend([join(ARM_CPPLIB, lib+".l") for lib in ["cpp_ps", "cpprt_p"]]) else: diff --git a/workspace_tools/toolchains/gcc.py b/workspace_tools/toolchains/gcc.py index 6496cb32f8..a14f1a1503 100644 --- a/workspace_tools/toolchains/gcc.py +++ b/workspace_tools/toolchains/gcc.py @@ -24,43 +24,46 @@ from workspace_tools.settings import GOANNA_PATH class GCC(mbedToolchain): LINKER_EXT = '.ld' LIBRARY_EXT = '.a' - + STD_LIB_NAME = "lib%s.a" CIRCULAR_DEPENDENCIES = True DIAGNOSTIC_PATTERN = re.compile('((?P\d+):)(\d+:)? (?Pwarning|error): (?P.+)') - + def __init__(self, target, options=None, notify=None, macros=None, tool_path=""): mbedToolchain.__init__(self, target, options, notify, macros) - + if target.core == "Cortex-M0+": cpu = "cortex-m0" elif target.core == "Cortex-M4F": cpu = "cortex-m4" else: cpu = target.core.lower() - + self.cpu = ["-mcpu=%s" % cpu] if target.core.startswith("Cortex"): self.cpu.append("-mthumb") - + if target.core == "Cortex-M4F": self.cpu.append("-mfpu=fpv4-sp-d16") self.cpu.append("-mfloat-abi=softfp") - + # Note: We are using "-O2" instead of "-Os" to avoid this known GCC bug: # http://gcc.gnu.org/bugzilla/show_bug.cgi?id=46762 - common_flags = ["-c", "-O2", "-Wall", "-Wextra", + common_flags = ["-c", "-Wall", "-Wextra", "-Wno-unused-parameter", "-Wno-missing-field-initializers", "-fmessage-length=0", "-fno-exceptions", "-fno-builtin", "-ffunction-sections", "-fdata-sections", "-MMD", "-fno-delete-null-pointer-checks", ] + self.cpu - + if "save-asm" in self.options: common_flags.append("-save-temps") if "debug-info" in self.options: common_flags.append("-g") + common_flags.append("-O0") + else: + common_flags.append("-O2") main_cc = join(tool_path, "arm-none-eabi-gcc") main_cppc = join(tool_path, "arm-none-eabi-g++") @@ -71,16 +74,16 @@ class GCC(mbedToolchain): else: self.cc = [join(GOANNA_PATH, "goannacc"), "--with-cc=" + main_cc.replace('\\', '/'), "-std=gnu99", "--dialect=gnu", '--output-format="%s"' % self.GOANNA_FORMAT] + common_flags self.cppc= [join(GOANNA_PATH, "goannac++"), "--with-cxx=" + main_cppc.replace('\\', '/'), "-std=gnu++98", "--dialect=gnu", '--output-format="%s"' % self.GOANNA_FORMAT] + common_flags - + self.ld = [join(tool_path, "arm-none-eabi-gcc"), "-Wl,--gc-sections", "-Wl,--wrap,main"] + self.cpu self.sys_libs = ["stdc++", "supc++", "m", "c", "gcc"] - + self.ar = join(tool_path, "arm-none-eabi-ar") self.elf2bin = join(tool_path, "arm-none-eabi-objcopy") - + def assemble(self, source, object, includes): self.default_cmd(self.hook.get_cmdline_assembler(self.asm + ['-D%s' % s for s in self.get_symbols() + self.macros] + ["-I%s" % i for i in includes] + ["-o", object, source])) - + def parse_dependencies(self, dep_path): dependencies = [] for line in open(dep_path).readlines()[1:]: @@ -99,7 +102,7 @@ class GCC(mbedToolchain): else: dependencies = dependencies + [f.replace('\a', ' ') for f in file.split(" ")] return dependencies - + def parse_output(self, output): # The warning/error notification is multiline WHERE, WHAT = 0, 1 @@ -111,53 +114,55 @@ class GCC(mbedToolchain): match.group('severity').lower(), match.group('file'), match.group('line'), - match.group('message') + match.group('message'), + target_name=self.target.name, + toolchain_name=self.name ) continue - + # Each line should start with the file information: "filepath: ..." # i should point past the file path ^ # avoid the first column in Windows (C:\) i = line.find(':', 2) if i == -1: continue - + if state == WHERE: file = line[:i] message = line[i+1:].strip() + ' ' state = WHAT - + elif state == WHAT: match = GCC.DIAGNOSTIC_PATTERN.match(line[i+1:]) if match is None: state = WHERE continue - + self.cc_info( match.group('severity'), file, match.group('line'), message + match.group('message') ) - + def archive(self, objects, lib_path): self.default_cmd([self.ar, "rcs", lib_path] + objects) - + def link(self, output, objects, libraries, lib_dirs, mem_map): libs = [] for l in libraries: name, _ = splitext(basename(l)) libs.append("-l%s" % name[3:]) libs.extend(["-l%s" % l for l in self.sys_libs]) - + # NOTE: There is a circular dependency between the mbed library and the clib # We could define a set of week symbols to satisfy the clib dependencies in "sys.o", # but if an application uses only clib symbols and not mbed symbols, then the final - # image is not correctly retargeted + # image is not correctly retargeted if self.CIRCULAR_DEPENDENCIES: libs.extend(libs) - + self.default_cmd(self.hook.get_cmdline_linker(self.ld + ["-T%s" % mem_map, "-o", output] + objects + ["-L%s" % L for L in lib_dirs] + libs)) - + def binary(self, resources, elf, bin): self.default_cmd(self.hook.get_cmdline_binary([self.elf2bin, "-O", "binary", elf, bin])) @@ -165,25 +170,25 @@ class GCC(mbedToolchain): class GCC_ARM(GCC): def __init__(self, target, options=None, notify=None, macros=None): GCC.__init__(self, target, options, notify, macros, GCC_ARM_PATH) - + # Use latest gcc nanolib self.ld.append("--specs=nano.specs") - if target.name in ["LPC1768", "LPC4088", "LPC4330"]: + if target.name in ["LPC1768", "LPC4088", "LPC4330", "UBLOX_C027"]: self.ld.extend(["-u", "_printf_float", "-u", "_scanf_float"]) - + self.sys_libs.append("nosys") class GCC_CR(GCC): def __init__(self, target, options=None, notify=None, macros=None): GCC.__init__(self, target, options, notify, macros, GCC_CR_PATH) - + additional_compiler_flags = [ "-D__NEWLIB__", "-D__CODE_RED", "-D__USE_CMSIS", "-DCPP_USE_HEAP", ] self.cc += additional_compiler_flags self.cppc += additional_compiler_flags - + self.ld += ["-nostdlib"] @@ -196,7 +201,7 @@ class GCC_CW(GCC): ARCH_LIB = { "Cortex-M0+": "armv6-m", } - + def __init__(self, target, options=None, notify=None, macros=None): GCC.__init__(self, target, options, notify, macros, CW_GCC_PATH) @@ -204,7 +209,7 @@ class GCC_CW(GCC): class GCC_CW_EWL(GCC_CW): def __init__(self, target, options=None, notify=None, macros=None): GCC_CW.__init__(self, target, options, notify, macros) - + # Compiler common = [ '-mfloat-abi=soft', @@ -217,7 +222,7 @@ class GCC_CW_EWL(GCC_CW): '-nostdinc++', '-I%s' % join(CW_EWL_PATH, "EWL_C++", "include"), '-include', join(CW_EWL_PATH, "EWL_C++", "include", 'lib_ewl_c++.prefix') ] - + # Linker self.sys_libs = [] self.CIRCULAR_DEPENDENCIES = False diff --git a/workspace_tools/toolchains/iar.py b/workspace_tools/toolchains/iar.py index 544538dfa6..eb47bd4cec 100644 --- a/workspace_tools/toolchains/iar.py +++ b/workspace_tools/toolchains/iar.py @@ -26,14 +26,13 @@ class IAR(mbedToolchain): LIBRARY_EXT = '.a' LINKER_EXT = '.icf' STD_LIB_NAME = "%s.a" - + DIAGNOSTIC_PATTERN = re.compile('"(?P[^"]+)",(?P[\d]+)\s+(?PWarning|Error)(?P.+)') - + def __init__(self, target, options=None, notify=None, macros=None): mbedToolchain.__init__(self, target, options, notify, macros) - + c_flags = [ - "-Oh", "--cpu=%s" % target.core, "--thumb", "--dlib_config", join(IAR_PATH, "inc", "c", "DLib_Config_Full.h"), "-e", # Enable IAR language extension @@ -47,7 +46,10 @@ class IAR(mbedToolchain): if "debug-info" in self.options: c_flags.append("-r") - + c_flags.append("-On") + else: + c_flags.append("-Oh") + IAR_BIN = join(IAR_PATH, "bin") main_cc = join(IAR_BIN, "iccarm") self.asm = [join(IAR_BIN, "iasmarm")] + ["--cpu", target.core] @@ -60,7 +62,7 @@ class IAR(mbedToolchain): self.ld = join(IAR_BIN, "ilinkarm") self.ar = join(IAR_BIN, "iarchive") self.elf2bin = join(IAR_BIN, "ielftool") - + def parse_output(self, output): for line in output.splitlines(): match = IAR.DIAGNOSTIC_PATTERN.match(line) @@ -70,6 +72,8 @@ class IAR(mbedToolchain): match.group('file'), match.group('line'), match.group('message'), + target_name=self.target.name, + toolchain_name=self.name ) match = self.goanna_parse_line(line) if match is not None: @@ -79,28 +83,28 @@ class IAR(mbedToolchain): match.group('line'), match.group('message') ) - + def get_dep_opt(self, dep_path): return ["--dependencies", dep_path] - + def cc_extra(self, base): return ["-l", base + '.s'] - + def parse_dependencies(self, dep_path): return [path.strip() for path in open(dep_path).readlines() if (path and not path.isspace())] - + def assemble(self, source, object, includes): self.default_cmd(self.hook.get_cmdline_assembler(self.asm + ['-D%s' % s for s in self.get_symbols() + self.macros] + ["-I%s" % i for i in includes] + ["-o", object, source])) - + def archive(self, objects, lib_path): if exists(lib_path): remove(lib_path) self.default_cmd([self.ar, lib_path] + objects) - + def link(self, output, objects, libraries, lib_dirs, mem_map): args = [self.ld, "-o", output, "--config", mem_map] self.default_cmd(self.hook.get_cmdline_linker(args + objects + libraries)) - + def binary(self, resources, elf, bin): self.default_cmd(self.hook.get_cmdline_binary([self.elf2bin, '--bin', elf, bin])) diff --git a/workspace_tools/utils.py b/workspace_tools/utils.py index 3995f0c918..b51ba337c2 100644 --- a/workspace_tools/utils.py +++ b/workspace_tools/utils.py @@ -24,9 +24,9 @@ from shutil import copyfile def cmd(l, check=True, verbose=False, shell=False, cwd=None): text = l if shell else ' '.join(l) if verbose: print text - + rc = call(l, shell=shell, cwd=cwd) - + if check and rc != 0: raise Exception('ERROR %d: "%s"' % (rc, text)) @@ -34,7 +34,7 @@ def cmd(l, check=True, verbose=False, shell=False, cwd=None): def run_cmd(command, wd=None, redirect=False): p = Popen(command, stdout=PIPE, stderr=STDOUT if redirect else PIPE, cwd=wd) stdout, stderr = p.communicate() - + return stdout, stderr, p.returncode @@ -57,7 +57,7 @@ def copy_file(src, dst): def delete_dir_files(dir): if not exists(dir): return - + for f in listdir(dir): file = join(dir, f) if not isdir(file):