How to adjust the default increment of 1 to 2?

Status
Not open for further replies.

eebhoi01

Advanced Member level 4
Joined
Feb 22, 2012
Messages
116
Helped
0
Reputation
0
Reaction score
0
Trophy points
1,296
Activity points
2,347
Hello Everyone!

Pleas let me know how should I write so that the increment would be by 2. I understand that this code will increment the value of cnt++ by one up to 255. Help me make it by two's please, THanks

 

Just change the cnt++ to cnt+=2

cnt is the variable, ++ means increment by 1, += means add the given number to the variable

Code:
if (kp != oldstate) { // Pressed key differs from previous
cnt = 1;
oldstate = kp;
}
else { // Pressed key is same as previous
cnt+=2;

}
Lcd_Chr(1, 10, kp); // Print key ASCII value on LCD

if (cnt == 255) { // If counter varialble overflow
cnt = 0;
Lcd_Out(2, 10, " ");
}

WordToStr(m, txt); // Transform counter value to string
Lcd_Out(2, 10, txt);
 
Thank you sir, I appreciate it much ^_^
 

Can you clarify, why you need to increment this variable by 2 instead 1? It could generate some troubles in your code. I think condition

Code C - [expand]
1
if (cnt == 255)

could be missed in some situations. Maybe change it to

Code C - [expand]
1
if (cnt >= 255)

 

That will work if cnt is a 16 bit (or more) variable, not if it's an 8 bit, since it will never be more than 255 and will roll over from 254 to 0, missing the test again.
 


Its only for display purposes sir ^_^, im not using it to other complicated codes.

That will work if cnt is a 16 bit (or more) variable, not if it's an 8 bit, since it will never be more than 255 and will roll over from 254 to 0, missing the test again.

Hello Sir FoxyRick,

How about if I do the other way around. Say if I press another botton it will decrease by two, should I use cnt-- and then cnt-=2?
 

cnt-- will subtract 1 from cnt.

cnt-=2 will subtract 2 from cnt.

You do not need to do both of them (if you do, you will subtract 3 all together)
 

cnt-- will subtract 1 from cnt.

cnt-=2 will subtract 2 from cnt.

You do not need to do both of them (if you do, you will subtract 3 all together)

ok i got it thanks ^^
 

Status
Not open for further replies.

Similar threads

Cookies are required to use this site. You must accept them to continue using the site. Learn more…