• Post comments:0 Comments
  • Reading time:2 mins read

Ref: https://www.arduino.cc/en/Tutorial/BuiltInExamples/SerialEvent

While you are communicating with ATFC touchscreen, you don’t want to keep waiting for the msgs in the loop, that will take most of your Arudino in doing nothing.

What you want is a msg come and then you leave your current job and start to deal with it. And that is called interrupt.

There are several kinds of interrupts available for Arudino and other MCUs too. In this article, we only focus on the Serial Interrupt on Arduino (serialEvent). In this case, whenever the ATFC touchscreen sends a msg back to Arduino, you can deal with it immediately instead keep waiting until the end of time.

There is a built-in serialEvent() function in Arduino, you can check the example and instruction on the official Arduino site.

void serialEvent(){ //This function is called when new Serial data comes.
   #do whatever you want here
}

The ATFC touch screen returns data into 3 different types:

int – data start with “@”

float – data start with “#”

String – data start with “$”

To process the returned data from ATFC touch screen, we can use the function as below:

void setup() {
   // put your setup code here, to run once:
   Serial.begin(9600);
 }
 void loop() {
   // put your main code here, to run repeatedly:
 }
void serialEvent() {
   int received_var_int;
   float received_var_float;
   String received_var_string;
   unsigned short body_id = ATFMessageService(&received_var_int, &received_var_float, &recived_var_string);
   //Handle the returned data here or you can store the data and handle it later in the main loop.
}
unsigned short ATFMessageService(int *m_ReciverVarInt, float *m_ReciverVarFloat, String *m_ReciverVarString)
 {
   char n_TempChar;
   unsigned short m_ReciverBodyID;
   n_TempChar = Serial.available();
   if(n_TempChar)
   {
     delay(2); // 2ms delay to make sure the data is successfully received.
     n_TempChar = Serial.read();
     while(n_TempChar!='@'&&n_TempChar!='#'&&n_TempChar!='$'&&n_TempChar>=0)
     {
       n_TempChar = Serial.read();
     }
   m_ReciverBodyID = Serial.parseInt();
   if(n_TempChar=='@') {
      *m_ReciverVarInt = Serial.parseInt(); 
   } else if(n_TempChar=='#') {
      *m_ReciverVarFloat = Serial.parseFloat();
   } else if(n_TempChar=='$') {
      Serial.read();
      *m_ReciverVarString = Serial.readStringUntil('\r');
   }
   return m_ReciverBodyID;
 }
}

close

Updates

Tips

Coupons

We don’t spam! Read our privacy policy for more info.

Leave a Reply