Docs

Micro-controllers, wireless transmission and database

Head

Publish data to MQTT broker using STM32 & SIM7600

SIM7600 comes in different version. The one I am using is SIM7600G (Global) that can work with many bands. I checked here in Australia with two different providers (Telstra and Vodafone). Both sim cards worked fine.

The pin outs are quite simple. Connect four pins VCC,GND,UART(RX) and UART(TX), it will just work. This module includes proper power regulator, so we can connect 5V to the V pin. Also the TX/RX serial communication already includes necessary 3.3V level shifter. So we can connect to 3.3V ESP or STM microcontroller directly.

AT command manual, Schematic and Datasheet can be found in the following links. https://www.adrive.com/public/bPqyGe/BK-SIM7600E-H.zip

Items can be purchased from https://www.aliexpress.com/store/605000. I bought my items from https://www.aliexpress.com/item/4000224044192.html

This project assumes you have already installed STM32CubeIDE. You need to have previously done a basic program using STM32CubeIDE. I have made a complete video from installing STM32CubeIDE to LED blink program. You can watch it by clicking this link. https://www.youtube.com/watch?v=kXg467nVd_A

See page No. 31 & 32 of SIM7500 SIM7600 SIM7800 Series MQTT AT Command Manual V1.00 for MQTT Connction

I am going to use free broker https://test.mosquitto.org/ for MQTT Broker

Do the wiring connection for STM32

Diagram

Image1

Image2

Upload the code from CubeIDE

STM32CubeIDE Settings

ADC1 - IN9 (tick)

Parameter Settings --> ADC Settings --> Continuous Conversion Mode (Enabled)

Enable USART1 asynchronous

Configuration → Parameter Settings → Basic Parameters → Baud rate 115200

Additional code on top of STM32CubeIDE generated code

/* USER CODE BEGIN Includes */
#include <string.h>
#include <stdio.h>
/* USER CODE END Includes */

/* USER CODE BEGIN 0 */
const char apn[]  = "live.vodafone.com"; // Change this to your Provider details
const char host[] = "tcp://test.mosquitto.org"; // Change this to your host
const int  port = 1883;
const char username[] = "";
const char password[] = "";
const char topic[] = "pot/adc/1";
const uint32_t timeOut =10000;
char ATcommand[80];
uint8_t buffer[160] = {0};
uint8_t ATisOK = 0;
uint8_t CGREGisOK = 0;
uint32_t previousTick;
uint16_t readValue;
char charData[15];

void SIMTransmit(char *cmd)
{
  memset(buffer,0,sizeof(buffer));
  HAL_UART_Transmit(&huart1,(uint8_t *)cmd,strlen(cmd),1000);
  HAL_UART_Receive (&huart1, buffer, 100, 1000);
}

