Intermediate
30 min

Achieve trouble-free NB-IoT connectivity with BC66-NA and STM32L073RZ

Stay connected and responsive in any environment

NB IoT 2 Click with Nucleo-64 with STM32L073RZ MCU

Published Feb 26, 2024

Click board™

NB IoT 2 Click

Dev. board

Nucleo-64 with STM32L073RZ MCU

Compiler

NECTO Studio

MCU

STM32L073RZ

Experience IoT in a new light with NB-IoT technology, redefining what's achievable and setting the stage for boundless innovation

A

A

Hardware Overview

How does it work?

NB IoT 2 Click is based on the BC66-NA, a high-performance NB-IoT module with extremely low power consumption from Quectel Wireless Solutions. It is designed to communicate with the infrastructures of mobile network operators through NB-IoT radio protocols (3GPP Rel.13 and 3GPP Rel.14). It supports a broad range of frequency bands such as B1/B2/B3/B4/B5/B8/B12/ B13/B17/B18/B19/B20/B25/B28/B66/B71/B85. It also provides several interfaces, UART and SPI, and protocol stacks such as UDP/TCP, MQTT, LwM2M, and others. These protocols allowing data and SMS transmission using NB technology make this module the perfect choice for building IoT applications such as smart gas and water meters, even without needing an external MCU unit. To turn ON this Click board™, the user has to press the onboard push-button labeled PWRKEY down for a period longer, at least 500ms, which represents the Ignition (Power-On) button. The PWRKEY button cannot be pulled down constantly; otherwise, the module cannot enter

power-save mode. This feature is shown by the yellow diode labeled as CONNECT to indicate the device's Operational Status. NB IoT 2 Click communicates with MCU using the UART interface as its default communication protocol with the option for the users to use another interface, such as SPI if they want to configure the module and write the library by themselves. It supports automatic baud rate detection, operates at 115200 bps by default configuration, and is used for data transmission and exchanging AT commands with the host MCU. In addition to these features, the BC66-NA uses two GPIO pins connected to the mikroBUS™ socket. The WUP pin routed on the INT pin of the mikroBUS™ represents the external interrupt pin used for waking up the device from a power-saving mode, while the RST pin on the mikroBUS™ socket can perform Hardware Reset function by putting this pin in a logic low state. This Click board™ also has a micro USB connector, allowing the module to be powered and configured by a personal computer.

Also, it has an additional header labeled ADC IN because the BC66-NA provides a 10-bit ADC input channel to read the voltage value.  The interface is available in Active mode and has to be woken up first to ensure availability in Sleep mode. NB IoT 2 Click possesses the SMA antenna connector with an impedance of 50Ω. This Click board™ can be used to connect the appropriate antenna that MIKROE offers. Besides the SMA connector, it has a SIM card slot that provides multiple connections and interface options. This Click board™ can be operated only with a 3.3V logic voltage level and comes with a proper logic voltage level conversion performed by the appropriate voltage level translator TXB0106. The board must complete the proper logic voltage level conversion before use with MCUs with different logic levels. However, the Click board™ comes equipped with a library containing functions and an example code that can be used as a reference for further development.

NB IoT 2 Click hardware overview image

Features overview

Development board

Nucleo-64 with STM32L073RZ MCU offers a cost-effective and adaptable platform for developers to explore new ideas and prototype their designs. This board harnesses the versatility of the STM32 microcontroller, enabling users to select the optimal balance of performance and power consumption for their projects. It accommodates the STM32 microcontroller in the LQFP64 package and includes essential components such as a user LED, which doubles as an ARDUINO® signal, alongside user and reset push-buttons, and a 32.768kHz crystal oscillator for precise timing operations. Designed with expansion and flexibility in mind, the Nucleo-64 board features an ARDUINO® Uno V3 expansion connector and ST morpho extension pin

headers, granting complete access to the STM32's I/Os for comprehensive project integration. Power supply options are adaptable, supporting ST-LINK USB VBUS or external power sources, ensuring adaptability in various development environments. The board also has an on-board ST-LINK debugger/programmer with USB re-enumeration capability, simplifying the programming and debugging process. Moreover, the board is designed to simplify advanced development with its external SMPS for efficient Vcore logic supply, support for USB Device full speed or USB SNK/UFP full speed, and built-in cryptographic features, enhancing both the power efficiency and security of projects. Additional connectivity is

