inav icon indicating copy to clipboard operation
inav copied to clipboard

Sonar module I2C

Open Hydrologisst opened this issue 9 years ago • 97 comments

Hello evrybody, Many new FC boards does not have 8 motor output pins. So I'm searching sonar with I2C output. And I'm found this one: [http://bit.ly/2ACnhzw] But this module designed for PIXHAWK or APM controllers. One question it will work with INAV F4 FC (Matek F405-AIO) ? Thanks for help.

Hydrologisst avatar Nov 12 '17 22:11 Hydrologisst

I'm not sure if we support this module. @DzikuVx I wonder if it's compatible with what you designed.

digitalentity avatar Nov 13 '17 06:11 digitalentity

No it is not compatible . You might use this https://github.com/iNavFlight/INAV-Rangefinder-I2C-interface but you will need to program Attiny85 or Arduino to n between Inav and us100

DzikuVx avatar Nov 13 '17 15:11 DzikuVx

I'm not very good at programing, maybe it's possible to get prepared program code in notepad file?

Hydrologisst avatar Nov 13 '17 15:11 Hydrologisst

Code is the link I gave you

pon., 13 lis 2017, 16:22 użytkownik Hydrologisst [email protected] napisał:

I'm not very good at programing, maybe it's possible to get prepared program code in notepad file?

— You are receiving this because you were mentioned.

Reply to this email directly, view it on GitHub https://github.com/iNavFlight/inav/issues/2475#issuecomment-343952421, or mute the thread https://github.com/notifications/unsubscribe-auth/AA7Am1qjH4CmcWmbM82x05BvpxTNVQC9ks5s2F7RgaJpZM4QbFMP .

-- Pozdrawiam, Paweł Spychalski

DzikuVx avatar Nov 13 '17 15:11 DzikuVx

Would that code work on an arduino nano or pro micro? @DzikuVx

The module @Hydrologisst mentioned basically attaches an ultrasonic module (HC-SR04) to an arduino to allow communication via I2C. According to @DzikuVx specs, its basically the same thing, should his code work on an arduino micro or nano then one should be able to use the module mentioned by @Hydrologisst since it has the isp header pads which can be used to program the arduino using @DzikuVx code.

sammichael25 avatar Nov 13 '17 19:11 sammichael25

Pins would have to be modified, but besides that should be working

pon., 13 lis 2017, 20:00 użytkownik sammichael25 [email protected] napisał:

Would that code work on an arduino nano or pro micro? @DzikuVx https://github.com/dzikuvx

— You are receiving this because you were mentioned.

Reply to this email directly, view it on GitHub https://github.com/iNavFlight/inav/issues/2475#issuecomment-344021807, or mute the thread https://github.com/notifications/unsubscribe-auth/AA7Am3O9L41ZeSqxOk7fnJfpyfHH80Nuks5s2JHSgaJpZM4QbFMP .

-- Pozdrawiam, Paweł Spychalski

DzikuVx avatar Nov 13 '17 20:11 DzikuVx

Any chance you can add an edited version that could work with atmega 328p and 128p arduinos. :)

sammichael25 avatar Nov 14 '17 17:11 sammichael25

Rather slim in the next few months, busy on few other projects

Od: sammichael25 Wysłano: wtorek, 14 listopada 2017 18:52 Do: iNavFlight/inav DW: Paweł Spychalski; Mention Temat: Re: [iNavFlight/inav] Sonar module I2C (#2475)

Any chance you can add an edited version that could work with atmega 328p and 128p arduinos. :) — You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub, or mute the thread.

DzikuVx avatar Nov 14 '17 20:11 DzikuVx

I have a US 100 on order from China. When I get it I'll interface it via i2c with an ATmega 328. While the chip is larger, it's easier to program (from an Arduino board) and more available than the ATtiny 85.

I've done quite a bit of Arduino programming specifically with audio and ultrasonic sensors. So this dovetails well with my experience and INAV.

As the sensor is coming from China, I probably won't be able to start this project for 2-3 weeks.

teckel12 avatar Nov 21 '17 03:11 teckel12

Hello, I just wired up an Arduino Nano and a bidirectional logic level shifter between the FC and US-100. I replaced the TinyWireS library with Wire library. I also took the watchdog and sleepmode stuff out of the code and put there delay(96) in the beginning of the loop. The Arduino seems to work (the LED lights up when distance < 10cm), but I am not able to get the iNav end to work. No matter which sonar I choose (HCSR04 or SRF10), the sonar icon is always red. I tried swapping the I2C wires on the FC, I even tried the alternative SCL/SDA position (I have an Omnibus F3). Am I missing something in the configurator? Here is the code:

/*
 * Decide on rangefinder type here. Only one type should be uncommented
 */
 #define USE_US100
 // #define USE_HCSR04

