Main Content

Communicate with Arduino Server Using UDP Blocks

This example shows how to use the UDP Receive and UDP Send blocks to communicate with a remote server. In this example, the server is running on an Arduino® Uno. Both UDP blocks communicate from or to the remote Arduino server.

Setup

Plug in an Arduino Uno and Ethernet Shield to your computer. Load the following program using the Arduino IDE. Configure your network settings to use the IP and port setting in the code.

#include <SPI.h>
#include <Ethernet.h>
#include <EthernetUdp.h>

// Specify maximum UDP packet size
#define MAX_PACKET_SIZE 512

// Specify MAC and IP address for Ethernet shield
byte mac[] = {  
  0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192, 168, 1, 177);

// Specify UDP port to listen on
unsigned int localPort = 9999;

// Create data array for storing the received UDP packet data payload
char packetData[MAX_PACKET_SIZE];

EthernetUDP Udp;

void setup() {
  Ethernet.begin(mac,ip);
  Udp.begin(localPort);
}

void loop() {
  
  // Process received packet
  int packetSize = Udp.parsePacket();

  if (packetSize > MAX_PACKET_SIZE)
  {
    packetSize = MAX_PACKET_SIZE;
  }

  // If a packet was received, send a response packet
  if (packetSize)
  {
    // Read the received UDP packet data
    Udp.read(packetData,MAX_PACKET_SIZE);

    // Transmit an UDP packet back to the remote IP address and port specified in the received packet header
    // The transmitted UDP packet data byte values are the received values + 1
    Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());    
    for (int i =0; i < packetSize; i++)
    {
      Udp.write(packetData[i]+1);
    }
    Udp.endPacket();    
  }
  delay(1);
}

An INO file is also included in this example.

Send and Receive Data from Server

This model contains a UDP Send and UDP Receive block. The UDP Send block sends data from a counter to the server on the Arduino. The Arduino server then increments the signal by one and returns it to the UDP Receive block.

Use the following command to open the model.

open_system('demoinstrslUDPTransmitReceive');

Use the following command to close the model.

close_system('demoinstrslUDPTransmitReceive');

Results

The Arduino server increments each value from the counter by one. The output in the model displays the incremented values.

See Also

|

Related Topics