I'ts a couple of days I'm fighting against a problem that looks simple but ...
I need to test every single bit of an extended DI (pcf8514) to activate relays.
I've prepared a simple sketch to test the "FOR" instruction and using the serial monitor to check results.
Well after the for instructions the sketch does'nt return to wait for a new input but it continues to loop around the 2 for instructions?
Where is my mistake?
thanks for any help
int cnt=0;
int input=0;
int input1=0;
int mask=B00001;
int divalue [8];
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
if (Serial.available() > 0)
{
// read the incoming byte:
input1 = Serial.read();
// say what you got:
Serial.print("I received: ");
Serial.println(input1, BIN);
}
for (int cnt=0; cnt <=7; cnt++);
{
input= input1>>cnt;
divalue [cnt] = mask & input;
Serial.println (cnt);
}
Also, please read Nick Gammon's posts at the top of this Forum on the proper was to post source code using code tags. Also, using Ctrl-T on the source code in the IDE formats it into a common C style that is easier for us to read.
Your for loops are outside of the "if(Serial.available())" block so they will execute every time through loop(), unconditionally (even if you remove the misplaced semi-colons). Move the } that closes the if loop to after the last for loop to only run the for loops when there is incoming data.
Also, depending on how the line endings are set in serial monitor (just left of baud setting), you will send 1, 2 or 3 bytes from serial monitor for each byte that you type in. Set line endings to none and only the byte that you send will be received. Otherwise you will receive the byte that you type and a carriage return and/or line feed.
Code fixed per larryd and my comments and properly posted in code tags and indented (per econjack):
int cnt = 0;
int input = 0;
int input1 = 0;
int mask = B00001;
int divalue [8];
void setup()
{
// put your setup code here, to run once:
Serial.begin(9600);
}
void loop()
{
// put your main code here, to run repeatedly:
if (Serial.available() > 0)
{
// read the incoming byte:
input1 = Serial.read();
// say what you got:
Serial.print("I received: ");
Serial.println(input1, BIN);
// moved } to after last for loop
for (int cnt = 0; cnt <= 7; cnt++) // removed ;
{
input = input1 >> cnt;
divalue [cnt] = mask & input;
Serial.println (cnt);
}
Serial.print("I calculated: ");
for (int cnt = 0; cnt < 8; cnt++) // removed ;
{
Serial.println(divalue [cnt]);
}
}
}