Beginner
10 min

Attain global connection and precise location tracking with LENA-R8 and PIC18F57Q43

For developers targeting the tracking and telematics sectors

4G LTE&GNSS Click with Curiosity Nano with PIC18F57Q43

Published Apr 01, 2024

Click board™

4G LTE&GNSS Click

Development board

Curiosity Nano with PIC18F57Q43

Compiler

NECTO Studio

MCU

PIC18F57Q43

Achieve universal connectivity and precise global tracking capabilities, thanks to LENA-R8's support for 14 LTE bands, four GSM/GPRS bands, and integrated u-blox GNSS technology

A

A

Hardware Overview

How does it work?

4G LTE&GNSS Click is based on the LENA-R8 (LENA-R8001M10-00C), a multi-mode LTE Cat 1bis module with wide network support from u-blox. This cellular module has 14 LTE bands and four GSM/GPRS bands, delivering universal network connectivity and comprehensive global coverage. Its integrated u-blox GNSS functionality positions it as a premier choice for global tracking and telematics applications, where precision and reliability are paramount. The LENA-R8's capability to support connectivity and location services natively simplifies the deployment of devices in cloud-based ecosystems, offering streamlined solutions for Connectivity as a Service (CaaS) and Location as a Service (LaaS). This makes it an invaluable component for developers seeking to create smaller, more efficient solutions without compromising GNSS performance or global accessibility. Beyond its global LTE Cat 1bis connectivity, the LENA-R8 excels in facilitating a wide array of IoT applications, particularly in the tracking and telematics domains. Its compatibility with a broad spectrum of LTE and 2G bands ensures optimal roaming coverage across different geographical regions, enabling the creation of IoT devices that are truly global with a single product SKU. The module's high level of integration includes support for MQTT Anywhere services on the Thingstream platform, enhancing its utility for seamless global roaming. It also boasts concurrent reception capabilities for up to four GNSS (GPS, GLONASS, Galileo, and BeiDou), with GPS and Galileo being the default configuration. This multifunctionality, combined with dedicated interfaces for the cellular modem and GNSS subsystems, allows for independent operation and flexible usage, optimizing performance and power efficiency. The LENA-R8's support for CellLocate, a network-based location service, further underscores its versatility and suitability for a wide range of high-performance, location-dependent applications. The LENA-R8 communicates with the host MCU using the UART interface with commonly

used UART RX and TX pins with the hardware flow control pins UART CTS, RTS, RI (Clear to Send, Ready to Send, and Ring Indicator). It operates at 115200 bps by default configuration to transmit and exchange data with the host MCU. Besides UART pins, this Click board™ also uses an RST pin as an abrupt hardware reset of LENA-R8. This reset is performed without storing the current parameter settings, and a clean network detach. The LENA-R8 also includes a USB High-Speed 2.0 compliant interface with a maximum 480 Mbit/s data rate. The module itself acts as a USB device and can be connected to any compatible USB host. The interface is available for communication with the external host application processor (AT commands, data, FW update by means of FOAT), FW update by means of a dedicated tool, and diagnostics. In addition, on the back side of the board, there is a USB BOOT jumper that allows you to select the Boot mode. By placing it at position 1, the FW update by the dedicated tool over the USB interface is enabled, and at position 0 for boot in normal operating mode. In addition to its integrated Power (PWR) button for manual activation, the LENA-R8 module can be powered through an external PWR pin. Furthermore, the module has two distinct LED indicators to convey critical operational status information visually. The yellow LED, labeled NI, serves as a network status indicator, offering immediate feedback on the module's connectivity status within a network. This is crucial for troubleshooting and confirming successful network integration. Similarly, the red LED, labeled TP, acts as a time pulse indicator, emitting a precise signal to denote time synchronization events. This is especially beneficial for applications requiring high timing accuracy, such as time-sensitive data collection or GPS-based positioning. The board features u.Fl connectors for LTE and GNSS antennas, accommodating accessories like the LTE Flat Rotation Antenna and the GNSS Active External Antenna, in combination with an IPEX-SMA cable

for flexible and efficient connectivity options. This setup ensures optimal signal strength and quality for local and satellite communications. Notably, the GNSS antenna connection includes a power selection feature, allowing users to adjust the antenna's power supply according to specific requirements, enhancing the precision and reliability of satellite navigation. Additionally, the board is equipped with a nano SIM card holder that supports both 1.8V and 3.0V SIM cards, ensuring compatibility with a wide range of cellular networks and allowing users to select the most appropriate service provider for their particular use case. This Click board™ also uses the TPS7A7002, a Low-Dropout Regulator (LDO) from Texas Instruments, to generate the required 3.8V power supply necessary for the module's optimal operation. This power is derived from the 5V mikroBUS™ power rail or a USB connection if available, ensuring versatility in power sourcing. The board has several test points for further diagnostics and operational adjustments. TP1 is dedicated to diagnosing the module's internal conditions, providing a typical output of 1.8V when the cellular component of the module is activated. This allows for real-time monitoring of the module's power state. TP2 presents the same function as the PWR pin, TP3 as Reset, and TP4 as USB Boot. TP5 and TP6 connect the GNSS UART, enabling serial communication between the internal u-blox M10 GNSS chipset and an external host. This feature allows for direct data exchange and configuration between the GNSS module and the host device, enhancing the module's functionality and flexibility in GNSS applications. This Click board™ can operate with either 3.3V or 5V logic voltage levels selected via the VCC SEL jumper. This way, both 3.3V and 5V capable MCUs can use the communication lines properly. Also, this Click board™ comes equipped with a library containing easy-to-use functions and an example code that can be used as a reference for further development.