/*
 * Set I2C Slave address
 */
#define I2C_SLAVE_ADDRESS 0x14

#define DEBUG;

#define TRIGGER_PIN 2
#define ECHO_PIN 3
#define LED_PIN LED_BUILTIN

#define STATUS_OK 0
#define STATUS_OUT_OF_RANGE 1


#include <Wire.h>

#ifndef TWI_RX_BUFFER_SIZE
#define TWI_RX_BUFFER_SIZE ( 16 )
#endif

/*
 * Configuration magic, do not touch
 */
#ifdef USE_US100
  #define PULSE_TO_CM 59 //Multiplier pulse length to distance in [cm]
  #define MEASUREMENT_PERIOD_RATIO 6 // measurement rate = MEASUREMENT_PERIOD_RATIO * 16, 96ms in this case
  #define MAX_RANGE 300 //Range of 4 meters
#endif

#ifdef USE_HCSR04
  #define PULSE_TO_CM 58 //Multiplier pulse length to distance in [cm]
  #define MEASUREMENT_PERIOD_RATIO 5 // measurement rate = MEASUREMENT_PERIOD_RATIO * 16, 80ms in this case
  #define MAX_RANGE 300 //Range of 4 meters
#endif

#define PULSE_TIMEOUT (MAX_RANGE * PULSE_TO_CM) //this is an equivalent of 4 meters range


volatile uint8_t i2c_regs[] =
{
    0, //status
    0, //older 8 of distance
    0, //younger 8 of distance
};

const byte reg_size = sizeof(i2c_regs);

volatile byte reg_position = 0;

/**
 * This function is executed when there is a request to read sensor
 * To get data, 2 reads of 8 bits are required
 * First requests send 8 older bits of 16bit unsigned int
 * Second request send 8 lower bytes
 * Measurement is executed when request for first batch of data is requested
 */
void requestEvent()
{  
  if (reg_position >= reg_size) {
    reg_position = 0;
  }
  
  Wire.write(i2c_regs[reg_position]);

  reg_position++;
}

void receiveEvent(uint8_t howMany) {

    if (howMany < 1) {
        // Sanity-check
        return;
    }

    if (howMany > TWI_RX_BUFFER_SIZE)
    {
        // Also insane number
        return;
    }

    reg_position = Wire.read();

    howMany--;

    if (!howMany) {
        // This write was only to set the buffer for next read
        return;
    }

    // Everything above 1 byte is something we do not care, so just get it from bus as send to /dev/null
    while(howMany--) {
      Wire.read();
    }
}

void setup() {
  pinMode(TRIGGER_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);
  pinMode(LED_PIN, OUTPUT);

  /*
   * Setup I2C
   */
  Wire.begin(I2C_SLAVE_ADDRESS);
  Wire.onRequest(requestEvent);
  Wire.onReceive(receiveEvent);

}

long microsecondsToCentimeters(long microseconds){
//  return microseconds / PULSE_TO_CM;
  return (microseconds * 34 / 100 / 2) / 10;
}

void loop() {
  
  delay(96); 

  digitalWrite(TRIGGER_PIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIGGER_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIGGER_PIN, LOW);

  long duration = pulseIn(ECHO_PIN, HIGH, PULSE_TIMEOUT);

  if (duration > 0) {
    i2c_regs[0] = STATUS_OK;
  } else {
    i2c_regs[0] = STATUS_OUT_OF_RANGE;
  }
    
  uint16_t cm = (uint16_t) microsecondsToCentimeters(duration);

  #ifdef DEBUG
  if (cm <10) {
    digitalWrite(LED_PIN, HIGH);
  } else {
    digitalWrite(LED_PIN, LOW);
  }
  #endif
    
  i2c_regs[1] = cm >> 8;
  i2c_regs[2] = cm & 0xFF;
  
}

Pokornz avatar Nov 24 '17 13:11 Pokornz

@Pokornz In general, this code and your conversion is not the best way to approach this. I've created the NewPing sonar library which would work better and be more suited to this task.

I'll be reworking this code to work better and on the ATmega 328/Arduino. Waiting for my US100 sensor.

My guess is that your problem is the voltage. The sensors you're using are 5v but the FC is 3.3v. You really should be using logic level converters for this task. Also, you may need resistors for i2c communication.

In any case, this should all be sorted out when I upgrade this code to use better sonar control. I would suggest getting a US100 sensor as that will make things MUCH easier once my code update happens.

teckel12 avatar Nov 24 '17 16:11 teckel12

