Disclaimer

This is sample documentation for a suggested Serial function. It does not yet exist in the arduino core, and therefore cannot be used at this time without hacking the core. If you wish to try it, feel free to download the following zip file and extract it into the /hardware/cores/ directory. Then, create a new board definition in the boards.txt file that uses chirps as the build core instead of arduino.

http://engr.georgefox.edu/wiki/uploads/Chirps/chirps.zip

Please enjoy,
-Chris Hammond

Serial.onReceive(MyFunction)

Description

Used during setup() to specify a user written function to be called whenever a serial 'packet' is received (defined as a string of bytes followed by a 10 ms pause) or whenever the serial receive buffer overflows.

Syntax

This function requires the separate definition of the function to be called. The function definition should be of the following format:

void MyFunction(){
   //user code goes here
}

As this function is called during an Interrupt, certain operations, such as delay() which are dependent on interrupts will not work. If any of these functions are needed, it is possible to re-enable other interrupts using the command sei() at the beginning of MyFunction. However, extreme care should be taken in this case as concurrency issues can arise from MyFunction being called by an interrupt during the operation of another instance of MyFunction. The syntax for this case is shown below:

void MyFunction(){
   sei();
   //user code goes here
}

Parameters

MyFunction, the name of the user written function to be called. (No parenthesis are needed after MyFunction, as we are not actually calling it when we call attachReceiveFunction)

Returns

nothing

Example

void MyFunction(){
   int i;
   int length = Serial.available();
   int string_buffer[32];   

   //copy data out of the receive buffer
   for(i = 0; i < length; i++){
      string_buffer[i] = Serial.read();
   }

   //run a string compare function, or otherwise parse the received data
   if(MySpecialStingCompare(string_buffer,"Hello Arduino")){
      Serial.println("Hello World");
   }
}

void setup(){
   Serial.begin(19200);
   Serial.onReceive(MyFunction);
}

void loop(){
   //do nothing
}

Share