Attemp to integrate sonar (ultrasonic sensor)

User avatar
guru_florida
Posts: 45
Joined: Sat Mar 26, 2011 4:51 am

Re: Attemp to integrate sonar (ultrasonic sensor)

Post by guru_florida »

penpen77 wrote:the code for SRF08 works perfectly with my i2c shield for HC-SR04, just need some tweaking with address


I dont get it, the SR04 is not an i2c sensor, how could the SRF08 code work for it?

My code will try to change the i2c address of the sensor so that multiple SRF08's can be put on the same bus. If there are other i2c sonar sensors out there I can take a look at how they do the address change, or simply have an option not to do the address moving but then only 1 sonar sensor can be present.

C

penpen77
Posts: 73
Joined: Tue Jan 24, 2012 10:45 pm

Re: Attemp to integrate sonar (ultrasonic sensor)

Post by penpen77 »

i2c shield for SR04 in the beginning of the thread, page 2, wrap echo/trigger blocking call request into i2c stream non-blocking event. With this "shield/wrapper", you have a decent working i2c sonar for ~5€

Blocking event like echo/trigger will degrade loop execution time, especially if there is several call at each execution (to have a median value, SR04 returned values aren't always accurate). And you don't have to sacrify 2 I/Os

so, with your code, just need to change i2c address and tweak srf08 i2c response/request handler.

User avatar
guru_florida
Posts: 45
Joined: Sat Mar 26, 2011 4:51 am

Re: Attemp to integrate sonar (ultrasonic sensor)

Post by guru_florida »

I see now, thanks. I took a look at the code. You will want to set the address of the sonar to 0xF0. This is where my code will look for the first sensor. The shield code ignores the register byte in i2c transactions so that is good in the sense my code tries to read register 2, the shield will return the sonar code anyway. The only issue I see is my code reads a 16bit value. So it will read from the sonar shield twice, You will want to reduce that read call to 8bit.

Note: The shield code specifies the i2c address as 0x09. This would be the 7bit address (i.e. not including r/w bit), So to my code this equals 0x12 address.

So, try this:
1. Do one of:
a. Recompile the shield code to change i2c address from 0x09 to Ox78, or (0x78 = 0xF0 in 8bit i2c addr format)
b. Change my code and redefine SRF08_SENSOR_FIRST parameter from 0xF0 to 0x12...my code will then look for sensors at 0x12, 0x014, 0x16, etc.
1. Uncomment the SONAR_MULTICAST_PING define.
2. Change i2c_readReg16 to i2creadReg8 in "case 3" within the sonar's state machine code. There are actually 2 locations, but with SONAR_MULTICAST_PING disabled only the bottom of the two matter. The full line is:
srf08_ctx.range[srf08_ctx.current] = i2c_readReg16(SRF08_SENSOR_FIRST+(srf08_ctx.current<<1), SRF08_ECHO_RANGE);
change to:
srf08_ctx.range[srf08_ctx.current] = i2c_readReg8(SRF08_SENSOR_FIRST+(srf08_ctx.current<<1), SRF08_ECHO_RANGE);



penpen77 wrote:i2c shield for SR04 in the beginning of the thread, page 2, wrap echo/trigger blocking call request into i2c stream non-blocking event. With this "shield/wrapper", you have a decent working i2c sonar for ~5€

Blocking event like echo/trigger will degrade loop execution time, especially if there is several call at each execution (to have a median value, SR04 returned values aren't always accurate). And you don't have to sacrify 2 I/Os

so, with your code, just need to change i2c address and tweak srf08 i2c response/request handler.

User avatar
Bledi
Posts: 187
Joined: Sat Sep 10, 2011 6:36 pm

Re: Attemp to integrate sonar (ultrasonic sensor)

Post by Bledi »

I just order an SR04. I ll try to use your works to add it to the arduino use for I2C GPS (EOSBandi)

haley0918
Posts: 28
Joined: Tue Mar 06, 2012 9:09 am

Re: Attemp to integrate sonar (ultrasonic sensor)

Post by haley0918 »

Bledi wrote:I just order an SR04. I ll try to use your works to add it to the arduino use for I2C GPS (EOSBandi)


I'm interested to include the SR04 into I2C_GPS_NAV too, possibly tying multiple SR04 together under one I2C address
Otherwise the arduino is kind of a waste for GPS only

Tifani
Posts: 63
Joined: Sun Nov 06, 2011 5:15 pm

Re: Attemp to integrate sonar (ultrasonic sensor)

Post by Tifani »

Hi !
Why not Ultrasonic Range Finder - Maxbotix LV-EZ1 ???
(I have one)
Regards
Tom

User avatar
guru_florida
Posts: 45
Joined: Sat Mar 26, 2011 4:51 am

Re: Attemp to integrate sonar (ultrasonic sensor)

Post by guru_florida »

Tifani wrote:Hi !
Why not Ultrasonic Range Finder - Maxbotix LV-EZ1 ???
Tom


It could work. The A6 and A7 input line is unused.

Twister
Posts: 2
Joined: Sat Feb 18, 2012 6:03 pm

Re: Attemp to integrate sonar (ultrasonic sensor)

Post by Twister »

Is the DYP-ME007 working on a flyduino mega?

dongfang
Posts: 5
Joined: Tue Mar 13, 2012 4:33 pm

Re: Attemp to integrate sonar (ultrasonic sensor)

Post by dongfang »

Hi All,

I think Vallekano's code do not work in my board(Arduino Nano) as it miss one "pinMode(HCSR04_EchoPin, INPUT);" command.

And I've merged Vallekano's code and mahowik's code together, so:

1. It still use D8 for TX pin, and D12 for RX pin
2. alt-hold data based on sonar data in range 0 - 200cm; 200cm-500cm for mix of sonar+baro; above 500cm:based on baro only
3. EstAlt will still use multiwii 1.9's existing code when sonar do not have valid data, (though I don't understand the Algorithm, and how to set Kp1)
4. I removed some unnecessary code


Till now, below code works for me very well: (please use Vallekano's patch first, and change the code below)

Sensors.pde:

Code: Select all

/////////////////////////////////////////
// ************************************************************************************************************
// HC-SR04 Ultrasonic Sonar
// ************************************************************************************************************

#if defined(HCSR04)

volatile unsigned long HCSR04_starTime = 0;
volatile unsigned long HCSR04_echoTime = 0;
volatile static int32_t  tempSonarAlt=0;

void Sonar_init()
{
  PCICR  |= (1<<0); // D8
  PCMSK0 = (1<<0); // pin 8
  pinMode(HCSR04_EchoPin, INPUT);
  pinMode(HCSR04_TriggerPin, OUTPUT);
  Sonar_update();
}

ISR(PCINT0_vect) {
  uint8_t pin = PINB;
  if (pin & 1<<PCINT0) {
    HCSR04_starTime = micros();
  }
  else {
    HCSR04_echoTime = micros() - HCSR04_starTime;
    if (HCSR04_echoTime <= 25000)
      tempSonarAlt = HCSR04_echoTime / 58;
    else
      tempSonarAlt = 9999;
  }
}


void Sonar_update()
{
    SonarAlt=tempSonarAlt;
    static int32_t sonarTempDistance=0;
    sonarTempDistance = (sonarTempDistance - (sonarTempDistance >> 3)) + SonarAlt;
    SonarAlt= sonarTempDistance >> 3;
   
    digitalWrite(HCSR04_TriggerPin, LOW);     
    delayMicroseconds(2);
    digitalWrite(HCSR04_TriggerPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(HCSR04_TriggerPin, LOW);

}

#endif


IMU.pde

Code: Select all

void getEstimatedAltitude(){
  static uint8_t inited = 0;
  static int16_t AltErrorI = 0;
  static float AccScale  = 0.0f;
  static uint32_t deadLine = INIT_DELAY;
  int16_t AltError;
  int16_t InstAcc;
  int16_t Delta;

  if (currentTime < deadLine) return;
  deadLine = currentTime + UPDATE_INTERVAL;
  // Soft start

  if (!inited) {
    inited = 1;
    EstAlt = BaroAlt;

    // Apunto la altura de despegue
    InitialAlt = BaroAlt;
    if(SONAR && (SonarAlt < 9999)){
      InitialAlt-=SonarAlt;
    }

    EstVelocity = 0;
    AltErrorI = 0;
    AccScale = 100 * 9.80665f / acc_1G;
  }

  // Implementacion del sonar
  if(SONAR && (SonarAlt < 9999)) {
    BaroAlt=Fang_getAdjustedBaroAltBySONAR(BaroAlt,SonarAlt,InitialAlt) ;
  }

  // Estimation Error
  AltError = BaroAlt - EstAlt;
  AltErrorI += AltError;
  AltErrorI=constrain(AltErrorI,-25000,+25000);
  // Gravity vector correction and projection to the local Z
  //InstAcc = (accADC[YAW] * (1 - acc_1G * InvSqrt(isq(accADC[ROLL]) + isq(accADC[PITCH]) + isq(accADC[YAW])))) * AccScale + (Ki) * AltErrorI;
#if defined(TRUSTED_ACCZ)
  InstAcc = (accADC[YAW] * (1 - acc_1G * InvSqrt(isq(accADC[ROLL]) + isq(accADC[PITCH]) + isq(accADC[YAW])))) * AccScale +  AltErrorI / 1000;
#else
  InstAcc = AltErrorI / 1000;
#endif

  // Integrators
  Delta = InstAcc * dt + (Kp1 * dt) * AltError;
  if(SONAR && (SonarAlt < 9999)){
    EstAlt=BaroAlt;
  }
  else{
    EstAlt += (EstVelocity/5 + Delta) * (dt / 2) + (Kp2 * dt) * AltError;
  }
  EstVelocity += Delta*10;
}

int Fang_getAdjustedBaroAltBySONAR(int BaroAlt, int SonarAlt,int InitialBarAlt)
{
#define SONAR_FADE_START_RANGE 200
#define SONAR_FADE_END_RANGE 500

  if(SonarAlt<SONAR_FADE_START_RANGE)
    return SonarAlt+InitialBarAlt;
  else if (SonarAlt>=SONAR_FADE_END_RANGE)
    return BaroAlt;
  else{
    float mixlevel=(SonarAlt-SONAR_FADE_START_RANGE)*1.0/(SONAR_FADE_END_RANGE-SONAR_FADE_START_RANGE);
    return (SonarAlt+InitialBarAlt)*(1-mixlevel)+BaroAlt*mixlevel;
  }
}
Last edited by dongfang on Wed Mar 14, 2012 12:31 am, edited 1 time in total.

dongfang
Posts: 5
Joined: Tue Mar 13, 2012 4:33 pm

Re: Attemp to integrate sonar (ultrasonic sensor)

Post by dongfang »

Another things is, my sonar(called SRF-06) has the same sample code to the DYP-ME007, and I can use Vallekano's HCSR04 code in it.

That's means SRF-06, DYP-ME007 and HCSR04 are mostly the same to developer (maybe they are the same).

Vallekano
Posts: 25
Joined: Sun Dec 25, 2011 7:07 pm

Re: Attemp to integrate sonar (ultrasonic sensor)

Post by Vallekano »

dongfang wrote:Hi All,

I think Vallekano's code do not work in my board(Arduino Nano) as it miss one "pinMode(HCSR04_EchoPin, INPUT);" command.

And I've merged Vallekano's code and mahowik's code together, so:

1. It still use D8 for TX pin, and D12 for RX pin
2. alt-hold data based on sonar data in range 0 - 200cm; 200cm-500cm for mix of sonar+baro; above 500cm:based on baro only
3. EstAlt will still use multiwii 1.9's existing code when sonar do not have valid data, (though I don't understand the Algorithm, and how to set Kp1)
4. I removed some unnecessary code


Till now, below code works for me very well: (please use Vallekano's patch first, and change the code below)

Sensors.pde:

Code: Select all

/////////////////////////////////////////
// ************************************************************************************************************
// HC-SR04 Ultrasonic Sonar
// ************************************************************************************************************

#if defined(HCSR04)

volatile unsigned long HCSR04_starTime = 0;
volatile unsigned long HCSR04_echoTime = 0;
volatile static int32_t  tempSonarAlt=0;

void Sonar_init()
{
  PCICR  |= (1<<0); // D8
  PCMSK0 = (1<<0); // pin 8
  pinMode(HCSR04_EchoPin, INPUT);
  pinMode(HCSR04_TriggerPin, OUTPUT);
  Sonar_update();
}

ISR(PCINT0_vect) {
  uint8_t pin = PINB;
  if (pin & 1<<PCINT0) {
    HCSR04_starTime = micros();
  }
  else {
    HCSR04_echoTime = micros() - HCSR04_starTime;
    if (HCSR04_echoTime <= 25000)
      tempSonarAlt = HCSR04_echoTime / 58;
    else
      tempSonarAlt = 9999;
  }
}


void Sonar_update()
{
    SonarAlt=tempSonarAlt;
    static int32_t sonarTempDistance=0;
    sonarTempDistance = (sonarTempDistance - (sonarTempDistance >> 3)) + SonarAlt;
    SonarAlt= sonarTempDistance >> 3;
   
    digitalWrite(HCSR04_TriggerPin, LOW);     
    delayMicroseconds(2);
    digitalWrite(HCSR04_TriggerPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(HCSR04_TriggerPin, LOW);

}

#endif


IMU.pde

Code: Select all

void getEstimatedAltitude(){
  static uint8_t inited = 0;
  static int16_t AltErrorI = 0;
  static float AccScale  = 0.0f;
  static uint32_t deadLine = INIT_DELAY;
  int16_t AltError;
  int16_t InstAcc;
  int16_t Delta;

  if (currentTime < deadLine) return;
  deadLine = currentTime + UPDATE_INTERVAL;
  // Soft start

  if (!inited) {
    inited = 1;
    EstAlt = BaroAlt;

    // Apunto la altura de despegue
    InitialAlt = BaroAlt;
    if(SONAR && (SonarAlt < 9999)){
      InitialAlt-=SonarAlt;
    }

    EstVelocity = 0;
    AltErrorI = 0;
    AccScale = 100 * 9.80665f / acc_1G;
  }

  // Implementacion del sonar
  if(SONAR && (SonarAlt < 9999)) {
    oldBaroAlt=BaroAlt;
    BaroAlt=Fang_getAdjustedBaroAltBySONAR(BaroAlt,SonarAlt,InitialAlt) ;
  }

  // Estimation Error
  AltError = BaroAlt - EstAlt;
  AltErrorI += AltError;
  AltErrorI=constrain(AltErrorI,-25000,+25000);
  // Gravity vector correction and projection to the local Z
  //InstAcc = (accADC[YAW] * (1 - acc_1G * InvSqrt(isq(accADC[ROLL]) + isq(accADC[PITCH]) + isq(accADC[YAW])))) * AccScale + (Ki) * AltErrorI;
#if defined(TRUSTED_ACCZ)
  InstAcc = (accADC[YAW] * (1 - acc_1G * InvSqrt(isq(accADC[ROLL]) + isq(accADC[PITCH]) + isq(accADC[YAW])))) * AccScale +  AltErrorI / 1000;
#else
  InstAcc = AltErrorI / 1000;
#endif

  // Integrators
  Delta = InstAcc * dt + (Kp1 * dt) * AltError;
  if(SONAR && (SonarAlt < 9999)){
    EstAlt=BaroAlt;
  }
  else{
    EstAlt += (EstVelocity/5 + Delta) * (dt / 2) + (Kp2 * dt) * AltError;
  }
  EstVelocity += Delta*10;
}

int Fang_getAdjustedBaroAltBySONAR(int BaroAlt, int SonarAlt,int InitialBarAlt)
{
#define SONAR_FADE_START_RANGE 200
#define SONAR_FADE_END_RANGE 500

  if(SonarAlt<SONAR_FADE_START_RANGE)
    return SonarAlt+InitialBarAlt;
  else if (SonarAlt>=SONAR_FADE_END_RANGE)
    return BaroAlt;
  else{
    float mixlevel=(SonarAlt-SONAR_FADE_START_RANGE)*1.0/(SONAR_FADE_END_RANGE-SONAR_FADE_START_RANGE);
    return (SonarAlt+InitialBarAlt)*(1-mixlevel)+BaroAlt*mixlevel;
  }
}


I have forgotten it a bit but will try your updates this week.

dongfang
Posts: 5
Joined: Tue Mar 13, 2012 4:33 pm

Re: Attemp to integrate sonar (ultrasonic sensor)

Post by dongfang »

Well, I found the same issue that mahowik met: the motor noise is too big, and Sonar return wrong distance data to the board. I've tried to isolate the noise but failed.

It's sonar's issue...

adam
Posts: 15
Joined: Sun Oct 02, 2011 4:26 pm
Location: Taiwan

Re: Attemp to integrate sonar (ultrasonic sensor)

Post by adam »

Vallekano wrote:
Steeze McQueen wrote:
Vallekano wrote:I use D8 and D12

Thank you for getting the HC-SR04 working! I think I'm being a bit thick today, plus this is my first arduino project so I'm still learning. My question is, what pins are you using off the HC-SR04? I see a Vcc, Trig, Echo, and GND. How do those correspond to pins D8 and D12 on the arduino? Also, and you may not know this, but I'm using a seeeduino mega board, not a pro mini. In that case, how do the pins D8 and D12 on a pro mini correspond to pins on the arduino mega?


Sorry for the delay.

VCC -> 5V
GND -> GND
ECHO -> D8
TRIGGER -> D12


if i have time this afternoon or tomorrow i'll record a video of MultiWiiconf


Hi Vallekano ,

I am ready to join HC-SR04 group now, But the "D12" make me confused!
The "D12" provide power to wii sensor like picture below, How can I do, Thank You.

Image

Vallekano
Posts: 25
Joined: Sun Dec 25, 2011 7:07 pm

Re: Attemp to integrate sonar (ultrasonic sensor)

Post by Vallekano »

I use an Arduino ONE that has an output of 3.3V. I think the Arduino Pro Mini (5V version) also has an output of 3.3V that can be used instead of pin 12.

If you do not have that output you will have to use a LM117 to pass the 5V to 3.3V, as illustrated in the diagrams.

dr.tom
Posts: 141
Joined: Fri Mar 30, 2012 4:46 pm
Location: Croatia
Contact:

Re: Attemp to integrate sonar (ultrasonic sensor)

Post by dr.tom »

Did someone try the HC-SR04 sonar @ 2.0 code?

adam
Posts: 15
Joined: Sun Oct 02, 2011 4:26 pm
Location: Taiwan

Re: Attemp to integrate sonar (ultrasonic sensor)

Post by adam »

Vallekano wrote:I use an Arduino ONE that has an output of 3.3V. I think the Arduino Pro Mini (5V version) also has an output of 3.3V that can be used instead of pin 12.

If you do not have that output you will have to use a LM117 to pass the 5V to 3.3V, as illustrated in the diagrams.


Hi Vallekano ,

Thanks for your help.

I follow your steps, Now can get altitude reading from DEBUG3, How can I get altitude hold ? Next for autolanding...

My QuadX , wmp + HCSR04, No Baro.

User avatar
kos
Posts: 286
Joined: Thu Feb 16, 2012 4:51 am
Location: Fr

Re: Attemp to integrate sonar (ultrasonic sensor)

Post by kos »

copterrichie wrote:This is great news and one step closer to auto landing in my opinion.


thing that is still required is a 'switch' to be activated when all landing gears touch the ground .. i just realized there is two unused inputs (1) on the nunchuck that could be used for that purpose.



1 : https://raw.github.com/todbot/wiichuck_ ... ck_funcs.h

Code: Select all

//  groundContact()
static int nunchuck_zbutton() {
      return ((nunchuck_buf[5] >> 0) & 1) ? false : true;
}

// crashContact()
static int nunchuck_cbutton() {
      return ((nunchuck_buf[5] >> 1) & 1) ? false : true; 
}

dr.tom
Posts: 141
Joined: Fri Mar 30, 2012 4:46 pm
Location: Croatia
Contact:

Re: Attemp to integrate sonar (ultrasonic sensor)

Post by dr.tom »

I think the better way to detect
-landing : absence of gyro & acc variations (due to model firmly standing od the ground)
-crash : high G readings on acc & gyro followed by absence of acc and gyro variations

seems to me like DJI has somethign like that, in case of a crash it stops motors from running,
without switches, because if model falls sideways and breaks, no switch on landing legs woud activate either

and by managing it in the code, the system is 'cleaner', no switches & wires going down the frame and landing gears...

copterrichie
Posts: 2261
Joined: Sat Feb 19, 2011 8:30 pm

Re: Attemp to integrate sonar (ultrasonic sensor)

Post by copterrichie »

kos wrote: thing that is still required is a 'switch' to be activated when all landing gears touch the ground .. i just realized there is two unused inputs (1) on the nunchuck that could be used for that purpose.



1 : https://raw.github.com/todbot/wiichuck_ ... ck_funcs.h

Code: Select all

//  groundContact()
static int nunchuck_zbutton() {
      return ((nunchuck_buf[5] >> 0) & 1) ? false : true;
}

// crashContact()
static int nunchuck_cbutton() {
      return ((nunchuck_buf[5] >> 1) & 1) ? false : true; 
}


One idea would be to read the Z Axis of the Accelerometer, it should return to 1G on touchdown.

User avatar
kos
Posts: 286
Joined: Thu Feb 16, 2012 4:51 am
Location: Fr

Re: Attemp to integrate sonar (ultrasonic sensor)

Post by kos »

dr.tom wrote:and by managing it in the code, the system is 'cleaner', no switches & wires going down the frame and landing gears...



there are still some cases where a mechanical switch is preferable ?

- landing on a not so flat ground , Z Axis will not return 1g
- crashed against a wall : as the copter fall down after hitting the wall , acc and gyro variations can be read from sensors

also maybe by reading the throttle input we can make autolanding a little more clever :

Code: Select all

if (AUTOLANDING && ACC && ( SONAR || BARO)){
  if (autoLanding && !failSafe){
    if (! groundContact){ 
      Alt =- 0.10;
      grounded = 0;
   }else{
     GROUND_LED_PIN_ON;
     if (!grounded) {
         grounded =1;
     }
     if ( rcData[THROTTLE]<MINCHECK){
       grounded++;
     if (grounded>20){
       armed=0;
       autoLanding=0;
    }
}

}

Olaf.J
Posts: 16
Joined: Tue Jul 12, 2011 10:10 pm

Use with Atmega 2560

Post by Olaf.J »

Hi,

has anybody successfully implemented this code for the Atmega 2560 (Flyduino)? I think, I will get it to use the Trigger-Pin, but I have really no idea, how to modify the code for using the echo-pin with interrupts. I'm using 8-channel transmitter/receiver, so I think the pins PK0 - PK7 are already in use. So I thought, I could use Pin PF5 (analog pin 5), hope that this is the Pin "input5" at the flyduino board...

Olaf.J
Posts: 16
Joined: Tue Jul 12, 2011 10:10 pm

SRF04 with Flyduino (Atmega2560)

Post by Olaf.J »

Hi, I think I've got it. It was a little bit difficult because of no experience with arduino, but it seems to work now with the Flyduino (Atmega2560):

In the def.h, I defined the following:

Code: Select all

/* Pin to interrupt map:
* PCINT 16-23 = PCIE2 = pcmsk2 = PCINT2_vect
* PCINT 0-7 = PCIE0 = pcmsk0 = PCINT0_vect
* PCINT 8-15 = PCIE1 = pcmsk1 = PCINT1_vect
*/

#if defined MEGA
 #if defined(HCSR04)
  #define SONAR 1
  #define HCSR04_TriggerPin 12
  #define HCSR04_TriggerPin_PINMODE_OUT            pinMode(HCSR04_TriggerPin,OUTPUT);
  #define HCSR04_TriggerPin_PIN_HIGH           PORTB |= 1<<6;
  #define HCSR04_TriggerPin_PIN_LOW            PORTB &= ~(1<<6);
  #define HCSR04_EchoPin 11
  #define HCSR04_EchoPin_PINMODE_IN             pinMode(HCSR04_EchoPin,INPUT);
  #define HCSR04_EchoPin_PCINT  PCINT5
  #define HCSR04_EchoPin_PCICR   PCICR |= (1<<PCIE0); // PCINT 0-7 belong to PCIE0
  #define HCSR04_EchoPin_PCMSK   PCMSK0 = (1<<HCSR04_EchoPin_PCINT); // Mask Pin PCINT5 - all other PIns PCINT0-7 are not allowed to create interrupts!
  #define HCSR04_EchoPin_PCINT_vect    PCINT0_vect  // PCINT0-7 belog PCINT0_vect
  #define HCSR04_EchoPin_PIN  PINB  // PCINT0-7 belong to PINB
 #else
  #define SONAR 0
 #endif
#else
 #define SONAR 0
#endif


In the Sensors I used this code:

Code: Select all

/////////////////////////////////////////
// ************************************************************************************************************
// HC-SR04 Ultrasonic Sonar
// ************************************************************************************************************

#if defined(HCSR04)

volatile unsigned long HCSR04_startTime = 0;
volatile unsigned long HCSR04_echoTime = 0;
volatile static int32_t  tempSonarAlt=0;

void Sonar_init()
{
  HCSR04_EchoPin_PCICR;
  HCSR04_EchoPin_PCMSK;
  HCSR04_EchoPin_PINMODE_IN;
  HCSR04_TriggerPin_PINMODE_OUT;
  Sonar_update();
}

// EchoPin will change to high signalize beginning
// and back to low after 58*cm us
// First interrupt is needed to start measurement, second interrupt to calculate the distance


ISR(HCSR04_EchoPin_PCINT_vect) {
  if (HCSR04_EchoPin_PIN & (1<<HCSR04_EchoPin_PCINT)) {            //indicates if the EchoPin is at a high state
    HCSR04_startTime = micros();
  }
  else {
    HCSR04_echoTime = micros() - HCSR04_startTime;
    if (HCSR04_echoTime <= 17400)                                  // maximum = 3 meter
      tempSonarAlt = HCSR04_echoTime / 58;
    else
      tempSonarAlt = 9999;
  }
}

void Sonar_update()
{
    SonarAlt=tempSonarAlt;
    static int32_t sonarTempDistance=0;
    sonarTempDistance = (sonarTempDistance - (sonarTempDistance >> 3)) + SonarAlt;
    SonarAlt= sonarTempDistance >> 3;
    debug4=SonarAlt;
    HCSR04_TriggerPin_PIN_LOW;
    delayMicroseconds(2);
    HCSR04_TriggerPin_PIN_HIGH;
    delayMicroseconds(10);
    HCSR04_TriggerPin_PIN_LOW;
}

#endif


Now, the height in cm is shown in debug4 in multiwii gui :)

AltHold not yet tested...

Olaf.J
Posts: 16
Joined: Tue Jul 12, 2011 10:10 pm

Re: Attemp to integrate sonar (ultrasonic sensor)

Post by Olaf.J »

Hi,

Sonar-Results are very good - about 99% of the altitude-values of the sonar are valid :)

But altitude control is not really good. Before mixing sonar and baro, I first want to get a stable alt-control only with sonar. But the copter is oscillating all the time. If I increase P to maximum, the copter is shooting into the air a few meters, followed by falling down to earth. If I decrease P, the copter will also oscillate but with lower amplitude. I think, this is also, because the battery gets lower all the time, so you had to increase the "initialThrottleHold" - but I see no chance to calculate this value on the fly :(

Has anybody running the sonar with good alt-hold without mixing sonar and baro at low height? Which code is working fine for this?

noobee
Posts: 66
Joined: Fri Feb 25, 2011 2:57 pm

Re: Attemp to integrate sonar (ultrasonic sensor)

Post by noobee »

Olaf.J wrote:Hi,

Sonar-Results are very good - about 99% of the altitude-values of the sonar are valid :)

But altitude control is not really good. Before mixing sonar and baro, I first want to get a stable alt-control only with sonar. But the copter is oscillating all the time. If I increase P to maximum, the copter is shooting into the air a few meters, followed by falling down to earth. If I decrease P, the copter will also oscillate but with lower amplitude. I think, this is also, because the battery gets lower all the time, so you had to increase the "initialThrottleHold" - but I see no chance to calculate this value on the fly :(

Has anybody running the sonar with good alt-hold without mixing sonar and baro at low height? Which code is working fine for this?


have you tried in increasing d at the same time (to a more negative value) with slightly higher p?

sandmen
Posts: 24
Joined: Mon Feb 21, 2011 3:26 pm

Re: Attemp to integrate sonar (ultrasonic sensor)

Post by sandmen »

@Olaf.J
I can confirm that your code work's.
Altitude not tested :-)
Thank you

Olaf.J
Posts: 16
Joined: Tue Jul 12, 2011 10:10 pm

Re: Attemp to integrate sonar (ultrasonic sensor)

Post by Olaf.J »

noobee wrote:have you tried in increasing d at the same time (to a more negative value) with slightly higher p?


No, not yet. Unfortunately it's raining and windy at the moment - cannot try it any more today. I'll try this as soon as possible.
Thanks for the tip.

penpen77
Posts: 73
Joined: Tue Jan 24, 2012 10:45 pm

Re: Attemp to integrate sonar (ultrasonic sensor)

Post by penpen77 »

it's seems the tintywire lib needed for i2cshield has been moved out the orignal repository, so i put the files here
Attachments
TinyWireCB.rar
(6.02 KiB) Downloaded 300 times

ziojos
Posts: 11
Joined: Mon Feb 20, 2012 6:43 am

Re: Attemp to integrate sonar (ultrasonic sensor)

Post by ziojos »

Olaf.J wrote:Hi,

Sonar-Results are very good - about 99% of the altitude-values of the sonar are valid :)

But altitude control is not really good. Before mixing sonar and baro, I first want to get a stable alt-control only with sonar. But the copter is oscillating all the time. If I increase P to maximum, the copter is shooting into the air a few meters, followed by falling down to earth. If I decrease P, the copter will also oscillate but with lower amplitude. I think, this is also, because the battery gets lower all the time, so you had to increase the "initialThrottleHold" - but I see no chance to calculate this value on the fly :(

Has anybody running the sonar with good alt-hold without mixing sonar and baro at low height? Which code is working fine for this?


Hi Olaf, I have integrated the SR04 In quite the same way, I have solid result 4-450 cm :D on an Arduino with only Sonar but on MWii (motor OFF) I have two case:

With RC Radio off I have good data from 4 to 230 cm with rare spikes :(
Whith RC Radio on I have the the same range but more spikes :!: :?:

I don't understand why in MWii framework the sonar do worse, may be digital noise or power stabilizzation

I use pin 12 to trigger the sonar and pin 4 to echo Interrup, I have added a condenser (100uF) on SR04 power and this gave better results but some spike remain and I have programmed a simple anti-spike,

The sonar work very well in fly from 0 to 2 mt on solid ground , on grass I have less than 2 mt (variable).
To avoid the Hula Hop you need the derivative term (on altitude speed) to brake the oscillation

ciao

Olaf.J
Posts: 16
Joined: Tue Jul 12, 2011 10:10 pm

Re: Attemp to integrate sonar (ultrasonic sensor)

Post by Olaf.J »

ziojos wrote:To avoid the Hula Hop you need the derivative term (on altitude speed) to brake the oscillation


Hi, "derivative" is the D-Parameter, right? I'll try this - had removed it, because I didn't understood the D-calculation of the baro-control of MWii 2.0, but I implemented it for sonar now - but not tested yet due to weather...

ziojos
Posts: 11
Joined: Mon Feb 20, 2012 6:43 am

Re: Attemp to integrate sonar (ultrasonic sensor)

Post by ziojos »

Olaf.J wrote:
ziojos wrote:To avoid the Hula Hop you need the derivative term (on altitude speed) to brake the oscillation


Hi, "derivative" is the D-Parameter, right? I'll try this - had removed it, because I didn't understood the D-calculation of the baro-control of MWii 2.0, but I implemented it for sonar now - but not tested yet due to weather...


Right ;)

Olaf.J
Posts: 16
Joined: Tue Jul 12, 2011 10:10 pm

Re: Attemp to integrate sonar (ultrasonic sensor)

Post by Olaf.J »

Hi zjojos and noobee,

thanks for your info about the D-parameter - I successfully implemented it and found suitable parameters for PID. When hoovering, the height is hold pretty good, if I move the copter, it first goes down 50-80 cm and then goes up to the target-height slowly. When stopping, it first goes up 50-80 cm and then back to the target-height. I think, the main reason for this is the weight of the copter - the total flight-weight is 1435 g. So everything looks fine at the moment :)

sandmen
Posts: 24
Joined: Mon Feb 21, 2011 3:26 pm

Re: Attemp to integrate sonar (ultrasonic sensor)

Post by sandmen »

@Olaf,
do you want to share your implementation?
Thanks
Peter

Olaf.J
Posts: 16
Joined: Tue Jul 12, 2011 10:10 pm

Re: Attemp to integrate sonar (ultrasonic sensor)

Post by Olaf.J »

sandmen wrote:@Olaf,
do you want to share your implementation?
Thanks
Peter


Hi, it's not yet ready (it's sonar-mode only without mixing baro at the moment and I use a fix height of 180 cm at the moment, instead of height at activating), but if you want to test it already, here's the modified code for flyduino (atmega2560):

def.h - the pins should be changed to pin 9 for trigger and pin 10 for echo for compatibility-reasons (flyduino connection diagram from 13/6/11), but I haven't implemented that yet.

Code: Select all


/* Pin to interrupt map:
* PCINT 16-23 = PCIE2 = pcmsk2 = PCINT2_vect
* PCINT 0-7 = PCIE0 = pcmsk0 = PCINT0_vect
* PCINT 8-15 = PCIE1 = pcmsk1 = PCINT1_vect
*/

#if defined MEGA
#if defined(HCSR04)
  #define SONAR 1
  #define HCSR04_TriggerPin 12 // should be modified to 9 in next version
  #define HCSR04_TriggerPin_PINMODE_OUT            pinMode(HCSR04_TriggerPin,OUTPUT);
  #define HCSR04_TriggerPin_PIN_HIGH           PORTB |= 1<<6;  // should be modified for pin 9 in next version
  #define HCSR04_TriggerPin_PIN_LOW            PORTB &= ~(1<<6);   // should be modified for pin 9 in next version
  #define HCSR04_EchoPin 11     // should be modified to 10 in next version
  #define HCSR04_EchoPin_PINMODE_IN             pinMode(HCSR04_EchoPin,INPUT);
  #define HCSR04_EchoPin_PCINT  PCINT5     // should be modified for pin 10 in next version
  #define HCSR04_EchoPin_PCICR   PCICR |= (1<<PCIE0); // PCINT 0-7 belong to PCIE0
  #define HCSR04_EchoPin_PCMSK   PCMSK0 = (1<<HCSR04_EchoPin_PCINT); // Mask Pin PCINT5 - all other PIns PCINT0-7 are not allowed to create interrupts!
  #define HCSR04_EchoPin_PCINT_vect    PCINT0_vect  // PCINT0-7 belog PCINT0_vect
  #define HCSR04_EchoPin_PIN  PINB  // PCINT0-7 belong to PINB
#else
  #define SONAR 0
#endif
#else
  #define SONAR 0
#endif


config.h

Code: Select all

#define HCSR04



sensors

Code: Select all

// ************************************************************************************************************
// HC-SR04 Ultrasonic Sonar
// ************************************************************************************************************

#if defined(HCSR04)

volatile unsigned long HCSR04_startTime = 0;
volatile unsigned long HCSR04_echoTime = 0;
volatile unsigned long SonarSuccess = 0;
volatile unsigned long SonarFail = 0;
unsigned int HCSR04_current_loops = 0;
volatile static int32_t  tempSonarAlt=0;

// The cycle time is between 3000 and 6000 microseconds
// The recommend cycle period for sonar request should be no less than 40ms -> 40000 microseconds
// A reading every 13 loops (40000 / 3000 aprox)
unsigned int HCSR04_loops = 13;

void Sonar_init()
{
  HCSR04_EchoPin_PCICR;
  HCSR04_EchoPin_PCMSK;
  HCSR04_EchoPin_PINMODE_IN;
  HCSR04_TriggerPin_PINMODE_OUT;
  Sonar_update();
}

// EchoPin will change to high signalize beginning
// and back to low after 58*cm us
// First interrupt is needed to start measurement, second interrupt to calculate the distance


ISR(HCSR04_EchoPin_PCINT_vect) {
  //
  // Here is a routine missing, to check, if the interrupt was raised for echo pin - not needed at the moment, because we don't have any interrupts
  // for this interrupt group, but maybe later
  //
  if (HCSR04_EchoPin_PIN & (1<<HCSR04_EchoPin_PCINT)) {            //indicates if the EchoPin is at a high state
    HCSR04_startTime = micros();
  }
  else {
    HCSR04_echoTime = micros() - HCSR04_startTime;
    if (HCSR04_echoTime <= 25000)                                  // maximum = 4,31 meter - 30000 us means out of range
      tempSonarAlt = HCSR04_echoTime / 58;
    else
      tempSonarAlt = 9999;
  }
}

void Sonar_update()
{
  HCSR04_current_loops++;
  if ((HCSR04_current_loops >= HCSR04_loops) && baroMode) {
    HCSR04_current_loops = 0;
    LastSonarAlt = SonarAlt;
    SonarAlt = tempSonarAlt;
    debug2 = SonarAlt;
    if (SonarAlt < 500) {
      SonarSuccess += 1;  // count successful readings of height
      debug3 = SonarSuccess;
    } else {
      SonarAlt = 9999;
      SonarFail += 1;  // count failed readings of heigt
      debug4 = SonarFail;
    }

    // create a trigger pulse for 10 us
    HCSR04_TriggerPin_PIN_LOW;
    delayMicroseconds(2);
    HCSR04_TriggerPin_PIN_HIGH;
    delayMicroseconds(10);
    HCSR04_TriggerPin_PIN_LOW;
  }
}

#endif



imu

Code: Select all

void getEstimatedAltitude(){
  uint8_t index;
  static uint32_t deadLine = INIT_DELAY;

  static int16_t BaroHistTab[BARO_TAB_SIZE];
  static int8_t BaroHistIdx;
  static int32_t BaroHigh,BaroLow;
  int32_t temp32;
  int16_t last;
 
  if (currentTime < deadLine) return;
  deadLine = currentTime + UPDATE_INTERVAL;

  //**** Alt. Set Point stabilization PID ****
  //calculate speed for D calculation
  last = BaroHistTab[BaroHistIdx];  // letzter Wert aus BaroHistTab
  BaroHistTab[BaroHistIdx] = BaroAlt/10;  // durch 10 teilen
  BaroHigh += BaroHistTab[BaroHistIdx];
  index = (BaroHistIdx + (BARO_TAB_SIZE/2))%BARO_TAB_SIZE;
  BaroHigh -= BaroHistTab[index];
  BaroLow  += BaroHistTab[index];
  BaroLow  -= last;

  BaroHistIdx++;
  if (BaroHistIdx == BARO_TAB_SIZE) BaroHistIdx = 0;

  BaroPID = 0;

  //D
  #ifdef SONAR
    temp32 = D8[PIDALT]*(SonarAlt-LastSonarAlt) / 40; // example climbed from 150 to 170 cm, D=7 -> temp32=7*(170-150)/40=3,5 -> BaroPID = -3,5
  #else
    temp32 = D8[PIDALT]*(BaroHigh - BaroLow) / 40;
  #endif
  BaroPID-=temp32;

  EstAlt = BaroHigh*10/(BARO_TAB_SIZE/2);

  // Olaf
  // Use sonar to hold at 180 cm instead of last height
 
  #ifdef SONAR
    if (SonarAlt < 500)
      temp32 = 180 - SonarAlt;
    else
      temp32 = 0;  // if no valid result from SONAR -> no P-Value!
  #else
    temp32 = AltHold - EstAlt;
    if (abs(temp32) < 10 && abs(BaroPID) < 10) BaroPID = 0;  //remove small differences to reduce noise near zero position
  #endif

 
  //P
  BaroPID += P8[PIDALT]*constrain(temp32,(-2)*P8[PIDALT],2*P8[PIDALT])/100;  // temp32 auf should be for example in range +- 32 for P=16 (= 1.6 in GUI)   
  // example: climbed from 150 cm to 170 cm, target height: 180 cm, P=40
  // BaroPID += 40*(180-170)/100 = increase BaroPID for 4,0
 
  BaroPID = constrain(BaroPID,-150,+150); //sum of P and D should be in range 150

  //I
  errorAltitudeI += temp32*I8[PIDALT]/50; //example: height is 170 cm, target heigth 180 cm, I = 15 (0.015 in GUI) -> 10*15/50 = increase for 3
  errorAltitudeI = constrain(errorAltitudeI,-30000,30000);
  temp32 = errorAltitudeI / 500; //I in range +/-60 // this is a long term PID - will for example compensate decreasing battery voltage
  BaroPID+=temp32;
}


MultiWii_2_0

Code: Select all

static int32_t  SonarAlt;
static int32_t  LastSonarAlt;

[...]

      case 1:
        taskOrder++;
        #if BARO
          Baro_update(); 
          #if defined(SONAR)
          Sonar_update(); 
          #endif
          break;
        #endif



I began with the standard values with not really good success. So I increased the D-value to 20, this made it much more stable. Then I increase P still it began to oscillate (slowly) and then decreased it (I think it's 3 at the moment). I increased the I-value slightly from 0.015 to 0.020, otherwise the copter came down sloswly, when the battery voltage decreased.

If the code is ready incl. baro-mixing, I will share the code again of course, if it's of interest for anybody. I'm not sure at the moment, if the baro-PID-values and the sonar-PID-values can be the same or if we need different PIDs for baro and sonar, because baro has (at least at my copter) much more noise.

nicodh
Posts: 44
Joined: Sun Apr 08, 2012 1:42 pm

Re: Attemp to integrate sonar (ultrasonic sensor)

Post by nicodh »

Hi Olaf,
About baro mixing, i remember in arducopter, they use a condition to use the baro or the sonar. Because the sonar is usable only if distance to obstacle is less than (let's say 6 meters) you can use the sonar reading in the loops when you are at a maximum of that altitude, other wise you use the baro.

copterrichie
Posts: 2261
Joined: Sat Feb 19, 2011 8:30 pm

Re: Attemp to integrate sonar (ultrasonic sensor)

Post by copterrichie »

If anyone is interested, $2.80US

Ultrasonic Module HC-SR04

http://cgi.ebay.com/ws/eBayISAPI.dll?Vi ... SS:US:1123

bverissimo
Posts: 1
Joined: Sat Apr 28, 2012 3:21 am

Re: Attemp to integrate sonar (ultrasonic sensor)

Post by bverissimo »

adam wrote:
Vallekano wrote:I use an Arduino ONE that has an output of 3.3V. I think the Arduino Pro Mini (5V version) also has an output of 3.3V that can be used instead of pin 12.

If you do not have that output you will have to use a LM117 to pass the 5V to 3.3V, as illustrated in the diagrams.


Hi Vallekano ,

Thanks for your help.

I follow your steps, Now can get altitude reading from DEBUG3, How can I get altitude hold ? Next for autolanding...

My QuadX , wmp + HCSR04, No Baro.





Hi , how did you manage to conect the HC-Sr04 on the arduino pro mini ..wich pins you use ?
And please can o send me yyour code try to edit mine but nothing ..many thanks in advance ..

didlawowo69
Posts: 38
Joined: Tue Oct 11, 2011 1:42 pm

Re: Attemp to integrate sonar (ultrasonic sensor)

Post by didlawowo69 »

no one have a video of demo ?

Dehas
Posts: 14
Joined: Sun Aug 14, 2011 8:19 am
Location: France Les Vosges

Re: Attemp to integrate sonar (ultrasonic sensor)

Post by Dehas »

@ penpen77: I try to use your code and i have this error "smartDigitalWrite' was not declared in this scope" in arduino 1.0.

Katch
Posts: 280
Joined: Thu Aug 04, 2011 1:44 pm

Re: Attemp to integrate sonar (ultrasonic sensor)

Post by Katch »

Any updates with this?

Seeing a lot of other dev using i2c/secondary MCU set ups but would like to try my HC-SR04 on my 2560 Megapirate board. It already has a header for sonar so I'll trace the pins and work out what they are connected to and see about applying this code.

If it follows Megapirate_ng code specs it should be pins 9 and 10

copterrichie
Posts: 2261
Joined: Sat Feb 19, 2011 8:30 pm

Re: Attemp to integrate sonar (ultrasonic sensor)

Post by copterrichie »

I really want to give this a try, any updates?

copterrichie
Posts: 2261
Joined: Sat Feb 19, 2011 8:30 pm

Re: Attemp to integrate sonar (ultrasonic sensor)

Post by copterrichie »

Dehas wrote:@ penpen77: I try to use your code and i have this error "smartDigitalWrite' was not declared in this scope" in arduino 1.0.


If my memory serves me right, the smartDigitalwrite is a special library but I believe you can use digitalWrite().

viewtopic.php?f=7&t=1033&start=20

Lapino
Posts: 84
Joined: Tue Aug 16, 2011 10:01 am

Re: Attemp to integrate sonar (ultrasonic sensor)

Post by Lapino »

push :)
any updates regarding implementation of HC-SR04 sonar?

penpen77
Posts: 73
Joined: Tue Jan 24, 2012 10:45 pm

Re: Attemp to integrate sonar (ultrasonic sensor)

Post by penpen77 »

smartDigitalWrite is just digitalwrite without all check/test, comment unnecessary lines, that's all. You can use digitalWrite, it's just mater of binary size.

Lapino, once you have an i2c wrapper for hcsr04, the implementation is done, just use code of other i2c sonar.

Lapino
Posts: 84
Joined: Tue Aug 16, 2011 10:01 am

Re: Attemp to integrate sonar (ultrasonic sensor)

Post by Lapino »

So I've to build a ATTINY4313 Sonar device or how can I realize an i2c wrapper? Must be some kind of hardware am I right?

Cronalex
Posts: 51
Joined: Tue Mar 20, 2012 8:41 pm

Re: Attemp to integrate sonar (ultrasonic sensor)

Post by Cronalex »

I would use this sonar Maxbotix LV-EZ0 you can?

Tommie
Posts: 438
Joined: Sun Apr 08, 2012 9:50 am

Re: Attemp to integrate sonar (ultrasonic sensor)

Post by Tommie »

Lapino wrote:So I've to build a ATTINY4313 Sonar device or how can I realize an i2c wrapper? Must be some kind of hardware am I right?

Right. And it's not that difficult: viewtopic.php?f=8&t=1549&p=16225#p16225

wilco1967
Posts: 156
Joined: Thu Aug 18, 2011 6:04 pm
Location: Winterswijk, Netherlands

Re: Attemp to integrate sonar (ultrasonic sensor)

Post by wilco1967 »

Just managed to get the HCSR04 working using the TinyGPS route in altitude hold mode.
I'm using the modified BARO PID code derived from Olaf.J 's solution posted earlier in this tread....

I initially wanted to use my Mega, and directly wire the sonar to the Flyduino, but I could not get Olaf's code compiled, as it seems to interfere with the recently added TinyGPS code in dev20120606. And I'm only starting to figure out how to program the Arduino, so not good enough to figure it out myself (yet)...
I assume Olaf used the bare 2.0 code (or even earlier) for the HCSR04 to Mega connection, and I'm using dev20120606.

With the TinyGPS route, the Sonar is working,, and I used the basis of Olaf Baro code (the getEstimatedAltitude part that goes in IMU) to get altitude hold....

Code: Select all

//wilco
void getEstimatedAltitude(){
  uint8_t index;
  static uint32_t deadLine = INIT_DELAY;

  static int16_t BaroHistTab[BARO_TAB_SIZE];
  static int8_t BaroHistIdx;
  static int32_t BaroHigh,BaroLow;
  int32_t temp32;
  int16_t last;
 
  if (currentTime < deadLine) return;
  deadLine = currentTime + UPDATE_INTERVAL;

  //**** Alt. Set Point stabilization PID ****
  //calculate speed for D calculation
  last = BaroHistTab[BaroHistIdx];  // letzter Wert aus BaroHistTab
  BaroHistTab[BaroHistIdx] = BaroAlt/10;  // durch 10 teilen
  BaroHigh += BaroHistTab[BaroHistIdx];
  index = (BaroHistIdx + (BARO_TAB_SIZE/2))%BARO_TAB_SIZE;
  BaroHigh -= BaroHistTab[index];
  BaroLow  += BaroHistTab[index];
  BaroLow  -= last;

  BaroHistIdx++;
  if (BaroHistIdx == BARO_TAB_SIZE) BaroHistIdx = 0;

  if (SonarAlt < 0) return; //wilco.... -1 = not a correct reading, Exit this routine and leave BaroPID at last value, so copter does not jump.
  BaroPID = 0;

  //D
  #ifdef SONAR
    temp32 = conf.D8[PIDALT]*(SonarAlt-LastSonarAlt) / 40; // example climbed from 150 to 170 cm, D=7 -> temp32=7*(170-150)/40=3,5 -> BaroPID = -3,5
  #else
    temp32 = conf.D8[PIDALT]*(BaroHigh - BaroLow) / 40;
  #endif
  BaroPID-=temp32;

  EstAlt = BaroHigh*10/(BARO_TAB_SIZE/2);

  // Olaf
  // Use sonar to hold at 180 cm instead of last height
 
  #ifdef SONAR
    if (SonarAlt < 500)
      temp32 = 100 - SonarAlt;
    else
      temp32 = 0;  // if no valid result from SONAR -> no P-Value!
  #else
    temp32 = AltHold - EstAlt;
    if (abs(temp32) < 10 && abs(BaroPID) < 10) BaroPID = 0;  //remove small differences to reduce noise near zero position
  #endif

 
  //P
  BaroPID += conf.P8[PIDALT]*constrain(temp32,(-2)*conf.P8[PIDALT],2*conf.P8[PIDALT])/100;  // temp32 auf should be for example in range +- 32 for P=16 (= 1.6 in GUI)   
  // example: climbed from 150 cm to 170 cm, target height: 180 cm, P=40
  // BaroPID += 40*(180-170)/100 = increase BaroPID for 4,0
 
  BaroPID = constrain(BaroPID,-150,+150); //sum of P and D should be in range 150

  //I
  errorAltitudeI += temp32*conf.I8[PIDALT]/50; //example: height is 170 cm, target heigth 180 cm, I = 15 (0.015 in GUI) -> 10*15/50 = increase for 3
  errorAltitudeI = constrain(errorAltitudeI,-30000,30000);
  temp32 = errorAltitudeI / 500; //I in range +/-60 // this is a long term PID - will for example compensate decreasing battery voltage
  BaroPID+=temp32;
}
//wilco


I'm running a normal 328P on the multiwii, and a Attiny4313 to connect the HCSR04 (No GPS on this copter). I've temporarily connected all to my quad, and it is holding altitude pretty good.

Weather is very windy at the moment, and I can only fly around the house, where there is a lot of turbulence, but still, it manages quite OK...

made a small modification that if the sonar data is faulty/out of range (-1), the BaroPID is not reset to zero, (or even worse, run through the PID algorithm), but simply left at the last state.... That way, the copter does not jump if momentarily loosing the sonar distance (which happens quite often).

I need to activate Baro, even though my quad does not have a baro (just sonar now), otherwise the baroPID routine will not run.... but time permitting, I'm going to have a shot at improving that.... Right now I get lots of I2C errors, due to the missing Baro... (zero errors if no baro defined, so TinyGPS is working perfect).
And if I'm feeling very lucky, I might even attempt to integrate Baro + Sonar in the same routine.....
These are my first attempts to actually change something more that the config.h.... so please bare with me.... :roll:

But I still would like to go the route with directly connected HCSR04 to the Flyduino.... Any progress on that with the latest dev as a base ?
I think we're getting close to a working Sonar hold.

Wilco

Tommie
Posts: 438
Joined: Sun Apr 08, 2012 9:50 am

Re: Attemp to integrate sonar (ultrasonic sensor)

Post by Tommie »

Can you please publish a patch relative to the latest svn _shared version? I'd be delighted to include it into my git branch.

Cronalex
Posts: 51
Joined: Tue Mar 20, 2012 8:41 pm

Re: Attemp to integrate sonar (ultrasonic sensor)

Post by Cronalex »

Cronalex wrote:I would use this sonar Maxbotix LV-EZ0 you can?

up

Bazed
Posts: 1
Joined: Mon Jun 25, 2012 4:44 pm

Re: Attemp to integrate sonar (ultrasonic sensor)

Post by Bazed »

Has anyone had issues with the TinyWire library in the TinySonarI2C code? I'm not sure, but it looks like the tinywire libs have been updated, now it's called tinywireS and tinywireM (slave & master).
Been trying to change the original code in the tinysonari2c to work with the new libs, but no luck so far. Anyone else having this problem?

Post Reply