Sending sensor data via UDP - arduino

I'm trying to send sensor data via UDP. At the moment I'm struggling with the "packing" of the UDP packets. It says "incomingData" is not declared when I try to send it.
I would appreciate any kind of advice.
Code below.
Thank you :)
//Version 1.012
//necessary libraries
#include <SPI.h>
#include <Ethernet2.h>
#include <EthernetUdp2.h>
//Pin settings
#define CTD 19
//Network Settings
byte mac[] = { 0x90, 0xA2, 0xDA, 0x10, 0xEC, 0xAB }; //set MAC Address Ethernet Shield (Backside)
byte ip[] = { XXX, XXX, X, X }; //set IP-Address
byte gateway[] = { XXX, XXX, X, X }; //set Gateway
byte subnet[] = { 255, 255, 255, 1 }; //set Subnetmask
//local UDP port to listen on
unsigned int localPort = 4000;
//Recipient IP
IPAddress RecipientIP(127, 0, 0, 1);
//Recipient UDP port
unsigned int RecipientPort = 4444;
//Buffer for sending data
char packetBuffer[UDP_TX_PACKET_MAX_SIZE];
//EthernetUDP instance
EthernetUDP Udp;
void setup()
{
//Start Ethernet
Ethernet.begin(mac, ip);
//Start UDP
Udp.begin(localPort);
//for debug only
Serial.begin(9600);
//Serial baud rate for CTD
Serial1.begin(1200);
//Version 1.012
Serial.print("Version 1.012");
//CTD
pinMode(CTD, INPUT);
}
void loop()
{
//If CTD is sending
if (Serial1.available())
{
//read incoming data
int incomingData = Serial1.read();
//for debug only
Serial.print("Data: ");
Serial.println(incomingData, BIN);
}
//Send UDP packets
int packetSize = Udp.parsePacket();
if (packetSize) {
// read the packet into packetBufffer
Udp.read(packetBuffer, UDP_TX_PACKET_MAX_SIZE);
// send to the IP address and port
Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
Udp.write(incomingData);
Udp.endPacket();
}
}

In your code you have declared incomingData as int inside void loop () function inside if (Serial1.available()) .
But if the above if loop fails the incomingData will not be declared and say packetsize is greater than zero ( packet available) then if (packetSize) segment will be executed.Thus incomingData is not declared but it is used .That's why you get the error you stated.

Related

Simple Arduino Client Server communication via Ethernet, IP

Simple Ethernet communication between two Arduino boards. I used two Arduino UNO boards, Two Arduino Ethernet Shields.
Here is my Server Code
//Server
#include <SPI.h>
#include <Ethernet.h>
// network configuration. gateway and subnet are optional.
// the media access control (ethernet hardware) address for the shield:
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
//the IP address for the shield:
byte ip[] = { 192,168,1,180 };
// the router's gateway address:
byte gateway[] = { 192, 168, 1, 1 };
// the subnet:
byte subnet[] = { 255, 255, 255, 0 };
EthernetServer server = EthernetServer(10001);
void setup()
{
// initialize the ethernet device
Ethernet.begin(mac, ip, gateway, subnet);
// start listening for clients
server.begin();
}
void loop()
{
// if an incoming client connects, there will be bytes available to read:
EthernetClient client = server.available();
if (client == true) {
// read bytes from the incoming client and write them back
// to any clients connected to the server:
server.write(client.read());
}
}
Here is my Client Code
//Client
#include <Ethernet.h>
#include <SPI.h>
byte mac[] = {0xDE,0xAD,0xBE,0xEF,0xFE,0xEC};
IPAddress ip(192,168,1,177);
IPAddress server(192,168,1,180);
EthernetClient client(10001);
void setup()
{
Ethernet.begin(mac, ip);
Serial.begin(9600);
delay(1000);
Serial.println("connecting...");
if (client.connect(server, 10001)) {
Serial.println("connected");
client.println("GET /search?q=arduino HTTP/1.0");
client.println();
} else {
Serial.println("connection failed");
}
}
void loop()
{
if (client.available()) {
char c = client.read();
Serial.print(c);
}
if (!client.connected()) {
Serial.println();
Serial.println("disconnecting.");
client.stop();
for(;;)
;
}
}
I input those two codes to two Arduino boards. Wiring and other connection are correct and reliable.
But I got this output from client serial monitor
connecting...
connection failed
disconnecting.
According to my view, error may happen in client code. Can you help me to find the error?