provided through dedicated connectors for external SMPS experimentation, a USB connector for the ST-LINK, and a MIPI® debug connector, expanding the possibilities for hardware interfacing and experimentation. Developers will find extensive support through comprehensive free software libraries and examples, courtesy of the STM32Cube MCU Package. This, combined with compatibility with a wide array of Integrated Development Environments (IDEs), including IAR Embedded Workbench®, MDK-ARM, and STM32CubeIDE, ensures a smooth and efficient development experience, allowing users to fully leverage the capabilities of the Nucleo-64 board in their projects.

Nucleo 64 with STM32L073RZ MCU double side image

Microcontroller Overview

MCU Card / MCU

default

Architecture

ARM Cortex-M0

MCU Memory (KB)

192

Silicon Vendor

STMicroelectronics

Pin count

64

RAM (Bytes)

20480

You complete me!

Accessories

Click Shield for Nucleo-64 comes equipped with two proprietary mikroBUS™ sockets, allowing all the Click board™ devices to be interfaced with the STM32 Nucleo-64 board with no effort. This way, Mikroe allows its users to add any functionality from our ever-growing range of Click boards™, such as WiFi, GSM, GPS, Bluetooth, ZigBee, environmental sensors, LEDs, speech recognition, motor control, movement sensors, and many more. More than 1537 Click boards™, which can be stacked and integrated, are at your disposal. The STM32 Nucleo-64 boards are based on the microcontrollers in 64-pin packages, a 32-bit MCU with an ARM Cortex M4 processor operating at 84MHz, 512Kb Flash, and 96KB SRAM, divided into two regions where the top section represents the ST-Link/V2 debugger and programmer while the bottom section of the board is an actual development board. These boards are controlled and powered conveniently through a USB connection to program and efficiently debug the Nucleo-64 board out of the box, with an additional USB cable connected to the USB mini port on the board. Most of the STM32 microcontroller pins are brought to the IO pins on the left and right edge of the board, which are then connected to two existing mikroBUS™ sockets. This Click Shield also has several switches that perform functions such as selecting the logic levels of analog signals on mikroBUS™ sockets and selecting logic voltage levels of the mikroBUS™ sockets themselves. Besides, the user is offered the possibility of using any Click board™ with the help of existing bidirectional level-shifting voltage translators, regardless of whether the Click board™ operates at a 3.3V or 5V logic voltage level. Once you connect the STM32 Nucleo-64 board with our Click Shield for Nucleo-64, you can access hundreds of Click boards™, working with 3.3V or 5V logic voltage levels.

Click Shield for Nucleo-64 accessories 1 image

LTE Flat Rotation Antenna is a versatile choice for boosting the performance of 3G/4G LTE devices. With a wide frequency range of 700-2700MHz, it ensures optimal connectivity on major cellular bands worldwide. This flat antenna features an SMA male connector, making it easy to attach directly to your device or SMA module connector. One of its standout features is its adjustable angle, which can be set in 45⁰ increments (0⁰/45⁰/90⁰), allowing you to fine-tune the antenna's orientation for maximum signal reception. With an impedance of 50Ω and a VSW Ratio of <2.0:1, this antenna ensures a reliable and efficient connection. Its 5dB gain, vertical polarization, and omnidirectional radiation pattern enhance signal strength, making it suitable for various applications. Measuring 196mm in length and 38mm in width, this antenna offers a compact yet effective solution for improving your connectivity. With a maximum input power of 50W, it can handle the demands of various devices.

NB IoT 2 Click accessories image

Used MCU Pins

mikroBUS™ mapper

NC
NC
AN
Reset
PC12
RST
SPI Chip Select
PB12
CS
SPI Clock
PB3
SCK
SPI Data OUT
PB4
MISO
SPI Data IN
PB5
MOSI
Power Supply
3.3V
3.3V
Ground
GND
GND
NC
NC
PWM
Wake-Up Interrupt
PC14
INT
UART TX
PA2
TX
UART RX
PA3
RX
NC
NC
SCL
NC
NC
SDA
NC
NC
5V
Ground
GND
GND
1

Take a closer look

Click board™ Schematic

NB IoT 2 Click Schematic schematic

Step by step

Project assembly

Click Shield for Nucleo-64 accessories 1 image hardware assembly

Start by selecting your development board and Click board™. Begin with the Nucleo-64 with STM32L073RZ MCU as your development board.

