Send data from Arduino yun to particular IP address

Components used:

(1)Arduino Yun(which already got WiFi module)
(2) DHT22 Temperature Sensor

I am trying to send temperature sensor data from Arduino Yun to particular IP address.

But I have one question how to read the data from the computer, which is connected to that particular IP address. Also, do I need to write the server program in order to read the data?

Can anyone help me with this

Below is the code I have tried(I’m not getting any error):

// Example testing sketch for various DHT humidity/temperature sensors
// Written by ladyada, public domain

#include “DHT.h”
#include <Bridge.h>
#include <YunClient.h>

#define DHTPIN A0 // what pin we’re connected to

// Uncomment whatever type you’re using!
//#define DHTTYPE DHT11 // DHT 11
#define DHTTYPE DHT22 // DHT 22 (AM2302)
//#define DHTTYPE DHT21 // DHT 21 (AM2301)

// Connect pin 1 (on the left) of the sensor to +5V
// Connect pin 2 of the sensor to whatever your DHTPIN is
// Connect pin 4 (on the right) of the sensor to GROUND
// Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor

DHT dht(DHTPIN, DHTTYPE);
IPAddress ip(any ip address);
void setup()
{
// YunClient client;
// int port=5555;
// if(client.connect(ip,port))
// {
// Serial.println(“Done!”);
// }
// else
// {
// Serial.println(“Fail”);
// }
Serial.begin(9600);
Serial.println(“DHTxx test!”);

dht.begin();
}

void loop()
{
YunClient client;
int port=58045;
if(client.connect(ip,port))
{
Serial.println(“Done!”);
}
else
{
Serial.println(“Fail”);
}
// Reading temperature or humidity takes about 250 milliseconds!
// Sensor readings may also be up to 2 seconds ‘old’ (its a very slow sensor)
float h = dht.readHumidity();
float t = dht.readTemperature();

// check if returns are valid, if they are NaN (not a number) then something went wrong!
if (isnan(t) || isnan(h))
{
Serial.println(“Failed to read from DHT”);
}
else
{
Serial.print(“Humidity: “);
Serial.print(h);
Serial.print(” %\t”);
client.write(Serial.print(h));

Serial.print(“Temperature: “);
Serial.print(t);
Serial.println(” *C”);
client.write(Serial.print(t));

}
}

Help me with this code. Or anyone please provide me some other option

Darshit23:
But I have one question how to read the data from the computer, which is connected to that particular IP address. Also, do I need to write the server program in order to read the data?

Your code is attempting to use a YunClient to make a TCP stream connection. You will, of course, need something running on the destination computer that is listening for incoming connections on your chosen port. There will need to be a server that listens for and accepts the incoming connection, then hands the connection over to a client that reads the incoming data and does something with it (whatever it is that you want to do.) This is basic network socket programming, and can get rather complicated to discuss in a forum topic such as this, especially since we don't know your level of expertise on the subject. (Based on the question, I can only assume your experience level is near zero.)

Looking at your sketch, you don't call Bridge.begin() anywhere. I think you will need to do this in setup() before you try to do anything with YunClient.

Also, in loop(), you are opening a YunClient on each pass, and never closing it. You will be swamping your destination computer with connection requests, and will quickly use up your Yun's and remote computer resources having so many open connections.

The simple solution is to call the YunClient's close() method after sending your data. The issue here is that you will be spending most of your time opening and closing the network connection, and little time doing anything else. A better approach is to call the connected() method of the YunClient and only attempt to connect if it's not already connected. That way, the connection stays open and can be reused from loop to loop. I have a simple example of this that I can share, but before I get into it:

Or anyone please provide me some other option

A good question: is the YunClient the best way to handle this? Maybe not. I'll respond with a few more questions: what are you trying to accomplish? Where are you trying to send the data? What services are already available on that computer which might make the job easier?

Thank you for your help..I really appreciate that. Actually I am new to Arduino Yun, so i would like help from you.

I'm trying to send temperature sensor data from Wifi module(which is on Arduino Yun) to other Wifi module(iMX6 freescale board)

Can you please share me the sample program which somehow try to do this?

Thank you for your help in advance.

Here is an example sketch that attempts to open an outgoing TCP stream (like Telnet) connection to a server. It will attempt to open a connection whenever one isn’t already open. If a connection is open, it will keep sending data over that connection. If the connection should close for whatever reason, it will try to reopen the connection.

#include <Bridge.h>
#include <YunClient.h>

#define PORT 255

// Define our client object
YunClient client;
bool Connected;