4G LTE&GNSS Click hardware overview image

Features overview

Development board

PIC18F57Q43 Curiosity Nano evaluation kit is a cutting-edge hardware platform designed to evaluate microcontrollers within the PIC18-Q43 family. Central to its design is the inclusion of the powerful PIC18F57Q43 microcontroller (MCU), offering advanced functionalities and robust performance. Key features of this evaluation kit include a yellow user LED and a responsive

mechanical user switch, providing seamless interaction and testing. The provision for a 32.768kHz crystal footprint ensures precision timing capabilities. With an onboard debugger boasting a green power and status LED, programming and debugging become intuitive and efficient. Further enhancing its utility is the Virtual serial port (CDC) and a debug GPIO channel (DGI

GPIO), offering extensive connectivity options. Powered via USB, this kit boasts an adjustable target voltage feature facilitated by the MIC5353 LDO regulator, ensuring stable operation with an output voltage ranging from 1.8V to 5.1V, with a maximum output current of 500mA, subject to ambient temperature and voltage constraints.

PIC18F57Q43 Curiosity Nano double side image

Microcontroller Overview

MCU Card / MCU

default

Architecture

PIC

MCU Memory (KB)

128

Silicon Vendor

Microchip

Pin count

48

RAM (Bytes)

8196

You complete me!

Accessories

Curiosity Nano Base for Click boards is a versatile hardware extension platform created to streamline the integration between Curiosity Nano kits and extension boards, tailored explicitly for the mikroBUS™-standardized Click boards and Xplained Pro extension boards. This innovative base board (shield) offers seamless connectivity and expansion possibilities, simplifying experimentation and development. Key features include USB power compatibility from the Curiosity Nano kit, alongside an alternative external power input option for enhanced flexibility. The onboard Li-Ion/LiPo charger and management circuit ensure smooth operation for battery-powered applications, simplifying usage and management. Moreover, the base incorporates a fixed 3.3V PSU dedicated to target and mikroBUS™ power rails, alongside a fixed 5.0V boost converter catering to 5V power rails of mikroBUS™ sockets, providing stable power delivery for various connected devices.

Curiosity Nano Base for Click boards 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.

4G LTE&GNSS Click accessories 1 image

GNSS Active External Antenna is a unique multi-band type of antenna coming from u-blox that is the perfect selection for high precision GNSS applications, which require highly accurate location abilities such as RTK. The ANN-MB-00 is a multi-band (L1, L2/E5b/B2I) active GNSS antenna with a 5m cable and SMA connector. The antenna supports GPS, GLONASS, Galileo, and BeiDou and includes a high-performance multi-band RHCP dual-feed patch antenna element, a built-in high-gain LNA with SAW pre-filtering, and a 5 m antenna cable with SMA connector, and is waterproof.

4G LTE&GNSS Click accessories 2 image

IPEX-SMA cable is a type of RF (radio frequency) cable assembly. "IPEX" refers to the IPEX connector, a miniature coaxial connector commonly used in small electronic devices. "SMA" stands for SubMiniature Version A and is another coaxial connector commonly used in RF applications. An IPEX-SMA cable assembly has an IPEX connector on one end and an SMA connector on the other, allowing it to connect devices or components that use these specific connectors. These cables are often used in applications like WiFi or cellular antennas, GPS modules, and other RF communication systems where a reliable and low-loss connection is required.

4G LTE&GNSS Click accessories 3 image

Used MCU Pins

mikroBUS™ mapper

Module Power-ON
PA0
AN
Reset / ID SEL
PA7
RST
UART RTS / ID COMM
PD4
CS
NC
NC
SCK
NC
NC
MISO
NC
NC
MOSI
Power Supply
3.3V
3.3V
Ground
GND
GND
Ring Indicator
PB0
PWM
UART CTS
PA6
INT
UART TX
PC2
TX
UART RX
PC3
RX
NC
NC
SCL
NC
NC
SDA
Power Supply
5V
5V
Ground
GND
GND
1

Take a closer look

Schematic

4G LTE&GNSS Click Schematic schematic

Step by step

Project assembly

Curiosity Nano Base for Click boards front image hardware assembly

Start by selecting your development board and Click board™. Begin with the Curiosity Nano with PIC18F57Q43 as your development board.

Curiosity Nano Base for Click boards front image hardware assembly
Charger 27 Click front image hardware assembly
PIC18F47Q10 Curiosity Nano front image hardware assembly
Prog-cut hardware assembly
Charger 27 Click complete accessories setup image hardware assembly
Curiosity Nano with PICXXX Access MB 1 - 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
PIC18F57Q43 Curiosity 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