Click Shield for Nucleo-64 accessories 1 image hardware assembly
Nucleo 64 with STM32F401RE MCU front image hardware assembly
LTE IoT 5 Click front image hardware assembly
Prog-cut hardware assembly
LTE IoT 5 Click complete accessories setup image hardware assembly
Nucleo-64 with STM32XXX MCU Access MB 1 Mini B Conn - upright/background hardware assembly
Necto image step 2 hardware assembly
Necto image step 3 hardware assembly
Necto image step 4 hardware assembly
Necto image step 5 hardware assembly
Necto image step 6 hardware assembly
Clicker 4 for STM32F4 HA MCU Step hardware assembly
Necto No Display image step 8 hardware assembly
Necto image step 9 hardware assembly
Necto image step 10 hardware assembly
Debug Image Necto Step hardware assembly

Track your results in real time

Application Output

1. Application Output - In Debug mode, the 'Application Output' window enables real-time data monitoring, offering direct insight into execution results. Ensure proper data display by configuring the environment correctly using the provided tutorial.

2. UART Terminal - Use the UART Terminal to monitor data transmission via a USB to UART converter, allowing direct communication between the Click board™ and your development system. Configure the baud rate and other serial settings according to your project's requirements to ensure proper functionality. For step-by-step setup instructions, refer to the provided tutorial.

3. Plot Output - The Plot feature offers a powerful way to visualize real-time sensor data, enabling trend analysis, debugging, and comparison of multiple data points. To set it up correctly, follow the provided tutorial, which includes a step-by-step example of using the Plot feature to display Click board™ readings. To use the Plot feature in your code, use the function: plot(*insert_graph_name*, variable_name);. This is a general format, and it is up to the user to replace 'insert_graph_name' with the actual graph name and 'variable_name' with the parameter to be displayed.

Software Support

Library Description

This library contains API for NB IoT 2 Click driver.

Key functions:

  • nbiot2_set_rst_pin_state - This function sets RST pin state

  • nbiot2_hw_reset - NB IoT 2 hardware reset function

  • nbiot2_send_cmd - NB IoT 2 send command function

Open Source

Code example

The complete application code and a ready-to-use project are available through the NECTO Studio Package Manager for direct installation in the NECTO Studio. The application code can also be found on the MIKROE GitHub account.

/*!
 * @file main.c
 * @brief NB IoT 2 Click Example.
 *
 * # Description
 * This example reads and processes data from NB IoT 2 clicks.
 *
 * The demo application is composed of two sections :
 *
 * ## Application Init
 * Initializes driver, wake-up module and sets default configuration 
 * for connecting device to network.
 *
 * ## Application Task
 * This application is split into two examples:
 * - TCP/UDP example - connecting to echo server and writing and reading data.
 * - SMS example - Sending SMS message to desired number using TEXT or PDU mode. 
 *
 * ## Additional Function
 * - static void nbiot2_clear_app_buf ( void )
 * - static err_t nbiot2_process ( void )
 * - static void nbiot2_config_device_for_example ( void )
 * - static void nbiot2_check_connection ( void )
 * - static void nbiot2_log_response ( void )
 * - static void nbiot2_error_check( err_t error_flag );
 * - static err_t nbiot2_check_response ( void )
 * - static void nbiot2_config_device_for_network ( void )
 * - static void nbiot2_send_sms ( void )
 * - static void nbiot2_config_device_for_tcp_udp ( void )
 * - static void nbiot2_tcp_udp_example ( void )
 *
 * @note
 * In order for the examples to work, user needs to set the APN and SMSC (SMS PDU mode only) 
 * of entered SIM card as well as the phone number to which he wants to send an SMS.
 * Enter valid values for the following macros: SIM_APN, SIM_SMSC and PHONE_NUMBER_TO_MESSAGE.
 * Example: 
    SIM_APN "internet"
    SIM_SMSC "+381610401"
    PHONE_NUMBER_TO_MESSAGE "+381659999999"
 * 
 * @author Stefan Ilic
 *
 */

#include "board.h"
#include "log.h"
#include "conversions.h"
#include "nbiot2.h"

// Example selection macros
#define NBIOT2_TCP_UDP_EXAMPLE
// #define NBIOT2_SMS_EXAMPLE

// SMS example selection macros
// #define SMS_PDU_MODE
#define SMS_TEXT_MODE

// SMS example parameters
#define PHONE_NUMBER_TO_MESSAGE             ""              // Set Phone number to message
#define SIM_SMSC                            ""              // Set SIM SMSC

// TCP/UDP example parameters
#define REMOTE_IP                           "77.46.162.162" // TCP/UDP echo server IP address
#define REMOTE_PORT                         "51111"         // TCP/UDP echo server port

