Sending UDP from Arduino Uno to InfluxDB - arduino

So I’ve got an Arduino Uno and the Ethernet Shield V2 and connected these to a temperature sensor. Everything is working fine, the temperature is shown as desired, the problem is that I don’t seem to be able to save the results in my influxDB database.
Here my sketch:
#include <SPI.h>
#include <Ethernet.h>
#include <EthernetUdp.h>
const int sensorPin = A0;
int sensorVal;
// 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
};
byte host = {192, 168, 0, 153};
unsigned int port = 8089; // local port to listen on
EthernetUDP Udp;
void setup(){
//////////////////////
// PUT YOUR SETUP CODE HERE TO RUN ONCE
//////////////////////
Serial.begin(9600); // open serial port
Ethernet.begin(mac, host);
// 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
}
// 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 UDP
Udp.begin(port);
}
float getTemperature() {
sensorVal = analogRead(sensorPin);
float voltage = (sensorVal/1024.0) * 5.0;
float temperatureC = (voltage - 0.5)*100;
return temperatureC;
}
void loop(){
//////////////////////
// PUT YOUR MAIN CODE HERE; TO RUN REPEATEDLY
//////////////////////
String line, temperature;
delay(1000);
temperature = String(getTemperature(), 2);
Serial.println(temperature);
line = String(“temperature value=” + temperature);
Serial.println(line);
Serial.println(“Sending UDP packet…”);
Udp.beginPacket(host, port);
Udp.print(“temperature value=”);
Udp.print(temperature);
Udp.endPacket();
}
These are the setting from the config file of the influxDB:
[[udp]]
enabled = true
bind-address = “:8089”
database = “arduino”
retention-policy = “”
InfluxDB precision for timestamps on received points ("" or “n”, “u”, “ms”, “s”, “m”, “h”)
precision = “s”
I would appreciate if somebody could give me some clues about what I’m doing wrong.
Cheers

According to the documentation, you want to pass a remote IP (not local IP) when you call Udp.beginPacket.
Does host represent a remote IP address? Looks like you are using host as a local IP to begin Ethernet as well. It is likely that you are not sending packets to a remote host. Make sure you pass a local IP to Ethernet.begin() and pass a remote IP to Udp.beginPacket().

Related

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];

getting arduino ethernet shield to work?

I've recently bought an Arduino ethernet shield but couldn't get it work.
I've tried to use the example's code but it did not work. I have even tried to get a static IP without DHCP and it's always the same problem .
I've used this code :
#include <SPI.h>
#include <Ethernet.h>
// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = { 0x90, 0xA2, 0xDA, 0x0F, 0xE1, 0xBF };
// if you don't want to use DNS (and reduce your sketch size)
// use the numeric IP instead of the name for the server:
//IPAddress server(74,125,232,128); // numeric IP for Google (no DNS)
char server[] = "www.google.com"; // name address for Google (using DNS)
// Set the static IP address to use if the DHCP fails to assign
IPAddress ip(192,168,1,10);
// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
EthernetClient client;
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for Leonardo only
}
// start the Ethernet connection:
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...");
// if you get a connection, report back via serial:
if (client.connect(server, 80)) {
Serial.println("connected");
// Make a HTTP request:
client.println("GET /search?q=arduino HTTP/1.1");
client.println("Host: www.google.com");
client.println("Connection: close");
client.println();
}
else {
// kf you didn't get a connection to the server:
Serial.println("connection failed");
}
}
void loop()
{
// if there are incoming bytes available
// from the server, read them and print them:
if (client.available()) {
char c = client.read();
Serial.print(c);
}
// if the server's disconnected, stop the client:
if (!client.connected()) {
Serial.println();
Serial.println("disconnecting.");
client.stop();
// do nothing forevermore:
while(true);
}
}
and I got this answer:
Failed to configure Ethernet using DHCP
connecting...
connected
disconnecting.
How can I be sure that my ethernet shield is working correctly and how can I resolve this problem?
With a failed DHCP you don't have DNS address to resolve "www.google.com".
Modify your code like this and try again :
IPAddress server(74,125,232,128);
//char server[] = "www.google.com";

Get client IP address with Arduino

