Skip to content

Serial Comunication between Arduinos – With Wire & Wireless

– please check an updated code sample on the following post –
http://lab.guilhermemartins.net/2013/08/01/new-basic-arduino-serial-communication/

 

I´ve created this example to make two Arduinos talk in a simple and clear fashion.
You will see below an example with wires, and another one without wires.

- – - – - – - – - – - – - – - – - – - – - – - – - – - – - – - – - – - – - – - – - – -

Setup with TX and RX pins connected by wire:

On the sender Arduino there is a potenciometer, the values are read and sent through the serial port.
On the receiver Arduino one Led intensity will change accordingly the pot value.

Tx on Arduino#1 -> connect to ->  Rx  on Arduino#2
Rx on Arduino#1 -> connect to ->  Tx on Arduino#2

NOTE:
Don´t forget to disconnect Tx / Rx wires before upload

// SENDER

int analogValue5, val5;

void setup() {
// Serial port enable
Serial.begin(19200);
}

void loop() {
// read analog pin 5
analogValue5 = analogRead(5);

// remap values from the analogValue5 variable to 0 / 255
val5 = map(analogValue5, 0, 1023, 0, 255);

// send the value to the serial port
Serial.println(val5, BYTE);

}

- – - – - – - – - – - – - – - – - – - – - – - – - – - – - – - – - – - – - – - – - – -

// RECIEVER

byte incomingByte;

void setup() {
// Serial port enable
Serial.begin(19200);

// declare pin 11 as output, this is the LED
pinMode (11, OUTPUT);
}

void loop() {

// if there is bytes available coming from the serial port
if (Serial.available()) {

// set the values to the ‘incomingByte’ variable
incomingByte = Serial.read();

// write the value to the pin 11
analogWrite(11, int(incomingByte));

}
}


- – - – - – - – - – - – - – - – - – - – - – - – - – - – - – - – - – - – - – - – - – -
- – - – - – - – - – - – - – - – - – - – - – - – - – - – - – - – - – - – - – - – - – -
- – - – - – - – - – - – - – - – - – - – - – - – - – - – - – - – - – - – - – - – - – -

Wireless setup with XBee modules:

Recently I got two XBee modules, and here is the setup to make them talk to each other:
As a start I used 2 potenciometers to control the intensity of two LEDs and It works pretty well.  :]

I´m using this adapters to connect the XBee to the circuit. They are very simple to assemble and to use.

- – - – - – - – - – - – - – - – - – - – - – - – - – - – - – - – - – - – - – - – - – -

// SENDER

int analogValue2, analogValue5, val2, val5;

void setup()
{
// start serial port at 19200 bps
Serial.begin(19200);
}

void loop()
{
// read analog input
analogValue2 = analogRead(2);
analogValue5 = analogRead(5);

// remap values

val2 = map(analogValue2, 0, 1023, 253, 0);  // 254 and 255 for SYNC
val5 = map(analogValue5, 0, 1023, 253, 0);

Serial.print(254, BYTE); //SYNC char
Serial.print(val2, BYTE);

Serial.print(255, BYTE); //SYNC char
Serial.print(val5, BYTE);

delay(150);
}

- – - – - – - – - – - – - – - – - – - – - – - – - – - – - – - – - – - – - – - – - – -

// RECIEVER

byte incomingByte, sensor1, sensor2;

void setup() {

// start serial port at 19200 bps
Serial.begin(19200);
Serial.println(“Ready!”);

// led pins

pinMode (5, OUTPUT);
pinMode (6, OUTPUT);

delay(1000);

}

void loop() {
if (Serial.available()) {   // are there any bytes available on the serial port ???

// assign bytes to the var ‘incomingByte’
incomingByte = Serial.read();

Serial.print(int(incomingByte));

// from now on is pretty clear I guess   :)

if ((int(incomingByte) == 254)) {
sensor1 = Serial.read();
Serial.print(“Sensor 1 = “);
Serial.print(int(sensor1));
}

if ((int(incomingByte) == 255)) {
sensor2 = Serial.read();
Serial.print(“  Sensor 2 = “);
Serial.print(int(sensor2));
}
}

analogWrite (5, sensor1);
analogWrite (6, sensor2);
}
Share