// SIM APN config
#define SIM_APN                             ""
#define MESSAGE_CONTENT                     "NB IoT 2 Click Example"   // Message content

#define PROCESS_BUFFER_SIZE                 200

#define CONFIGURATION_FOR_EXAMPLE           0
#define EXAMPLE                             1

static nbiot2_t nbiot2;
static log_t logger;

static char app_buf[ PROCESS_BUFFER_SIZE ] = { 0 };
static int32_t app_buf_len = 0;
static int32_t app_buf_cnt = 0;

static err_t app_error_flag;

static uint8_t app_connection_status = CONFIGURATION_FOR_EXAMPLE;

/**
 * @brief NB IoT 2 clearing application buffer.
 * @details This function clears memory of application buffer and reset its length and counter.
 * @note None.
 */
static void nbiot2_clear_app_buf ( void );

/**
 * @brief NB IoT 2 data reading function.
 * @details This function reads data from device and concatenates data to application buffer.
 * @return @li @c  0 - Read some data.
 *         @li @c -1 - Nothing is read.
 *         @li @c -2 - Application buffer overflow.
 * See #err_t definition for detailed explanation.
 * @note None.
 */
static err_t nbiot2_process ( void );

/**
 * @brief Configure device for example.
 * @details Configure device for sending messages or sending messages to TCP/UDP Echo server.
 * @return Nothing.
 * @note None.
 */
static void nbiot2_config_device_for_example ( void );

/**
 * @brief Wait for connection signal.
 * @details Wait for connection signal from CREG URC.
 * @return Nothing.
 * @note None.
 */
static void nbiot2_check_connection ( void );

/**
 * @brief Logs application buffer.
 * @details This function logs data from application buffer.
 * @note None.
 */
static void nbiot2_log_response ( void );

/**
 * @brief Check for errors.
 * @details This function checks for different types of 
 * errors and logs them on UART or logs the response if no errors occured.
 * @note None.
 */
static void nbiot2_error_check( err_t error_flag );

/**
 * @brief NB IoT 2 response read function.
 * @details This function reads the response of the sent command and writes it on the USB UART.
 * @return @li @c  0 - Response OK.
 *         @li @c -1 - Response ERROR.
 * See #err_t definition for detailed explanation.
 * @note None.
 */
static err_t nbiot2_check_response ( void );

/**
 * @brief Configure device for connection to the network.
 * @details Sends commands to configure and enable connection to the specified network.
 * @return Nothing.
 * @note None.
 */
static void nbiot2_config_device_for_network ( void );

/**
 * @brief Check for connection to the network.
 * @details Sends commands to check connection to the specified network.
 * @return Nothing.
 * @note None.
 */
static void nbiot2_check_connection_to_network ( void );

/**
 * @brief Send SMS example.
 * @details Sends commands to send SMS messages in TEXT or PDU mode.
 * @return Nothing.
 * @note None.
 */
static void nbiot2_send_sms ( void );

/**
 * @brief Configure device for TCP/UDP example.
 * @details Sends commands to connect with TCP/UDP server.
 * @return Nothing.
 * @note None.
 */
static void nbiot2_config_device_for_tcp_udp ( void );

/**
 * @brief TCP/UDP example.
 * @details Sends message to TCP/UDP server and receives data from it.
 * @return Nothing.
 * @note None.
 */
static void nbiot2_tcp_udp_example ( void );

