5 Unit5 Arduino Interrupt, Timer and Communication
5 Unit5 Arduino Interrupt, Timer and Communication
and communication
Sandip J. Murchite
Arduino Interrupt
• Interrupt
– Interrupts are the section of hardware
and software on microcontroller
which is capable of monitoring the
external event on the input pin.
T= 10ms
OCR2A= (16MHZ/1024) *10ms
=156.25 = 156
#define ledPin 13
Void Setuptimer()
{
noInterrupts(); // disable all interrupts
TCCR2A = 0;
TCCR2B = 0;
TCNT2 = 0;
OCR2A = 156;
TCCR2A |= (1 << WGM21);
TCCR2B = (1<<CS20) | (0<<CS21)|(1<<CS22);
TIMSK2 |= (1 << OCIE2A)
interrupts();
Serial.println("TIMER2 Setup Finished.");
}
void setup()
{ Serial.begin(9600);
pinMode(ledPin, OUTPUT);
Setuptimer ();
}
ISR(TIMER2_COMPA_vect)
{ digitalWrite(ledPin, digitalRead(ledPin) ^ 1); }
void loop()
{ }
Basic functions related to Serial Communication in Arduino
• Serial.begin(baud_rate)
• baud_rate : The baud rate that will be used for serial communication. Can be 4800, 9600,
14400, 19200, etc.
• This function is used to define the baud rate that will be used for serial communication.
• Example Serial.begin(9600)
defines 9600 baud rate for communication.
• Serial.available()
• This function is used to get the number of bytes available for reading from the serial port. It
gives the number of bytes of data that has arrived and is stored in the serial receive buffer.
• Example if(Serial.available())
If data available at serial port, take action.
• Serial.print(value)
• value : character, string, number to be printed.
• This function is used to print data to a serial port in a form that is human readable
(character, strings, numbers).
• Example Serial.print(“Hi 1234”)
• Serial.write(value)
• value : value to be sent as a single byte.
• This function writes data in binary form to the serial port. Data is sent in form of bytes or series of
bytes.
• Example Serial.write(100)
Serial communication program to transmit
and receive data
int inByte; void loop()
{
if (Serial.available() > 0)
{
void setup() inByte = Serial.read();
{
Serial.begin(9600);
pinMode(13, OUTPUT);
Serial.println("Type 1: LED ON, 0: LED OFF "); if (inByte == '1')
} {
digitalWrite(13, HIGH);
Serial.println("LED - On");
}
else
{
digitalWrite(13, LOW);
Serial.println("LED - off");
}
}
End of unit