After loading the code example, pressing the "DEBUG" button builds and programs it on the selected setup.

Application Output Step 1

After programming is completed, a header with buttons for various actions available in the IDE appears. By clicking the green "PLAY "button, we start reading the results achieved with Click board™.

Application Output Step 3

Upon completion of programming, the Application Output tab is automatically opened, where the achieved result can be read. In case of an inability to perform the Debug function, check if a proper connection between the MCU used by the setup and the CODEGRIP programmer has been established. A detailed explanation of the CODEGRIP-board connection can be found in the CODEGRIP User Manual. Please find it in the RESOURCES section.

Application Output Step 4

Software Support

Library Description

This library contains API for 4G LTE&GNSS Click driver.

Key functions:

  • c4gltegnss_set_sim_apn - This function sets APN for sim card

  • c4gltegnss_send_sms_text - This function sends text message to a phone number

  • c4gltegnss_parse_gga - This function parses the GGA data from the read response buffer

Open Source

Code example

This example can be found in NECTO Studio. Feel free to download the code, or you can copy the code below.

/*!
 * @file main.c
 * @brief 4G LTE GNSS Click Example.
 *
 * # Description
 * Application example shows device capability of connecting to the network and
 * sending SMS or TCP/UDP messages, or retrieving data from GNSS using standard "AT" commands.
 *
 * The demo application is composed of two sections :
 *
 * ## Application Init
 * Initializes the driver, restarts the device, and after that tests the communication by sending "AT" command.
 *
 * ## Application Task
 * Application task is split in few stages:
 *  - C4GLTEGNSS_CONFIGURE_FOR_NETWORK:
 * Sets configuration to device to be able to connect to the network (used only for SMS or TCP/UDP demo examples).
 *
 *  - C4GLTEGNSS_WAIT_FOR_CONNECTION:
 * Waits for the network registration indicated via CREG URC event and then checks
 * the connection status (used only for SMS or TCP/UDP demo examples).
 *
 *  - C4GLTEGNSS_CONFIGURE_FOR_EXAMPLE:
 * Sets the device configuration for sending SMS or TCP/UDP messages or for retrieving data from GNSS 
 * depending on the selected demo example.
 *
 *  - C4GLTEGNSS_EXAMPLE:
 * Depending on the selected demo example, it sends an SMS message (in PDU or TXT mode) or TCP/UDP message or 
 * waits for the GPS fix to retrieve location info from GNSS.
 *
 * By default, the TCP/UDP example is selected.
 *
 * ## Additional Function
 * - static void c4gltegnss_clear_app_buf ( void )
 * - static void c4gltegnss_log_app_buf ( void )
 * - static err_t c4gltegnss_process ( void )
 * - static void c4gltegnss_error_check ( err_t error_flag )
 * - static err_t c4gltegnss_rsp_check ( uint8_t *rsp )
 * - static err_t c4gltegnss_config_for_network ( void )
 * - static err_t c4gltegnss_check_connection ( void )
 * - static err_t c4gltegnss_config_for_example ( void )
 * - static err_t c4gltegnss_example ( void )
 *
 * @note
 * In order for the examples to work (except GNSS example), user needs to set the APN and SMSC (SMS PDU mode only)
 * of entered SIM card as well as the phone number (SMS mode only) 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 Filipovic
 *
 */

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

// Example selection macros
#define EXAMPLE_TCP_UDP                     0               // Example of sending messages to a TCP/UDP echo server
#define EXAMPLE_SMS                         1               // Example of sending SMS to a phone number
#define EXAMPLE_GNSS                        2               // Example of retrieving location info from GNSS
#define DEMO_EXAMPLE                        EXAMPLE_TCP_UDP // Example selection macro

// SIM APN config
#define SIM_APN                             "internet"      // Set valid SIM APN

// SMS example parameters
#define SIM_SMSC                            ""              // Set valid SMS Service Center Address - only in SMS PDU mode
#define PHONE_NUMBER_TO_MESSAGE             ""              // Set Phone number to message
#define SMS_MODE                            "1"             // SMS mode: "0" - PDU, "1" - TXT

// 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

// Message content
#define MESSAGE_CONTENT                     "4G LTE GNSS click board - demo example."

// Application buffer size
#define APP_BUFFER_SIZE                     256
#define PROCESS_BUFFER_SIZE                 256

/**
 * @brief Example states.
 * @details Predefined enum values for application example state.
 */
typedef enum
{
    C4GLTEGNSS_CONFIGURE_FOR_NETWORK = 1,
    C4GLTEGNSS_WAIT_FOR_CONNECTION,
    C4GLTEGNSS_CONFIGURE_FOR_EXAMPLE,
    C4GLTEGNSS_EXAMPLE

} c4gltegnss_example_state_t;

static c4gltegnss_t c4gltegnss;
static log_t logger;

/**
 * @brief Application example variables.
 * @details Variables used in application example.
 */
static uint8_t app_buf[ APP_BUFFER_SIZE ] = { 0 };
static int32_t app_buf_len = 0;
static err_t error_flag = C4GLTEGNSS_OK;
static c4gltegnss_example_state_t example_state;