void application_init ( void ) 
{
    log_cfg_t log_cfg;  /**< Logger config object. */
    nbiot2_cfg_t nbiot2_cfg;  /**< Click config object. */

    /** 
     * Logger initialization.
     * Default baud rate: 115200
     * Default log level: LOG_LEVEL_DEBUG
     * @note If USB_UART_RX and USB_UART_TX 
     * are defined as HAL_PIN_NC, you will 
     * need to define them manually for log to work. 
     * See @b LOG_MAP_USB_UART macro definition for detailed explanation.
     */
    LOG_MAP_USB_UART( log_cfg );
    log_init( &logger, &log_cfg );
    log_info( &logger, " Application Init " );

    // Click initialization.
    nbiot2_cfg_setup( &nbiot2_cfg );
    NBIOT2_MAP_MIKROBUS( nbiot2_cfg, MIKROBUS_1 );
    if ( UART_ERROR == nbiot2_init( &nbiot2, &nbiot2_cfg ) ) 
    {
        log_error( &logger, " Communication init." );
        for ( ; ; );
    }
    
    log_printf( &logger, " - Reseting device... \r\n" );
    nbiot2_hw_reset( &nbiot2 );
    Delay_ms( 4000 );
    app_error_flag = nbiot2_process( );
    nbiot2_error_check( app_error_flag );
    
    nbiot2_send_cmd( &nbiot2, NBIOT2_CMD_AT );
    app_error_flag = nbiot2_check_response( );
    nbiot2_error_check( app_error_flag );
    
    nbiot2_send_cmd( &nbiot2, NBIOT2_CMD_ATI );
    app_error_flag = nbiot2_check_response( );
    nbiot2_error_check( app_error_flag );
    
    nbiot2_send_cmd_with_parameter( &nbiot2, NBIOT2_CMD_CFUN, "1" );
    app_error_flag = nbiot2_check_response( );
    nbiot2_error_check( app_error_flag );
    
    nbiot2_send_cmd_with_parameter( &nbiot2, NBIOT2_CMD_QSPCHSC, "1" );
    app_error_flag = nbiot2_check_response( );
    nbiot2_error_check( app_error_flag );
    
    nbiot2_send_cmd_with_parameter( &nbiot2, NBIOT2_CMD_CPSMS, "1" );
    app_error_flag = nbiot2_check_response( );
    nbiot2_error_check( app_error_flag );
    
    nbiot2_set_apn( &nbiot2, SIM_APN );
    app_error_flag = nbiot2_check_response( );
    nbiot2_error_check( app_error_flag );   
    
    nbiot2_send_cmd_with_parameter( &nbiot2, NBIOT2_CMD_QRST, "1" );
    Delay_ms( 2000 );
    app_error_flag = nbiot2_process( );
    nbiot2_error_check( app_error_flag );  
    
    nbiot2_send_cmd_with_parameter( &nbiot2, NBIOT2_CMD_QBAND, "1,20" );
    app_error_flag = nbiot2_check_response( );
    nbiot2_error_check( app_error_flag );      
    
    nbiot2_send_cmd_with_parameter( &nbiot2, NBIOT2_CMD_CEREG, "2" );
    app_error_flag = nbiot2_check_response( );
    nbiot2_error_check( app_error_flag );   
    
    nbiot2_send_cmd_with_parameter( &nbiot2, NBIOT2_CMD_CSCON, "1" );
    app_error_flag = nbiot2_check_response( );
    nbiot2_error_check( app_error_flag );  
    
    nbiot2_send_cmd_with_parameter( &nbiot2, NBIOT2_CMD_QNBIOTEVENT, "1,1" );
    app_error_flag = nbiot2_check_response( );
    nbiot2_error_check( app_error_flag );  
    
    nbiot2_send_cmd_with_parameter( &nbiot2, NBIOT2_CMD_SM, "LOCK" );
    app_error_flag = nbiot2_check_response( );
    nbiot2_error_check( app_error_flag );  
    
    nbiot2_send_cmd_with_parameter( &nbiot2, NBIOT2_CMD_QSCLK, "0" );
    app_error_flag = nbiot2_check_response( );
    nbiot2_error_check( app_error_flag );  
    
    log_info( &logger, " Application Task " );
    
    app_connection_status = CONFIGURATION_FOR_EXAMPLE;
    
    app_buf_len = 0;
    app_buf_cnt = 0;
}

void application_task ( void ) 
{   
    switch( app_connection_status )
    {
        case CONFIGURATION_FOR_EXAMPLE:
        {
            nbiot2_config_device_for_example( );
            break;
        }
        case EXAMPLE:
        {
            #if defined( NBIOT2_TCP_UDP_EXAMPLE )
                nbiot2_tcp_udp_example( );
            #endif   
            #if defined( NBIOT2_SMS_EXAMPLE )
                nbiot2_send_sms( );
                Delay_ms( 10000 );
            #endif
            break;
        }
        default:
        {
            log_error( &logger, "Application status error!" );
            app_connection_status = CONFIGURATION_FOR_EXAMPLE;
            Delay_ms( 1000 );
            break;
        }
    }
}

void main ( void ) 
{
    application_init( );

    for ( ; ; ) 
    {
        application_task( );
    }
}

static void nbiot2_clear_app_buf ( void ) 
{
    memset( app_buf, 0, app_buf_len );
    app_buf_len = 0;
    app_buf_cnt = 0;
}

