Junk data appears in serial monitor and breaks blynk

Hello,

I experience some strange problem. My board is Arduino MKR 1400 GSM. I use BLE connection over serial with HM-10 module. My sketch looks like follows:

#include "StdAfx.h"
#include "Defines.h"
#define BLYNK_PRINT Serial1
#define BLESerial Serial1

// Blynk App token
char auth[] = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";

// Timer class instances..
MillisTimers tmLedFlash;
MillisTimers tmCmdDelay;


// timers stuff
bool g_setupStatus = true;
bool g_doorState = DoorStates::LOCK;
bool g_rLedState = false;
bool g_gLedState = false;
bool g_bLedState = false;
bool g_fsrStateChange = false;
uint32_t g_fsrStateChangeTime = 0UL;

void setup()
{
  g_setupStatus = false; // Initialization failed at the stage, lets keep setting up

  //setup door simulation pin
  pinMode(doorPin, INPUT_PULLUP);

  // set LED pin to output mode
  pinMode(rLedPin, OUTPUT);
  pinMode(gLedPin, OUTPUT);
  pinMode(bLedPin, OUTPUT);

  // all LED indicator on startup
  digitalWrite(rLedPin, HIGH);
  digitalWrite(gLedPin, HIGH);
  digitalWrite(bLedPin, HIGH);

  Serial.begin(baudrate);
  while (!Serial)
  {
    ; // Need to wait the USB connection to be established? wait, so can see setup logs in monitor
  }
  
  BLESerial.begin(baudrate);
  Blynk.begin(BLESerial, auth); // Start talking to Blynk app
  Serial.println("Waiting for connections...");

  // init timers
  tmLedFlash.init();
  tmCmdDelay.init();

  g_setupStatus = true;

  // shut off leds when setup is completed
  if (g_setupStatus)
  {
    digitalWrite(rLedPin, LOW);
    digitalWrite(gLedPin, LOW);
    digitalWrite(bLedPin, LOW);
  }
}

void loop()
{
  Blynk.run();

  // read from the HM-10 and print in the Serial
  if (BLESerial.available())
    Serial.write(BLESerial.read());

  // read from the Serial and print to the HM-10
  if (Serial.available())
    BLESerial.write(Serial.read());


  g_doorState = digitalRead(doorPin);

  if (g_doorState == DoorStates::OPEN)
  { // door opned
    if (tmLedFlash.WhileRepeat(550, 0))
    {
      //digitalWrite(rLedPin, (g_rLedState) ? HIGH : LOW);  // start blinking with led
      Blynk.virtualWrite(V1, (g_rLedState) ? ON : OFF);
      g_rLedState = !g_rLedState;
      #ifdef VM_DEBUG
      Serial.println("Door: OPEN");
      #endif
    }
  }
  else {                                                  // door locked
   if (tmCmdDelay.WhileRepeat(550, 0))
   {
     // digitalWrite(rLedPin, LOW);                         // shut off the led
      Blynk.virtualWrite(V1, OFF);
      #ifdef VM_DEBUG
      Serial.println("Door: LOCKED");
      #endif
    }
  }
}

Stdafx.h

// StdAfx.h

#ifndef _STDAFX_h
#define _STDAFX_h

// Libraries
#include <stdarg.h>
#include <wiring_private.h> 	    // for Hardware UART
#include <BlynkSimpleSerialBLE.h>   // BLE bridge for Blynk
#include <Wire.h> 				    // BUS communication dependancy
#include <LiquidCrystal_I2C.h>      // LCD with I2C module
#include <LcdDisplay.h>             // Layer class for I2C and LCD, own
#include <OneWire.h> 			// One wire stuff, e.g. temp sensors
#include <DallasTemperature.h> 	// External temperature one wire sensors
#include <MKRGSM.h>
//#include <Gsm.h>
#include <MillisTimers.h>

#endif

MillisTimers.cpp

#include <Arduino.h>
#include "MillisTimers.h"