I have an Arduino Uno with Ethernet Shield as server, and I make requests on the Arduino through the Internet. I use two libraries to do it (Ethernet.h and SPI.h).
I want to check the client IP address, so I accept only HTTP requests from a known IP address (for example, 50.50.50.50) which is the static IP address in my office. How can I get the the client IP address on the Arduino?
have a look at the following, this works for TCP:
http://forum.arduino.cc/index.php?PHPSESSID=jh6t8omt7vrb8nget5c9j5dbk4&/topic,82416.0.html
The following is a quote from the author's post, I am just copying the excellent work:
To make it work, I did the following:
I added the following lines to the end of the EthernetClient.cpp file:
uint8_t *EthernetClient::getRemoteIP(uint8_t remoteIP[])
{
W5100.readSnDIPR(_sock, remoteIP);
return remoteIP;
}
I then added the following line (under the virtual void stop(); line)to the EthernetClient.h file:
uint8_t *getRemoteIP(uint8_t RemoteIP[]);//adds remote ip address
Finally I used the following code in my sketch to access the remote IP:
client.getRemoteIP(rip); // where rip is defined as byte rip[] = {0,0,0,0 };
to display the IP in the serial monitor, I used:
for (int bcount= 0; bcount < 4; bcount++)
{
Serial.print(rip[bcount], DEC);
if (bcount<3) Serial.print(".");
}
I've done this using UDP, hopefully this will help you.
Get UDP.h from Google here: UDP.h
Code:
#include <SPI.h>
#include <Ethernet.h>
#include <Udp.h>
// ***** ETHERNET VARS *****
// MAC address and IP for arduino
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = { 192,168,1,98};
unsigned int localPort = 8888; // local port to listen on
// SenderIP and SenderPort are set when message is received
byte SenderIP[IP_LENGTH]; // holds received packet's originating IP
unsigned int SenderPort; // holds received packet's originating port
// buffer for receiving data
char packetBuffer[UDP_TX_PACKET_MAX_SIZE]; //buffer to hold incoming packet
int packetSize = 0;
void setup()
{
Ethernet.begin(mac,ip); //start Ethernet
Udp.begin(localPort); //start UDP
}
void loop()
{
if(NewPortMessage())
{
// Do stuff, SenderIP is the IP where the UDP message was received from
}
}
boolean NewPortMessage()
{
packetSize = Udp.available();
if(packetSize > 0)
{
packetSize -= 8; //subtract UDP 8-byte header
// read the packet into packetBufffer and get the senders IP addr and port number
Udp.readPacket(packetBuffer,UDP_TX_PACKET_MAX_SIZE, SenderIP, SenderPort);
return true;
}
clearPacketBuffer();
return false;
}
void clearPacketBuffer()
{
for(int i=0; i < packetSize; i++)
packetBuffer[i] = 0;
}
what about changing the approach? you could use SOA and you could make your arduino a web client instead of a web server.......then you could handle all of this restrictions in the web server that host your web service, this web service will be the core of your app, and this way you could call it from any mobile device you want :D
just an idea arduino web servers are not very useful, with this approach you could use the internet instead of using LAN only
good luck with your project

My Arduino + Ethernet shield WebServer sketch sometimes fails to connect to the client. Causes?

