I have been working on a rotary encoder, the code I used when the encoder is in just the right spot it goes up really fast, I added comments Where what I tried adding to prevent that but it did not do anything, Please help me out,
#define OutA 7
#define OutB 6
int counter;
int theState;
int LastState;
void setup()
{
Serial.begin(9600);
pinMode (OutA, INPUT);
pinMode(OutB, INPUT);
theState = digitalRead(OutA);
}
void loop()
{
LastState = digitalRead(OutA);
if (theState != LastState)
{
if (digitalRead(OutB) != LastState)
{
counter++;
delay (1); //this is what I tried Adding
digitalWrite(OutB, LOW); //this is what I tried Adding
}
else
{
counter--;
}
Serial.println(counter);
}
LastState = theState;
}
That doesn't make sense... there is no "right spot" for an encoder. If coded correctly it will only increment on moving, never when it sits in some "right spot".
Using int for a boolean variable on an 8 bit processor may be "correct" in some strange meaning of the word but it is also slow and wasteful. AFAIK the compiler is not clever enough to optimize this.
I believe the Arduino uses a full byte to store a bool. So a byte may be an option if running low on memory.
To really do a bit at a time requires some coding into a struct:
See post 5
is wrong, it must be byte someval = 0b00001111;
otherwise compiler will use 16 bit arithmetic, increasing code a RAM memory usage and checking the MSB everytime at runtime only to find it is still 0.
I am afraid this is a wishful thinking. On Arduino 1.8.8 test code:
void setup() {
Serial.begin(115200);
}
byte someval=0xf;
void loop() {
if (someval&1) Serial.print('a');
if (someval&2) Serial.print('A');
if (digitalRead(2)==HIGH) someval=1;
if (digitalRead(3)==HIGH) someval=2;
if (digitalRead(4)==HIGH) someval=3;
}
Needs 186 bytes of RAM regardless if someval is byte or int. But Flash usage is 1740 bytes when someval is byte and 1758 bytes when someval is int. Comenting out if (digitalRead(4)==HIGH) someval=3; reduces Flash usage by 16 vs 24 bytes and commenting out if (someval&2) Serial.print('A'); reduces it by 14 vs 16 bytes. My conclusion:
The nonexistence of RAM difference is only due to the fact only one variable is used and so it is kept in registers and not placed in RAM
The compiler is not able to optimize away the MSB check even in the simplest scenario someval&2. If the variable were stored in RAM the unnecessary load into registers will increase the difference.
Be careful with that statement. While bool does occupy one byte of space in most cases (one exception is std::vector<bool>), it can store only one bit of information. That is, if you assign any non-zero value to a bool variable, it will be assigned the value 1.