int incomingByte = 0; // for incoming serial data
/*F********************************************************************
*
**********************************************************************/
void
setup()
{
Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
}
/*F********************************************************************
*
**********************************************************************/
void
loop()
{
// reply only when you receive data:
if( Serial.available() > 0)
{
incomingByte = Serial.read(); // read the incoming byte:
Serial.print( "I received: "); // say what you got:
Serial.println( incomingByte, DEC);
}
}
Arduino Mega example:
This code sends data received in one serial port of the Arduino Mega to
another. This can be used, for example, to connect a serial device to
the computer through the Arduino board.
/*F********************************************************************
*
**********************************************************************/
void
setup()
{
Serial.begin( 9600 );
Serial1.begin( 9600 );
}
/*F********************************************************************
*
**********************************************************************/
void
loop()
{
// read from port 0, send to port 1:
if( Serial.available())
{
int inByte = Serial.read();
Serial1.print( inByte, DEC);
}
// read from port 1, send to port 0:
if( Serial1.available())
{
int inByte = Serial1.read();
Serial.print(inByte, DEC);
}
}
See also
-
LANGUAGE begin()
-
LANGUAGE end()
-
LANGUAGE read()
-
LANGUAGE peek()
-
LANGUAGE flush()
-
LANGUAGE print()
-
LANGUAGE println()
-
LANGUAGE write()
-
LANGUAGE SerialEvent()
-
LANGUAGE Stream.available()