0% found this document useful (0 votes)
5 views

Using Int

The code is meant to determine the elapsed time between input state changes and enable outputs if below a threshold. However, it is not working properly when using unsigned long variables. Using int instead runs perfectly. The issues may be caused by StrobeTime never being updated, causing the elapsed time check to always return true. Suggestions are made to update the code to properly reset timers.

Uploaded by

Ari Baskoro
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Using Int

The code is meant to determine the elapsed time between input state changes and enable outputs if below a threshold. However, it is not working properly when using unsigned long variables. Using int instead runs perfectly. The issues may be caused by StrobeTime never being updated, causing the elapsed time check to always return true. Suggestions are made to update the code to properly reset timers.

Uploaded by

Ari Baskoro
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Using int for millis()

neubauerp Des '22 post #1


Hello,
I am working on a project where apart from other functions i have to determine the elapsed time
between input state changes, then if it is below a set threshold, enable the outputs.
The code needs to run pretty fast, as it handles two inputs of a camshaft sensor, one is 1
cycle/rotation, the other is 6 cycle/rotation. Expected max RPM is 3750.
Here are the relevant lines from my code :

unsigned long CurrTime;


unsigned long StrobeTime;

void loop(){

CurrTime=millis();

if (input state change detection) {


StrobeTime = millis();
}

if (CurrTime-StrobeTime > 500 ){

/disabling outputs/
}

Now when i use unsigned long for the variables, the code runs very slow, the outputs are acting
funny, dropping out, etc.
I have tried using int, it runs perfectly even up to 4200 RPM, the max rpm of my drill that i use to
test it.
If i use unsigned int, it behaves exactly like when using unsigned long.
Video:
unsigned long/int: unsigned long - YouTube
int: integer - YouTube
The three leds represent the outputs.
Is this simple math really this slow when using unsigned or long variables?
Can cause any problems if i use normal int for storing the millis() output?

Solved by gcjr in post #23


amounts to on cylinder event / 10msec which is pretty slow consider -- see if it make sense to
you? am i interpreting what you want to do correctly? #include <digitalWriteFast.h> const int
PinIdent = 6; //pin 6 = cylinder identification input const int PinCyl = 7; //pin 7 = cylinder strobe …

b707 Des '22 post #2

neubauerp:
Now when i use unsigned long for the variables, the code runs very slow, the outputs are acting
funny, dropping out, etc.
I have tried using int, it runs perfectly

It can't be caused by difference between unsigned int and int, it more probable that you have an
error(s) in your code.
Please show cookies
We use 🍪
your sketch in full.

Our websites use cookies (also from third parties) for functional and analytical purposes, and to show you personalised advertisement. You can
neubauerp
adjust this in Cookie Settings or learn more by reading our cookie policy. Des '22 post #3

#include <digitalWriteFast.h>
const int ident = 6; //pin 6 = cylinder identification input
const int cyl = 7; //pin 7 = cylinder strobe input
ONLY REQUIRED ACCEPT ALL
Lewatiint
const ke konten
cyl14 utama
= 2; //pin 2 = 1-4 cylinder output
const int cyl52 = 3; //pin 3 = 5-2 cylinder output
const int cyl36 = 4; //pin 4 = 6-3 cylinder output

int identState = 0;
int cylState = 0;
int LastIdentState = 0;
int LastCylState = 0;
bool sync = 0;
int counterCyl = 0;
int counterIdent = 0;
int CurrTime;
int StrobeTime;

void setup() {
//define IO pins
pinModeFast(cyl14, OUTPUT);
pinModeFast(cyl52, OUTPUT);
pinModeFast(cyl36, OUTPUT);
pinModeFast(ident, INPUT);
pinModeFast(cyl, INPUT);
Serial.begin(2000000);
}

void loop() {

identState = digitalReadFast(ident);

if (identState != LastIdentState) {

if (identState == HIGH) {
counterIdent++;

counterCyl = 1;

} else {

counterIdent++;
counterCyl = 4;
}
}

LastIdentState = identState;

if (counterIdent > 1) {
sync = true;
} else {
sync = false;
}

if (counterIdent > 4) {
counterIdent = 2;
}

cylState = digitalReadFast(cyl);

CurrTime = millis();

We use cookies
if (cylState != HIGH) {
🍪
if (cylState != LastCylState) {

Our websites use cookies (also from third parties) for functional and analytical purposes, and to show you personalised advertisement. You can
counterCyl++;
adjust thisSerial.print("current
in Cookie Settings or learn more bycylinder:
reading our cookie");policy.
Serial.println(counterCyl);
StrobeTime = millis();
}
Lewati
} ke konten utama
LastCylState = cylState;

if (CurrTime - StrobeTime > 500) {

counterIdent = 0;
}

if (counterCyl > 6) {
counterCyl = 1;
}

//writing outputs depending on where the counter sits and sync is ok

if ((counterCyl == 1 || counterCyl == 4) && sync == true) {

digitalWriteFast(cyl14, HIGH);
} else {
digitalWriteFast(cyl14, LOW);
}
if ((counterCyl == 5 || counterCyl == 2) && sync == true) {

digitalWriteFast(cyl52, HIGH);
} else {
digitalWriteFast(cyl52, LOW);
}
if ((counterCyl == 3 || counterCyl == 6) && sync == true) {

digitalWriteFast(cyl36, HIGH);
} else {
digitalWriteFast(cyl36, LOW);
}

//end of loop
}

killzone_kid Des '22 post #4


Faraday

neubauerp:
if (CurrTime - StrobeTime > 500) {

Well if StrobeTime > CurrTime even for 1ms this expression will return true if you use unsigned long
and false if you use int.

b707 Des '22 post #5


You never update StrobeTime , so your timers runs only once after program statrts.
But if you using int for timer, it overflow after 32 seconds and the program start you logic from the
beginning

mrburnette Des '22 post #6


Faraday

neubauerp:
Is this simple math really this slow when using unsigned or long variables?

INT is either 16-bit or 32-bit, depending upon hardware architecture: UNO, Mega, etc. being 8-bit uC
but C/C++ does the 16-bit integer manipulation. Due and other more advanced microcontrollers are
32-bit architecture and C++ honors that native datatype.

We use cookies
this fundamental area.
🍪
Other casts in C++ are very efficient, a few clock cycles used only. Compilers are very optimized in

Our websites use cookies (also from third parties) for functional and analytical purposes, and to show you personalised advertisement. You can
I would not think your experience is indicative of INT byte-size or format.
adjust this in Cookie Settings or learn more by reading our cookie policy.
It would be simple to test in loop() by just capturing micros() at the beginning, perform some integer
math in a do-while loop, and capturing the elapsed time using micros before the close of loop().
Maybe to the inner loop for 10^4 - 10^5 times just to get a decent interval.
Lewati ke konten utama
Repeat above only with an unsigned int.
Compare. And please post the results if you perform the experiment. Your current sketch is not
provided, so further help is not possible.
UPDATE
See you posted your code and others are offering assistance.

neubauerp Des '22 post #7

killzone_kid:
Well if StrobeTime > CurrTime even for 1ms this expression will return true if you use unsigned
long and false if you use int.

So basically i have created a scenario, when StrobeTime > CurrTime can be true when using
unsigned long, and this causes the errors?

b707:
You never update StrobeTime , so your timers runs only once after program statrts.
But if you using int for timer, it overflow after 32 seconds and the program start you logic from
the beginning

Isnt StrobeTime being updated every time when


` if (cylState != LastCylState) {

if (cylState != HIGH) {`

is true?

mrburnette:
It would be simple to test in loop() by just capturing micros() at the beginning, perform some
integer math in a do-while loop, and capturing the elapsed time using micros before the close of
loop(). Maybe to the inner loop for 10^4 - 10^5 times just to get a decent interval.
Repeat above only with an unsigned int.

Sorry but i have just picked up an arduino a week ago, this is the first ever program that i wrote in
my life, sooo.. I dont really understand what you are saying

gcjr Des '22 post #8


looks like the code turns on one of 3 LEDs depending on which pair of cylinders are being
recognized and depending on identState that presumably toggles at once per rotation
shouldn't identState be the only thing resetting counterCyl ? i see counterCyl being set to 1, 4
depending on indentState and later reset to 1 when > 6
if identState toggles once per rotation, shouldn't it only reset counterCyl to something once (can't
say it harmless otherwise

b707 Des '22 post #9

neubauerp:
Isnt StrobeTime being updated every time when

please point the exact line of the code where you updated it.

GolamMostafa Des '22 post #10


Shannon

mrburnette:
We
INT use cookies 🍪
INT
Ouror int? use cookies (also from third parties) for functional and analytical purposes, and to show you personalised advertisement. You can
websites
adjust this in Cookie Settings or learn more by reading our cookie policy.

neubauerp Des '22 post #11


I want to use it for ditching the distributor on a 6 cylinder engine, and using a wasted spark coilpack.
Lewati keiskonten
counterCyl reset toutama
1 when it is more that 6, to jump back to cyl #1 after detecting cyl#6.
identState resets counterCyl to 1 or 4 to eliminate incorrect counts if one input of cylState is not
read for some reason.

This is the oscillogram of the two signals.


counterCyl cant be anything else than 1 when ident is going high. also it cant be anything else than 4
when ident is going low.

mrburnette Des '22 post #12


Faraday

GolamMostafa:
INT or int?

Seriously?
in code, int
in a paragraph to denote emphasis:

INT
INT
int
You struck a pet-peeve, pet peeve at DuckDuckGo

neubauerp Des '22 post #13


Do i need to reset CurrTime and StrobeTime to zero at the begining of the loop?

Koepel Des '22 post #14


Don't use 'int', but 'unsigned int' is allowed, or even uin8_t Don't use uint8_t, see reply #25.
If your 'unsigned int' is 16 bits, then a millis-timer can run up to 65 seconds. As always, you have to
carefully check your code that it is not doing funny things after another 65 seconds.
I used the 16-bit unsigned int in my millis_overdone.ino to run 400 millis-timer on a Arduino Uno.
Try the sketch in Wokwi here: millis_overdone.ino - Wokwi Arduino and ESP32 Simulator (all the
timers blink the led, but that is not visible in Wokwi).

b707 Des '22 post #15


It depends on your algorithm
But as far I understand your code - no

We use cookies
killzone_kid
Faraday
🍪 Des '22 post #16

Our websites use cookies (also from third parties) for functional and analytical purposes, and to show you personalised advertisement. You can
neubauerp:
adjust this in Cookie Settings or learn more by reading our cookie policy.

and this causes the errors?

I don’t know, and tbh don’t want to know, but you were looking for difference in behaviour when
Lewati ke
changing varkonten utama
type, feel free to investigate
gcjr Des '22 post #17
it looks ident rises just before the cylinder pulse and could be used to set the cylinder count to zero
because the cylinder input would rise just after it and set it to 1
i think you're using sync as a flag to indicate the events are occurring and can toggles the LEDs and
flag is reset after a timeout to inhibit toggling LEDs after a timeout period.

GolamMostafa Des '22 post #18


Shannon

mrburnette:
You struck a pet-peeve, pet peeve at DuckDuckGo

It has nothing to do with personal liking/disliking; it is the Compiler that puts objection against the
usage of INT.

mrburnette Des '22 post #19


Faraday

GolamMostafa:
It has nothing to do with personal liking/disliking; it is the Compiler that puts objection against
the usage of INT.

Rather it has everything to do with petty responses to how written communications are utilized. Not
only wasting my time but yours; my time is better utilized to go for a fresh cup of coffee.

GolamMostafa Des '22 post #20


Shannon

mrburnette:
Rather it has everything to do with petty responses to how written communications are utilized.

That means that the written communication can violate C++ Language's established conventions?

b707 Des '22 post #21


of course yes
Human communications are not regulated by programming language syntaxes...

gcjr Des '22 post #23

neubauerp:
The code needs to run pretty fast, as it handles two inputs of a camshaft sensor, one is 1
cycle/rotation, the other is 6 cycle/rotation. Expected max RPM is 3750.

amounts to on cylinder event / 10msec which is pretty slow


consider -- see if it make sense to you? am i interpreting what you want to do correctly?

#include <digitalWriteFast.h>
const int PinIdent = 6; //pin 6 = cylinder identification input
const int PinCyl = 7; //pin 7 = cylinder strobe input

const int cyl14 = 2; //pin 2 = 1-4 cylinder output


const int cyl52 = 3; //pin 3 = 5-2 cylinder output
const int cyl36 = 4; //pin 4 = 6-3 cylinder output

byte identLst;
We use cookies
byte cylLst;
bool sync;
🍪
Our websites use cookies (also from third parties) for functional and analytical purposes, and to show you personalised advertisement. You can
adjustcounterCyl;
int this in Cookie Settings or learn more by reading our cookie policy.

int counterIdent;
unsigned long CurrTime;
unsigned long StrobeTime;
Lewati ke konten utama
void setup ()
{
//define IO pins
pinModeFast (cyl14, OUTPUT);
pinModeFast (cyl52, OUTPUT);
pinModeFast (cyl36, OUTPUT);

pinModeFast (PinIdent, INPUT);


pinModeFast (PinCyl, INPUT);
Serial.begin (2000000);
}

void loop ()
{
unsigned long msec = millis ();

byte ident = digitalReadFast (PinIdent);


if (identLst != ident) {
identLst = ident;
sync = true;

if (HIGH == ident)
counterCyl = 0;
}

byte cyl = digitalReadFast (PinCyl);


if (cylLst != cyl) {
cylLst = cyl;

if (HIGH == cyl) {
counterCyl++;

Serial.print ("current cylinder: ");


Serial.println (counterCyl);
StrobeTime = msec;
}
}

// engine stopped
if (msec - StrobeTime > 500) {
sync = 0;
}

if (sync) {
digitalWriteFast (cyl14, counterCyl == 1 || counterCyl == 4);
digitalWriteFast (cyl52, counterCyl == 5 || counterCyl == 2);
digitalWriteFast (cyl36, counterCyl == 3 || counterCyl == 6);
}
}

neubauerp Des '22 post #24


In reality ident and cylinder pulse rises at the same time, this oscillogram was taken using the
arduino as i just have an 1 channel scope at home. It draws a bit funky but way better than 1
channel.
I am using the sync flag to make sure the sensor had at least one rotation before enabling any
outputs, as on power on, it can count from anywhere.
` if (CurrTime - StrobeTime > 500) {

counterIdent = 0;

}`

We use
engine, cookies
messing 🍪
is used to detect engine stalling, as stalling could result in a brief opposide direction rotation of the
up the counting. This resets counterIdent to zero, resulting in sync=false, thus the
sensor needs again a full revolution to synchnorize ident and cyl before enabling outputs.
Our websites use cookies (also from third parties) for functional and analytical purposes, and to show you personalised advertisement. You can
adjust this in Cookie Settings or learn more by reading our cookie policy.
Coding_Badly Des '22 post #25

Koepel:
Lewati
or evenke konten utama
uin8_t
...which is risky / problematic because of the promotion rules. Please don't suggest that again to
folks new to C programming.

mrburnette Des '22 post #26


Faraday

GolamMostafa:
That means that the written communication can violate C++ Language's established
conventions?

Short answer, yes.


Research papers early on have a page of conventions, so INT can easily represent the abbreviation
for integer while int can represent the data type specification in "the code"...
I could easily write a macro to cause the pre-processor to accept INT as a synonym for int, thus the
"code" is ligimate but the compiler is spared the 'error' output from a syntax mistake.

When "we" say code we often forget the compiler only gets what the pre-processor reguritates.
Capitalization Rules in Writing (tutorialspoint.com)

Capitalize acronyms

Acronyms are the initials of the first letter of multiple words. It is mandatory to capitalize the whole
acronym while writing it in any sentence.

neubauerp Des '22 post #28


Thats it! Thank you!!
I finally see what i am doing wrong.
I have moved CurrTime = millis(); to the beginning of the loop, and replaced StrobeTime =
millis(); with StrobeTime = CurrTime;. Both are unsigned longs.
The output artifacts are gone!
I have printed the

StrobeTime = millis();
Serial.println(CurrTime-StrobeTime);

line, and the result was always 0 or -1 if using integer!

GolamMostafa Des '22 post #29


Shannon
By definition and design, the counter (I call it millisCounter) from which millis() function reads the
accumulated time is a 32-bit unsigned counter. So, I will always go with the following declaration
and then debug my sketch to see why it is not running at the expected speed.

unsigned long int presentMillis = millis();

RayLivingston Des '22 post #30


Am I reading this right? OP is trying to control ignition timing, on a 6-cylinder engine, at up to 3750
RPM, by POLLING a 36-1 crank sensor, using millis() for timing?
If the above is true, it will NEVER work! Timing jitter would be massive, resulting in extremely poor
running, and serious risk of damaging the engine. Never mind that a single error in crank sensing
could easily result in the cylinders being fired out of sequence, which will nearly guarantee engine
damage.

neubauerp
We use cookies 🍪
No, millis is only used to detect if the engine has stalled.
Des '22 post #31

Our websites use cookies (also from third parties) for functional and analytical purposes, and to show you personalised advertisement. You can
adjust this in Cookie Settings or learn more by reading our cookie policy.

Lewati ke konten utama


gcjr Des '22 post #32

RayLivingston:
Timing jitter would be massive,

i'm curious, what is the tolerance?

Ditutup pada Jun 13


This topic was automatically closed 180 days after the last reply. New replies are no longer
allowed.

Back to top

Help Center FOLLOW US


Contact Us

Trademark & Copyright

Brand Guidelines

Distributors

Careers

© 2020 Arduino Terms of Service Privacy Policy Security Cookie Settings

We use cookies 🍪
Our websites use cookies (also from third parties) for functional and analytical purposes, and to show you personalised advertisement. You can
adjust this in Cookie Settings or learn more by reading our cookie policy.

You might also like