My Arduino web server sketch sporadically fails on:
EthernetClient client = server.available();
if (client)
This morning, it connected just fine on the first run. Now, it can't connect to the client again. A couple of days ago, it worked several times, but failed several time as well. I have the shield connected via an Ethernet cable to my home router. I've verified the IP address assigned to the Arduino. I've tried ports 80 and 8080. What could be going wrong and what else can I try? Could my ISP be blocking something here? Please don't be afraid to suggest the obvious, since I know almost nothing about networks.
If relevant, here is a larger piece of the code, which loops on
Serial.println("Listening");
Code:
#include <SPI.h>
#include <Ethernet.h>n
// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = { 0x90, 0xA2, 0xDA, 0x00, 0xF7, 0x99 };
IPAddress ip(192,168,2,5);
// Initialize the Ethernet server library
// with the IP address and port you want to use
// (port 80 is default for HTTP):
EthernetServer server(80);
String roundOpenTag = "";
String roundCloseTag = "";
void setup()
{
// Start the Ethernet connection and the server:
Ethernet.begin(mac, ip);
server.begin();
int ledPin = 8;
// Initialize the digital pin as an output.
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
Serial.println("Setting up");
}
void loop()
{
// Listen for incoming clients
EthernetClient client = server.available();
Serial.println("Listening");
if (client)
{
Serial.println("Server available");
// An HTTP request ends with a blank line
boolean currentLineIsBlank = true;
while (client.connected()) {
Serial.println("Client connected");
if (client.available())
{
char c = client.read();
I don't see the purpose in including the rest of the sketch. I really appreciate your help.
You have a empty Seiral.begin() in your setup() function. Try removing it.
Edit:
When you call Serial.begin() you have to provide the baut rate(speed) at which you want to communicate. You can read more about the function at Arduino library page.
You had two problems in your code
You had a empty Serial.begin() function call, without any parameter
You had duplicate Serial.begin() function. You had already specified it in the beginning of the setup() function.

Arduino Ethernet and DHCP cannot communicate out to the Internet

I have this web client example that gets an IP address via DHCP. It connects to my router at IP address 192.168.0.1 successfully, but then it fails to send a GET HTTP to google.com. Essentially, I cannot allow the traffic from Arduino to go out into the Internet.
I have a Linksys/Cisco E2000 router connected to the Arduino.
My code is below.
#include <SPI.h>
#include <Ethernet.h>
#include <EthernetDHCP.h>
// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = {0x90, 0xA2, 0xDA, 0x00, 0x78, 0x0B};
byte ip[] = {192, 168, 0, 125};
byte gateway[] = {192, 168, 0, 1};
byte subnet[] = {255,255,255,0};
byte serverLocal[] = { 192,168,0,1 }; // Google
byte serverExternal[] = { 173,194,33,104 }; // Google
// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
Client clientLocal(serverLocal, 80);
Client clientExternal(serverExternal, 80);
const char* ip_to_str(const uint8_t*);
void setup() {
Serial.begin(9600);
Serial.println("Attempting to obtain a DHCP lease...");
// Initiate a DHCP session. The argument is the MAC (hardware) address that
// you want your Ethernet shield to use. This call will block until a DHCP
// lease has been obtained. The request will be periodically resent until
// a lease is granted, but if there is no DHCP server on the network or if
// the server fails to respond, this call will block forever.
// Thus, you can alternatively use polling mode to check whether a DHCP
// lease has been obtained, so that you can react if the server does not
// respond (see the PollingDHCP example).
EthernetDHCP.begin(mac);
// Since we're here, it means that we now have a DHCP lease, so we print
// out some information.
const byte* ipAddr = EthernetDHCP.ipAddress();
const byte* gatewayAddr = EthernetDHCP.gatewayIpAddress();
const byte* dnsAddr = EthernetDHCP.dnsIpAddress();
Serial.println("A DHCP lease has been obtained.");
Serial.print("My IP address is ");
Serial.println(ip_to_str(ipAddr));
Serial.print("Gateway IP address is ");
Serial.println(ip_to_str(gatewayAddr));
Serial.print("DNS IP address is ");
Serial.println(ip_to_str(dnsAddr));
// if you get a connection, report back via serial:
if (clientLocal.connect()) {
Serial.println("connected internally");
// Make a HTTP request:
clientLocal.println("GET /index.html HTTP/1.0");
clientLocal.println();
}
else {
// kf you didn't get a connection to the server:
Serial.println("connection failed internally");
}
// if you get a connection, report back via serial:
if (clientExternal.connect()) {
Serial.println("connected externally");
// Make a HTTP request:
clientExternal.println("GET /search?q=arduino HTTP/1.0");
clientExternal.println();
}
else {
// kf you didn't get a connection to the server:
Serial.println("connection failed externally");
}
}
void loop()
{
// if there are incoming bytes available
// from the server, read them and print them:
if (clientLocal.available()) {
char c = clientLocal.read();
Serial.print(c);
}
// if the server's disconnected, stop the client:
if (!clientLocal.connected()) {
Serial.println();
Serial.println("disconnecting.");
clientLocal.stop();
}
// if there are incoming bytes available
// from the server, read them and print them:
if (clientLocal.available()) {
char c = clientLocal.read();
Serial.print(c);
}
// if the server's disconnected, stop the client:
if (!clientExternal.connected()) {
Serial.println();
Serial.println("disconnecting.");
clientExternal.stop();
// do nothing forevermore:
for(;;)
;
}
}
// Just a utility function to nicely format an IP address.
const char* ip_to_str(const uint8_t* ipAddr)
{
static char buf[16];
sprintf(buf, "%d.%d.%d.%d\0", ipAddr[0], ipAddr[1], ipAddr[2], ipAddr[3]);
return buf;
}
Here's an example of working code (maybe you used this as a source?). The only differences I could see are the lines:
Serial.begin(9600);
delay(1000);
just before the line:
if (clientLocal.connect()) {
I doubt the additional Serial.begin() has any effect but the delay() may be required (although it's a long shot...)

Resources