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);
}
,

80 thoughts on “Serial Comunication between Arduinos – With Wire & Wireless”

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

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

  3. 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. 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. 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.

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

  7. 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?

  8. @ 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?

  9. 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?

  10. 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.

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

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

  13. 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);

    }
    }

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

  14. 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

  15. 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!

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

  17. 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

  18. 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.

  19. 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?

  20. 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.

  21. 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”

  22. 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 ?

  23. 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.

  24. 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.

  25. 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!

  26. 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 ??

  27. 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!

  28. 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.

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

  30. can i use this for labview ?

    if can’t

    what solution work with labview.

    sorry for bad english.

    thank

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

  32. 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

  33. 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!!

  34. 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…

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

  36. 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….

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.