I am writing some code and I want to send some values to a function. For example:
void loop(){
If (output < 100){
set alarm(1)
//error code = 1
}
else if (output >500){
set alarm(3)
//error code = 3
}
}
void set alarm(){
while (alarm >0){
Serial.print("The alarm is active")
Serial.print (Place the alarm error in here)
}
}
In short I want to call that particular function and set a code (between brackets) that is transfered via serial. I dont kno if thats how it is done, so bare with me if I am making a terrible mistake. the purpose of the "sketch" was just to show what I need, so that someone can offer guidance in the best way to achieve the purpose.
Please feel free to ask if you find the code incomplete or need further details!
C and derived languages are "space delimited", hence "set space alarm " is not valid function name.
If you compile your code you will get an error. That is one of the tasks compiler does for your, so it is perfectly OK to always compile your code even when if you know it may not function properly.
Another point - if you are learning to use functions, get into habit to enter the parameters, even of type
"void" which is not required by language standards.
Same with "return". This enforces the role of function to process parameters and report on results.
Such as void setAlarm(void) {..... return; }
Cheers Vaclav
I'd like to take Bulldog's example and modify it a bit. I'm not a big fan of global data because everything has access to it. Instead, I try to encapsulate the data and keep it as private as possible. My example, encapsulates the alarm state so if something changes it, it is easier to isolate where the change took place.
void setup()
{
Serial.begin(9600);
}
void loop()
{
int output = 200; //example
int alarmState; // the variable is no longer global, so it can only be changed within loop().
alarmState = setAlarm(output);
switch (alarmState) {
case 1:
Serial.println("Alarm state = 1");
break;
case 2:
Serial.println("Alarm state = 2");
break;
case 3:
Serial.println("Alarm state = 3");
break;
default:
Serial.println("I should never see this");
break;
}
}
int setAlarm(int value)
{
int state;
if (value < 100) {
state = 1;
} else if (value < 500) {
state = 2;
} else {
state = 3;
}
return state;
}