static err_t nbiot2_process ( void ) 
{
    int32_t rx_size;
    char rx_buf[ PROCESS_BUFFER_SIZE ] = { 0 };
    rx_size = nbiot2_generic_read( &nbiot2, rx_buf, PROCESS_BUFFER_SIZE );
    if ( rx_size > 0 ) 
    {
        int32_t buf_cnt = 0;
        if ( ( app_buf_len + rx_size ) > PROCESS_BUFFER_SIZE ) 
        {
            nbiot2_clear_app_buf(  );
            return NBIOT2_ERROR;
        } 
        else 
        {
            buf_cnt = app_buf_len;
            app_buf_len += rx_size;
        }
        for ( int32_t rx_cnt = 0; rx_cnt < rx_size; rx_cnt++ ) 
        {
            if ( rx_buf[ rx_cnt ] != 0 ) 
            {
                app_buf[ ( buf_cnt + rx_cnt ) ] = rx_buf[ rx_cnt ];
            }
            else
            {
                app_buf_len--;
                buf_cnt--;
            }
        }
        return NBIOT2_OK;
    }
    return NBIOT2_ERROR;
}

static void nbiot2_config_device_for_example ( void )
{
#if defined( NBIOT2_TCP_UDP_EXAMPLE )
    nbiot2_config_device_for_tcp_udp( );
#endif
#if defined( NBIOT2_SMS_EXAMPLE )
    nbiot2_config_device_for_network( );
    for( ; ; )
    {
        nbiot2_check_connection_to_network( );
        if ( CONFIGURATION_FOR_EXAMPLE != app_connection_status )
        {
            break;
        }
    }
#endif 
}

static void nbiot2_check_connection( void )
{
    #define CONNECTED "+CGATT: 1"

    if ( strstr( app_buf, CONNECTED ) != 0 )
    {
        app_connection_status = EXAMPLE;
    }
}

static err_t nbiot2_check_response ( void )
{
    uint32_t timeout_cnt = 0;
    uint32_t timeout = 100000;
    err_t error_flag;
    while ( ( 0 == strstr( app_buf, NBIOT2_RSP_OK ) ) && 
            ( 0 == strstr( app_buf, NBIOT2_RSP_ERROR ) ) )
    {
        error_flag = nbiot2_process( );
        if ( ( NBIOT2_OK != error_flag ) && ( NBIOT2_ERROR != error_flag ) )
        {
            return error_flag;
        }
        if ( timeout_cnt++ > timeout )
        {
            nbiot2_clear_app_buf( );
            return NBIOT2_ERROR_TIMEOUT;
        }
        Delay_ms( 1 );
    }
    if ( strstr( app_buf, NBIOT2_RSP_OK ) )
    {
        return NBIOT2_OK;
    }
    else if ( strstr( app_buf, NBIOT2_RSP_ERROR ) )
    {
        return NBIOT2_ERROR;
    }
    else
    {
        return NBIOT2_ERROR;
    }
}

static void nbiot2_log_response ( void )
{    
    if ( app_buf_len > 0 ) 
    {
        log_printf( &logger, "%s", app_buf );
        nbiot2_check_connection();
    }
    log_printf( &logger, "-----------------------------------\r\n" );
}

static void nbiot2_error_check( err_t error_flag )
{
    switch ( error_flag )
    {
        case NBIOT2_OK:
        {
            nbiot2_log_response( );
            break;
        }
        case NBIOT2_ERROR:
        {
            log_error( &logger, " Overflow!" );
            break;
        }
        case NBIOT2_ERROR_TIMEOUT:
        {
            log_error( &logger, " Timeout!" );
            break;
        }
        
        default:
        {
            log_error( &logger, " Unknown!" );
            break;
        }
    }
    nbiot2_clear_app_buf(  );
    Delay_ms( 500 );
}

static void nbiot2_config_device_for_network( void )
{
    nbiot2_send_cmd( &nbiot2, NBIOT2_CMD_CIMI );
    app_error_flag = nbiot2_check_response( );
    nbiot2_error_check( app_error_flag );  

    nbiot2_set_apn( &nbiot2, SIM_APN );
    app_error_flag = nbiot2_check_response( );
    nbiot2_error_check( app_error_flag );  

    nbiot2_send_cmd_with_parameter( &nbiot2, NBIOT2_CMD_CREG, "2" );
    app_error_flag = nbiot2_check_response( );
    nbiot2_error_check( app_error_flag );  
}