// Make the client connect to the desired server and port
IPAddress addr(192, 168, 42, 185);
  
// Or define it using a single unsigned 32 bit value
// IPAddress addr(0xc0a8sab9); // same as 192.168.42.185
  
// Or define it using a byte array
// const uint8 addrBytes = {192, 168, 42, 185};
// IPAddress addr(addrBytes);

// Or connect by a server name and port.
// Note that the Yun doesn't support mDNS by default, so "Yun.local" won't work
// client.connect("ServerName.com", PORT);


void setup()
{
  pinMode(13, OUTPUT);
  digitalWrite(13, HIGH);
  // Bridge startup
  Bridge.begin();
  
  Serial.begin(115200);
  while (!Serial)
  {
    digitalWrite(13, HIGH);
    delay(125);
    digitalWrite(13, LOW);
    delay(125);
  }  
  Serial.println("Client connecting on port 255");
  Connected = false;
}

void loop()
{
  // Is a connection currently active?
  if (!Connected)
  {
    // Not currently connected, try to establish a connection
    client.connect(addr, PORT);
    if (client.connected())
    {
      Serial.println("Connected to the server.");

      // Send something to the client
      client.println("Hello Server!");
       
      // Remember that there is a connection
      Connected = true;
    }
    else
    {
      // The connection attempt has failed.
      Serial.println("Could not connect to the server.");  
    
      // Give some time before trying again.
      // A real program needs to be more inteligent here.
      delay(5000);
    }
  }
  
  // Is a connection currently active?
  // Not an ELSE clause from the above IF, because a
  // new connection might have just been established.
  if (Connected)
  {
    // We think we are connected. Is that true?
    if (client.connected())
    {
      // Yes, we really are connected.
      // Send something to the client
      client.println("Data...");
      
      // Delay just to prevent too much data streaming
      // to the server, a real application will need to
      // be more intelligent here.
      delay(1000);
      
      // Read all incoming bytes available from the server and print them
      while (client.available())
      {
        char c = client.read();
        Serial.print(c);
      }
      Serial.flush();
    }
    else
    {
       // We think we are connected, but we aren't.
       // The connection must've just closed on us.
       Serial.println("Server connection closed!");
       
       // Clean up the client connection
       client.stop();
       
       // Track that we are no longer connected.
       // This will try to establish a connection the next time around.
       Connected = false;
    }
  }
}

There are global variables defined for the client and address objects, since they must survive iterations through loop (it won’t work if they are defined in setup() or loop()). There is also a global Connected flag to keep track if we think there is an active connection.

setup() gets things going by starting the Bridge - the D13 LED will be on steady while waiting for the Bridge to start. Then, it waits for a USB Serial Monitor connection, and flashes the D13 LED while waiting. This is just so you can see the output messages, for your real program you probably don’t want to do this or else it won’t do anything without a serial connection.

loop() starts by checking whether we think there is a connection already active. if not, it attempts to connect to the server. If successful, it sends a message to the server and sets the Connected flag. If it could not connect, it prints a message and delays before trying again. You will probably not want to use delay() in your real program - a more intelligent retry mechanism using the BlinkWithoutDelay example sketch concepts might be better.,

If we think there is an active connection, we check the client object to see if there really is a connection. If so, then the sketch sends some data to the server, echos whatever is received to the serial port, and delays to prevent swamping the server with data (I use another Yun that acts as the server and echos all of the data the Serial port, so the delay prevents things from scrolling faster than I can read.) You will likely want to do something more intelligent here to give yourself a reasonable data rate. If we think there is a connection but the client says there isn’t, then the connection must have just closed for whatever reason. In this case, the sketch prints out a message, cleans up the client connection, and sets the Connected flag to false. This will trigger a new connection attempt at the next pass of loop().

You will need to write some code for your iMX6 board to act as a server. How you do that is beyond the scope of this forum. It will need to listen for incoming connections and accept them as they arrive, and then process data as it comes in on the connection. It will also have to react to the connection unexpectedly closing.

To get you started, I have written a simple server sketch that you can run if you have another Yun. It tries to accept an incoming connection, and when it gets one it sends an initial message to the client, then listens for and echos any data to the serial port. If the connection closes, it tries to accept a new connection. If you send it a capital X through the serial monitor, it will force the connection closed to be able to test the client re-connection mechanism. I won’t give a detailed explanation of the code, as the structure is very similar to the client code.

#include <Bridge.h>
#include <YunServer.h>
#include <YunClient.h>

