Hey guys. I have been stuck on trying to get one function of code to work.
What it needs to do is; after specific time print 1 serial character, then check the serial for a response.
If it gets the response it needs it turns an LED off and if it doesn't it waits until it does.
This is going to be used in an xbee project and I need 1 of the modules to check if it is in range/connected to the other one.
I have tried many combinations to get this to work.
Example code:
int led = 4;
int data;
long pretime = 0;
long interval = 0;
long checktime = 0;
long currenttime = 0;
void setup(){
Serial.begin(9600);
pinMode(led, OUTPUT);
digitalWrite(led, LOW);
}
void loop(){
data = Serial.read();
interval = 5000;
unsigned long currenttime = millis();
if(currenttime - pretime > interval){
Serial.println("b");
if (data == 'c'){
digitalWrite(led, LOW);
pretime = millis();
checktime = millis();
}
else if (data != 'c'){
checktime = millis();
if(currenttime - checktime > interval){
digitalWrite(led, HIGH);
pretime = millis();
checktime = millis();
}
}
}
}
long currenttime = 0;
unsigned long currenttime = millis();
Two different variables, with different types, is rarely a good idea. Get rid of one of them.
unsigned long currenttime = millis();
if(currenttime - pretime > interval){
Serial.println("b");
if (data == 'c'){
}
else if (data != 'c'){
checktime = millis();
if(currenttime - checktime > interval){
If data is not 'c', and currenttime minus pretime is greater than interval, set checktime to just about the same time that currenttime was just set to. Then, see if the difference is greater than interval. Unless interval is 0, the chances that the difference will be greater than interval are 0.
I'd suggest that some comments in your code would be a good thing, that each { belongs on its own line, and that the Tools + Auto Format menu item be used.
Also, look at what you say you want to do:
after specific time print 1 serial character, then check the serial for a response.
You read serial first, even if there is nothing to read. Then, maybe you send a character, and then see if what you read before sending the character is the response you expect.
I'd suggest that you send the character, delay() for a while, and then read the response, if one has arrived.
Only when you get that working should you try to use millis() to avoid the use of delay().