BLYNK
HOME       📲 GETTING STARTED       📗 DOCS       ❓HELP CENTER       👉 SKETCH BUILDER

SOLVED: Any timer kills my sketch (ESP core version)

#1

First Blynk project - still a WIP, however I’m having a fundamental problem - the attached code compiles & runs OK, BUT… if I instantiate a Ticker or BlynkTimer - the code never gets past Blynk.begin…
I’m sure it will be easy for the experts ! Quirky code is // commented out.

//==========================================
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
// #include <Ticker.h>

#define topLED	2		// GPIO2 NodeMCU LED - near antenna - input pin is used to select WiFi mode
#define botLED	16	// GPIO16 NodeMCU LED - near USB connector

// used with target_state to reflect the status back to blynk
#define GATE_CLOSED	0
#define GATE_OPEN		1
// motor step count to match open/c.osed positions
#define CLOSED_POSITION 0
#define OPEN_POSITION 1400

#define STEP_FORWARD	HIGH
#define STEP_BACKWARD	LOW

// Ticker stepTimer;
BlynkTimer timer;

unsigned char	target_state = GATE_CLOSED;	// 	assume closed to begin with at reset time
unsigned long currentPosition, targetPosition;
unsigned long prev_stepMS, step_periodMS = 50L;

// EasyDriver Pins
// ESP8266 has very few I/O pins free for user...
const int smEnable = D1; //Driver enable pin
const int smDirection = D2; //Direction pin
const int smStep = D3; //Step pin
unsigned long stepDurationMS = 50L;	// millisecs per half-step phase

int pinData;

//==========================================
// You should get Auth Token in the Blynk App.
// Go to the Project Settings (nut icon).
char auth[] = "token"; //MC TEST

//==========================================
// Your local WiFi credentials.for the ESP/Blynk server
// Set password to "" for open networks.
char ssid[] = "SSID";
char pass[] = "passphrase";

//==========================================
void setup() {
	// pinMode (topLED, OUTPUT);
	// pinMode (botLED, OUTPUT);
	
	pinMode(smDirection, OUTPUT);
  pinMode(smStep, OUTPUT);
  pinMode(smEnable, OUTPUT);
  digitalWrite(smEnable, HIGH); 	

	Serial.begin(115200);		// <<<<< ==== use this value in serial terminal etc..
	delay(100);
  Serial.println("\nStarting...\nwait for Wifi & Blynk server");
  Blynk.begin(auth, ssid, pass); // can take several seconds
	// digitalWrite(botLED, 0); // note the LED is inverted
	Serial.println(F("Connected - the Blynk server is alive!"));
	prev_stepMS = millis();

// timer.setInterval(stepDurationMS, moveStepper);
	
	// ###########################################################
	// We don't know where the motor is parked...
	// so all movements will be relative to the initial position
	// until some sort of end stop or calibration is available,
	// ###########################################################
}
//==========================================
void loop() {
	Blynk.run();
	// timer.run();	// moveStepper();
}
//==========================================
						// take care to accommodate reversing the 
						// target motor if it is still running
						// in the opposite direction

						// We could #define the virtual pin numbers to be more readable
						// - but they still have to match the vPin assignments in the BLYNK app
//==========================================
BLYNK_WRITE(V0) { //momentary button Widget is writing to pin V0
  pinData = param.asInt(); 
	if (pinData) {	// pin has been set to '1'
		Serial.println(F("CLOSE THE GATES"));
	}
	// target_state = GATE_CLOSED;
	targetPosition = CLOSED_POSITION;
}
//==========================================
BLYNK_WRITE(V1) { //momentary button Widget is writing to pin V1
  pinData = param.asInt(); 
	if (pinData) {	// pin has been set to '1'
		Serial.println(F("OPEN THE GATES"));
	}
	// target_state = GATE_OPEN;
	targetPosition = OPEN_POSITION;
}
//==========================================
BLYNK_WRITE(V2) { // button Widget is writing to pin V2
	pinData = param.asInt(); 
	target_state = pinData; // !target_state; 
	Serial.print(F("TOGGLE GATES TO "));
	if (target_state == GATE_OPEN) {
		Serial.println(F("OPENING STATE"));
		targetPosition = OPEN_POSITION;
	} else {
		Serial.println(F("CLOSING STATE"));
		targetPosition = CLOSED_POSITION;
	}
}
//==========================================
void moveStepper() {
	static bool stepPhase = 0;	// alternates 0/1
	if (targetPosition != currentPosition) {	// we have somewhere to go...
		if (millis() - prev_stepMS > step_periodMS) {  // the time is right for a step
			// ###########################################################
			// until some sort of end-stop or calibration is available,
			// the motor & position are driven until targetPosition == currentPosition
			// ###########################################################
			if (targetPosition > currentPosition)	{ // choose forward por reverse
				digitalWrite(smDirection, STEP_FORWARD);
				currentPosition++;
				Serial.write('+');
			} else {
					digitalWrite(smDirection, STEP_BACKWARD);
					currentPosition--;
					Serial.write('-');
			}
			//-----------------
			stepPhase = !stepPhase;	// the step pulse swaps every step_periodMS
			digitalWrite(smStep, stepPhase);	// toggle the step pulse
			prev_stepMS = millis();
		}
	} else {
		if ((targetPosition == OPEN_POSITION) && (target_state != GATE_OPEN)) {
			target_state = GATE_OPEN;
			Serial.println(F("|open"));
		} else if ((targetPosition == CLOSED_POSITION) && (target_state != GATE_CLOSED)) {
			target_state = GATE_CLOSED;
			Serial.println(F("|closed"));
		}
	}
}
//==========================================
0 Likes