As I wrote, I am using logic level shifters and I am using US-100. There are no pull-up resistors on the I2C lines in the original scheme. The code is taken from here: https://github.com/iNavFlight/INAV-Rangefinder-I2C-interface What is not good about the conversion? What can I improve? (except for deleting the comments that are not relevant) And is iNav supposed to automatically recognize that there is an I2C sonar connected, or do you have to enable something? As I wrote, I tried both sonar options in the configuration tab and neither of those worked.

Pokornz avatar Nov 24 '17 16:11 Pokornz

@Pokornz Sorry, your message was hard to follow as half the code was shown as text.

The code in general (not what you added) could be greatly improved, some just doesn't make much sense. But I've been the author of the sonar NewPing library for Arduino for many years, so it's evolved quite a bit over this fairly simplistic and prone to errors methods.

In any case, I need to do a refresh of this code, but without the US100 I'm not even going to bother because it's not very realistic to write the code and perfect the hardware connection to be easily reproducible without a sensor that can be connected without multiple power supplies and logic level converters.

Like I said, give me a couple weeks, I need the hardware to arrive. If you get it working, that's great, but it will be a lot easier and cleaner once I give it a work over.

teckel12 avatar Nov 24 '17 23:11 teckel12

Ok, good. But I am sort of time pressed (my bachelors thesis is based on the quadcopter) :D. Do you know, if some settings in iNav need to be changed in order for the FC to know that there is an I2C sonar instead of a regular one? I can't find that information and it is missing in the documentation. In the inav/src/main/drivers, there are files rangefinder_hcsr04 and rangefinder_hcsr04_i2c.

BTW, how can I insert the code in the message so it is all displayed as a code (want to make it easier to read). I clicked the "<>" button and pasted the Arduino code.

Pokornz avatar Nov 25 '17 09:11 Pokornz

@Pokornz @teckel12 US100 is 5V hardware, our FCs are 3.3V. When I was designing https://github.com/iNavFlight/INAV-Rangefinder-I2C-interface I decided that keeping the logic on 3.3V and protecting uC inputs with inline resistors is the best option. It can be either ATtiny running 3.3V or Arduino with 3.3V logic. That is just cheaper and smaller than logic level shifters since you can not use resistors to interface I2C (Problems are pullups, if they can not be easily disabled on 5V device, it will cause problems.)

You can buy 3.3V arduinos for cheap. Like here: https://goo.gl/Dq8wC3 The best option, period ;)

CLI rangefinder_hardware HCSR04I2C is the answer to how to configure INAV to use I2C interface

As long as you will keep interface consistent with https://github.com/iNavFlight/INAV-Rangefinder-I2C-interface you can connect any rangefinding hardware this way: 3 bytes for each packet byte 0: status, 0 = OK, 1 = out of range byte 1: 8 older bits of range in cm byte 2: 8 younger bits of range in cm

DzikuVx avatar Nov 25 '17 15:11 DzikuVx

Thank you @DzikuVx . The command should be mentioned in the notes of README.md I think ;)

I understand that getting a 3.3V microcontroller is the best, but I have bunch of Arduino Nanos laying around and I don't have a month to spare for waiting for China shipments.

I changed the rangefinder_hardware, but it still doesn't recognize the sonar. Here is the scheme: i2c Is there something wrong, or am I missing something in the code (I finally figured out how to paste the code nicely)? I know that this may not be an issue with iNav, but any help is very appreciated :) P.S.: As I said before, the Arduino is lighting up when cm<10, so the sonar part is OK. It's also lit up when the distance is too great.

Pokornz avatar Nov 25 '17 18:11 Pokornz

Ammm... Looks good, hard to tell. Maybe 5here is something with i2c slave implementation. Never tested it with atmega32u4

DzikuVx avatar Nov 25 '17 20:11 DzikuVx

Strange thing is that the LED on the Arduino also turns on when the distance is > ~70cm.. I tried putting Wire.setClock(400000); in the code since iNav uses 400kHz, but nothing has changed. (I also tried lowering the i2c_speed to 100kHz first). When I ask for status, there is RANGEFINDER=UNAVAILABLE and I2C Errors: 0, config size: 3421, max available config: 4096

Pokornz avatar Nov 26 '17 02:11 Pokornz

@DzikuVx The US-100 and the ATmega 328 will run at 3.3 or 5v, so no logic level conversion is needed.

After I get my US-100 I'm going a different route with the ultrasonic control and wiring to keep it simple, faster, and more reliable. At least that's the plan.

teckel12 avatar Nov 27 '17 02:11 teckel12

@teckel12 Are you telling me that the Arduino Nano (5V) can be directly connected to the FC (Omnibus F3) without any danger for the STM32F3? You should look at the diagram, the conversion is NOT between ATmega 328 and US-100. @DzikuVx Did you have to adjust the i2c_speed on your FC?

Pokornz avatar Nov 27 '17 06:11 Pokornz