{ 74 } Comments

  1. Jose | January 4, 2009 at 9:09 pm | Permalink

    I want to see you do the wireless part with ladyadas softserial library on pins 2 & 3. I am having problems.
    Thanks
    -Jose

  2. GUI | January 4, 2009 at 9:50 pm | Permalink

    SoftSerial library emulates rx / tx pins and if you want to have a reliable connection you should the original Serial protocol.

  3. Rico Bravo | January 6, 2009 at 2:12 am | Permalink

    Ok, got it working here is the code below for anyone that wants to do it with the AFsoftserial software:
    #include

    int LEDpin = 5;
    byte address;
    byte data;

    AFSoftSerial mySerial = AFSoftSerial(2, 3);

    void setup() {
    pinMode(LEDpin,OUTPUT);
    pinMode(13, OUTPUT);
    Serial.begin(9600);
    Serial.println(“Chip 2 online”);
    // set the data rate for the SoftwareSerial port
    mySerial.begin(9600);

    }

    void loop() // run over and over again
    {

    if (mySerial.available()) {
    // Serial.print((char)mySerial.read()); // took this out so I do not loose a byte
    address = mySerial.read();
    Serial.print(address);
    if (address == ’2′)
    {
    data = mySerial.read();
    if (data == ’5′);
    {
    digitalWrite(LEDpin,HIGH);
    delay(1000);
    digitalWrite(LEDpin,LOW);
    }

    Serial.print(data);

    }

    }
    if (Serial.available()) {
    mySerial.print((char)Serial.read());
    }
    delay(50);

    }

  4. Jose | January 6, 2009 at 2:53 am | Permalink

    Oh,
    Here is the sender arduino code the above is the receiver arduino code!

    #include
    #define Button 6
    //int inPin = 6; //
    int val = 0;
    int old_val = 0;
    int state = 0;
    int val5 = 86;
    AFSoftSerial mySerial = AFSoftSerial(2, 3);

    void setup() {
    pinMode(Button,INPUT); //
    pinMode(13, OUTPUT);
    Serial.begin(9600);
    Serial.println(“Chip 1 online”);
    delay(2000);
    // set the data rate for the SoftwareSerial port
    mySerial.begin(9600);
    // mySerial.println(“Whats for dinner?”);
    }

    void loop() // run over and over again
    {
    val = digitalRead(Button); // read input value and store it. Yum, fresh
    // check if there was a transition
    if ((val == HIGH) && (old_val == LOW))
    {
    state = 1 – state;
    mySerial.println(2);
    mySerial.println(5);
    Serial.println(“Rising Edge”);
    delay(250);
    }
    old_val = val; // val is now old, let’s store it

    if (mySerial.available()) {
    Serial.print((char)mySerial.read());
    }
    if (Serial.available()) {
    mySerial.print((char)Serial.read());
    }

    delay(50);
    Serial.println(val); //

    }

  5. GUI | January 6, 2009 at 9:57 am | Permalink

    must try this!
    thanks for sharing! ;-)

  6. Shawn | February 19, 2009 at 1:30 am | Permalink

    I got our Xbee’s in the mail today. I am going to start off with your example here to try and get an understanding before attempting to use them in a robot, etc. I wish I had one of the protoshields you are using though.

  7. GUI | February 19, 2009 at 7:01 am | Permalink

    Glad to know that, If you need help just say!
    Protoshields are great, I advice you to get a bunch of them :-)

  8. wesley | August 10, 2009 at 1:38 pm | Permalink

    Hi there

    Sorry – new to arduino and trying to understand basic rx tx. I’ve set up everything (the hardwired setup) exactly like you have yet the LED only goes on or off – the pot has very little control – definitely no smooth fading. Does the value of the pot matter? No idea what i could be doing wrong?

  9. GUI | September 1, 2009 at 7:08 am | Permalink

    @ wesley
    It’s hard to tell what might be wrong with your setup! Have you double check all the connections / wirings?
    Can you send me a photo?

  10. filipe | December 31, 2009 at 2:21 pm | Permalink

    Para comunicar é preciso ter o TX, e o RX? ou dá para ter um master, ligado a um slave apenas com um TX(no master) e um RX(no slave)? só um fio?

  11. GUI | December 31, 2009 at 2:26 pm | Permalink

    Não te quero induzir em erro, mas julgo que sim, se usares apenas uma ligação de Tx (master) – Rx (slave) tens comunicação unidireccional.

  12. filipe | December 31, 2009 at 2:26 pm | Permalink

    Isto porque tenho um controlo remoto de apenas um canal, e queria com a penas um canal controlar vários servos/motores

  13. GUI | December 31, 2009 at 6:28 pm | Permalink

    sim é possivel, como pretendes fazer a distinção do sinal, ou seja, como vais fazer para mexer um servo e não outro?

  14. Cihan | September 2, 2010 at 11:38 am | Permalink

    I want to control a servo using 2 xbees by a potentiometer in the same manner as led . But I am having a trouble. Can anybody help me please?

    //Sender Code*************************

    int analogValue5, val5;

    void setup() {
    // Serial port enable
    Serial.begin(9600);
    }

    void loop() {
    // read analog pin 5
    analogValue5 = analogRead(0);

    // remap values from the analogValue5 variable to 0 / 255
    val5 = map(analogValue5, 0, 1023, 0, 180);

    // send the value to the serial port
    Serial.println(val5, BYTE);

    }
    ********************************************

    receiver code *********************************
    byte incomingByte;

    #include
    Servo servoMotor;

    void setup() {
    // Serial port enable
    Serial.begin(9600);

    servoMotor.attach(9);
    servoMotor.write(0) ;

    // declare pin 11 as output, this is the LED
    pinMode (9, OUTPUT);
    }

    void loop() {

    // if there is bytes available coming from the serial port
    if (Serial.available()) {

    // set the values to the ‘incomingByte’ variable
    incomingByte = Serial.read();

    servoMotor.write(int(incomingByte));
    delay(300);

    }
    }

    ***************************************************

  15. Brett Levine | January 3, 2011 at 7:56 pm | Permalink

    Hey Guilherme,

    I love your work and your site. I stumbled across this post when working with XBees to control my flame effects. Thanks for making this available, I’d love to talk more about electromechanical devices and art.

    Brett Levine

  16. Varad Gunjal | March 11, 2011 at 2:44 pm | Permalink

    Hey, I am trying to establish wireless communication between 2 XBee modules by using the XBee API. So far, I have gotten the communication to work to an extent that I can control the LED of one Arduino, by the other, using wireless communication between the 2 XBees.
    I, now, want to go in for wireless transmission of data i.e. strings hard-coded in the program itself should be sent by one and received by the other, upon writing the code to one Arduino, and be displayed on the receiving end’s serial monitor. I tried to tweak the code given above for this purpose, however failed miserably.

    Please help!

  17. Varad Gunjal | March 11, 2011 at 2:58 pm | Permalink

    P.S. I need it using the NewSoftSerial library, as my make of the XBee module is working best with this library.

  18. Jon | March 18, 2011 at 8:41 pm | Permalink

    Thanks for sharing this. I was wondering how does SYNC char work in your code? Because I am trying to send data from two analog sensors and one digital switch from one xbee module to the other one so the LEDs on the receiving side would light up correspondingly. I am trying to figure out how to “label” serial data so the receiving side would “read and interpret” the data accordingly. And it seems like you were able to do that with the SYNC char so I am hoping you can explain to me how SYNC works.

    Thank you

  19. goodsha | April 3, 2011 at 2:51 pm | Permalink

    this is a great post. for a start i would like to thank all the geniuses who come up with this software that are really making communication easy, technology has really helped us. for some of us who do not understand the language of technology but love to use its end product, all i can say is KEEP UP.

  20. GUI | April 12, 2011 at 8:28 am | Permalink

    Thanx, glad to know it helped ;)

  21. Mak Ajanovic | May 22, 2011 at 12:56 am | Permalink

    What mode is the Xbee operating in? I am assuming it is in Transparent mode? How did u set up the Xbee? or did u just use it out of the box and it worked?

  22. Kawal | June 9, 2011 at 5:19 pm | Permalink

    Thats a really cool,easy,beginner friendly tutorial.I have ordered two xbees and will start off with this tutorial.I was completely blank in wireless communication but this helped a lot.

  23. Kawal | June 9, 2011 at 5:36 pm | Permalink

    what does SYNC means and why is it needed ?

  24. GUI | June 16, 2011 at 9:44 pm | Permalink

    cool! glad to know that it helped ;)

  25. GUI | June 16, 2011 at 9:48 pm | Permalink

    SYNC is a byte that is used by the Receiver to know exactly what it will receive on the next time

    for instance, and looking to the code, imagine you send me “255″, I know that the next value will be assigned to the var “sensor2″

  26. Kawal | June 17, 2011 at 3:38 pm | Permalink

    How about i declare some other characters like “A”for the first potentiometer and “B” for the second potentiometer instead of 254 and 255. Will it still work ?

  27. GUI | June 17, 2011 at 4:21 pm | Permalink

    Yes you can do that and you should ;)

  28. phil | June 25, 2011 at 2:28 pm | Permalink

    im about to buy some of the modules and i am also working on mac os. as i see you use a macbookpro what software did you use to configure the xbees? or dont you need to configure them if you use em with two arduino-boards? i am a bit confused about all the forum posts in the net about how hard it is to make xbees running on macos.

  29. Mike | November 5, 2011 at 3:00 am | Permalink

    Would you please send me the Xbee firmware configuration for your setup here? Did you use API mode for xbee? Did you use one Router API and one Coordinator API? Let me know please, I am trying to do this example.

  30. GUI | November 5, 2011 at 12:57 pm | Permalink

    In order to configure the xbees you need to use X-CTU software provided by Digi/Maxstream, note that this application run on Windows only.
    You can also use AT commands but I never did it.
    Better is to check Ladyada’s tutorial: http://www.ladyada.net/make/xbee/configure.html

  31. GUI | November 5, 2011 at 12:58 pm | Permalink

    In order to configure the xbees you need to use X-CTU software provided by Digi/Maxstream, better is to check Ladyada’s tutorial: http://www.ladyada.net/make/xbee/configure.html

  32. uzma | February 13, 2012 at 3:41 pm | Permalink

    i am trying to get the output from the ping sensor to my system..can any one help me with this please

  33. DSBerry | February 23, 2012 at 9:02 pm | Permalink

    Just wanted to pop in here to say

    THANK YOU

    Was having a serious block receiving sensor values over xbee and you SOLVED it. THANK YOU!

  34. andrew | February 27, 2012 at 11:35 pm | Permalink

    please any body new to xbee i want to know how to setup a xbee module so it can communicte to another xbee module can you help me please ??

  35. GUI | February 28, 2012 at 10:37 am | Permalink

    hi! check this tutorial: http://www.ladyada.net/make/xbee/point2point.html

  36. xbee | March 8, 2012 at 6:07 pm | Permalink

    Hi,
    I have managed to make it work.
    Now i have three digital pushbuttons which i need to synchronize with xbees.

    How do i do that ?

    Thank you!

  37. GUI | March 8, 2012 at 6:08 pm | Permalink

    Hi! Have you tried the arduino forums? I’m sure it has been explained there.

  38. GUI | March 8, 2012 at 6:09 pm | Permalink

    THANKS!!!

  39. Diogo | March 17, 2012 at 6:06 pm | Permalink

    Boa tarde,

    Eu sou aluno da Universidade de Coimbra e estou a desenvolver um projeto que pretende medir a temperatura interior de certas divisoes de um casa e consoante a temperatura exterior saber quando o utilizador deve abrir as janelas para manter a habitacao numa temperatura pretendida.
    O nosso problema é que pretendíamos montar um sistema com placas arduino a medir a temperatura e enviar os dados sem recurso a fios para um pc para serem analisados, e não sabemos se o material que queremos encomendar sera o mais indicado.

    Desenhei uma imagem demonstrativa do que nós pretendemos fazer. (http://dl.dropbox.com/u/716078/imagem.png)

    Como nunca trabalhamos com estas placas, não sabemos se este esquema, que teóricamente nos parece que irá funcionar, irá realmente funcionar na prática e como tal gostaríamos de saber se nos podes ajudar a decidir que material temos de comprar.

    Também vimos a placa arduino uno, mas não sabemos se é possível ligar-lhe a placa xbee e os sensores. Achas que é possível?

    Obrigado,
    Diogo Mestre.

  40. Luis Rodallegas | May 20, 2012 at 2:27 am | Permalink

    Ola amigo me podrias ayudar hacer una comunicacion inalambrica por medio de una interfaz de labview? saludos

  41. Tanan | June 6, 2012 at 6:17 pm | Permalink

    can i use this for labview ?

    if can’t

    what solution work with labview.

    sorry for bad english.

    thank

  42. GUI | June 6, 2012 at 10:20 pm | Permalink

    hi! I never used labview, but if it supports serial communication you will surelly be able to use this

  43. GUI | June 6, 2012 at 10:20 pm | Permalink

    Ola, lamento mas nunca utilizei labview, no entanto se ele tiver comunicacão serie acredito que o poderás utilizar ;)

  44. GUI | June 6, 2012 at 10:21 pm | Permalink

    Boa tarde, lamentávelmente só vi este comentário agora.. conseguiram resolver a situação?

  45. ben | July 21, 2012 at 8:57 pm | Permalink

    i m very interested abt this topic but i have a question….
    1.)will the communication run if laptop is disconnected
    2.)instead of wire i.e transmission medium can it be possible to use rf module
    3.)can two analog data from the pot could be sent
    The main reason or all this question ask’s only topic send two analog data from two pot to another ardunio . the simple thing is two ardunio communicating over rf module
    it would be great if ill get the code
    thank you

  46. GUI | July 22, 2012 at 12:45 am | Permalink

    answering to your questions:
    1. yes, the communication can run only with the arduinos
    2. yes, once you have the serial communication solved it will work with any interface
    3. doesn’t understand the question
    4. the code is all there!!

  47. ben | July 22, 2012 at 11:13 am | Permalink

    i have two questions
    1.)will both ardunio still communicate if computer connection is removed from both ardunio’s
    2.)after removing computer connection will i be able to use rf module…

  48. ben | July 22, 2012 at 11:25 am | Permalink

    thanx a lot the third question is
    3.)what is the code for transmitting and receiving analog values from two potentiometers (A0 and A1)

  49. ben | July 22, 2012 at 11:35 am | Permalink

    yah i saw the code the problem is solved now i have one ardunio i want to buy one more and i got this idea abt buying atmega328 and some crystals and make one more ardunio is it possible….

  50. ben | July 22, 2012 at 4:56 pm | Permalink

    what does this mean “NOTE: Don´t forget to disconnect Tx / Rx wires before upload “

  51. GUI | July 22, 2012 at 5:35 pm | Permalink

    yes, and yes

  52. GUI | July 22, 2012 at 5:36 pm | Permalink

    the code for the two pots is on the post!

  53. GUI | July 22, 2012 at 5:37 pm | Permalink

    yes it’s possible

  54. GUI | July 22, 2012 at 5:38 pm | Permalink

    serial comm takes both digital pins 0 and 1, they must be free in order to be able to upload code to the arduino.
    you will notice if you ever use anything connected to those pins ;)

  55. ben | July 23, 2012 at 6:59 pm | Permalink

    thanx a lot ….all those answers are very much usefulllll….again thanx for the help i ll implement it soon

  56. ben | July 23, 2012 at 7:03 pm | Permalink

    wat abt the other pins in ardunio….that us other than digital and analog pins…

  57. GUI | July 23, 2012 at 8:47 pm | Permalink

    please speak plain english, and please be objective

  58. eslam | July 23, 2012 at 10:01 pm | Permalink

    every time I try to upload the reciver code it gives me error ( stray ‘/’ in program ) please help

  59. ben | August 7, 2012 at 6:12 pm | Permalink

    following serial reading in rx

    ?HÌz;X?HÌz;X?HÌz;X?HÌz;X?HÌz;X?HÌz;X?HÌz;X?HÌz;X?HÌz;X?HÌz;X:H?HÌz;X?HÌ

  60. lorentz | January 3, 2013 at 5:43 am | Permalink

    i like the way the problem is solver..
    is it possible to simoultanouslt send all 6 analog read values via serial instead of 2.
    and receive correctly..
    can u pls help me with the code..
    thanks

  61. Revathi Babu K | August 1, 2013 at 9:53 am | Permalink

    hello sir……..
    i want the details abut how to interface3arduinos……..coz i need to transmitt an array of data through GSM interfaced with arduino

  62. GUI | August 1, 2013 at 10:19 am | Permalink

    I have never done such a thing, please check the Arduino forums, I’m sure you will find your answer there.

  63. Fabiolus | August 2, 2013 at 5:54 pm | Permalink

    How did you setup the xbee configuration for the receiver and transmitter using X-CTCU?

    Thank You

  64. GUI | August 14, 2013 at 9:27 am | Permalink

    yes X-CTU

  65. Rob | October 29, 2013 at 2:16 am | Permalink

    Thank you soooo much your example code was unspeakably useful. I appreciate you taking the time to post about your project, it will save me hours of research!

  66. GUI | November 1, 2013 at 9:58 am | Permalink

    great! glad to know that it helped you!

  67. paolo | February 12, 2014 at 3:38 pm | Permalink

    I can’t understand because it doesn’t work: the receiving code stamp on serialmonitor the ascii caracter converted like: 505352505351505353505348505352505351505353505348505352505351505353505348505352505351505353

    So the LED doesn’t turn ON

  68. Widhi | March 31, 2014 at 9:46 pm | Permalink

    Hi! why the code ‘BYTE’ wrong and the warning :

    “As of Arduino 1.0, the ‘BYTE’ keyword is no longer supported. Please use Serial.write() instead.”

    how to solve the problem?
    thanks

  69. Widhi | March 31, 2014 at 9:48 pm | Permalink

    I got warning :
    “As of Arduino 1.0, the ‘BYTE’ keyword is no longer supported. Please use Serial.write() instead.”

    how to solve it?
    thanks

  70. guibot | March 31, 2014 at 10:54 pm | Permalink

    just use Serial.write(your value);

    your value must be 1 BYTE (0 – 255);

  71. Gerardo | May 27, 2014 at 11:59 pm | Permalink

    Hello, how much for a Code that can send analog readings from accelerometer and aslo 4 push buttons and recibe these data to another xbee with arduino ?

  72. guibot | May 28, 2014 at 8:42 am | Permalink

    hello Hector, apologize but I won’t have the time to make this code for you, have a look on the arduino forums, I’m sure you will find what you need
    good luck

  73. Dan Ionescu | June 6, 2014 at 1:54 pm | Permalink

    No xbee configuration is necessary ? just wire these things and they are ready to go ?

  74. guibot | June 6, 2014 at 6:55 pm | Permalink

    your xbees need to be paired in order to communicate

{ 2 } Trackbacks

  1. [...] Guilherme Martins : Serial Communication between Arduinos – With Wire & Wireless  Uncategorized  Add comments Feb 012012   Guilherme Martins wrote a nice easy to understand article in 2008 on using Serial communication between to Arduinos : Serial Comunication between Arduinos – With Wire & Wireless. [...]

  2. [...] This is an updated example of basic serial communication between Arduinos, the old example can be found here. [...]

Post a Comment

Your email is never published nor shared. Required fields are marked *