static void nbiot2_check_connection_to_network( void )
{
    nbiot2_send_cmd_check( &nbiot2, NBIOT2_CMD_CGATT );
    app_error_flag = nbiot2_check_response( );
    nbiot2_error_check( app_error_flag );  

    nbiot2_send_cmd_check( &nbiot2, NBIOT2_CMD_CEREG );
    app_error_flag = nbiot2_check_response( );
    nbiot2_error_check( app_error_flag );  

    nbiot2_send_cmd_check( &nbiot2, NBIOT2_CMD_COPS );
    app_error_flag = nbiot2_check_response( );
    nbiot2_error_check( app_error_flag );  

    if ( CONFIGURATION_FOR_EXAMPLE != app_connection_status )
    {
        log_info( &logger, "CONNECTED TO NETWORK" );
    }
}

static void nbiot2_send_sms ( void )
{
#if defined( SMS_TEXT_MODE )
    nbiot2_send_cmd_with_parameter( &nbiot2, NBIOT2_CMD_CMGF, "1" );
    app_error_flag = nbiot2_check_response( );
    nbiot2_error_check( app_error_flag );  

    log_printf( &logger, "> Sending message to phone number...\r\n" );
    nbiot2_send_sms_text_mode( &nbiot2, PHONE_NUMBER_TO_MESSAGE, MESSAGE_CONTENT );
    app_error_flag = nbiot2_check_response( );
    nbiot2_error_check( app_error_flag );  
    if ( NBIOT2_OK != app_error_flag )
    {
        log_printf( &logger, "> Message sent...\r\n" );
        Delay_ms( 10000 );
    }
#elif defined( SMS_PDU_MODE )
    nbiot2_send_cmd_with_parameter( &nbiot2, NBIOT2_CMD_CMGF, "0" );
    app_error_flag = nbiot2_check_response( );
    nbiot2_error_check( app_error_flag );  
    
    nbiot2_send_sms_pdu ( &nbiot2, SIM_SMSC, PHONE_NUMBER_TO_MESSAGE, MESSAGE_CONTENT );
    app_error_flag = nbiot2_check_response( );
    nbiot2_error_check( app_error_flag );  
    if ( NBIOT2_OK != app_error_flag )
    {
        log_printf( &logger, "> Message sent...\r\n" );
        Delay_ms( 10000 );
    }
#endif
}

static void nbiot2_config_device_for_tcp_udp ( void )
{
    nbiot2_send_cmd_with_parameter( &nbiot2, NBIOT2_CMD_CGATT, "1" );
    app_error_flag = nbiot2_check_response( );
    nbiot2_error_check( app_error_flag );  
    
    if ( NBIOT2_OK == app_error_flag )
    {
        app_connection_status = EXAMPLE;
    }
}

