Docs

Micro-controllers, wireless transmission and database

Head

Blue Pill USB data to MySQL server using STM32CubeIDE

Prerequisites

This project assumes you have already installed STM32CubeIDE. You need to have previously done a basic blink sketch with blue-pill 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

STM32CubeIDE Settings

Click RCC → High Speed Clock (HSE) to Crystal/Ceramic Resonator

Click connectivity → Click USB

(Tick) Device (FS)

Click Middleware → Click USB_DEVICE

For Class for FS IP → select Communication Device Class (virtual Port Com)

Click Clock Configuration tab → HCLK (MHz) to 72

Additional code on top of STM32CubeIDE generated code

/* USER CODE BEGIN Includes */
#include "usbd_cdc_if.h"
#include "string.h"
/* USER CODE END Includes */

/* USER CODE BEGIN PV */
int data = 12345678;
char charData[15];
/* USER CODE END PV */

  /* USER CODE BEGIN WHILE */
  while (1)
  {
    sprintf(charData, "%d\n", data);
    CDC_Transmit_FS((uint8_t *) charData, strlen(charData));
    data++;
    HAL_Delay(1000);
    /* USER CODE END WHILE */
    /* USER CODE BEGIN 3 */
  }
  /* USER CODE END 3 */

NodeJS setup

npm init

npm install serialport mysql

create app.js

contents of app.js below and change COM7 to your Port

Serial Port testing code

const serialPort = require('serialport'); 
const port = new serialPort("COM7");
const parser = new serialPort.parsers.Readline();
port.pipe(parser);
parser.on('data', (data) => console.log(data));

Test run

node app.js

Open MySQL Workbench

Create Schema (usb)

Create Table (stm32)

Complete NodeJS code

const serialPort = require('serialport')
const mysql  = require("mysql");

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

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

const port = new serialPort('COM7');

const parser = new serialPort.parsers.Readline()

port.pipe(parser)

parser.on('data', (line)=>{
    created = new Date();
    mysqlConnection.query('INSERT INTO stm32 SET datetime= ?, reading = ?', [created , parseInt(line)], (err, rows) => {
        if(!err)
        {
            console.log("Data inserted: ");
            console.log(rows);
        }
        else
        {
            console.log(err);
        }  
    });
});