how to set up RGB leds on arduino ethernet with udp instruction?

I'm working on a kind of traffic light with RGB LEDs. I try to take a udp value sent from a server to the arduino mega and ethernet shield, then the arduino should change the color of the LED.
Sadly until now, it does not work. In the serial monitor, I find out that the udp packet was received, but then the LED does not work. I was hoping that you guys can help me to figure out why my code isn't working. Thank you in advance! Here is my code:
/*
Web Server
*/
#include <SPI.h>
#include <Ethernet.h>
#include <EthernetUdp.h>
void Color(int R, int G, int B) //set up for the RGB led
{
analogWrite(3, R) ; // Rojo
analogWrite(5, G) ; // Green - Verde
analogWrite(6, B) ; // Blue - Azul
}
// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = {
0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
IPAddress ip(10, 90, 111, 150);
unsigned int localPort = 8888; // local port to listen on
// buffers for receiving and sending data
char packetBuffer[UDP_TX_PACKET_MAX_SIZE]; // buffer to hold incoming packet,
char ReplyBuffer[] = "acknowledged"; // a string to send back
// An EthernetUDP instance to let us send and receive packets over UDP
EthernetUDP Udp;
// Initialize the Ethernet server library
// with the IP address and port you want to use
// (port 80 is default for HTTP):
EthernetServer server(80);
void setup() { //seting up the outputs for the rgb
pinMode(3, OUTPUT);
pinMode(5, OUTPUT);
pinMode(6, OUTPUT);
// You can use Ethernet.init(pin) to configure the CS pin
//Ethernet.init(10); // Most Arduino shields
//Ethernet.init(5); // MKR ETH shield
//Ethernet.init(0); // Teensy 2.0
//Ethernet.init(20); // Teensy++ 2.0
//Ethernet.init(15); // ESP8266 with Adafruit Featherwing Ethernet
//Ethernet.init(33); // ESP32 with Adafruit Featherwing Ethernet
// start the Ethernet connection and the server:
Ethernet.begin(mac, ip);
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
Serial.println("Ethernet WebServer Example");
// Check for Ethernet hardware present
if (Ethernet.hardwareStatus() == EthernetNoHardware) {
Serial.println("Ethernet shield was not found. Sorry, can't run without hardware. :(");
while (true) {
delay(1); // do nothing, no point running without Ethernet hardware
}
}
if (Ethernet.linkStatus() == LinkOFF) {
Serial.println("Ethernet cable is not connected.");
}
// start the server
Udp.begin(localPort);
server.begin();
Serial.print("server is at ");
Serial.println(Ethernet.localIP());
}
void loop() {
// if there's data available, read a packet
int packetSize = Udp.parsePacket();
if (packetSize) {
Serial.print("Received packet of size ");
Serial.println(packetSize);
Serial.print("From ");
IPAddress remote = Udp.remoteIP();
for (int i=0; i < 4; i++) {
Serial.print(remote[i], DEC);
if (i < 3) {
Serial.print(".");
}
}
Serial.print(", port ");
Serial.println(Udp.remotePort());
// read the packet into packetBufffer
Udp.read(packetBuffer, UDP_TX_PACKET_MAX_SIZE);
Serial.println("Contents:");
Serial.println(packetBuffer);
// send a reply to the IP address and port that sent us the packet we received
Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
Udp.write(ReplyBuffer);
Udp.endPacket();
}
char numero = packetBuffer;
if (numero = "1") Color(250, 0, 0) ;
if (numero = "2") Color(100, 110, 0);
if (numero = "3") Color(0, 255, 0);
delay(10);
}
From now, it just receives the udp, and while compiling I get:
warning: invalid conversion from 'const char*' to 'char' [-fpermissive]
but in the end, it compiles.
edited:
i changed the code in this way (just in the final part), and now when i send the udp packet, no matter what i send, i get the green light on, but only the green one, here is the code
void loop() {
// if there's data available, read a packet
int packetSize = Udp.parsePacket();
if (packetSize) {
Serial.print("Received packet of size ");
Serial.println(packetSize);
Serial.print("From ");
IPAddress remote = Udp.remoteIP();
for (int i=0; i < 4; i++) {
Serial.print(remote[i], DEC);
if (i < 3) {
Serial.print(".");
}
}
Serial.print(", port ");
Serial.println(Udp.remotePort());
// read the packet into packetBufffer
Udp.read(packetBuffer, UDP_TX_PACKET_MAX_SIZE);
Serial.println("Contents:");
Serial.println(packetBuffer);
char numero = packetBuffer;
if (numero = 'R') Color(250, 0, 0) ;
if (numero = 'A') Color(100, 100, 0);
if (numero = 'V') Color(0, 255, 0);
// send a reply to the IP address and port that sent us the packet we received
Udp.beginPacket(Udp.remoteIP(), Udp.remotePort());
Udp.write(ReplyBuffer);
Udp.endPacket();
}
I'd recommend to find some C++ tutorial for starters.
Anyway:
char numero = packetBuffer; // wrong, you are assigning part of address to char, not character at that address...
if (numero = 'R') Color(250, 0, 0) ; // better but still wrong - numero is set to 'R' and it's also always true
if (numero = 'A') Color(100, 100, 0); // similar to previous
if (numero = 'V') Color(0, 255, 0); // and again
Correct version:
char numero = packetBuffer[0]; // get the first character in buffer
if (numero == 'R') Color(250, 0, 0) ; // compare numero with 'R'
if (numero == 'A') Color(100, 100, 0); // compare numero with 'A'
if (numero == 'V') Color(0, 255, 0); // ...
If there is nothing else wrong, that should fix it

NodeMCU Arduino framework UDP Packet sending problem

I've been trying to send an UDP Packet from readed ADC Value via UDP to any terminal. Unfortunately, I can't get any input on UDP terminal from the ESP directly. Here's the code:
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#include <string>
using namespace std;
//////////DEFINITIONS/////////////
#define ADC A0 //macrodef for reading the adc
///////////WiFi&UDP CONFIG///////////////////
WiFiUDP UdpPilot; // UDP Object for pilot
char udpSendingPacket[255] = "Hello there!"; //tab to send packet to board
unsigned int Port = 4210; // UDP port to send to
IPAddress destin_IP(192, 168, 0, 197); //IP Adress to send to
const char *softApName = "xxxxxxxx";
const char * pass = "xxxxxxxx";
/////////////////VARIABLES////////////////
int adcValueReaded = 0; //val to read from ADC
char adcToString[255];
void setup() {
WiFi.mode(WIFI_STA); //Station mode on WiFiUdp
Serial.begin(9600); //Begin serial
Serial.println(WiFi.begin( softApName, pass ) ? "WiFi Connection Ready!" : "WiFi Connection Failed!");
Serial.println(UdpPilot.begin(Port) ? "Port listening Ready!" : "Port listening Failed!");
}
void loop() {
adcValueReaded = analogRead(ADC);
if(adcValueReaded >= 500){
itoa(adcValueReaded, adcToString, 10);
UdpPilot.beginPacket(destin_IP, Port);
UdpPilot.write(adcToString);
UdpPilot.endPacket();
Serial.println(adcToString);
Serial.println(adcValueReaded);
}
yield();
}
Looking forward for your help.

Unintentional strange characters added to packets during udp communication in Arduino

Stackoverflow!
Unusual strange characters are added to packets during udp communication in Arduino.
Hi. Stack overflow. I encountered problems that I could not solve while using Udp with Arduino. I have looked up a lot of information to solve this problem. I also tested various cases. But I can not solve it.
The problem occurs from the 24th byte of the packet. The characters exceeding 23 characters are converted into strange characters and the subsequent sentences are not output. Is the packet transmission of udp communication limited to 24 bytes? If so, I am glad, but I want to know how to solve it. Please help me.
The test environment is as follows. Two Arduino are connected via a LAN cable. In addition, the following source code has been uploaded to Arduino. The serial monitor is as follows.
TX serial monitor
.
.
17:46:31.521 -> Sending UDP message
17:46:32.516 -> Sending UDP message
17:46:33.514 -> Sending UDP message
17:46:34.519 -> Sending UDP message
17:46:35.515 -> Sending UDP message
17:46:36.510 -> Sending UDP message
RX serial monitor
17:38:51.664 -> 010010010101001010101001K;⸮ <----------problem
17:38:52.662 -> Received packet of size 31
17:38:52.662 -> From 192.168.1.251, port 5678
17:38:52.662 -> Contents:
17:38:52.662 -> 01001001010100101010100j⸮ <------- problem
17:38:53.663 -> Received packet of size 31
17:38:53.663 -> From 192.168.1.251, port 5678
17:38:53.663 -> Contents:
17:38:53.663 -> 010010010101001010101001;ے <------------problem
17:38:56.770 -> Received packet of size 31
---------Source Code-------------
///////////TX
#include <SPI.h>
#include <Ethernet.h>
#include <EthernetUdp.h>
#define MSG_INTERVAL 1000
// network parameters
byte mac[] = {
0x90, 0xA2, 0xDA, 0x0E, 0x05, 0x04}; // ethernet interface MAC address
IPAddress localIp(192, 168, 1, 251); // local ip address
IPAddress destIp(192, 168, 1, 15); // destination ip address
unsigned int port = 5678; // destination port
// EthernetUDP to send and receive messages.
EthernetUDP Udp;
// message string
char message[] = "0100100101010010101010010101010";
// timing
//unsigned long previousLedMillis;
//unsigned long ledInterval;
unsigned long previousSendMillis;
unsigned long sendInterval;
// setup the arduino and shields
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(115200);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
// start ethernet and udp
Ethernet.begin(mac,localIp); // static ip version
// open UDP port
Udp.begin(port);
// show the local ip address (useful for dhcp)
Serial.print("Local IP: ");
Serial.println(Ethernet.localIP());
// initialize send interval
sendInterval = MSG_INTERVAL;
}
// do tasks
void loop() {
// check if udp string has to be sent
if(millis() - previousSendMillis >= sendInterval) {
sendMessage();
}
}
// send udp string
void sendMessage() {
Serial.println("Sending UDP message");
// store current millis
previousSendMillis = millis();
// send udp message
Udp.beginPacket(destIp, port);
Udp.write(message);
Udp.endPacket();
}
/////RX
#include <SPI.h>
#include <Ethernet.h>
#include <EthernetUdp.h>
// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = {
0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress ip(192, 168, 1, 15);
IPAddress remIp(92, 168, 1, 176);
unsigned int localPort = 5678; // local port to listen on
// An EthernetUDP instance to let us send and receive packets over UDP
EthernetUDP Udp;
char packetBuffer[UDP_TX_PACKET_MAX_SIZE]; //buffer to hold incoming packet,
void setup()
{
// start the Ethernet and UDP:
Ethernet.begin(mac,ip);
Udp.begin(localPort);
pinMode(5, OUTPUT);
Serial.begin(115200);
Serial.print("Local IP: ");
Serial.println(Ethernet.localIP());
}
void loop()
{
int packetSize = Udp.parsePacket();
if(packetSize)
{
Serial.print("Received packet of size ");
Serial.println(packetSize);
Serial.print("From ");
IPAddress remote = Udp.remoteIP();
for (int i =0; i < 4; i++)
{
Serial.print(remote[i], DEC);
if (i < 3)
{
Serial.print(".");
}
}
Serial.print(", port ");
Serial.println(Udp.remotePort());
// read the packet into packetBufffer
Udp.read(packetBuffer,UDP_TX_PACKET_MAX_SIZE);
//Udp.read(packetBuffer,1024);
Serial.println("Contents:");
Serial.println(packetBuffer);
//for (int i=0;i<packetSize;i++){
// Serial.print(packetBuffer[i]);
//}
//Serial.print('\n');
}
}
yes you have right, some problem with length 24!!
if you read inside the EthernetUDP.h file, you will see:
#define UDP_TX_PACKET_MAX_SIZE 24
so if you want use more characters, dont use this const, choose your personal size.
change
char packetBuffer[UDP_TX_PACKET_MAX_SIZE];
to
char packetBuffer[50];
or use another define:
#define UDP_MAX_BUFFER 50 //for example
char packetBuffer[UDP_MAX_BUFFER];

