Hello
I want to read the PWM signal from RC receiver and write this value to a servo that is connected to the arduino and also I want to send this PWM value as a UDP packet to other Arduino
for the first part I used interrupt and everything works very well.
But when I tried to send the PWM value via UDP nothing was working (both the servo and the UDP)
I use Arduino UNO and Ethernet Shield
and here is the code:
#include<Servo.h>
#include<SPI.h>
#include<Ethernet.h>
#include<EthernetUdp.h>
/////////////////////////////////////////////////////////////////////////////////////////////////////////
// Network Configurations
/////////////////////////////////////////////////////////////////////////////////////////////////////////
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress sourceIp(192, 168, 1, 177);
unsigned int sourcePort = 8888; // local port to listen on
IPAddress destIP(192,168,1,170);
unsigned int destPort = 8889;
EthernetUDP Udp;
byte signalBuffer[2]= {0};
/////////////////////////////////////////////////////////////////////////////////////////////////////////
// channel in pins
#define SIGNAL_IN_ID 0 // interrupt ID of pin 2
#define SIGNAL_IN_PIN 2
// channel output pin
#define SIGNAL_OUT_PIN 5
Servo servo;
// Bit Flag, that is set in bUpdateFlagsShared to indicating the new Signal.
#define SIGNAL_FLAG 1
// shared Flag
volatile uint8_t bUpdateFlagsShared;
// Shared variables
volatile uint16_t unSignalInShared;
// Next variables are only used the the interrupt routine.
uint32_t ulSignalStart;
void setup() {
Serial.begin(9600);
servo.attach(SIGNAL_OUT_PIN);
attachInterrupt(SIGNAL_IN_ID,calculatePWM,CHANGE);
// start the Ethernet and UDP:
Ethernet.begin(mac,sourceIp);
Udp.begin(sourcePort);
}
void loop() {
// local variables to copy the shared variables.
static uint16_t unSignalIn;
static uint8_t bUpdateFlags;
// check if new signal
if(bUpdateFlagsShared)
{
// turn interrupts off quickly and make a copy of the shared variables
noInterrupts();
bUpdateFlags = bUpdateFlagsShared;
if(bUpdateFlags & SIGNAL_FLAG)
{
unSignalIn = unSignalInShared;
}
bUpdateFlagsShared = 0;
interrupts();
}
if(bUpdateFlags & SIGNAL_FLAG)
{
if(servo.readMicroseconds() != unSignalIn)
{
servo.writeMicroseconds(unSignalIn);
Serial.println(unSignalIn);
}
// send the value via UDP... this may be moved inside the if block
signalBuffer[0] = unSignalIn;
signalBuffer[1] = unSignalIn >> 8;
Udp.beginPacket(destIP, destPort);
Udp.write(signalBuffer,2);
Udp.endPacket();
}
bUpdateFlags = 0;
}
// simple interrupt service routine
void calculatePWM()
{
if(digitalRead(SIGNAL_IN_PIN) == HIGH)
{
ulSignalStart = micros();
}
else
{
unSignalInShared = (uint16_t)(micros() - ulSignalStart);
bUpdateFlagsShared |= SIGNAL_FLAG;
}
}
any ideas to solve this problem?
thank you and best regards