/**
 * @brief 4G LTE GNSS clearing application buffer.
 * @details This function clears memory of application buffer and reset its length.
 * @note None.
 */
static void c4gltegnss_clear_app_buf ( void );

/**
 * @brief 4G LTE GNSS log application buffer.
 * @details This function logs data from application buffer to USB UART.
 * @note None.
 */
static void c4gltegnss_log_app_buf ( void );

/**
 * @brief 4G LTE GNSS 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.
 * See #err_t definition for detailed explanation.
 * @note None.
 */
static err_t c4gltegnss_process ( 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.
 * @param[in] error_flag  Error flag to check.
 */
static void c4gltegnss_error_check ( err_t error_flag );

/**
 * @brief Response check.
 * @details This function checks for response and
 * returns the status of response.
 * @param[in] rsp  Expected response.
 * @return @li @c  0 - OK response.
 *         @li @c -2 - Timeout error.
 *         @li @c -3 - Command error.
 *         @li @c -4 - Unknown error.
 * See #err_t definition for detailed explanation.
 */
static err_t c4gltegnss_rsp_check ( uint8_t *rsp );

/**
 * @brief Configure device for connection to the network.
 * @details Sends commands to configure and enable
 * connection to the specified network.
 * @return @li @c  0 - OK response.
 *         @li @c -2 - Timeout error.
 *         @li @c -3 - Command error.
 *         @li @c -4 - Unknown error.
 * See #err_t definition for detailed explanation.
 */
static err_t c4gltegnss_config_for_network ( void );

/**
 * @brief Wait for connection signal.
 * @details Wait for connection signal from CREG URC.
 * @return @li @c  0 - OK response.
 *         @li @c -2 - Timeout error.
 *         @li @c -3 - Command error.
 *         @li @c -4 - Unknown error.
 * See #err_t definition for detailed explanation.
 */
static err_t c4gltegnss_check_connection ( void );

/**
 * @brief Configure device for example.
 * @details Configure device for the specified example.
 * @return @li @c  0 - OK response.
 *         @li @c -2 - Timeout error.
 *         @li @c -3 - Command error.
 *         @li @c -4 - Unknown error.
 * See #err_t definition for detailed explanation.
 */
static err_t c4gltegnss_config_for_example ( void );

/**
 * @brief Execute example.
 * @details This function executes SMS, TCP/UDP or GNSS example depending on the DEMO_EXAMPLE macro.
 * @return @li @c  0 - OK response.
 *         @li @c -2 - Timeout error.
 *         @li @c -3 - Command error.
 *         @li @c -4 - Unknown error.
 * See #err_t definition for detailed explanation.
 */
static err_t c4gltegnss_example ( void );

void application_init ( void ) 
{
    log_cfg_t log_cfg;  /**< Logger config object. */
    c4gltegnss_cfg_t c4gltegnss_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.
    c4gltegnss_cfg_setup( &c4gltegnss_cfg );
    C4GLTEGNSS_MAP_MIKROBUS( c4gltegnss_cfg, MIKROBUS_1 );
    if ( UART_ERROR == c4gltegnss_init( &c4gltegnss, &c4gltegnss_cfg ) ) 
    {
        log_error( &logger, " Communication init." );
        for ( ; ; );
    }
    // Power cycle device
    c4gltegnss_set_power_state ( &c4gltegnss, C4GLTEGNSS_POWER_STATE_OFF );
    c4gltegnss_set_power_state ( &c4gltegnss, C4GLTEGNSS_POWER_STATE_ON );
    
    // Dummy write to activate AT commands interface
    c4gltegnss_send_cmd( &c4gltegnss, C4GLTEGNSS_CMD_AT );
    c4gltegnss_process( );
    c4gltegnss_clear_app_buf( );
    
    // Check communication
    c4gltegnss_send_cmd( &c4gltegnss, C4GLTEGNSS_CMD_AT );
    error_flag = c4gltegnss_rsp_check( C4GLTEGNSS_RSP_OK );
    c4gltegnss_error_check( error_flag );
    
    log_info( &logger, " Application Task " );
    example_state = C4GLTEGNSS_CONFIGURE_FOR_NETWORK;
}

void application_task ( void ) 
{
    switch ( example_state )
    {
        case C4GLTEGNSS_CONFIGURE_FOR_NETWORK:
        {
            if ( C4GLTEGNSS_OK == c4gltegnss_config_for_network( ) )
            {
                example_state = C4GLTEGNSS_WAIT_FOR_CONNECTION;
            }
            break;
        }
        case C4GLTEGNSS_WAIT_FOR_CONNECTION:
        {
            if ( C4GLTEGNSS_OK == c4gltegnss_check_connection( ) )
            {
                example_state = C4GLTEGNSS_CONFIGURE_FOR_EXAMPLE;
            }
            break;
        }
        case C4GLTEGNSS_CONFIGURE_FOR_EXAMPLE:
        {
            if ( C4GLTEGNSS_OK == c4gltegnss_config_for_example( ) )
            {
                example_state = C4GLTEGNSS_EXAMPLE;
            }
            break;
        }
        case C4GLTEGNSS_EXAMPLE:
        {
            c4gltegnss_example( );
            break;
        }
        default:
        {
            log_error( &logger, " Example state." );
            break;
        }
    }
}

void main ( void ) 
{
    application_init( );

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

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

static void c4gltegnss_log_app_buf ( void )
{
    for ( int32_t buf_cnt = 0; buf_cnt < app_buf_len; buf_cnt++ )
    {
        log_printf( &logger, "%c", app_buf[ buf_cnt ] );
    }
}

static err_t c4gltegnss_process ( void ) 
{
    uint8_t rx_buf[ PROCESS_BUFFER_SIZE ] = { 0 };
    int32_t overflow_bytes = 0;
    int32_t rx_cnt = 0;
    int32_t rx_size = c4gltegnss_generic_read( &c4gltegnss, rx_buf, PROCESS_BUFFER_SIZE );
    if ( ( rx_size > 0 ) && ( rx_size <= APP_BUFFER_SIZE ) ) 
    {
        if ( ( app_buf_len + rx_size ) > APP_BUFFER_SIZE ) 
        {
            overflow_bytes = ( app_buf_len + rx_size ) - APP_BUFFER_SIZE;
            app_buf_len = APP_BUFFER_SIZE - rx_size;
            memmove ( app_buf, &app_buf[ overflow_bytes ], app_buf_len );
            memset ( &app_buf[ app_buf_len ], 0, overflow_bytes );
        }
        for ( rx_cnt = 0; rx_cnt < rx_size; rx_cnt++ ) 
        {
            if ( rx_buf[ rx_cnt ] ) 
            {
                app_buf[ app_buf_len++ ] = rx_buf[ rx_cnt ];
            }
        }
        return C4GLTEGNSS_OK;
    }
    return C4GLTEGNSS_ERROR;
}

static err_t c4gltegnss_rsp_check ( uint8_t *rsp )
{
    uint32_t timeout_cnt = 0;
    uint32_t timeout = 120000;
    c4gltegnss_clear_app_buf( );
    c4gltegnss_process( );
    while ( ( 0 == strstr( app_buf, rsp ) ) &&
            ( 0 == strstr( app_buf, C4GLTEGNSS_RSP_ERROR ) ) )
    {
        c4gltegnss_process( );
        if ( timeout_cnt++ > timeout )
        {
            c4gltegnss_clear_app_buf( );
            return C4GLTEGNSS_ERROR_TIMEOUT;
        }
        Delay_ms( 1 );
    }
    Delay_ms( 100 );
    c4gltegnss_process( );
    if ( strstr( app_buf, rsp ) )
    {
        return C4GLTEGNSS_OK;
    }
    else if ( strstr( app_buf, C4GLTEGNSS_RSP_ERROR ) )
    {
        return C4GLTEGNSS_ERROR_CMD;
    }
    else
    {
        return C4GLTEGNSS_ERROR_UNKNOWN;
    }
}

static void c4gltegnss_error_check ( err_t error_flag )
{
    switch ( error_flag )
    {
        case C4GLTEGNSS_OK:
        {
            c4gltegnss_log_app_buf( );
            break;
        }
        case C4GLTEGNSS_ERROR:
        {
            log_error( &logger, " Overflow!" );
            break;
        }
        case C4GLTEGNSS_ERROR_TIMEOUT:
        {
            log_error( &logger, " Timeout!" );
            break;
        }
        case C4GLTEGNSS_ERROR_CMD:
        {
            log_error( &logger, " CMD!" );
            break;
        }
        case C4GLTEGNSS_ERROR_UNKNOWN:
        default:
        {
            log_error( &logger, " Unknown!" );
            break;
        }
    }
    Delay_ms( 500 );
}

static err_t c4gltegnss_config_for_network ( void )
{
    err_t func_error = C4GLTEGNSS_OK;
#if ( ( DEMO_EXAMPLE == EXAMPLE_TCP_UDP ) || ( DEMO_EXAMPLE == EXAMPLE_SMS ) )
    // Set SIM APN
    c4gltegnss_set_sim_apn( &c4gltegnss, SIM_APN );
    error_flag = c4gltegnss_rsp_check( C4GLTEGNSS_RSP_OK );
    func_error |= error_flag;
    c4gltegnss_error_check( error_flag );

    // Enable full functionality
    #define FULL_FUNCTIONALITY "1"
    c4gltegnss_send_cmd_with_par( &c4gltegnss, C4GLTEGNSS_CMD_CFUN, FULL_FUNCTIONALITY );
    error_flag = c4gltegnss_rsp_check( C4GLTEGNSS_RSP_OK );
    func_error |= error_flag;
    c4gltegnss_error_check( error_flag );

    // Enable network registartion
    #define ENABLE_REG "2"
    c4gltegnss_send_cmd_with_par( &c4gltegnss, C4GLTEGNSS_CMD_CREG, ENABLE_REG );
    error_flag = c4gltegnss_rsp_check( C4GLTEGNSS_RSP_OK );
    func_error |= error_flag;
    c4gltegnss_error_check( error_flag );
    
    // Automatic registration
    #define AUTOMATIC_REGISTRATION "0"
    c4gltegnss_send_cmd_with_par( &c4gltegnss, C4GLTEGNSS_CMD_COPS, AUTOMATIC_REGISTRATION );
    error_flag = c4gltegnss_rsp_check( C4GLTEGNSS_RSP_OK );
    func_error |= error_flag;
#endif
    return func_error;
}

static err_t c4gltegnss_check_connection ( void )
{
#if ( ( DEMO_EXAMPLE == EXAMPLE_TCP_UDP ) || ( DEMO_EXAMPLE == EXAMPLE_SMS ) )
    #define CONNECTED "+CREG: 1"
    c4gltegnss_process( );
    if ( strstr( app_buf, CONNECTED ) )
    {
        Delay_ms( 100 );
        c4gltegnss_process( );
        c4gltegnss_log_app_buf( );
        log_printf( &logger, "\r\n" );
        c4gltegnss_clear_app_buf( );
        // Check signal quality
        c4gltegnss_send_cmd( &c4gltegnss, C4GLTEGNSS_CMD_CSQ );
        error_flag = c4gltegnss_rsp_check( C4GLTEGNSS_RSP_OK );
        c4gltegnss_error_check( error_flag );
        return error_flag;
    }
    return C4GLTEGNSS_ERROR;
#endif
    return C4GLTEGNSS_OK;
}

static err_t c4gltegnss_config_for_example( void )
{
    err_t func_error = C4GLTEGNSS_OK;
#if ( DEMO_EXAMPLE == EXAMPLE_TCP_UDP )
    #define ACTIVATE_PDP_CONTEXT "1,1"
    c4gltegnss_send_cmd_with_par( &c4gltegnss, C4GLTEGNSS_CMD_CGACT, ACTIVATE_PDP_CONTEXT );
    error_flag = c4gltegnss_rsp_check( C4GLTEGNSS_RSP_OK );
    func_error |= error_flag;
    c4gltegnss_error_check( error_flag );
#elif ( DEMO_EXAMPLE == EXAMPLE_SMS )
    c4gltegnss_send_cmd_with_par( &c4gltegnss, C4GLTEGNSS_CMD_CMGF, SMS_MODE );
    error_flag = c4gltegnss_rsp_check( C4GLTEGNSS_RSP_OK );
    func_error |= error_flag;
    c4gltegnss_error_check( error_flag );
#elif ( DEMO_EXAMPLE == EXAMPLE_GNSS )
    c4gltegnss_send_cmd_check( &c4gltegnss, C4GLTEGNSS_CMD_UGPS );
    error_flag = c4gltegnss_rsp_check( C4GLTEGNSS_RSP_OK );
    func_error |= error_flag;
    #define GPS_POWERED_OFF "+UGPS: 0"
    if ( strstr( app_buf, GPS_POWERED_OFF ) )
    {
        c4gltegnss_error_check( error_flag );
        #define ENABLE_GPS "1,0,1"
        c4gltegnss_send_cmd_with_par( &c4gltegnss, C4GLTEGNSS_CMD_UGPS, ENABLE_GPS );
        error_flag = c4gltegnss_rsp_check( C4GLTEGNSS_RSP_OK );
        func_error |= error_flag;
        c4gltegnss_error_check( error_flag );
        Delay_ms ( 1000 );
    }
    #define ENABLE_NMEA_GGA "1"
    c4gltegnss_send_cmd_with_par( &c4gltegnss, C4GLTEGNSS_CMD_UGGGA, ENABLE_NMEA_GGA );
    error_flag = c4gltegnss_rsp_check( C4GLTEGNSS_RSP_OK );
    func_error |= error_flag;
    c4gltegnss_error_check( error_flag );
#else
    #error "No demo example selected"
#endif
    return func_error;
}

static err_t c4gltegnss_example( void )
{
    err_t func_error = C4GLTEGNSS_OK;
#if ( DEMO_EXAMPLE == EXAMPLE_TCP_UDP )
    uint8_t cmd_buf[ 100 ] = { 0 };
    uint8_t urc_buf[ 20 ] = { 0 };
    uint16_t timeout_cnt = 0;
    uint16_t timeout = 30000;
    uint8_t * __generic_ptr socket_num_buf = 0;
    uint8_t tcp_socket_num[ 2 ] = { 0 };
    uint8_t udp_socket_num[ 2 ] = { 0 };

    // Create TCP socket
    #define RSP_USOCR "+USOCR:"
    #define TCP_PROTOCOL "6"
    c4gltegnss_send_cmd_with_par ( &c4gltegnss, C4GLTEGNSS_CMD_USOCR, TCP_PROTOCOL );
    error_flag = c4gltegnss_rsp_check( C4GLTEGNSS_RSP_OK );
    func_error |= error_flag;
    socket_num_buf = strstr( app_buf, RSP_USOCR ) + strlen ( RSP_USOCR );
    tcp_socket_num[ 0 ] = *socket_num_buf;
    c4gltegnss_error_check( error_flag );

    // Create UDP socket
    #define UDP_PROTOCOL "17"
    c4gltegnss_send_cmd_with_par ( &c4gltegnss, C4GLTEGNSS_CMD_USOCR, UDP_PROTOCOL );
    error_flag = c4gltegnss_rsp_check( C4GLTEGNSS_RSP_OK );
    func_error |= error_flag;
    socket_num_buf = strstr( app_buf, RSP_USOCR ) + strlen ( RSP_USOCR );
    udp_socket_num[ 0 ] = *socket_num_buf;
    c4gltegnss_error_check( error_flag );

    // Connect TCP socket to remote IP and port
    strcpy( cmd_buf, tcp_socket_num );
    strcat( cmd_buf, ",\"" );
    strcat( cmd_buf, REMOTE_IP );
    strcat( cmd_buf, "\"," );
    strcat( cmd_buf, REMOTE_PORT );
    c4gltegnss_send_cmd_with_par( &c4gltegnss, C4GLTEGNSS_CMD_USOCO, cmd_buf );
    error_flag = c4gltegnss_rsp_check( C4GLTEGNSS_RSP_OK );
    func_error |= error_flag;
    c4gltegnss_error_check( error_flag );

    // Connect UDP socket to remote IP and port
    #define ASYNC_CONNECT "1"
    strcpy( cmd_buf, udp_socket_num );
    strcat( cmd_buf, ",\"" );
    strcat( cmd_buf, REMOTE_IP );
    strcat( cmd_buf, "\"," );
    strcat( cmd_buf, REMOTE_PORT );
    strcat( cmd_buf, "," );
    strcat( cmd_buf, ASYNC_CONNECT );
    c4gltegnss_send_cmd_with_par ( &c4gltegnss, C4GLTEGNSS_CMD_USOCO, cmd_buf );
    error_flag = c4gltegnss_rsp_check( C4GLTEGNSS_RSP_OK );
    func_error |= error_flag;
    c4gltegnss_error_check( error_flag );

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

    // Write message to TCP socket
    strcpy( cmd_buf, tcp_socket_num );
    strcat( cmd_buf, "," );
    strcat( cmd_buf, message_len_buf );
    strcat( cmd_buf, ",\"" );
    strcat( cmd_buf, MESSAGE_CONTENT );
    strcat( cmd_buf, "\"" );
    c4gltegnss_send_cmd_with_par ( &c4gltegnss, C4GLTEGNSS_CMD_USOWR, cmd_buf );
    error_flag = c4gltegnss_rsp_check( C4GLTEGNSS_RSP_OK );
    func_error |= error_flag;
    c4gltegnss_error_check( error_flag );

    // Read response message from TCP socket
    #define URC_READ_SOCKET_DATA_TCP "+UUSORD:"
    strcpy( urc_buf, URC_READ_SOCKET_DATA_TCP );
    strcat( urc_buf, tcp_socket_num );
    for ( ; ; )
    {
        c4gltegnss_process( );
        uint8_t * __generic_ptr start_response_buf = strstr( app_buf, urc_buf );
        if ( start_response_buf )
        {
            Delay_ms( 100 );
            c4gltegnss_process( );
            uint8_t response_len_buf[ 5 ] = { 0 };
            uint8_t * __generic_ptr start_response_len = strstr( start_response_buf, "," ) + 1;
            memcpy ( response_len_buf, start_response_len, app_buf_len - ( start_response_len - app_buf ) );
            strcpy( cmd_buf, tcp_socket_num );
            strcat( cmd_buf, "," );
            strcat( cmd_buf, response_len_buf );
            c4gltegnss_log_app_buf( );
            c4gltegnss_clear_app_buf( );
            c4gltegnss_send_cmd_with_par ( &c4gltegnss, C4GLTEGNSS_CMD_USORD, cmd_buf );
            error_flag = c4gltegnss_rsp_check( C4GLTEGNSS_RSP_OK );
            func_error |= error_flag;
            c4gltegnss_error_check( error_flag );
            break;
        }
        if ( timeout_cnt++ > timeout )
        {
            break;
        }
        Delay_ms( 1 );
    }
    timeout_cnt = 0;

    // Write message to UDP socket
    strcpy( cmd_buf, udp_socket_num );
    strcat( cmd_buf, "," );
    strcat( cmd_buf, message_len_buf );
    strcat( cmd_buf, ",\"" );
    strcat( cmd_buf, MESSAGE_CONTENT );
    strcat( cmd_buf, "\"" );
    c4gltegnss_send_cmd_with_par( &c4gltegnss, C4GLTEGNSS_CMD_USOWR, cmd_buf );
    error_flag = c4gltegnss_rsp_check( C4GLTEGNSS_RSP_OK );
    func_error |= error_flag;
    c4gltegnss_error_check( error_flag );

    // Read response message from UDP socket
    #define URC_READ_SOCKET_DATA_UDP "+UUSORF:"
    strcpy( urc_buf, URC_READ_SOCKET_DATA_UDP );
    strcat( urc_buf, udp_socket_num );
    for ( ; ; )
    {
        c4gltegnss_process( );
        uint8_t * __generic_ptr start_response_buf = strstr( app_buf, urc_buf );
        if ( start_response_buf )
        {
            Delay_ms( 100 );
            c4gltegnss_process( );
            uint8_t response_len_buf[ 5 ] = { 0 };
            uint8_t * __generic_ptr start_response_len = strstr( start_response_buf, "," ) + 1;
            memcpy ( response_len_buf, start_response_len, app_buf_len - ( start_response_len - app_buf ) );
            strcpy( cmd_buf, udp_socket_num );
            strcat( cmd_buf, "," );
            strcat( cmd_buf, response_len_buf );
            c4gltegnss_log_app_buf( );
            c4gltegnss_clear_app_buf( );
            c4gltegnss_send_cmd_with_par ( &c4gltegnss, C4GLTEGNSS_CMD_USORF, cmd_buf );
            error_flag = c4gltegnss_rsp_check( C4GLTEGNSS_RSP_OK );
            func_error |= error_flag;
            c4gltegnss_error_check( error_flag );
            break;
        }
        if ( timeout_cnt++ > timeout )
        {
            break;
        }
        Delay_ms( 1 );
    }
    
    // Close TCP socket
    c4gltegnss_send_cmd_with_par ( &c4gltegnss, C4GLTEGNSS_CMD_USOCL, tcp_socket_num );
    error_flag = c4gltegnss_rsp_check( C4GLTEGNSS_RSP_OK );
    func_error |= error_flag;
    c4gltegnss_error_check( error_flag );
    
    // Close UDP socket
    c4gltegnss_send_cmd_with_par ( &c4gltegnss, C4GLTEGNSS_CMD_USOCL, udp_socket_num );
    error_flag = c4gltegnss_rsp_check( C4GLTEGNSS_RSP_OK );
    func_error |= error_flag;
    c4gltegnss_error_check( error_flag );
    Delay_ms( 5000 );
#elif ( DEMO_EXAMPLE == EXAMPLE_SMS )
    // Check SMS mode
    #define CMGF_PDU "+CMGF: 0"
    #define CMGF_TXT "+CMGF: 1"
    c4gltegnss_send_cmd_check( &c4gltegnss, C4GLTEGNSS_CMD_CMGF );
    error_flag = c4gltegnss_rsp_check( C4GLTEGNSS_RSP_OK );
    func_error |= error_flag;
    c4gltegnss_error_check( error_flag );
    if ( strstr( app_buf, CMGF_PDU ) )
    {
        // Send SMS in PDU mode
        c4gltegnss_send_sms_pdu( &c4gltegnss, SIM_SMSC, PHONE_NUMBER_TO_MESSAGE, MESSAGE_CONTENT );
        error_flag = c4gltegnss_rsp_check( C4GLTEGNSS_RSP_OK );
        func_error |= error_flag;
        c4gltegnss_error_check( error_flag );
    }
    else if ( strstr( app_buf, CMGF_TXT ) )
    {
        // Send SMS in TXT mode
        c4gltegnss_send_sms_text ( &c4gltegnss, PHONE_NUMBER_TO_MESSAGE, MESSAGE_CONTENT );
        error_flag = c4gltegnss_rsp_check( C4GLTEGNSS_RSP_OK );
        func_error |= error_flag;
        c4gltegnss_error_check( error_flag );
    }
    Delay_ms( 10000 );
    Delay_ms( 10000 );
    Delay_ms( 10000 );
#elif ( DEMO_EXAMPLE == EXAMPLE_GNSS )
    c4gltegnss_send_cmd_check( &c4gltegnss, C4GLTEGNSS_CMD_UGGGA );
    error_flag = c4gltegnss_rsp_check( C4GLTEGNSS_RSP_OK );
    func_error |= error_flag;
    if ( app_buf_len > ( sizeof ( C4GLTEGNSS_RSP_GGA ) + C4GLTEGNSS_GGA_ELEMENT_SIZE ) ) 
    {
        uint8_t element_buf[ 100 ] = { 0 };
        if ( C4GLTEGNSS_OK == c4gltegnss_parse_gga( app_buf, C4GLTEGNSS_GGA_LATITUDE, element_buf ) )
        {
            static uint8_t wait_for_fix_cnt = 0;
            if ( strlen( element_buf ) > 0 )
            {
                log_printf( &logger, "\r\n Latitude: %.2s degrees, %s minutes \r\n", element_buf, &element_buf[ 2 ] );
                c4gltegnss_parse_gga( app_buf, C4GLTEGNSS_GGA_LONGITUDE, element_buf );
                log_printf( &logger, " Longitude: %.3s degrees, %s minutes \r\n", element_buf, &element_buf[ 3 ] );
                memset( element_buf, 0, sizeof( element_buf ) );
                c4gltegnss_parse_gga( app_buf, C4GLTEGNSS_GGA_ALTITUDE, element_buf );
                log_printf( &logger, " Altitude: %s m \r\n", element_buf );
                wait_for_fix_cnt = 0;
            }
            else
            {
                if ( wait_for_fix_cnt % 5 == 0 )
                {
                    log_printf( &logger, " Waiting for the position fix...\r\n\n" );
                    wait_for_fix_cnt = 0;
                }
                wait_for_fix_cnt++;
            }
            c4gltegnss_clear_app_buf(  );
        }
    }
    Delay_ms( 1000 );
#else
    #error "No demo example selected"
#endif
    return func_error;
}

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

Additional Support

Resources