From 5e84d7732c4420552d8bf73a5a89646784737c99 Mon Sep 17 00:00:00 2001 From: Chris Date: Fri, 14 May 2021 16:38:29 -0700 Subject: [PATCH] Completed iBus Implementation --- .DS_Store | Bin 0 -> 6148 bytes Versions/.DS_Store | Bin 0 -> 6148 bytes .../dRehmFlight_Teensy_BETA_1.2/.DS_Store | Bin 0 -> 6148 bytes .../dRehmFlight_Teensy_BETA_1.2.ino | 222 +++++++------ .../dRehmFlight_Teensy_BETA_1.2/radioComm.ino | 36 ++- .../dRehmFlight_Teensy_BETA_1.2/src/.DS_Store | Bin 0 -> 6148 bytes .../src/IBUS/IBusBM.cpp | 296 ++++++++++++++++++ .../src/IBUS/IBusBM.h | 96 ++++++ 8 files changed, 536 insertions(+), 114 deletions(-) create mode 100644 .DS_Store create mode 100644 Versions/.DS_Store create mode 100644 Versions/dRehmFlight_Teensy_BETA_1.2/.DS_Store create mode 100644 Versions/dRehmFlight_Teensy_BETA_1.2/src/.DS_Store create mode 100644 Versions/dRehmFlight_Teensy_BETA_1.2/src/IBUS/IBusBM.cpp create mode 100644 Versions/dRehmFlight_Teensy_BETA_1.2/src/IBUS/IBusBM.h diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..0866282d68941ca37c5928049c1d06b6af0b7711 GIT binary patch literal 6148 zcmeHKyG{c!5S)b+C()#&^e^xSRusMfi5i7aAVr+SiT*0SE1$;fqeyhng(jMn)?=@C zYv z<9P5*nG}!$Qa}nw0V!}%1**IbcNaZXhe-h`a19Fh_o2}pd*PfIpAHVu0uWaWhjAXg z1hIL5*bC=GMrf8)Vp6SI3`;uWt@3)|oS1Z2H6K9C%tQ3^ztBDBNO$8rC>)|36Qdk+;pO-~ ck}|LPocq0SP7FHZK_}{Gz;%&Hf&W(E2Z|UKp#T5? literal 0 HcmV?d00001 diff --git a/Versions/.DS_Store b/Versions/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..1f722f1a9aca3c072cb50977149687a7d297aca2 GIT binary patch literal 6148 zcmeHKyG{c!5S)b+k!VsPrSTUag)cCtBp(pyL2wZu9i#{p>8|6qnSCH7I*?LPz^=3& zd%a`JQ{3JHkmkLe0TTdYx*|Sw7@F>@59}l&LZtJI7c9}?8IO1xWPcw}?i4LnSd+8Q zf5RBZoLGtXnX>6HkO~|saO%s6*8c_lhyMSNl&e%A75GyM$Y_2&Z}_CB zt%JvDtu6FB`j;`+(m7ZuCR!=xLQC=aUS82T_iJG9XmrMnPRt(x)g>(z_zeX<0kM=C ABme*a literal 0 HcmV?d00001 diff --git a/Versions/dRehmFlight_Teensy_BETA_1.2/.DS_Store b/Versions/dRehmFlight_Teensy_BETA_1.2/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..b1dc8a93a3322207a83e56fed12c1346dc7a5efc GIT binary patch literal 6148 zcmeHK!AiqG5Z!I7ZYyFBf_lrvTMw;@)q@afJ$Mr$dQfSTrf480rAaMXEBOxnBY(i( zab|Z~l9osk@Q@_-W8NP1ov zdvNvU^=6{k@gEt$cb6B5=!=dw{QUmHAW5s$cbUr<78aM3Dyh;+>DsxChfeCIgQVg1 zFY)TsO>aH2&*C_o+OBsVbce0-+EE;(ZV+|*IyvyW5OQ@9M1DMM#DmCB^g522P^zek zt@7q*RI49UE7sor_PAn=>UFSpclO5PqFUdo9iFuB9v(+epe3@`&<8Nl8Tq>T0d_~-s#2l2oRFaz_+fGjkfW&`#{wRL8fSZgiN rHYf_lWd^4yVCYf|u~>>XK(&D1LIcny%nX7DgntAy4LmRdf6BlI^($1o literal 0 HcmV?d00001 diff --git a/Versions/dRehmFlight_Teensy_BETA_1.2/dRehmFlight_Teensy_BETA_1.2.ino b/Versions/dRehmFlight_Teensy_BETA_1.2/dRehmFlight_Teensy_BETA_1.2.ino index d35ecd74..a4645f2e 100644 --- a/Versions/dRehmFlight_Teensy_BETA_1.2/dRehmFlight_Teensy_BETA_1.2.ino +++ b/Versions/dRehmFlight_Teensy_BETA_1.2/dRehmFlight_Teensy_BETA_1.2.ino @@ -4,7 +4,7 @@ //Version: Beta 1.2 /* - * + * * If you are using this for an academic or scholarly project, please credit me in any presentations or publications: * * Nicholas Rehm @@ -14,7 +14,7 @@ * Email: nrehm@umd.edu * */ - + //========================================================================================================================// //CREDITS + SPECIAL THANKS @@ -42,13 +42,14 @@ RcGroups 'jihlein' - IMU implementation overhaul + SBUS implementation //========================================================================================================================// -// USER-SPECIFIED DEFINES // +// USER-SPECIFIED DEFINES // //========================================================================================================================// //Uncomment only one receiver type -#define USE_PWM_RX +//#define USE_PWM_RX //#define USE_PPM_RX //#define USE_SBUS_RX +#define USE_IBUS_RX //Uncomment only one IMU #define USE_MPU6050_I2C //default @@ -82,6 +83,10 @@ RcGroups 'jihlein' - IMU implementation overhaul + SBUS implementation #include "src/SBUS/SBUS.h" //sBus interface #endif +#if defined USE_IBUS_RX + #include "src/IBUS/IBusBM.h" //iBus interface +#endif + #if defined USE_MPU6050_I2C #include "src/MPU6050/MPU6050.h" MPU6050 mpu6050; @@ -89,7 +94,7 @@ RcGroups 'jihlein' - IMU implementation overhaul + SBUS implementation #include "src/MPU9250/MPU9250.h" MPU9250 mpu9250(SPI2,36); #else - #error No MPU defined... + #error No MPU defined... #endif @@ -112,14 +117,14 @@ RcGroups 'jihlein' - IMU implementation overhaul + SBUS implementation #elif defined USE_MPU9250_SPI #define GYRO_FS_SEL_250 mpu9250.GYRO_RANGE_250DPS #define GYRO_FS_SEL_500 mpu9250.GYRO_RANGE_500DPS - #define GYRO_FS_SEL_1000 mpu9250.GYRO_RANGE_1000DPS + #define GYRO_FS_SEL_1000 mpu9250.GYRO_RANGE_1000DPS #define GYRO_FS_SEL_2000 mpu9250.GYRO_RANGE_2000DPS #define ACCEL_FS_SEL_2 mpu9250.ACCEL_RANGE_2G #define ACCEL_FS_SEL_4 mpu9250.ACCEL_RANGE_4G #define ACCEL_FS_SEL_8 mpu9250.ACCEL_RANGE_8G #define ACCEL_FS_SEL_16 mpu9250.ACCEL_RANGE_16G #endif - + #if defined GYRO_250DPS #define GYRO_SCALE GYRO_FS_SEL_250 #define GYRO_SCALE_FACTOR 131.0 @@ -151,7 +156,7 @@ RcGroups 'jihlein' - IMU implementation overhaul + SBUS implementation //========================================================================================================================// -// USER-SPECIFIED VARIABLES // +// USER-SPECIFIED VARIABLES // //========================================================================================================================// //Radio failsafe values for every channel in the event that bad reciever data is detected. Recommended defaults: @@ -170,19 +175,19 @@ float B_mag = 1.0; //Magnetometer LP filter parameter //Magnetometer calibration parameters - if using MPU9250, uncomment calibrateMagnetometer() in void setup() to get these values, else just ignore these float MagErrorX = 0.0; -float MagErrorY = 0.0; +float MagErrorY = 0.0; float MagErrorZ = 0.0; float MagScaleX = 1.0; float MagScaleY = 1.0; float MagScaleZ = 1.0; -//Controller parameters (take note of defaults before modifying!): +//Controller parameters (take note of defaults before modifying!): float i_limit = 25.0; //Integrator saturation level, mostly for safety (default 25.0) -float maxRoll = 30.0; //Max roll angle in degrees for angle mode (maximum 60 degrees), deg/sec for rate mode +float maxRoll = 30.0; //Max roll angle in degrees for angle mode (maximum 60 degrees), deg/sec for rate mode float maxPitch = 30.0; //Max pitch angle in degrees for angle mode (maximum 60 degrees), deg/sec for rate mode float maxYaw = 160.0; //Max yaw rate in deg/sec -float Kp_roll_angle = 0.2; //Roll P-gain - angle mode +float Kp_roll_angle = 0.2; //Roll P-gain - angle mode float Ki_roll_angle = 0.3; //Roll I-gain - angle mode float Kd_roll_angle = 0.05; //Roll D-gain - angle mode (if using controlANGLE2(), set to 0.0) float B_loop_roll = 0.9; //Roll damping term for controlANGLE2(), lower is more damping (must be between 0 to 1) @@ -205,8 +210,8 @@ float Kd_yaw = 0.00015; //Yaw D-gain (be careful when increasing too high, //========================================================================================================================// -// DECLARE PINS // -//========================================================================================================================// +// DECLARE PINS // +//========================================================================================================================// //NOTE: Pin 13 is reserved for onboard LED, pins 18 and 19 are reserved for the MPU6050 IMU for default setup //Radio: @@ -267,6 +272,13 @@ unsigned long channel_1_pwm_prev, channel_2_pwm_prev, channel_3_pwm_prev, channe bool sbusLostFrame; #endif +#if defined USE_IBUS_RX + IBusBM ibus; + bool ibusFailSafe; + bool ibusLostFrame; +#endif + + //IMU: float AccX, AccY, AccZ; float AccX_prev, AccY_prev, AccZ_prev; @@ -300,15 +312,15 @@ int s1_command_PWM, s2_command_PWM, s3_command_PWM, s4_command_PWM, s5_command_P //========================================================================================================================// -// VOID SETUP // +// VOID SETUP // //========================================================================================================================// void setup() { Serial.begin(500000); //usb serial delay(3000); //3 second delay for plugging in battery before IMU calibration begins, feel free to comment this out to reduce boot time - + //Initialize all pins - pinMode(13, OUTPUT); //pin 13 LED blinker on board, do not modify + pinMode(13, OUTPUT); //pin 13 LED blinker on board, do not modify pinMode(m1Pin, OUTPUT); pinMode(m2Pin, OUTPUT); pinMode(m3Pin, OUTPUT); @@ -330,7 +342,7 @@ void setup() { //Initialize radio communication radioSetup(); - + //Set radio channels to default (safe) values before entering main loop channel_1_pwm = channel_1_fs; channel_2_pwm = channel_2_fs; @@ -357,7 +369,7 @@ void setup() { servo5.write(0); servo6.write(0); servo7.write(0); - + delay(10); //Arm OneShot125 motors @@ -368,12 +380,12 @@ void setup() { m5_command_PWM = 125; m6_command_PWM = 125; commandMotors(); - + delay(100); //Warm up the loop calibrateAttitude(); //helps to warm up IMU and Madgwick filter before finally entering main loop - + //Indicate entering main loop with 3 quick blinks setupBlink(3,160,70); //numBlinks, upTime (ms), downTime (ms) @@ -385,12 +397,12 @@ void setup() { //========================================================================================================================// -// MAIN LOOP // +// MAIN LOOP // //========================================================================================================================// - + void loop() { - prev_time = current_time; - current_time = micros(); + prev_time = current_time; + current_time = micros(); dt = (current_time - prev_time)/1000000.0; loopBlink(); //indicate we are in main loop with short blink every 1.5 seconds @@ -413,10 +425,10 @@ void loop() { //Compute desired state getDesState(); //convert raw commands to normalized values based on saturated control limits - + //PID Controller - SELECT ONE: controlANGLE(); //stabilize on angle setpoint - //controlANGLE2(); //stabilize on angle setpoint using cascaded method + //controlANGLE2(); //stabilize on angle setpoint using cascaded method //controlRATE(); //stabilize on rate setpoint //Actuator mixing and scaling to PWM values @@ -428,14 +440,14 @@ void loop() { //Command actuators commandMotors(); //sends command pulses to each motor pin using OneShot125 protocol - servo1.write(s1_command_PWM); + servo1.write(s1_command_PWM); servo2.write(s2_command_PWM); servo3.write(s3_command_PWM); servo4.write(s4_command_PWM); servo5.write(s5_command_PWM); servo6.write(s6_command_PWM); servo7.write(s7_command_PWM); - + //Get vehicle commands for next loop iteration getCommands(); //pulls current available radio commands failSafe(); //prevent failures in event of bad receiver connection, defaults to failsafe values assigned in setup @@ -447,7 +459,7 @@ void loop() { //========================================================================================================================// -// FUNCTIONS // +// FUNCTIONS // //========================================================================================================================// void IMUinit() { @@ -458,9 +470,9 @@ void IMUinit() { #if defined USE_MPU6050_I2C Wire.begin(); Wire.setClock(1000000); //Note this is 2.5 times the spec sheet 400 kHz max... - + mpu6050.initialize(); - + if (mpu6050.testConnection() == false) { Serial.println("MPU6050 initialization unsuccessful"); Serial.println("Check MPU6050 wiring or try cycling power"); @@ -472,9 +484,9 @@ void IMUinit() { //do is set the desired fullscale ranges mpu6050.setFullScaleGyroRange(GYRO_SCALE); mpu6050.setFullScaleAccelRange(ACCEL_SCALE); - + #elif defined USE_MPU9250_SPI - int status = mpu9250.begin(); + int status = mpu9250.begin(); if (status < 0) { Serial.println("MPU9250 initialization unsuccessful"); @@ -499,7 +511,7 @@ void IMUinit() { void getIMUdata() { //DESCRIPTION: Request full dataset from IMU and LP filter gyro, accelerometer, and magnetometer data /* - * Reads accelerometer, gyro, and magnetometer data from IMU as AccX, AccY, AccZ, GyroX, GyroY, GyroZ, MagX, MagY, MagZ. + * Reads accelerometer, gyro, and magnetometer data from IMU as AccX, AccY, AccZ, GyroX, GyroY, GyroZ, MagX, MagY, MagZ. * These values are scaled according to the IMU datasheet to put them into correct units of g's, deg/sec, and uT. A simple first-order * low-pass filter is used to get rid of high frequency noise in these raw signals. Generally you want to cut * off everything past 80Hz, but if your loop rate is not fast enough, the low pass filter will cause a lag in @@ -566,12 +578,12 @@ void getIMUdata() { void calculate_IMU_error() { //DESCRIPTION: Computes IMU accelerometer and gyro error on startup. Note: vehicle should be powered up on flat surface /* - * Don't worry too much about what this is doing. The error values it computes are applied to the raw gyro and + * Don't worry too much about what this is doing. The error values it computes are applied to the raw gyro and * accelerometer values AccX, AccY, AccZ, GyroX, GyroY, GyroZ in getIMUdata(). This eliminates drift in the - * measurement. + * measurement. */ int16_t AcX,AcY,AcZ,GyX,GyY,GyZ,MgX,MgY,MgZ; - + //Read IMU values 12000 times int c = 0; while (c < 12000) { @@ -580,14 +592,14 @@ void calculate_IMU_error() { #elif defined USE_MPU9250_SPI mpu9250.getMotion9(&AcX, &AcY, &AcZ, &GyX, &GyY, &GyZ, &MgX, &MgY, &MgZ); #endif - + AccX = AcX / ACCEL_SCALE_FACTOR; AccY = AcY / ACCEL_SCALE_FACTOR; AccZ = AcZ / ACCEL_SCALE_FACTOR; GyroX = GyX / GYRO_SCALE_FACTOR; GyroY = GyY / GYRO_SCALE_FACTOR; GyroZ = GyZ / GYRO_SCALE_FACTOR; - + //Sum all readings AccErrorX = AccErrorX + AccX; AccErrorY = AccErrorY + AccY; @@ -611,13 +623,13 @@ void calibrateAttitude() { //Assuming vehicle is powered up on level surface! /* * This function is used on startup to warm up the attitude estimation and is what causes startup to take a few seconds - * to boot. + * to boot. */ //Warm up IMU and madgwick filter in simulated main loop for (int i = 0; i <= 10000; i++) { - prev_time = current_time; - current_time = micros(); - dt = (current_time - prev_time)/1000000.0; + prev_time = current_time; + current_time = micros(); + dt = (current_time - prev_time)/1000000.0; getIMUdata(); Madgwick(GyroX, -GyroY, -GyroZ, -AccX, AccY, AccZ, MagY, -MagX, MagZ, dt); loopRate(2000); //do not exceed 2000Hz @@ -629,7 +641,7 @@ void Madgwick(float gx, float gy, float gz, float ax, float ay, float az, float /* * This function fuses the accelerometer gyro, and magnetometer readings AccX, AccY, AccZ, GyroX, GyroY, GyroZ, MagX, MagY, and MagZ for attitude estimation. * Don't worry about the math. There is a tunable parameter B_madgwick in the user specified variable section which basically - * adjusts the weight of gyro data in the state estimate. Higher beta leads to noisier estimate, lower + * adjusts the weight of gyro data in the state estimate. Higher beta leads to noisier estimate, lower * beta leads to slower to respond estimate. It is currently tuned for 2kHz loop rate. This function updates the roll_IMU, * pitch_IMU, and yaw_IMU variables which are in degrees. If magnetometer data is not available, this function calls Madgwick6DOF() instead. */ @@ -641,11 +653,11 @@ void Madgwick(float gx, float gy, float gz, float ax, float ay, float az, float float mholder; //use 6DOF algorithm if MPU6050 is being used - #if defined USE_MPU6050_I2C + #if defined USE_MPU6050_I2C Madgwick6DOF(gx, gy, gz, ax, ay, az, invSampleFreq); return; #endif - + //Use 6DOF algorithm if magnetometer measurement invalid (avoids NaN in magnetometer normalisation) if((mx == 0.0f) && (my == 0.0f) && (mz == 0.0f)) { Madgwick6DOF(gx, gy, gz, ax, ay, az, invSampleFreq); @@ -738,7 +750,7 @@ void Madgwick(float gx, float gy, float gz, float ax, float ay, float az, float q1 *= recipNorm; q2 *= recipNorm; q3 *= recipNorm; - + //compute angles - NWU roll_IMU = atan2(q0*q1 + q2*q3, 0.5f - q1*q1 - q2*q2)*57.29577951; //degrees pitch_IMU = -asin(-2.0f * (q1*q3 - q0*q2))*57.29577951; //degrees @@ -854,16 +866,16 @@ void getDesState() { void controlANGLE() { //DESCRIPTION: Computes control commands based on state error (angle) /* - * Basic PID control to stablize on angle setpoint based on desired states roll_des, pitch_des, and yaw_des computed in + * Basic PID control to stablize on angle setpoint based on desired states roll_des, pitch_des, and yaw_des computed in * getDesState(). Error is simply the desired state minus the actual state (ex. roll_des - roll_IMU). Two safety features - * are implimented here regarding the I terms. The I terms are saturated within specified limits on startup to prevent + * are implimented here regarding the I terms. The I terms are saturated within specified limits on startup to prevent * excessive buildup. This can be seen by holding the vehicle at an angle and seeing the motors ramp up on one side until * they've maxed out throttle...saturating I to a specified limit fixes this. The second feature defaults the I terms to 0 - * if the throttle is at the minimum setting. This means the motors will not start spooling up on the ground, and the I + * if the throttle is at the minimum setting. This means the motors will not start spooling up on the ground, and the I * terms will always start from 0 on takeoff. This function updates the variables roll_PID, pitch_PID, and yaw_PID which * can be thought of as 1-D stablized signals. They are mixed to the configuration of the vehicle in controlMixer(). */ - + //Roll error_roll = roll_des - roll_IMU; integral_roll = integral_roll_prev + error_roll*dt; @@ -891,7 +903,7 @@ void controlANGLE() { integral_yaw = 0; } integral_yaw = constrain(integral_yaw, -i_limit, i_limit); //saturate integrator to prevent unsafe buildup - derivative_yaw = (error_yaw - error_yaw_prev)/dt; + derivative_yaw = (error_yaw - error_yaw_prev)/dt; yaw_PID = .01*(Kp_yaw*error_yaw + Ki_yaw*integral_yaw + Kd_yaw*derivative_yaw); //scaled by .01 to bring within -1 to 1 range //Update roll variables @@ -918,7 +930,7 @@ void controlANGLE2() { integral_roll_ol = 0; } integral_roll_ol = constrain(integral_roll_ol, -i_limit, i_limit); //saturate integrator to prevent unsafe buildup - derivative_roll = (roll_IMU - roll_IMU_prev)/dt; + derivative_roll = (roll_IMU - roll_IMU_prev)/dt; roll_des_ol = Kp_roll_angle*error_roll + Ki_roll_angle*integral_roll_ol - Kd_roll_angle*derivative_roll; //Pitch @@ -948,7 +960,7 @@ void controlANGLE2() { integral_roll_il = 0; } integral_roll_il = constrain(integral_roll_il, -i_limit, i_limit); //saturate integrator to prevent unsafe buildup - derivative_roll = (error_roll - error_roll_prev)/dt; + derivative_roll = (error_roll - error_roll_prev)/dt; roll_PID = .01*(Kp_roll_rate*error_roll + Ki_roll_rate*integral_roll_il + Kd_roll_rate*derivative_roll); //scaled by .01 to bring within -1 to 1 range //Pitch @@ -958,9 +970,9 @@ void controlANGLE2() { integral_pitch_il = 0; } integral_pitch_il = constrain(integral_pitch_il, -i_limit, i_limit); //saturate integrator to prevent unsafe buildup - derivative_pitch = (error_pitch - error_pitch_prev)/dt; + derivative_pitch = (error_pitch - error_pitch_prev)/dt; pitch_PID = .01*(Kp_pitch_rate*error_pitch + Ki_pitch_rate*integral_pitch_il + Kd_pitch_rate*derivative_pitch); //scaled by .01 to bring within -1 to 1 range - + //Yaw error_yaw = yaw_des - GyroZ; integral_yaw = integral_yaw_prev + error_yaw*dt; @@ -968,9 +980,9 @@ void controlANGLE2() { integral_yaw = 0; } integral_yaw = constrain(integral_yaw, -i_limit, i_limit); //saturate integrator to prevent unsafe buildup - derivative_yaw = (error_yaw - error_yaw_prev)/dt; + derivative_yaw = (error_yaw - error_yaw_prev)/dt; yaw_PID = .01*(Kp_yaw*error_yaw + Ki_yaw*integral_yaw + Kd_yaw*derivative_yaw); //scaled by .01 to bring within -1 to 1 range - + //Update roll variables integral_roll_prev_ol = integral_roll_ol; integral_roll_prev_il = integral_roll_il; @@ -1001,7 +1013,7 @@ void controlRATE() { integral_roll = 0; } integral_roll = constrain(integral_roll, -i_limit, i_limit); //saturate integrator to prevent unsafe buildup - derivative_roll = (error_roll - error_roll_prev)/dt; + derivative_roll = (error_roll - error_roll_prev)/dt; roll_PID = .01*(Kp_roll_rate*error_roll + Ki_roll_rate*integral_roll + Kd_roll_rate*derivative_roll); //scaled by .01 to bring within -1 to 1 range //Pitch @@ -1011,7 +1023,7 @@ void controlRATE() { integral_pitch = 0; } integral_pitch = constrain(integral_pitch, -i_limit, i_limit); //saturate integrator to prevent unsafe buildup - derivative_pitch = (error_pitch - error_pitch_prev)/dt; + derivative_pitch = (error_pitch - error_pitch_prev)/dt; pitch_PID = .01*(Kp_pitch_rate*error_pitch + Ki_pitch_rate*integral_pitch + Kd_pitch_rate*derivative_pitch); //scaled by .01 to bring within -1 to 1 range //Yaw, stablize on rate from GyroZ @@ -1021,7 +1033,7 @@ void controlRATE() { integral_yaw = 0; } integral_yaw = constrain(integral_yaw, -i_limit, i_limit); //saturate integrator to prevent unsafe buildup - derivative_yaw = (error_yaw - error_yaw_prev)/dt; + derivative_yaw = (error_yaw - error_yaw_prev)/dt; yaw_PID = .01*(Kp_yaw*error_yaw + Ki_yaw*integral_yaw + Kd_yaw*derivative_yaw); //scaled by .01 to bring within -1 to 1 range //Update roll variables @@ -1043,8 +1055,8 @@ void controlMixer() { * Takes roll_PID, pitch_PID, and yaw_PID computed from the PID controller and appropriately mixes them for the desired * vehicle configuration. For example on a quadcopter, the left two motors should have +roll_PID while the right two motors * should have -roll_PID. Front two should have -pitch_PID and the back two should have +pitch_PID etc... every motor has - * normalized (0 to 1) thro_des command for throttle control. Can also apply direct unstabilized commands from the transmitter with - * roll_passthru, pitch_passthru, and yaw_passthu. mX_command_scaled and sX_command scaled variables are used in scaleCommands() + * normalized (0 to 1) thro_des command for throttle control. Can also apply direct unstabilized commands from the transmitter with + * roll_passthru, pitch_passthru, and yaw_passthu. mX_command_scaled and sX_command scaled variables are used in scaleCommands() * in preparation to be sent to the motor ESCs and servos. */ //Quad mixing @@ -1081,7 +1093,7 @@ void scaleCommands() { /* * mX_command_scaled variables from the mixer function are scaled to 125-250us for OneShot125 protocol. sX_command_scaled variables from * the mixer function are scaled to 0-180 for the servo library using standard PWM. - * mX_command_PWM are updated here which are used to command the motors in commandMotors(). sX_command_PWM are updated + * mX_command_PWM are updated here which are used to command the motors in commandMotors(). sX_command_PWM are updated * which are used to command the servos. */ //Scaled to 125us - 250us for oneshot125 protocol @@ -1121,10 +1133,10 @@ void scaleCommands() { void getCommands() { //DESCRIPTION: Get raw PWM values for every channel from the radio /* - * Updates radio PWM commands in loop based on current available commands. channel_x_pwm is the raw command used in the rest of - * the loop. If using a PWM or PPM receiver, the radio commands are retrieved from a function in the readPWM file separate from this one which + * Updates radio PWM commands in loop based on current available commands. channel_x_pwm is the raw command used in the rest of + * the loop. If using a PWM or PPM receiver, the radio commands are retrieved from a function in the readPWM file separate from this one which * is running a bunch of interrupts to continuously update the radio readings. If using an SBUS receiver, the alues are pulled from the SBUS library directly. - * The raw radio commands are filtered with a first order low-pass filter to eliminate any really high frequency noise. + * The raw radio commands are filtered with a first order low-pass filter to eliminate any really high frequency noise. */ #if defined USE_PPM_RX || defined USE_PWM_RX @@ -1134,22 +1146,36 @@ void getCommands() { channel_4_pwm = getRadioPWM(4); channel_5_pwm = getRadioPWM(5); channel_6_pwm = getRadioPWM(6); - + #elif defined USE_SBUS_RX if (sbus.read(&sbusChannels[0], &sbusFailSafe, &sbusLostFrame)) { //sBus scaling below is for Taranis-Plus and X4R-SB - float scale = 0.615; - float bias = 895.0; + float scale = 0.615; + float bias = 895.0; channel_1_pwm = sbusChannels[0] * scale + bias; channel_2_pwm = sbusChannels[1] * scale + bias; channel_3_pwm = sbusChannels[2] * scale + bias; channel_4_pwm = sbusChannels[3] * scale + bias; channel_5_pwm = sbusChannels[4] * scale + bias; - channel_6_pwm = sbusChannels[5] * scale + bias; + channel_6_pwm = sbusChannels[5] * scale + bias; } + + #elif defined USE_IBUS_RX + ibus.loop(); + + //sBus scaling below is for Taranis-Plus and X4R-SB + float scale = 1; + float bias = 0; + channel_1_pwm = ibus.readChannel(0) * scale + bias; + channel_2_pwm = ibus.readChannel(1) * scale + bias; + channel_3_pwm = ibus.readChannel(2) * scale + bias; + channel_4_pwm = ibus.readChannel(3) * scale + bias; + channel_5_pwm = ibus.readChannel(4) * scale + bias; + channel_6_pwm = ibus.readChannel(5) * scale + bias; + #endif - + //Low-pass the critical commands and update previous values float b = 0.2; //lower=slower, higher=noiser channel_1_pwm = (1.0 - b)*channel_1_pwm_prev + b*channel_1_pwm; @@ -1165,10 +1191,10 @@ void getCommands() { void failSafe() { //DESCRIPTION: If radio gives garbage values, set all commands to default values /* - * Radio connection failsafe used to check if the getCommands() function is returning acceptable pwm values. If any of + * Radio connection failsafe used to check if the getCommands() function is returning acceptable pwm values. If any of * the commands are lower than 800 or higher than 2200, then we can be certain that there is an issue with the radio - * connection (most likely hardware related). If any of the channels show this failure, then all of the radio commands - * channel_x_pwm are set to default failsafe values specified in the setup. Comment out this function when troubleshooting + * connection (most likely hardware related). If any of the channels show this failure, then all of the radio commands + * channel_x_pwm are set to default failsafe values specified in the setup. Comment out this function when troubleshooting * your radio connection in case any extreme values are triggering this function to overwrite the printed variables. */ unsigned minVal = 800; @@ -1213,7 +1239,7 @@ void commandMotors() { int flagM4 = 0; int flagM5 = 0; int flagM6 = 0; - + //Write all motor pins high digitalWrite(m1Pin, HIGH); digitalWrite(m2Pin, HIGH); @@ -1245,30 +1271,30 @@ void commandMotors() { digitalWrite(m4Pin, LOW); wentLow = wentLow + 1; flagM4 = 1; - } + } if ((m5_command_PWM <= timer - pulseStart) && (flagM5==0)) { digitalWrite(m5Pin, LOW); wentLow = wentLow + 1; flagM5 = 1; - } + } if ((m6_command_PWM <= timer - pulseStart) && (flagM6==0)) { digitalWrite(m6Pin, LOW); wentLow = wentLow + 1; flagM6 = 1; - } + } } } float floatFaderLinear(float param, float param_min, float param_max, float fadeTime, int state, int loopFreq){ //DESCRIPTION: Linearly fades a float type variable between min and max bounds based on desired high or low state and time - /* - * Takes in a float variable, desired minimum and maximum bounds, fade time, high or low desired state, and the loop frequency + /* + * Takes in a float variable, desired minimum and maximum bounds, fade time, high or low desired state, and the loop frequency * and linearly interpolates that param variable between the maximum and minimum bounds. This function can be called in controlMixer() - * and high/low states can be determined by monitoring the state of an auxillarly radio channel. For example, if channel_6_pwm is being - * monitored to switch between two dynamic configurations (hover and forward flight), this function can be called within the logical + * and high/low states can be determined by monitoring the state of an auxillarly radio channel. For example, if channel_6_pwm is being + * monitored to switch between two dynamic configurations (hover and forward flight), this function can be called within the logical * statements in order to fade controller gains, for example between the two dynamic configurations. The 'state' (1 or 0) can be used * to designate the two final options for that control gain based on the dynamic configuration assignment to the auxillary radio channel. - * + * */ float diffParam = (param_max - param_min)/(fadeTime*loopFreq); //difference to add or subtract from param for each loop iteration for desired fadeTime @@ -1280,7 +1306,7 @@ float floatFaderLinear(float param, float param_min, float param_max, float fade } param = constrain(param, param_min, param_max); //constrain param within max bounds - + return param; } @@ -1288,9 +1314,9 @@ float switchRollYaw(int reverseRoll, int reverseYaw) { //DESCRIPTION: Switches roll_des and yaw_des variables for tailsitter-type configurations /* * Takes in two integers (either 1 or -1) corresponding to the desired reversing of the roll axis and yaw axis, respectively. - * Reversing of the roll or yaw axis may be needed when switching between the two for some dynamic configurations. Inputs of 1, 1 does not - * reverse either of them, while -1, 1 will reverse the output corresponding to the new roll axis. - * This function may be replaced in the future by a function that switches the IMU data instead (so that angle can also be estimated with the + * Reversing of the roll or yaw axis may be needed when switching between the two for some dynamic configurations. Inputs of 1, 1 does not + * reverse either of them, while -1, 1 will reverse the output corresponding to the new roll axis. + * This function may be replaced in the future by a function that switches the IMU data instead (so that angle can also be estimated with the * IMU tilted 90 degrees from default level). */ float switch_holder; @@ -1305,9 +1331,9 @@ void throttleCut() { //DESCRIPTION: Directly set actuator outputs to minimum value if triggered /* * Monitors the state of radio command channel_5_pwm and directly sets the mx_command_PWM values to minimum (120 is - * minimum for oneshot125 protocol, 0 is minimum for standard PWM servo library used) if channel 5 is high. This is the last function + * minimum for oneshot125 protocol, 0 is minimum for standard PWM servo library used) if channel 5 is high. This is the last function * called before commandMotors() is called so that the last thing checked is if the user is giving permission to command - * the motors to anything other than minimum value. Safety first. + * the motors to anything other than minimum value. Safety first. */ if (channel_5_pwm > 1500) { m1_command_PWM = 120; @@ -1316,7 +1342,7 @@ void throttleCut() { m4_command_PWM = 120; m5_command_PWM = 120; m6_command_PWM = 120; - + //uncomment if using servo PWM variables to control motor ESCs //s1_command_PWM = 0; //s2_command_PWM = 0; @@ -1329,7 +1355,7 @@ void throttleCut() { } void calibrateMagnetometer() { - #if defined USE_MPU9250_SPI + #if defined USE_MPU9250_SPI float success; Serial.println("Beginning magnetometer calibration in"); Serial.println("3..."); @@ -1368,7 +1394,7 @@ void calibrateMagnetometer() { else { Serial.println("Calibration Unsuccessful. Please reset the board and try again."); } - + while(1); //halt code so it won't enter main loop until this function commented out #endif Serial.println("Error: MPU9250 not selected. Cannot calibrate non-existent magnetometer."); @@ -1379,14 +1405,14 @@ void loopRate(int freq) { //DESCRIPTION: Regulate main loop rate to specified frequency in Hz /* * It's good to operate at a constant loop rate for filters to remain stable and whatnot. Interrupt routines running in the - * background cause the loop rate to fluctuate. This function basically just waits at the end of every loop iteration until - * the correct time has passed since the start of the current loop for the desired loop rate in Hz. 2kHz is a good rate to + * background cause the loop rate to fluctuate. This function basically just waits at the end of every loop iteration until + * the correct time has passed since the start of the current loop for the desired loop rate in Hz. 2kHz is a good rate to * be at because the loop nominally will run between 2.8kHz - 4.2kHz. This lets us have a little room to add extra computations * and remain above 2kHz, without needing to retune all of our filtering parameters. */ float invFreq = 1.0/freq*1000000.0; unsigned long checker = micros(); - + //Sit in loop until appropriate time has passed while (invFreq > (checker - current_time)) { checker = micros(); @@ -1401,7 +1427,7 @@ void loopBlink() { if (current_time - blink_counter > blink_delay) { blink_counter = micros(); digitalWrite(13, blinkAlternate); //pin 13 is built in LED - + if (blinkAlternate == 1) { blinkAlternate = 0; blink_delay = 100000; diff --git a/Versions/dRehmFlight_Teensy_BETA_1.2/radioComm.ino b/Versions/dRehmFlight_Teensy_BETA_1.2/radioComm.ino index 30b28bd9..4f836c82 100644 --- a/Versions/dRehmFlight_Teensy_BETA_1.2/radioComm.ino +++ b/Versions/dRehmFlight_Teensy_BETA_1.2/radioComm.ino @@ -7,13 +7,13 @@ //This file contains all necessary functions and code used for radio communication to avoid cluttering the main code -unsigned long rising_edge_start_1, rising_edge_start_2, rising_edge_start_3, rising_edge_start_4, rising_edge_start_5, rising_edge_start_6; +unsigned long rising_edge_start_1, rising_edge_start_2, rising_edge_start_3, rising_edge_start_4, rising_edge_start_5, rising_edge_start_6; unsigned long channel_1_raw, channel_2_raw, channel_3_raw, channel_4_raw, channel_5_raw, channel_6_raw; int ppm_counter = 0; unsigned long time_ms = 0; void radioSetup() { - //PPM Receiver + //PPM Receiver #if defined USE_PPM_RX //Declare interrupt pin pinMode(PPM_Pin, INPUT_PULLUP); @@ -23,7 +23,7 @@ void radioSetup() { //PWM Receiver #elif defined USE_PWM_RX - //Declare interrupt pins + //Declare interrupt pins pinMode(ch1Pin, INPUT_PULLUP); pinMode(ch2Pin, INPUT_PULLUP); pinMode(ch3Pin, INPUT_PULLUP); @@ -40,19 +40,23 @@ void radioSetup() { attachInterrupt(digitalPinToInterrupt(ch6Pin), getCh6, CHANGE); delay(20); - //SBUS Recevier + //SBUS Recevier #elif defined USE_SBUS_RX sbus.begin(); - + + //IBUS Recevier + #elif defined USE_IBUS_RX + ibus.begin(Serial5, IBUSBM_NOTIMER); + #else #error No RX type defined... #endif } unsigned long getRadioPWM(int ch_num) { - //DESCRIPTION: Get current radio commands from interrupt routines + //DESCRIPTION: Get current radio commands from interrupt routines unsigned long returnPWM; - + if (ch_num == 1) { returnPWM = channel_1_raw; } @@ -71,7 +75,7 @@ unsigned long getRadioPWM(int ch_num) { else if (ch_num == 6) { returnPWM = channel_6_raw; } - + return returnPWM; } @@ -90,35 +94,35 @@ void getPPM() { dt_ppm = micros() - time_ms; time_ms = micros(); - + if (dt_ppm > 5000) { //waiting for long pulse to indicate a new pulse train has arrived ppm_counter = 0; } - + if (ppm_counter == 1) { //first pulse channel_1_raw = dt_ppm; } - + if (ppm_counter == 2) { //second pulse channel_2_raw = dt_ppm; } - + if (ppm_counter == 3) { //third pulse channel_3_raw = dt_ppm; } - + if (ppm_counter == 4) { //fourth pulse channel_4_raw = dt_ppm; } - + if (ppm_counter == 5) { //fifth pulse channel_5_raw = dt_ppm; } - + if (ppm_counter == 6) { //sixth pulse channel_6_raw = dt_ppm; } - + ppm_counter = ppm_counter + 1; } } diff --git a/Versions/dRehmFlight_Teensy_BETA_1.2/src/.DS_Store b/Versions/dRehmFlight_Teensy_BETA_1.2/src/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..315699c75c83a45808ee36eef1faa003cb2ceac6 GIT binary patch literal 6148 zcmeHK%}yIJ5Vn)0aZ;h?fCSw3P;ML&s7P}_T9$C&R%t0c(2DG`5m{-ojGKJVi~~rX)c-!e2WL3?=4ai&=qFOfQ{4|vqt58Ox^^g&%#V`JKqW_E2SR@Sh>}o_Tscg_ zRL$dQhY)2^KCf<$$Mr_Dwr%fy-I;9L<35XSitqo?;`)C!iAKZ#G4Nk8z^#_oa$!s6ZJpa3zO^>AHZ&BB%Qa3@ kKv7RI#Nt!D0Zj?mZBzgqgSkeqfY2WSMFVxjz)~4_0j6YYPXGV_ literal 0 HcmV?d00001 diff --git a/Versions/dRehmFlight_Teensy_BETA_1.2/src/IBUS/IBusBM.cpp b/Versions/dRehmFlight_Teensy_BETA_1.2/src/IBUS/IBusBM.cpp new file mode 100644 index 00000000..624c11a4 --- /dev/null +++ b/Versions/dRehmFlight_Teensy_BETA_1.2/src/IBUS/IBusBM.cpp @@ -0,0 +1,296 @@ +/* + * Interface to the RC IBus protocol + * + * Based on original work from: https://gitlab.com/timwilkinson/FlySkyIBus + * Extended to also handle sensors/telemetry data to be sent back to the transmitter, + * interrupts driven and other features. + * + * This lib requires a hardware UART for communication + * Another version using software serial is here https://github.com/Hrastovc/iBUStelemetry + * + * Explaination of sensor/ telemetry prtocol here: + * https://github.com/betaflight/betaflight/wiki/Single-wire-FlySky-(IBus)-telemetry + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * Created 12 March 2019 Bart Mellink + * Updated 4 April 2019 to support ESP32 + * updated 13 jun 2019 to support STM32 (pauluzs) + * Updated 21 Jul 2020 to support MBED (David Peverley) + */ + +#include +#include "IBusBM.h" + +// pointer to the first class instance to be used to call the loop() method from timer interrupt +// will be initiated by class constructor, then daisy channed to other class instances if we have more than one +IBusBM* IBusBMfirst = NULL; + + +// Interrupt on timer0 - called every 1 ms +// we call the IBusSensor.loop() here, so we are certain we respond to sensor requests in a timely matter +#ifdef ARDUINO_ARCH_AVR +SIGNAL(TIMER0_COMPA_vect) { + if (IBusBMfirst) IBusBMfirst->loop(); // gets new servo values if available and process any sensor data +} +#else +void onTimer() { + if (IBusBMfirst) IBusBMfirst->loop(); // gets new servo values if available and process any sensor data +} +#endif + + +#if defined(ARDUINO_ARCH_MBED) +extern "C" { + void TIMER4_IRQHandler_v() { + if (NRF_TIMER4->EVENTS_COMPARE[0] == 1) { + onTimer(); + NRF_TIMER4->EVENTS_COMPARE[0] = 0; + } + } +} +#endif + + +/* + * supports max 14 channels in this lib (with messagelength of 0x20 there is room for 14 channels) + + Example set of bytes coming over the iBUS line for setting servos: + 20 40 DB 5 DC 5 54 5 DC 5 E8 3 D0 7 D2 5 E8 3 DC 5 DC 5 DC 5 DC 5 DC 5 DC 5 DA F3 + Explanation + Protocol length: 20 + Command code: 40 + Channel 0: DB 5 -> value 0x5DB + Channel 1: DC 5 -> value 0x5Dc + Channel 2: 54 5 -> value 0x554 + Channel 3: DC 5 -> value 0x5DC + Channel 4: E8 3 -> value 0x3E8 + Channel 5: D0 7 -> value 0x7D0 + Channel 6: D2 5 -> value 0x5D2 + Channel 7: E8 3 -> value 0x3E8 + Channel 8: DC 5 -> value 0x5DC + Channel 9: DC 5 -> value 0x5DC + Channel 10: DC 5 -> value 0x5DC + Channel 11: DC 5 -> value 0x5DC + Channel 12: DC 5 -> value 0x5DC + Channel 13: DC 5 -> value 0x5DC + Checksum: DA F3 -> calculated by adding up all previous bytes, total must be FFFF + */ + + +#if defined(_VARIANT_ARDUINO_STM32_) +void IBusBM::begin(HardwareSerial &serial, TIM_TypeDef * timerid, int8_t rxPin, int8_t txPin) { +#else +void IBusBM::begin(HardwareSerial &serial, int8_t timerid, int8_t rxPin, int8_t txPin) { +#endif + + #ifdef ARDUINO_ARCH_ESP32 + serial.begin(115200, SERIAL_8N1, rxPin, txPin); + #else + serial.begin(115200, SERIAL_8N1); + #endif + + this->stream = &serial; + this->state = DISCARD; + this->last = millis(); + this->ptr = 0; + this->len = 0; + this->chksum = 0; + this->lchksum = 0; + + // we need to process the iBUS sensor protocol handler frequently enough (at least once each ms) to ensure the response data + // from the sensor is sent on time to the receiver + // if timerid==IBUSBM_NOTIMER the user is responsible for calling the loop function + this->IBusBMnext = IBusBMfirst; + + if (!IBusBMfirst && timerid != IBUSBM_NOTIMER) { + #ifdef ARDUINO_ARCH_AVR + // on AVR architectures Timer0 is already used for millis() - we'll just interrupt somewhere in the middle and call the TIMER0_COMPA_vect interrupt + OCR0A = 0xAF; + TIMSK0 |= _BV(OCIE0A); + #else + // on other architectures we need to use a time + #if defined(ARDUINO_ARCH_ESP32) + hw_timer_t * timer = NULL; + timer = timerBegin(timerid, F_CPU / 1000000L, true); // defaults to timer_id = 0; divider=80 (1 ms); countUp = true; + timerAttachInterrupt(timer, &onTimer, true); // edge = true + timerAlarmWrite(timer, 1000, true); //1 ms + timerAlarmEnable(timer); + #elif defined(_VARIANT_ARDUINO_STM32_) + // see https://github.com/stm32duino/wiki/wiki/HardwareTimer-library + HardwareTimer *stimer_t = new HardwareTimer(timerid); + stimer_t->setOverflow(1000, HERTZ_FORMAT); // 1000 Hz + stimer_t->attachInterrupt(onTimer); + stimer_t->resume(); + #elif defined(ARDUINO_ARCH_MBED) + NRF_TIMER4->TASKS_STOP = 1; // Stop timer + NRF_TIMER4->MODE = TIMER_MODE_MODE_Timer; // Set the timer in Counter Mode + NRF_TIMER4->BITMODE = TIMER_BITMODE_BITMODE_16Bit << TIMER_BITMODE_BITMODE_Pos; + NRF_TIMER2->TASKS_CLEAR = 1; // clear the task first to be usable for later + + // Set prescaler & compare register. + // Prescaler = 0 gives 16MHz timer. + // Prescaler = 4 (2^4) gives 1MHz timer. + NRF_TIMER4->PRESCALER = 4 << TIMER_PRESCALER_PRESCALER_Pos; + NRF_TIMER4->CC[0] = 1000; + + // Enable interrupt on Timer 4 for CC[0] compare match events + NRF_TIMER4->INTENSET = TIMER_INTENSET_COMPARE0_Enabled << TIMER_INTENSET_COMPARE0_Pos; + NRF_TIMER4->SHORTS = TIMER_SHORTS_COMPARE0_CLEAR_Enabled << TIMER_SHORTS_COMPARE0_CLEAR_Pos; + + NVIC_EnableIRQ(TIMER4_IRQn); + + NRF_TIMER4->TASKS_START = 1; // Start TIMER2 + #else + // It should not be too difficult to support additional architectures as most have timer functions, but I only tested AVR and ESP32 + #warning "Timing only supportted for AVR, ESP32 and STM32 architectures. Use timerid IBUSBM_NOTIMER" + #endif + #endif + } + IBusBMfirst = this; +} + +// called from timer interrupt or mannually by user (if IBUSBM_NOTIMER set in begin()) +void IBusBM::loop(void) { + + // if we have multiple instances of IBusBM, we (recursively) call the other instances loop() function + if (IBusBMnext) IBusBMnext->loop(); + + // only process data already in our UART receive buffer + while (stream->available() > 0) { + // only consider a new data package if we have not heard anything for >3ms + uint32_t now = millis(); + if (now - last >= PROTOCOL_TIMEGAP){ + state = GET_LENGTH; + } + last = now; + + uint8_t v = stream->read(); + switch (state) { + case GET_LENGTH: + if (v <= PROTOCOL_LENGTH && v > PROTOCOL_OVERHEAD) { + ptr = 0; + len = v - PROTOCOL_OVERHEAD; + chksum = 0xFFFF - v; + state = GET_DATA; + } else { + state = DISCARD; + } + break; + + case GET_DATA: + buffer[ptr++] = v; + chksum -= v; + if (ptr == len) { + state = GET_CHKSUML; + } + break; + + case GET_CHKSUML: + lchksum = v; + state = GET_CHKSUMH; + break; + + case GET_CHKSUMH: + // Validate checksum + if (chksum == (v << 8) + lchksum) { + // Checksum is all fine Execute command - + uint8_t adr = buffer[0] & 0x0f; + if (buffer[0]==PROTOCOL_COMMAND40) { + // Valid servo command received - extract channel data + for (uint8_t i = 1; i < PROTOCOL_CHANNELS * 2 + 1; i += 2) { + channel[i / 2] = buffer[i] | (buffer[i + 1] << 8); + } + cnt_rec++; + } else if (adr<=NumberSensors && adr>0 && len==1) { + + // all sensor data commands go here + // we only process the len==1 commands (=message length is 4 bytes incl overhead) to prevent the case the + // return messages from the UART TX port loop back to the RX port and are processed again. This is extra + // precaution as it will also be prevented by the PROTOCOL_TIMEGAP required + sensorinfo *s = &sensors[adr-1]; + delayMicroseconds(100); + switch (buffer[0] & 0x0f0) { + case PROTOCOL_COMMAND_DISCOVER: // 0x80, discover sensor + cnt_poll++; + // echo discover command: 0x04, 0x81, 0x7A, 0xFF + stream->write(0x04); + stream->write(PROTOCOL_COMMAND_DISCOVER + adr); + chksum = 0xFFFF - (0x04 + PROTOCOL_COMMAND_DISCOVER + adr); + break; + case PROTOCOL_COMMAND_TYPE: // 0x90, send sensor type + // echo sensortype command: 0x06 0x91 0x00 0x02 0x66 0xFF + stream->write(0x06); + stream->write(PROTOCOL_COMMAND_TYPE + adr); + stream->write(s->sensorType); + stream->write(s->sensorLength); + chksum = 0xFFFF - (0x06 + PROTOCOL_COMMAND_TYPE + adr + s->sensorType + s->sensorLength); + break; + case PROTOCOL_COMMAND_VALUE: // 0xA0, send sensor data + cnt_sensor++; + uint8_t t; + // echo sensor value command: 0x06 0x91 0x00 0x02 0x66 0xFF + stream->write(t = 0x04 + s->sensorLength); + chksum = 0xFFFF - t; + stream->write(t = PROTOCOL_COMMAND_VALUE + adr); + chksum -= t; + stream->write(t = s->sensorValue & 0x0ff); + chksum -= t; + stream->write(t = (s->sensorValue >> 8) & 0x0ff); + chksum -= t; + if (s->sensorLength==4) { + stream->write(t = (s->sensorValue >> 16) & 0x0ff); + chksum -= t; + stream->write(t = (s->sensorValue >> 24) & 0x0ff); + chksum -= t; + } + break; + default: + adr=0; // unknown command, prevent sending chksum + break; + } + if (adr>0) { + stream->write(chksum & 0x0ff); + stream->write(chksum >> 8); + } + } + } + state = DISCARD; + break; + + case DISCARD: + default: + break; + } + } +} + +uint16_t IBusBM::readChannel(uint8_t channelNr) { + if (channelNr < PROTOCOL_CHANNELS) { + return channel[channelNr]; + } else { + return 0; + } +} + +uint8_t IBusBM::addSensor(uint8_t type, uint8_t len) { + // add a sensor, return sensor number + if (len!=2 && len!=4) len = 2; + if (NumberSensors < SENSORMAX) { + sensorinfo *s = &sensors[NumberSensors]; + s->sensorType = type; + s->sensorLength = len; + s->sensorValue = 0; + NumberSensors++; + } + return NumberSensors; +} + +void IBusBM::setSensorMeasurement(uint8_t adr, int32_t value) { + if (adr<=NumberSensors && adr>0) + sensors[adr-1].sensorValue = value; +} + diff --git a/Versions/dRehmFlight_Teensy_BETA_1.2/src/IBUS/IBusBM.h b/Versions/dRehmFlight_Teensy_BETA_1.2/src/IBUS/IBusBM.h new file mode 100644 index 00000000..9287d43a --- /dev/null +++ b/Versions/dRehmFlight_Teensy_BETA_1.2/src/IBUS/IBusBM.h @@ -0,0 +1,96 @@ +/* + * Interface to the RC IBus protocol + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * Created 12 March 2019 Bart Mellink + */ +#ifndef IBusBM_h +#define IBusBM_h + +#include + +#if defined(ARDUINO_ARCH_MBED) +#include "mbed.h" +#include "HardwareSerial.h" +#endif + +// if you have an opentx transciever you can add additional sensor types here. +// see https://github.com/cleanflight/cleanflight/blob/7cd417959b3cb605aa574fc8c0f16759943527ef/src/main/telemetry/ibus_shared.h +// below the values supported by the Turnigy FS-MT6 transceiver +#define IBUSS_INTV 0x00 // Internal voltage (in 0.01) +#define IBUSS_TEMP 0x01 // Temperature (in 0.1 degrees, where 0=-40'C) +#define IBUSS_RPM 0x02 // RPM +#define IBUSS_EXTV 0x03 // External voltage (in 0.01) +#define IBUS_PRESS 0x41 // Pressure (in Pa) +#define IBUS_SERVO 0xfd // Servo value + + +#if defined(ARDUINO_ARCH_MBED) +#define HardwareSerial arduino::HardwareSerial +#else + #if !defined(ARDUINO_ARCH_MEGAAVR) +class HardwareSerial; + #endif +#endif +class Stream; + +class IBusBM { + +public: +#if defined(_VARIANT_ARDUINO_STM32_) + #if !defined(STM32_CORE_VERSION) || (STM32_CORE_VERSION < 0x01090000) + #error "Due to API change, this sketch is compatible with STM32_CORE_VERSION >= 0x01090000" + #endif + #define IBUSBM_NOTIMER NULL // no timer interrupt used + void begin(HardwareSerial &serial, TIM_TypeDef * timerid=TIM1, int8_t rxPin=-1, int8_t txPin=-1); +#else + #define IBUSBM_NOTIMER -1 // no timer interrupt used + void begin(HardwareSerial &serial, int8_t timerid=0, int8_t rxPin=-1, int8_t txPin=-1); +#endif + uint16_t readChannel(uint8_t channelNr); // read servo channel 0..9 + uint8_t addSensor(uint8_t type, uint8_t len=2); // add sensor type and data length (2 or 4), returns address + void setSensorMeasurement(uint8_t adr, int32_t value); + + void loop(void); // used internally for interrupt handline, but needs to be defined as public + + volatile uint8_t cnt_poll; // count received number of sensor poll messages + volatile uint8_t cnt_sensor; // count times a sensor value has been sent back + volatile uint8_t cnt_rec; // count received number of servo messages + +private: + enum State {GET_LENGTH, GET_DATA, GET_CHKSUML, GET_CHKSUMH, DISCARD}; + + static const uint8_t PROTOCOL_LENGTH = 0x20; + static const uint8_t PROTOCOL_OVERHEAD = 3; // packet is , overhead=cmd+chk bytes + static const uint8_t PROTOCOL_TIMEGAP = 3; // Packets are received very ~7ms so use ~half that for the gap + static const uint8_t PROTOCOL_CHANNELS = 14; + static const uint8_t PROTOCOL_COMMAND40 = 0x40; // Command to set servo or motor speed is always 0x40 + static const uint8_t PROTOCOL_COMMAND_DISCOVER = 0x80; // Command discover sensor (lowest 4 bits are sensor) + static const uint8_t PROTOCOL_COMMAND_TYPE = 0x90; // Command discover sensor (lowest 4 bits are sensor) + static const uint8_t PROTOCOL_COMMAND_VALUE = 0xA0; // Command send sensor data (lowest 4 bits are sensor) + static const uint8_t SENSORMAX = 10; // Max number of sensors + + uint8_t state; // state machine state for iBUS protocol + HardwareSerial *stream; // serial port + uint32_t last; // milis() of prior message + uint8_t buffer[PROTOCOL_LENGTH]; // message buffer + uint8_t ptr; // pointer in buffer + uint8_t len; // message length + uint16_t channel[PROTOCOL_CHANNELS]; // servo data received + uint16_t chksum; // checksum calculation + uint8_t lchksum; // checksum lower byte received + typedef struct { + uint8_t sensorType; // sensor type (0,1,2,3, etc) + uint8_t sensorLength; // data length for defined sensor (can be 2 or 4) + int32_t sensorValue; // sensor data for defined sensors (16 or 32 bits) + } sensorinfo; + sensorinfo sensors[SENSORMAX]; + uint8_t NumberSensors = 0; // number of sensors + IBusBM* IBusBMnext = NULL; // pointer to the next class instance to be used to call the loop() method from timer interrupt +}; + +#endif