Hello.
I’m pulling my hair over my arduino code not working. So the problem is. When I read the temperature with dht.readTemperature() and output it to serial monitor, it works fine. When I send something over UDP, it works fine, but when I want to send read temperature over UDP, arduino crashes and starts working again, when I restart it.
It reads from temperature sensor only once and freezes after line UDP.endPacket(). I was googling, found that bug, applied the patch, tried many things, but nothing seems to be working.
Again, UDP and readTemperature() works fine on its own, but when I want to send temperature data over UDP, it freezes.
Thank you all for any provided help!
#include <DHT_U.h>
#include <Ethernet.h>
#include <EthernetUdp.h>
#include <SPI.h>
#include "Timer.h"
byte MAC[] = { 0xDE, 0x12, 0x44, 0xAF, 0xBE, 0x56 };
IPAddress IP(192, 168, 2, 100);
unsigned int localPort = 5000;
char packetBuffer[UDP_TX_PACKET_MAX_SIZE];
String dataReq;
int packetSize;
EthernetUDP UDP;
Timer t;
#define DHTPIN 13
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(9600);
Ethernet.begin(MAC, IP);
delay(1500);
UDP.begin(localPort);
for (int i = 2; i < 14; ++i) {
pinMode(i, OUTPUT);
}
Serial.println(Ethernet.localIP());
t.every(1000, takeTemperatureReading);
}
void loop() {
packetSize = UDP.parsePacket();
float temp = dht.readTemperature();
Serial.println(temp);
UDP.beginPacket(UDP.remoteIP(), UDP.remotePort());
UDP.print(temp);
UDP.endPacket(); //Packet has been sent
if (packetSize > 0) {
// Some stuff for recieving data
UDP.read(packetBuffer, UDP_TX_PACKET_MAX_SIZE); // Reading the data request, saving it in packetBuffer of UDP max size
String dataReq(packetBuffer); // converting char array to string
Serial.println(dataReq);
String type = dataReq.substring(0, 3);
int pin = dataReq.substring(3, 5).toInt();
int state = dataReq.substring(5, 6).toInt();
digitalWrite(pin, state);
}
memset(packetBuffer, 0, UDP_TX_PACKET_MAX_SIZE);
}