Greetings, I wanted to present some code for the Arduino Mega 2560 that can not only receive IBUS signal but also control servos without jitter.
This does not use the IBusBM library as this will only cause servo jitter.
I found this code online forever ago and use it on Arduino Uno without issues, but some slight additions had to be made for the MEGA's separate TX/RX connections
#include <string.h>
#define IBUS_BUFFSIZE 32
#define IBUS_MAXCHANNELS 10
#include <Servo.h>
static uint8_t ibusIndex = 0;
static uint8_t ibus[IBUS_BUFFSIZE] = { 0 };
static uint16_t rcValue[IBUS_MAXCHANNELS];
static boolean rxFrameDone;
int ch_width_1;
int ch_width_2;
int ch_width_3;
int ch_width_4;
int ch_width_5;
int ch_width_6;
int ch_width_7;
int ch_width_8;
int ch_width_9;
int ch_width_10;
Servo ch2; //servo on pin2
//add more servo outputs here
void setup() {
Serial.begin(115200);
Serial1.begin(115200); //IBus on RX1
ch2.attach(2);
}
void loop() {
readRx();
}
void readRx() {
rxFrameDone = false;
if (Serial1.available()) {
uint8_t val = Serial1.read();
//Look for 0x2040 as start of packet
if (ibusIndex == 0 && val != 0x20)
{
ibusIndex = 0;
return;
}
if (ibusIndex == 1 && val != 0x40) {
ibusIndex = 0;
return;
}
if (ibusIndex == IBUS_BUFFSIZE) //x == y; // is true if index is equal to buffersize and it is false if x is not equal to y
{
ibusIndex = 0;
int high = 3;
int low = 2;
for (int i = 0; i < IBUS_MAXCHANNELS; i++) {
rcValue[i] = (ibus[high] << 8) + ibus[low];
high += 2;
low += 2;
}
ch_width_1 = map(rcValue[0], 1000, 2000, 1000, 2000);
// Serial.println(ch_width_1);
ch2.writeMicroseconds(ch_width_1);
ch_width_2 = map(rcValue[1], 1000, 2000, 1000, 2000);
ch_width_3 = map(rcValue[2], 1000, 2000, 1000, 2000);
ch_width_4 = map(rcValue[3], 1000, 2000, 1000, 2000);
ch_width_5 = map(rcValue[4], 1000, 2000, 1000, 2000);
ch_width_6 = map(rcValue[5], 1000, 2000, 1000, 2000);
ch_width_7 = map(rcValue[6], 1000, 2000, 1000, 2000);
ch_width_8 = map(rcValue[7], 1000, 2000, 1000, 2000);
ch_width_9 = map(rcValue[8], 1000, 2000, 1000, 2000);
ch_width_10 = map(rcValue[9], 1000, 2000, 1000, 2000);
rxFrameDone = true;
return;
} else {
ibus[ibusIndex] = val;
ibusIndex++; //Increments the value of a variable by 1.
}
}
}