static void nbiot2_tcp_udp_example ( void )
{
    #define CONTEXTID       "1"
    #define TCP_PROTOCOL    "0"
    #define UDP_PROTOCOL    "1"
    #define URC_READ_SOCKET_DATA "+QIURC: \"recv\""
    
    char cmd_buf[ 100 ] = { 0 };
    uint16_t timeout_cnt = 0;
    uint16_t timeout = 30000;
    
    // Get message length
    uint8_t message_len_buf[ 5 ] = { 0 };
    uint16_t message_len = strlen( MESSAGE_CONTENT );
    uint16_to_str( message_len, message_len_buf );
    l_trim( message_len_buf );
    r_trim( message_len_buf );
    
    // Create TCP socket
    strcpy( cmd_buf, CONTEXTID );
    strcat( cmd_buf, "," );
    strcat( cmd_buf, TCP_PROTOCOL );
    strcat( cmd_buf, ",\"" );
    strcat( cmd_buf, "TCP" );
    strcat( cmd_buf, "\"" );
    strcat( cmd_buf, "," );
    strcat( cmd_buf, REMOTE_IP );
    strcat( cmd_buf, "," ); 
    strcat( cmd_buf, REMOTE_PORT ); 
    
    nbiot2_send_cmd_with_parameter( &nbiot2, NBIOT2_CMD_QIOPEN, cmd_buf );
    app_error_flag = nbiot2_check_response( );
    nbiot2_error_check( app_error_flag );  
    Delay_ms( 2000 );
    
    if ( NBIOT2_OK == app_error_flag )
    {
        log_info( &logger, "SENDING MESSAGES TO TCP" );
        // Write message to TCP socket
        strcpy( cmd_buf, TCP_PROTOCOL );
        strcat( cmd_buf, "," );
        strcat( cmd_buf, message_len_buf );
        strcat( cmd_buf, ",\"" );
        strcat( cmd_buf, MESSAGE_CONTENT );
        strcat( cmd_buf, "\"" );
        nbiot2_send_cmd_with_parameter( &nbiot2, NBIOT2_CMD_QISEND, cmd_buf );
    
        // Read response message from TCP socket
        for ( ; ; )
        {
            nbiot2_process( );
            uint8_t * __generic_ptr start_response_buf = strstr( app_buf, URC_READ_SOCKET_DATA );
            if ( start_response_buf )
            {
                log_info( &logger, "RECEIVED MESSAGE" );
                strcpy( cmd_buf, TCP_PROTOCOL );
                strcat( cmd_buf, "," );
                strcat( cmd_buf, "256" );
                nbiot2_clear_app_buf( );
                nbiot2_send_cmd_with_parameter( &nbiot2, NBIOT2_CMD_QIRD, cmd_buf );
                app_error_flag = nbiot2_check_response( );
                nbiot2_error_check( app_error_flag );  
            
                if ( NBIOT2_OK == app_error_flag )
                {
                    break;
                }
            }
            if ( timeout_cnt++ > timeout )
            {
                log_error( &logger, "TIMEOUT!!!" );
                break;
            }   
            Delay_ms( 1 );
        }
        timeout_cnt = 0;
        Delay_ms( 2000 );
        
        // Close TCP socket
        nbiot2_send_cmd_with_parameter( &nbiot2, NBIOT2_CMD_QICLOSE, TCP_PROTOCOL );
        app_error_flag = nbiot2_check_response( );
        nbiot2_error_check( app_error_flag );  
    }
    else
    {
        log_error( &logger, "Not connected to the TCP server" );
    }
    
    // Create UDP socket
    strcpy( cmd_buf, CONTEXTID );
    strcat( cmd_buf, "," );
    strcat( cmd_buf, UDP_PROTOCOL );
    strcat( cmd_buf, ",\"" );
    strcat( cmd_buf, "UDP" );
    strcat( cmd_buf, "\"" );
    strcat( cmd_buf, "," );
    strcat( cmd_buf, REMOTE_IP );
    strcat( cmd_buf, "," ); 
    strcat( cmd_buf, REMOTE_PORT ); 
    
    nbiot2_send_cmd_with_parameter( &nbiot2, NBIOT2_CMD_QIOPEN, cmd_buf );
    app_error_flag = nbiot2_check_response( );
    nbiot2_error_check( app_error_flag );  
    Delay_ms( 2000 );
    
    if ( NBIOT2_OK == app_error_flag )
    {
        log_info( &logger, "SENDING MESSAGES TO UDP" );
        // Write message to UDP socket
        strcpy( cmd_buf, UDP_PROTOCOL );
        strcat( cmd_buf, "," );
        strcat( cmd_buf, message_len_buf );
        strcat( cmd_buf, ",\"" );
        strcat( cmd_buf, MESSAGE_CONTENT );
        strcat( cmd_buf, "\"" );
        nbiot2_send_cmd_with_parameter( &nbiot2, NBIOT2_CMD_QISEND, cmd_buf );
    
        // Read response message from UDP socket
        for ( ; ; )
        {
            nbiot2_process( );
            uint8_t * __generic_ptr start_response_buf = strstr( app_buf, URC_READ_SOCKET_DATA );
            if ( start_response_buf )
            {
                log_info( &logger, "RECEIVED MESSAGE" );
                strcpy( cmd_buf, UDP_PROTOCOL );
                strcat( cmd_buf, "," );
                strcat( cmd_buf, "256" );
                nbiot2_clear_app_buf( );
                nbiot2_send_cmd_with_parameter( &nbiot2, NBIOT2_CMD_QIRD, cmd_buf );
                app_error_flag = nbiot2_check_response( );
                nbiot2_error_check( app_error_flag );  
            
                if ( NBIOT2_OK == app_error_flag )
                {
                    break;
                }
            }
            if ( timeout_cnt++ > timeout )
            {
                log_error( &logger, "TIMEOUT!!!" );
                break;
            }   
            Delay_ms( 1 );
        }
        timeout_cnt = 0;
        Delay_ms( 2000 );
        
        // Close UDP socket
        nbiot2_send_cmd_with_parameter( &nbiot2, NBIOT2_CMD_QICLOSE, UDP_PROTOCOL );
        app_error_flag = nbiot2_check_response( );
        nbiot2_error_check( app_error_flag );  
    }
    else
    {
        log_error( &logger, "Not connected to the UDP server" );
    }
    
    Delay_ms( 5000 );
}




// ------------------------------------------------------------------------ END

Additional Support

Resources

Love this project?

'Buy This Kit' button takes you directly to the shopping cart where you can easily add or remove products.