Tuesday, June 3, 2014

Arduino square wave pulse generator using the tone() library and serial port





Code:

/**
* Square wave pulse  generator
* How to use it: Send desired frequency in Hz using serial port Baud = 9600 8,N,1
* Note: CR or LF must be send as a line termination.
*
* Elimelec June-3th-2014
*/

unsigned int freq = 0; //frequency

int outPin = 13; //output pin


void setup(){

  Serial.begin(9600);//setup serial communication

}

void loop(){
  
  while(Serial.available() > 0){
      
      char tmpChar = Serial.read(); //read incoming character from serial port
  
     if(isDigit(tmpChar)){ //check if the in character it's a number
      
       freq =  (freq  * 10 ) + tmpChar - '0'; // convert from ascii code to it's corresponding number; '0' == DEC 48
     }       
     
     if(tmpChar == '\n' || tmpChar == '\r'){ //if CR or LF was received 
      
       if(freq > 0){
         Serial.print(freq);
         Serial.println(" Hz Set O.K");
         tone(outPin, freq); //set current frequency
       }
      
       freq = 0; // clear freq
     }
     
  }
   
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.