void mqttPublish(void)
{
  ATisOK = 0;
  CGREGisOK = 0;

  // Check for OK response for AT
  previousTick =  HAL_GetTick();
  while(!ATisOK && previousTick  + timeOut >  HAL_GetTick())
  {
    SIMTransmit("AT\r\n");
    HAL_Delay(1000);
    if(strstr((char *)buffer,"OK"))
    {
      ATisOK = 1;
    }
  }

  // Check for network registration.
  if(ATisOK)
  {
    previousTick =  HAL_GetTick();
    while(!CGREGisOK  && previousTick  + timeOut >  HAL_GetTick())
    {
      SIMTransmit("AT+CGREG?\r\n");
      if(strstr((char *)buffer,"+CGREG: 0,1")) // Use 0,5 For Roaming
      {
        CGREGisOK = 1;
      }
    }
  }

  // If registered
  if(CGREGisOK)
  {
	sprintf(ATcommand,"AT+CGSOCKCONT=1,\"IP\",\"%s\"\r\n",apn); // Specify the value of  PDP context
	SIMTransmit(ATcommand);
	SIMTransmit("AT+CMQTTSTART\r\n"); // Start MQTT Service
	SIMTransmit("AT+CMQTTACCQ=0,\"client01\"\r\n"); // Acquire a Client
	sprintf(ATcommand,"AT+CMQTTCONNECT=0,\"%s:%d\",60,1\r\n",host,port); // Connect to a MQTT Server
	// sprintf(ATcommand,"AT+CMQTTCONNECT=0,\"%s:%d\",60,1,%s,%s\r\n",host,port,username,password);
	SIMTransmit(ATcommand);
	sprintf(ATcommand,"AT+CMQTTTOPIC=0,%d\r\n",strlen(topic)); // Set the topic for publish message
	SIMTransmit(ATcommand);
	sprintf(ATcommand,"%s\r\n",topic);
	SIMTransmit(ATcommand);
	sprintf(ATcommand,"AT+CMQTTPAYLOAD=0,%d\r\n",strlen(charData)-2); // Set the payload
	SIMTransmit(ATcommand);
	SIMTransmit(charData);
	SIMTransmit("AT+CMQTTPUB=0,1,60\r\n"); // Publish
	SIMTransmit("AT+CMQTTDISC=0,120\r\n"); // Disconnect from Server
	SIMTransmit("AT+CMQTTREL=0\r\n"); // Release the Client
	SIMTransmit("AT+CMQTTSTOP\r\n"); // Stop MQTT Service
  }
}
/* USER CODE END 0 */

  /* USER CODE BEGIN 2 */
  HAL_ADC_Start(&hadc1);
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
    HAL_ADC_PollForConversion(&hadc1,1000);
    readValue = HAL_ADC_GetValue(&hadc1);
    sprintf(charData, "%d\r\n", readValue);
    mqttPublish();
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
  }
  /* USER CODE END 3 */

NEED TO DO A CHANGE TO ABOVE CubeIDE CODE

Find out your SIM card providers APN. You can google search or use https://wiki.apnchanger.org/ Replace

const char apn[]  = "live.vodafone.com";

In the place of "live.vodafone.com", put your providers APN

NodeJS setup

npm init

npm install mqtt mysql

create app.js

Serial Port testing code

let mqtt = require('mqtt')

let options = {
    host: 'test.mosquitto.org',
    port: 1883,
    protocol: 'mqtt',
    username: '',
    password: ''
}

// Initialize the MQTT client
let client = mqtt.connect(options);

// Setup the callbacks
client.on('connect', () => console.log('Connected'));

client.on('error', (error) => console.log(error));

// Called each time a message is received
client.on('message', (topic, message) => {
  console.log('Received message:', topic, message.toString())
});

// subscribe to topic 'pot/adc/1'
client.subscribe('pot/adc/1');

Test run

node app.js

Open MySQL Workbench

Create Schema (mqtt)

Create Table (stm32)

Complete NodeJS code

const mqtt = require('mqtt')
const mysql  = require("mysql");

let mysqlConnection = mysql.createConnection({
    host : "localhost",
    user : "root",
    password : "password",
    database : "mqtt",
});

mysqlConnection.connect((err)=>{
    if(!err)
    {
        console.log("Conneted to DB");
    }
    else
    {
        console.log(err);
    }
});

let options = {
    host: 'test.mosquitto.org',
    port: 1883,
    protocol: 'mqtt',
    username: '',
    password: ''
}

// Initialize the MQTT client
let client = mqtt.connect(options);

// Setup the callbacks
client.on('connect', () => console.log('Connected to MQTT broker'));

client.on('error', (error) => console.log(error));

// Called each time a message is received
client.on('message', (topic, message) => {
    created = new Date();
    mysqlConnection.query('INSERT INTO stm32 SET datetime= ?, reading = ?', [created , parseInt(message)], (err, rows) => {
        if(!err)
        {
            console.log("Data inserted: ");
            console.log(rows);
        }
        else
        {
            console.log(err);
        }  
    });
});

// subscribe to topic 'pot/adc/1'
client.subscribe('pot/adc/1');