RabbitMQ with Arduino Uno

I'm using RabbitMQ with Arduino for the first time and I need to publish data. So I've used the PubSubCLient class. This is the code:
#include <SPI.h>
#include <PubSubClient.h>
#include <Dhcp.h>
#include <Ethernet.h>
#include <EthernetUdp.h>
#include <Dns.h>
#include <EthernetServer.h>
#include <EthernetClient.h>
//declare variables
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xDE, 0xDE, 0xDD };
byte server[] = { 127, 0, 0, 1 };
byte ip[] = { 192, 168, 1, 22 };
String stringone = "localhost";
void callback(char* topic, byte* payload, unsigned int length) {
Serial.println(topic);
//convert byte to char
payload[length] = '\0';
String strPayload = String((char*)payload);
Serial.println(strPayload);
int valoc = strPayload.lastIndexOf(',');
String val = strPayload.substring(valoc+1);
Serial.println(val);
}
EthernetClient ethClient;
PubSubClient client(server, 5672, callback, ethClient);
void setup() {
// client is now configured for use
Serial.begin(9600);
Serial.println("==STARTING==");
if (Ethernet.begin(mac) == 0) {
Serial.println("Failed to configure Ethernet using DHCP");
// no point in carrying on, so do nothing forevermore:
// try to congifure using IP address instead of DHCP:
Ethernet.begin(mac, ip);
}
// give the Ethernet shield a second to initialize:
delay(1000);
Serial.println("connecting...");
for (byte thisByte = 0; thisByte < 4; thisByte++) {
// print the value of each byte of the IP address:
Serial.print(Ethernet.localIP()[thisByte], DEC);
Serial.print(".");
}
boolean con = client.connect("arduinoMQTT123");
while(con != 1) {
Serial.println("no con-while");
con = client.connect("arduinoMQTT123");
}
if(con) {
Serial.println("got con");
client.subscribe("/v2/feeds/FEED_ID.csv");
} else Serial.println("no con");
}
void loop() {
client.loop();
}
I keep getting an error, no connection. I think that's because I don't know how to use Arduino with RabbitMQ.
These two lines are the source of your troubles:
byte server[] = { 127, 0, 0, 1 };
...
PubSubClient client(server, 5672, callback, ethClient);
server[] must specify the address of your RabbitMQ server. 127.0.0.1 is the address for localhost. This is never routable.
Additionally, PubSubClient is an MQTT client, not a RabbitMQ (AMQP) client. Therefore, the AMQP port you specified, 5672, will not work.
You need to enable and configure the MQTT adapter in RabbitMQ and then use the appropriate MQTT port, typically 1883.

Resources