#2

I’ve edited your code so that it displays correctly.
When you post code on the forum it must have triple backticks at the beginning and end. This information is explained in the information displayed when you create a new thread.
Triple backticks look like this:
```
Please format your code correctly in future, or it will probably be deleted.

You’re using two different ways of referencing the I/O pins on your NodeMCU. You start off using GPIO numbers for pins 2 and 16, then switch to the ‘D’ numbers that are screen printed on the NodeMCU board. You use pins D1, D2 and D3, which are GPIO pins 5, 4 and 0 respectively.
Mixing the way you reference pins in this way can be confusing, as you could think that you were using two separate pins for two separate tasks, but in reality you’re using the same pin with two different names.

So, in total you’re using GPIO pins 0, 2, 4, 5 and 16.

If you read this topic:


You’ll see that pins 0 and 2 aren’t recommended for use.

I think that what’s happening is that you’re pilling one of these pins to the wrong state at boot-up, so either putting the NodeMCU into flash mode, or disabling the onboard Wi-Fi.

Pete.

0 Likes

#3

@PeteKnight Thanks for the pointers.
I did look for clues on the posting of code snippets - but didn’t see the items you were talking about - so I posted as ‘preformatted text’… obviously not what you were hoping for!

I’m still not suire how your answer helps identify why the timers are interfering with the code.

Your point about different notation for pins was a hangover from my pulling some code from earlier non-Blynk things - but from my observations (which may be nicorrect) - as you pinted out - some pins are repurposed - at different times by tghe core during operation, and sometimes for input or output only.

I developed this pin list when I was working on my first ever ESP project - and it seems to have held up since then.

My PIN Notes - observed with scope during specific test session

ESP8266MOD on NodeMCU (ESP-12E)
3V3 i/o tolerance

ESP pin Ardu function status
GPIO16 d0 (LED) OUT LED near USB
GPIO5 d1 IN OUT
GPIO4 d2 IN OUT
GPIO8 d3 IN OUT
GPIO2 d4 IN OUT LED near ESP, busy during upload
GPIO14 d5 n/a OUT HSCLK ext SPI
GPIO12 d6 n/a OUT HMISO ext SPI
GPIO13 d7 n/a OUT HMOSI ext SPI
GPIO15 d8 n/a OUT HCS ext SPI

GPIO3 serial up/down RXD0 (USB)
GPIO1 serial up/down TXD0 (USB)

CLK SPI onboard FLASH
SD0 SPI onboard FLASH
CMD SPI onboard FLASH
SD1 SPI onboard FLASH
GPIO9 SD2 NO NO unknown
GPIO10 SD3 IN ?? OUT has 1Vp-p sparkle

Sorry if this doesn’t format correctly - still looking for the forum tricks, and the solution to my original timer problem. Cheers

0 Likes

#4

It is clearly shown in the Welcome Topic that, as with every other forum out there, is required reading BEFORE posting in the forum…

And then it shows how again in the very posting space that you either need to erase or ignore when posting your initial topic…

I think your “solution” will be in rethinking how an ESP and Arduino code use GPIO pins. Best way to start is just FORGET the silkscreened designations on the board and use a chart like this to map pins using the IDE (GPIO) numbering.

As for whether a pin is input or output is determined in the void setup() with pinMode() and really shouldn’t change mid-way through your code.

Then study up on the timer of your choice… Blynk uses a SimpleTimer variant that is built into the library and called BlynkTimer. More timer command info here.

Once you understand the basics of the timer, you can troubleshoot your own code much better :wink:

0 Likes

#5

BTW, I have some example Stepper Motor code here that works perfectly with BlynkTimer.

0 Likes

#6

Thanks for the thought.
My issue is that as soon as I add the line…
timer.setInterval(stepDurationMS, moveStepper);

My code never gets past the end of setup.
Perhaps dies inside that function.

If that line is omitted - everything else runs as expected.
Same occurs if I use an ESP Ticker.

0 Likes

#7

@lcn, I’ve un-commented the following lines:

 #include <Ticker.h>
 
timer.setInterval(stepDurationMS, moveStepper);
 
timer.run(); // moveStepper();

and flashed your code onto a Wemos D1 Mini.

The code connects to Wi-Fi and Blynk and responds to button presses of switch widgets on pin V1, V2 and V3.

Can I ask what version of the ESP Core you’re using? (Tools/Board/Boards Manager and scroll to the bottom of the list to find “esp8266 by ESP8266 Community”).

I suspect your answer will be 2.5.0
If that’s the case then try downgrading to 2.4.2 and recompiling your code and re-testing.

BTW, you should do this test without any other hardware (stepper motors, motor driver hardware etc attached to your board).

Pete.

0 Likes

#8

You were right -
The current version is 2.5.0, now downgraded to 2.4.2
FANTASTIC - it works !

Many thanks - sounds like an issue for the dev team to identify.

Cheers - thanks for your help

0 Likes

#9

Works fine on my NodeMCU with Core 2.5.0 :thinking:

Mind you I did make some usual changes for my Local Server and preference for Blynk.config()

Of course I have no stepper or sensors hooked up, but pushing buttons does “things” in the serial monitor just fine.


Starting...
wait for Wifi & Blynk server
[10579] 
    ___  __          __
   / _ )/ /_ _____  / /__
  / _  / / // / _ \/  '_/
 /____/_/\_, /_//_/_/\_\
        /___/ v0.6.1 on NodeMCU

[10583] Connecting to 10.10.3.13:8080
[15584] Connecting to 10.10.3.13:8080
[15604] Ready (ping: 12ms).
Connected - the Blynk server is alive!
CLOSE THE GATES
OPEN THE GATES
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++CLOSE THE GATES
-------------------------------------------------------------TOGGLE GATES TO OPENING STATE
TOGGLE GATES TO CLOSING STATE


0 Likes

#10

It’s not a Blynk issue, it’s a buggy ESP core that causes issues with many different libraries.
You can use the latest pre-release version of the ESP core by installing the GIT version using these instructions:
https://arduino-esp8266.readthedocs.io/en/latest/installing.html#using-git-version

but personally I’m happy using 2.4.2 for the time being.

If you have problems with your board not connecting to Wi-Fi once you connect-up your hardware then it will be because of your choice of pins. Pins GPIO 0 and 2 can easily be pulled to the wrong state by your connected hardware, which can cause the board to go into flash mode, or for Wi-Fi to be disabled.

It’s also a good idea to include the line:

#define BLYNK_PRINT Serial

at the beginning of your sketch as it will give you some useful information about the Wi-Fi and Blynk connection process and if you suffer timeout disconnections they will be obvious from the serial monitor.
I suspect that your moveStepper function may cause disconnections because of the way that it’s written.

Pete.

1 Like

#11

@PeteKnight - yep, thanks - I meant the ESP team, but I’d also likle to see some complete unified documentation for Blynk.
The 'online docs are ‘ok’, but hardly comprehensive or consistent. They’re ‘pretty’, but thin on the meat to solve non-mainstream problems.
I’m with you on the pin usage - and have been careful steer clear of pins that I may iuse in the future, or are multi-purposed in the core.
Sorry - I commented out the serial #define earlier for some reason - but now I know the world is turning again - I’ll put that back in .

@Gunner
I certainly have zero external connections to the ESP for early devleopment. (Steppers are next)
Once the code gets past startup (now with 2.4.2), the buttons have been working fine.

I still have to add a second slower) timer to refresh the button states/labels based on the local states - but that’s just code.

Thanks for both of yours help.
Cheers MC

0 Likes

#12

That is the purpose of this forum :wink: … Blynk is in constant development and the developers try to catch up on the documentation as best as abled. But they welcome contributions :stuck_out_tongue_winking_eye:

0 Likes