void MillisTimers::init()
{
	this->enabled = true;
	this->passedCycles = -1;
	this->lastMillis = millis();
}

/* **
	Returns false if still delaying, true if time has passed
** */
bool MillisTimers::WhileRepeat(unsigned long delay, short repeatNumber)
{
	unsigned long currentTime = millis();
	short _repeats = repeatNumber;

	if (!this->enabled)
		return false;

	if (currentTime - lastMillis >= delay)
	{
		if (_repeats)
		{
			if (_repeats == this->passedCycles)
			{
				this->enabled = false;
				return false;
			}

			this->passedCycles++;
		}

		lastMillis = currentTime; // adjust the extra delay() in usage
		return true;
	}

	return false;
}

bool MillisTimers::AfterRepeat(unsigned long delay, bool repeat)
{
	if (this->enabled && millis() - lastMillis <= delay)
	{
		return false;
	}

	if (!repeat)
		this->enabled = false;

	return true;
}

bool MillisTimers::LastPeriod(unsigned long snappedTime, unsigned long period)
{
	if (millis() - snappedTime <= period)
		return true;

	return false;
}

MillisTimers.h

// MillisTimers.h

#ifndef _MILLISTIMERS_h
#define _MILLISTIMERS_h

class MillisTimers
{
protected:

public:
	void init();
	bool WhileRepeat(unsigned long delay, short repeatNumber);
	bool AfterRepeat(unsigned long delay, bool repeat);
	bool LastPeriod(unsigned long snappedTime, unsigned long period);

private:
	short passedCycles;
	unsigned long lastMillis;
	bool enabled;
};

#endif

The problem is that when I use any of the timers, e.g. here

if (tmLedFlash.WhileRepeat(550, 0))
    {
      //digitalWrite(rLedPin, (g_rLedState) ? HIGH : LOW);  // start blinking with led
      Blynk.virtualWrite(V1, (g_rLedState) ? ON : OFF);
      g_rLedState = !g_rLedState;
      #ifdef VM_DEBUG
      Serial.println("Door: OPEN");
      #endif
    }
  }

I periodically get junk data in serial monitor. All baud rates are set in and serial monitor is also set to the same rate.

The junk data is NULL or sometimes even part of Blynk auth token, any advice why it may happen?

Example serial monitor output:

Door: OPEN
Door: OPEN
Door: OPEN
Door: OPEN
ST
Door: OPEN
Door: OPEN
Door: OPEN
Door: OPEN
Door: OPEN
Door: OPEN
Door: OPEN
Door: OPEN
Door: OPEN
␀Door: OPEN
Door: OPEN
Door: OPEN
Door: OPEN
Door: OPEN
Door: OPEN
Door: OPEN
Door: OPEN
Door: OPEN
␀Door: OPEN
Door: OPEN
Door: OPEN
Door: OPEN

This one appeared when I connected back with blynk while the sketch was running. The longer string inside is the token. I changed it here for fake one for post purpose but maintained its length.

Door: OPEN
Door: OPEN
Door: OPEN
Door: OPEN
NN
Door: OPEN
Door: OPEN
Door: OPEN
␝␀␁␀ Q3aAvoDsgsGtDFfAERhDDfzzsdSsFak5Door: OPEN
Door: OPEN
␀Door: OPEN
Door: OPEN
Door: OPEN

When blynk app disconnects the serial output returns to normal, once I connect back with the app I get junk data.

The junk data breaks the blinking and it takes a while to return to proper operation. Hoping for advice.

Probaly because you told it to :stuck_out_tongue:

You can NOT use the Blynk connection BLESerial for anything else, like receiving the data ment for Serial…

Sharp eye, however I commented out the

  // read from the HM-10 and print in the Serial
  //if (BLESerial.available())
   // Serial.write(BLESerial.read());

  // read from the Serial and print to the HM-10
 // if (Serial.available())
  //  BLESerial.write(Serial.read());

Still getting exactly same issue as described. I sent my app log via email.

Exact same issue means you missed something else doing exactly same serial port crosstalk.

