Помогите расчитать дистанцию

Тема в разделе "Arduino & Shields", создана пользователем andrey127, 27 мар 2017.

  1. andrey127

    andrey127 Нуб

    Немогу расчитать дистанцию со спидометра.Что-то совсем затупил...
    Помогите.
    Код (C++):
    // Тестировалось на Arduino IDE 1.0.1
    #include <Adafruit_GFX.h>
    #include <Adafruit_PCD8544.h>
    #include <dht11.h>
    dht11 DHT;
    #define DHT11_PIN 8
    // pin 3 - Serial clock out (SCLK)
    // pin 4 - Serial data out (DIN)
    // pin 5 - Data/Command select (D/C)
    // pin 6 - LCD chip select (CS)
    // pin 7 - LCD reset (RST)
    Adafruit_PCD8544 display = Adafruit_PCD8544(3, 4, 5, 6, 7);


    int cruise = 0;
    int cruisespeed = 0;
    int cruisecancel = 0;
    float km = 0.00;
    #define reed A0// пин, к которому подключен геркон

    // переменные

    float radius = 17.0;// радиус колеса (в дюймах)- измените это для своем велосипеде

    int reedVal;

    long timer = 0;// время одного полного оборота (в милисекундах)
    int mph = 0;

    float circumference;

    boolean backlight;

    int maxReedCounter = 100;// минимальное время (в милисекундах) одного оборота

    int reedCounter;

    const static unsigned char PROGMEM logoBmp[] =
    {
      B11111111, B11111111, B10000000,
      B11111111, B11111111, B10000000,
      B11111111, B11111111, B10000000,
      B11111100, B00000011, B10000000,
      B11111000, B00000001, B10000000,
      B11111100, B00000011, B10000000,
      B11111111, B11000011, B10000000,
      B11111111, B10000111, B10000000,
      B11111111, B10001111, B10000000,
      B11111111, B00001111, B10000000,
      B11111110, B00011111, B10000000,
      B11111110, B00011111, B10000000,
      B11111100, B00111111, B10000000,
      B11111100, B01111111, B10000000,
      B11111000, B00000011, B10000000,
      B11111000, B00000001, B10000000
    };
    static const char lcd_image_mas[8] =
    { 0x00, 0x00, 0x00, 0x0E, 0x11, 0x11, 0x11, 0x0E};


    void setup() {
      Serial.begin(9600);
      display.begin();              // Инициализация дисплея
      display.setContrast(60);      // Устанавливаем контраст
      display.setTextColor(BLACK);  // Устанавливаем цвет текста
      display.setTextSize(1);       // Устанавливаем размер текста
      display.clearDisplay();       // Очищаем дисплей
      display.display();
      cruise = 0;
      Serial.println("DHT TEST PROGRAM ");
      Serial.print("LIBRARY VERSION: ");
      Serial.println(DHT11LIB_VERSION);
      Serial.println();
      Serial.println("Type,\tstatus,\tHumidity (%),\tTemperature (C)");
      reedCounter = maxReedCounter;
      circumference = 2*3.14*radius;
      pinMode(1,OUTPUT);// tx
      pinMode(2,OUTPUT);// свич подсветки
      pinMode(reed, INPUT);
    cli();// остановка прерываний
    // устанавливаем прерывание timer1 на частоте 1 кГц
    TCCR1A = 0;// устанавливаем внутренний регистр TCCR1A в 0
    TCCR1B = 0;// то же самое для TCCR1B
    TCNT1 = 0;
    // устанавливаем инкремент для счетчика 1 кГц
    OCR1A = 1999;// = (1/1000) / ((1/(16*10^6))*8) - 1
    // активируем режим CTC
    TCCR1B |= (1 << WGM12);
    TCCR1B |= (1 << CS11);
    // таймер сравнивает прерывание
    TIMSK1 |= (1 << OCIE1A);
    sei();//allow interrupts
    // Конец настройки таймера
    }
    ISR(TIMER1_COMPA_vect) {// Прерывание с частотой 1 кГц для измерений герконом

    reedVal = digitalRead(reed);// получаем значение A0

    if (reedVal){// если геркон замкнул контакт

    if (reedCounter == 0){// минимальное время между импульсяами прошло

    mph = (56.8*float(circumference))/float(timer);// расчет миль в час
    km = km+float(circumference)/100000;
    timer = 0;// перезагрузка таймера

    reedCounter = maxReedCounter;// перезагрузка reedCounter

    }

    else{

    if (reedCounter > 0){// не позволяем reedCounter принять негативное значение

    reedCounter -= 1;// декремент reedCounter

    }

    }

    }

    else{// если геркон не замкнут

    if (reedCounter > 0){// не позволяем reedCounter принять негативное значение

    reedCounter -= 1;// декремент reedCounter

    }

    }

    if (timer > 2000){

    mph = 0;// если не поступают импульсы от геркона, значит скорость равна 0

    }

    else{

    timer += 1;// инкремент таймера

    }

    }

    //void displayMPH(){

    //display.setCursor(40,40);
    //display.println(mph);

    //}
    void loop() {
      // Рисуем заранее подготовленное лого
      // Подготовлен массив из 16 пар байтов
      // каждый байт состоит из 8 битов, соответсвенно
      // получаем матрицу 16х16 битов, 1-черный цвет, 0-белый цвет
      int chk;
      Serial.print("DHT11, \t");
      chk = DHT.read(DHT11_PIN);    // READ DATA
      switch (chk){
        case DHTLIB_OK:
                    Serial.print("OK,\t");
                    break;
        case DHTLIB_ERROR_CHECKSUM:
                    Serial.print("Checksum error,\t");
                    break;
        case DHTLIB_ERROR_TIMEOUT:
                    Serial.print("Time out error,\t");
                    break;
        default:
                    Serial.print("Unknown error,\t");
                    break;
      }
     
     
     
     
      // =-=-=-=-=-=-=-=-=-=-=Дисплей=-=-=-=-=-=-=-=-=-=-=-=-=-=-
      Serial.print(DHT.humidity,1);
      Serial.print(",\t");
      Serial.println(DHT.temperature,1);
      display.setTextSize(1);
      display.setTextColor(BLACK);
      display.clearDisplay();
      display.drawLine (0, 37, 84, 37, 1);
      display.drawLine (0, 11, 84, 11, 1);
      if(cruise == 0)
      {
      display.setCursor(10,2);
      display.println("SPEEDOMETR");
     
      }
      if(cruise == 1)
      {
      display.setCursor(1,2);
      display.println("CRUISE");
      display.setCursor(47,2);
      display.println(cruisespeed);
      display.setCursor(57,2);
      display.println("km/h");
      }
      if(DHT.temperature >9)
      {
      display.setCursor(79,40);
      display.drawRect(75, 40, 3, 3, 1);
      display.println("C");
      display.setTextSize(1);
      display.setTextColor(BLACK);
      display.setCursor(60,40);
      display.println(DHT.temperature);
      }
      if(DHT.temperature <10)
      {
      display.setCursor(79,40);
      display.drawRect(75, 40, 3, 3, 1);
      display.println("C");
      display.setTextSize(1);
      display.setTextColor(BLACK);
      display.setCursor(67,40);
      display.println(DHT.temperature);
      }
      display.setTextColor(WHITE, BLACK); // 'inverted' text
      display.setTextSize(1);
      display.setTextColor(BLACK);
      display.setCursor(0,40);
      display.println(km);
      display.setCursor(50,40);
      display.println("KM");
      if(DHT.temperature <10)
      {
        display.setCursor(60,40);
        display.println("*");
      }
      display.setTextSize(2);
      display.setCursor(5,17);
      display.println(mph);
      display.setCursor(35,17);
      display.println("KM/H");
      display.display();
     

      delay(1000);
    }
    Вот тут расчитать надо:
    Код (C++):
    km = km+float(circumference)/100000;
     
    Пытался подобрать.
     
  2. sslobodyan

    sslobodyan Гик

    это длина окружности колеса. в скетче считается от радиуса в 17 дюймов. я так думаю, что стоит указать правильный радус в строке
     
  3. andrey127

    andrey127 Нуб

    А формула расчёта у меня правильная?
     
  4. Tomasina

    Tomasina Сушитель лампочек Модератор

    нет. Надо 100000.0
     
  5. sslobodyan

    sslobodyan Гик

    Я почему-то думал, что тип результата вычислений определяется по первому операнду (если нет явного приведения типов), а результат деления флоата на инт будет флоат. Ну и так, как у нас км - флоат, то посчитаться должно правильно. В чем моя ошибка?
     
  6. Tomasina

    Tomasina Сушитель лампочек Модератор

    лучше перестраховаться и привести все элементы формулы к float ;)