#define PORT 255
YunServer server(PORT);
YunClient client;

static boolean clientActive = false;

int clientCount;

void setup()
{
  clientCount = 0;
  
  pinMode(13, OUTPUT);
  digitalWrite(13, HIGH);
  // Bridge startup
  Bridge.begin();
  
  Serial.begin(115200);
  while (!Serial)
  {
    digitalWrite(13, HIGH);
    delay(125);
    digitalWrite(13, LOW);
    delay(125);
  }  
  Serial.println("Server listening on port 255");
  server.noListenOnLocalhost();
  server.begin();
  client = server.accept();
}



void loop()
{
  if (client.connected())
  {
    if (!clientActive)
    {
      clientCount++;
      Serial.print("New client connection: ");
      Serial.println(clientCount);
      
      // Send to the client
      client.println("Hello Client!");
    }
      
    clientActive = true;
    
    // Have a connection. Read and echo any input to the serial port
    if (client.available())
    {
      Serial.print("From client: \"");
      
      while (client.available())
        Serial.print((char)client.read());
      
      Serial.println("\"");
    }
    
    // Look to see if an 'X' is typed on the Serial port,
    // and if so, close the connection.
    while (Serial.available())
    {
       char c = (char)Serial.read();
       if (clientActive && (c == 'X'))
       {
          Serial.println("Closing client connection...");
          // Force the connection closed.
          client.stop();
          clientActive = false;
       }
    }
  }
  else // No connection, try to accept one.
  {
    if (clientActive)
    {
      client.stop();
      Serial.println("Client disconnected.");
    }
      
    clientActive = false;
    
    client = server.accept();
  }
}

You can use this as a test server on a second Yun to test your own client code, or use it for ideas on your iMX code (which will no doubt be very different.)

FYI:

The i.MX 6 series of applications processors is a feature and performance scalable multicore platform that includes single-, dual- and quad-core families based on the ARM® Cortex® architecture, including Cortex-A9, combined Cortex-A9 + Cortex-M4 and Cortex-A7 based solutions.

i.MX 6 (exclude i.MX 6UltraLite):

  • Cortex-A9 (CPU): 800 MHz ~ 1200 MHz single-, dual- and quad-core
  • Cortex-M4 (MCU): 200 MHz/32 bits with FPU

Arduino Yun:

  • MIPS32 24Kc (CPU): 400 MHz single-core
  • ATmega32U4 (MCU): 16 MHz/8 bits

The fastest Arduino Due:

  • Cortex-M3 (MCU) : 84 MHz/32 bits

In other word you do not need Yun to do what you want. i.MX 6 does it far better.

FYI:

The list of programming language i.MX 6 supports:

Same as

sonnyyu:
The list of programming language Yun/Yun Shield supports:

  • Erlang (a general-purpose concurrent, garbage-collected programming language and runtime system)
  • Java
  • JavaScript
  • Lua
  • PHP
  • Perl
  • Python
  • Ruby
  • 4th (an imperative stack-based computer programming language and programming environment)
  • eggdrop (Eggdrop is a popular IRC bot and the oldest still in active development)
  • sigscheme (SigScheme is a R5RS Scheme interpreter for embedded use.)
  • slsh (Interpreter for S-Lang scripts)
  • tcl (Tool Command Language)
  • vala (C-sharp like language for the GObje)
  • C
  • C++
  • MIPS Assembly Language
  • Shell Scripts
  • Fortran

exclude MIPS Assembly Language, but with ARM Assembly Language.
(To be fair, i.MX 6 /ARM does support more programming language than Yun/MIPS, such like go language...)

ShapeShifter:
Here is an example sketch that attempts to open an outgoing TCP stream (like Telnet) connection to a se…

test your own client code, or use it for ideas on your iMX code (which will no doubt be very different.)

Great post! Your example is exactly what I was looking for. I just want simple communication of data between Yuns.

However, how can the Yun Server keep multiple TCP connections open at once? My project could have up to 12 Yun clients that all need to send data to a “master” Yun. Any idea how to do this?

zerox12:
Great post! Your example is exactly what I was looking for. I just want simple communication of data between Yuns.

However, how can the Yun Server keep multiple TCP connections open at once? My project could have up to 12 Yun clients that all need to send data to a "master" Yun. Any idea how to do this?

This is actually the opposite situation of the current discussion, so I'm continuing the discussion of this new question in a new thread: Allow YunServer to manage multiple YunClient connections

Please continue any discussion about this new topic in that new thread, so that we can leave this thread for the original topic of establishing outgoing connections.