Serial event

Hello,

I would like to ask a question regarding the SerialEvent() function. Looking at the following code:

char data_in; // global variable


void setup() {
	Serial.begin(115200);
	data_in = 'r'; // initialize default
}

void loop() {
	if(data_in == 'r') {
		Serial.print("something1")
	}
	
	else if (data_in == 't') {
		Serial.print("something2")

	}

	else Serial.print("something3")

}

void SerialEvent() {
	while(Serial.available()) {
		data_in = (char) Serial.read();
	}
}

I am wondering if this is correct? I am trying to use different parts of code with respect to what I send via the receive port.

So if I send a char 't' via the serial port, the "else if" should execute constantly until I send a diffrent char. If I write the serial data to data_in variable, will it initialize to the value I have sent over the serial (and stay the same in all subsequent iterations until I change the value)?

I am having some problems with this code, since the value I send via the serial event doesn't change (the data_in part).

Thank you for your help and best regards,
K

Hi,

Try changing SerialEvent() by serialEvent().

Best Regards.

will it initialize to the value I have sent over the serial (and stay the same in all subsequent iterations until I change the value)?

'

I would expect so.
If you just want a single 'r' or 't', then change data_in to not be 'r' and 't' after printing something1, something2

void SerialEvent() {
	while(Serial.available()) {
		data_in = (char) Serial.read();
	}
}

Aside for the incorrect name, why are you reading the data in a while loop? If you have the Serial Monitor set to append anything to the data sent, the data will arrive relatively close together, and all that data_in will end up containing is the last character.

Thank you for all your help.

It seems my mistake was in the function name SerialEvent() instead of serialEvent().

I have a sensor attached to a custom board (Atmega328p-au) and I need to change what it returns based on a serial receive command.
It works fine now.

About using while loop - I followed the example from http://arduino.cc/en/Tutorial/SerialEvent.
I removed the while loop and it works the same.

Best regards,
K

I removed the while loop and it works the same.

In the case where you send data slowly or get around to reading it quickly. It's not a good idea, in general, though, to use a while loop that way.

Trie it like this

char data_in; // global variable


void setup() {
	Serial.begin(115200);
	data_in = 'r'; // initialize default
}

void loop() {
	if(data_in == 'r') {
		Serial.print("something1")
	}
	
	else if (data_in == 't') {
		Serial.print("something2")

	}

	else Serial.print("something3")

}

void serialEvent() {
	while(Serial.available()) {
		data_in = (char) Serial.read();
	}
}

Trie it like this

Or, try code that actually compiles.