Confirm your modified code has actually uploaded to the MCU.

Step through your code, line by line if necessary, so you know each and every step and what it is supposed to do… and then you can better catch when it does something differently.

The issue was #define BLESerial Serial1. The BLESerial existed in one of Blynk .h files and it got referenced to it by some reason even I did not include it directly. Not first time I experience similar issue. Not sure it is sketches specific or Visual Code problem. On daily basis I work in Visual Studio which always references #define or var to nearest definition or definition that belongs to related header.

By the way, once we are on the subject. Any way to prevent Blynk from “freezing” arduino if Blynk app is not connected via BLE? I know it is possible to check WIFI connection status but did not find any way to determine that for BLE.

At the moment application won’t pass this stage: Blynk.begin(BLESerial, auth); until app is connected.

Can’t really assist further as I never liked & rairly used Blynk with any BT or BLE connection… too unstable, and no benefits whatsoever over WiFi (App still needs internet to login).

My project is an object detector that is being installed in car, therefore WIFI is not an option. It simply must be BT/BLE.

I had a hope to use Blynk as target solution for my client app but seems I will be forced to code own client app to control the behavior the way I want. Seems Blynk has too many limits if comes to BT/BLE even Low Energy is widely implemented feature within all new stuff and mobiles.

Blynk is primarily an IoT app, so it’s not really surprising that it doesn’t fit your particular application.
You could of course set-up a stand-alone Blynk server within the vehicle, but that’s probably not an ideal solution either.

Pete.

And how IoT excludes BLE/BT? If you limit IoT terminology to control smart house or devices within closed industry environment then yes, however if you will read about trends and future you will see that BT/BLE is the actual future of IoT. You may want to read more about LPWA, M2M, etc.

I am pretty familiar with it as I am building my master thesis about that :smiley:

Anyway, that’s not real point of the issue now. I just find no way of making Blynk app being able to connect while the Arduino app is running. It requires the Blynk to connect first to go any further what is pretty strange behavior, especially the app is used to display info only, so it could get connected any time while sketch is running.

In that case I bow to your superior knowledge, but don’t be offended if I don’t rush out and buy shares in the companies that are making Bluetooth chips and devices.

Good luck with your project and your thesis.

Pete.

1 Like

Pretty rude reply. No further comment.

Regards

I see nothing rude about not sharing your opinions on the future direction of technology trends, or wishing you well for the future.

However, as you’ve flagged my post for moderation I will let one of the other moderators deal with it in whatever way they deem appropriate.

Pete.

2 Likes

It is not my opinion, it is what number of experts say within numerous of science articles - that’s why I pointed out to read about it. Yes - I flagged your reply as I find it haughty and mocking tone while having regular discussion based on facts, not subjective opinions.

Just because “experts” write articles about where they see things going in future doesn’t make them facts!

I’m old enough to have been told by experts that we would all be travelling around in flying cars by now, and that there would never be a time when workers had a computer on every desk; so I’m somewhat sceptical about predictions regarding future technology.

Pete.

2 Likes

Once the time will come, remember to think about me :wink:

The word “internet” in IoT generally does the job there :stuck_out_tongue: BT/BLE is usualy meant as a personal LAN, not as a fulltime link to a WAN.

Incorrect, since Blynk uses a server to process the interaction between App and Hardware. Thus when using BT/BLE, the App does double duty as both the GUI and the BT/BLE <--> Network interface to the server.

A little searching of this forum and you would see others have “solved” similar “off-line” issues with a Local Server/AP combo (usually an RPi) that runs the Server and, via a WiFi Access Point in the RPi, connect the App and MCU’s together. And, if using Blynk Python or NodeJS client libraries, the RPi can act as a hardware client, using it’s own GPIO, as well as Local Server.

I have often thought of using a spare tablet and RPI to do just that… basically replacing my truck radio with an RPi running all the things, media, backup camera, mood lighting, vehicular alarm, GPS, etc… but then since I don’t really go anywhere to justify the efforts, I had left that one on the back burner :blush:

1 Like