Go Down

Topic: Arduino Mega does not count (Read 352 times) previous topic - next topic

AdamK24

Hello guys.
I have a problem with that code. For some reasons it dose not count speed, fuel consumption, nothing.
I try many things with no results, it stil show only zeros.
This code worked on uno, i have made many changes and it start working on mega but the most important thing does not work.
I think that it is something with TIMER or PinInterrupt.
For testing it i use ON/OFF signal from oder arduino
In serial print i see changes in a pin state, but nothing in variables as (vss_pulses).
Can some one with more experience look at that code.
I would be thankfull.

Code: [Select]
// Bi-TripCo by Nick Stavrou
// Bi-Fuel (LPG + Unleaded) Trip Computer
// Metric version
// Arduino UNO, 0.96" OLED display and DS3231 RTC module
// Release date: 29 Mar 2017
// Details can be found at www.instructables.com

// Libraries
#include "PinChangeInterrupt.h" // enables the interrupts at the other pin except the ones at the digital pins 2 and 3
#include <avr/sleep.h>          // enables the sleep function
#include <avr/power.h>          // power management
#include <EEPROMex.h>           // enables some special functions for writing to and reading from EEPROM
#include <EEPROMVar.h>
#include <Wire.h>               // IIC LIBRARY
#include "RTClib.h"             // Real Time Clock Library
#include <math.h>               // enables complex math functions
#include <Adafruit_ST7735.h>  // Include Adafruit_ST7735 library to drive the display
#include <Adafruit_GFX.h>     
#include <OneWire.h>
#include <DallasTemperature.h>


#define OLED_RESET 4
//Adafruit_SSD1306 display(OLED_RESET);

// Declare pins for the display:
#define TFT_CS     4
#define TFT_RST    3  // You can also connect this to the Arduino reset in which case, set this #define pin to -1!
#define TFT_DC     2
// The rest of the pins are pre-selected as the default hardware SPI for Arduino Uno (SCK = 51 and SDA = 52)

Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_RST);

RTC_DS3231 rtc;

#define ONE_WIRE_BUS 5
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);

// variables declaration
volatile static float vss_pulse_distance = 0.0003816033;  // distance coefficient -- change this according to your measurements (km/pulse)
volatile float LPG_injector_flow;                         
volatile static float unleadedFlow = 1743e-11;            // gasoline injector flow coef. -- change this according to your measurements (litres/microseconds)

byte LPG1, LPG2, LPG3, LPG4, digitLPG, pos = 0;
volatile unsigned long vss_pulses;
volatile float traveled_distance, traveled_distance2, traveled_distance3, seconds_passed, speed, avg_speed, distance_to_LPGstation;
volatile float used_LPG, used_LPG2, instant_LPG_consumption, avg_LPG_consumption, LPG_in_tank, Full_tank = 49;
volatile float used_Unleaded, used_Unleaded2;
volatile float average_L_100km_Unlead;
volatile float instant_unlead_consumption;

volatile unsigned long unleadTime1=0, unleadTime2=0, unleadinj_Open_Duration=0;
volatile unsigned long LPG_injector_open_duration = 0, injTime1=0, injTime2=0;
int postemp;
int vss_pin = 10; // VSS signal input at digital pin 2 (INT0)
int LPG_pin = 11; // LPG injector signal input at digital pin 3 (INT1)
int ignition_pin = 12; // ignition signal input
int unleaded_pin = 13; // Unleaded injector signal input


boolean buttonState, buttonState2;
boolean lastButtonState2 = HIGH;
long lastDebounceTime = 0, logohold, counter, counter2;
volatile boolean ignition = false;
boolean ignoreRelease = false;
boolean inst_disp = true;
byte menunumber = 0,  menunumbermax = 10;
int h=0, m=0, s, m1;
boolean timeRead = false, displaychange = true;
//float thermReading, sensors.getTempCByIndex(0);
boolean dots = true;

//Below are the variables declaration for the thermistor -- you can find more info at: https://learn.adafruit.com/thermistor/using-a-thermistor
#define THERMISTORPIN A0
#define THERMISTORNOMINAL 10000
#define TEMPERATURENOMINAL 25   

#define NUMSAMPLES 5
#define BCOEFFICIENT 3630
#define SERIESRESISTOR 10000
int samples[NUMSAMPLES];
int i=0;

const unsigned char leaf [] PROGMEM= {

};

const unsigned char  dist_to_LPG [] PROGMEM= {

};

const unsigned char  average [] PROGMEM= {

};

const unsigned char averagecons [] PROGMEM= {

};
const unsigned char avspeed [] PROGMEM = {

};
const unsigned char dist [] PROGMEM= {

};
const unsigned char Unleaded_fill_nozzle [] PROGMEM= {

};

const unsigned char  logo [] PROGMEM= {

};

const unsigned char petrolstationpump [] PROGMEM = {

};

const unsigned char speedometer [] PROGMEM = {

};

const unsigned char snowflake [] PROGMEM = {

};

void setup()
{

   // start serial port
 Serial.begin(9600);
 sensors.begin();
 
 
 // Display setup:

  // Use this initializer if you're using a 1.8" TFT
  tft.initR(INITR_BLACKTAB);  // Initialize a ST7735S chip, black tab
  tft.setRotation(1);
  tft.setTextWrap(false);  // By default, long lines of text are set to automatically "wrap" back to the leftmost column.
                           // To override this behavior (so text will run off the right side of the display - useful for
                           // scrolling marquee effects), use setTextWrap(false). The normal wrapping behavior is restored
                           // with setTextWrap(true).
 
 
  pinMode(24, OUTPUT); //wygaszenie podÅ›wietlenia
  pinMode(7, INPUT); // Button 2
  pinMode(6, INPUT); // Button 1
 
  pinMode(vss_pin, INPUT);
  pinMode(LPG_pin, INPUT);
  pinMode(ignition_pin, INPUT);
  pinMode(unleaded_pin, INPUT);

  // below recalls the values stored in case of power loss
  traveled_distance = EEPROM.readFloat(0);
  traveled_distance2 = EEPROM.readFloat (5);
  used_LPG = EEPROM.readFloat (10);
  used_LPG2 = EEPROM.readFloat(15);
  LPG_in_tank = EEPROM.readFloat(20);
  seconds_passed = EEPROM.readFloat(25);
  used_Unleaded = EEPROM.readFloat(30);
  traveled_distance3 = EEPROM.readFloat (35);
  used_Unleaded2 = EEPROM.readFloat(45);
  LPG1 = EEPROM.readByte (40);
  LPG2 = EEPROM.readByte (41);
  LPG3 = EEPROM.readByte (42);
  LPG4 = EEPROM.readByte (43);
  LPG_injector_flow = (LPG1 * 1000 + LPG2 * 100 + LPG3 * 10 + LPG4) * 1e-11;

  noInterrupts();
  // set and initialize the TIMER1
    TCCR1A = 0; // set entire TCCR1A register to 0
    TCCR1B = 0; // set entire TCCR1B register to 0
    TCCR1B |= (1 << CS12);
    TIMSK1 |= (1 << TOIE1);
    TCNT1 = 3036;

  attachPCINT(digitalPinToPinChangeInterrupt(ignition_pin), ignitionSignal, CHANGE);

  interrupts();
  delay(10);
}



}

AdamK24

SECOND PART OF CODE:
Code: [Select]
}

void loop()
// Debug - see what torque is sending on your serial monitor


{// When the ignition switch is turned, executes the next two ifs
  if (ignition == true && digitalRead(12) == LOW)
  {
      detachInterrupt(digitalPinToInterrupt(vss_pin));
      detachInterrupt(digitalPinToInterrupt(LPG_pin));
      detachPCINT(digitalPinToPinChangeInterrupt(unleaded_pin));
      delay(50);
      ignition = false;
      if (menunumber == 11)
      {   
            EEPROM.writeByte(40, LPG1); //stores the new LPG coef.
            EEPROM.writeByte(41, LPG2);
            EEPROM.writeByte(42, LPG3);
            EEPROM.writeByte(43, LPG4);
         LPG_injector_flow = (LPG1 * 1000 + LPG2 * 100 + LPG3 * 10 + LPG4) * 1e-11;
         inst_disp = true;
         tft.fillScreen(ST7735_BLACK);
         menunumber = 0;
       
      }
      if (menunumber == 12) // same as previous for "Time Set" menu
      {
        DateTime dt = rtc.now();
        s = dt.second();
        if (m != m1) s = (((millis() - counter)/1000))%60;
        else s = dt.second(), m = dt.minute();
        rtc.adjust(DateTime(dt.year(), dt.month(), dt.day(), h, m, s));
        ignoreRelease = true;
        lastButtonState2 = LOW;
        menunumber = 8;
        tft.fillScreen(ST7735_BLACK);
      }
      // when the ignition switched off it stores the values to the EEPROM
      EEPROM.writeFloat (0, traveled_distance);
      EEPROM.writeFloat (5, traveled_distance2);
      EEPROM.writeFloat (10, used_LPG);
      EEPROM.writeFloat (15, used_LPG2);
      EEPROM.writeFloat (20, LPG_in_tank);
      EEPROM.writeFloat (25, seconds_passed);
      EEPROM.writeFloat (30, used_Unleaded);
      EEPROM.writeFloat (35, traveled_distance3);
      EEPROM.writeFloat (45, used_Unleaded2);
      digitalWrite(24, HIGH); //podswietlenie
      //display.ssd1306_command(SSD1306_DISPLAYOFF);
      tft.sleep();
     
      tft.fillScreen(ST7735_BLACK);
      sleep_enable(); // enables the sleep mode
      set_sleep_mode(SLEEP_MODE_PWR_DOWN); // set the sleep mode
      cli();
      //sleep_bod_disable(); // disables the brown out detector to consume less power while sleeping
      sei();
      sleep_mode(); // microcontroller goes to sleep 
  }
  // when it wakes up continues from here -- also the first time we turn the ignition key to ON starts from here
  if (ignition == true && digitalRead(12) == HIGH)
  {
     
      digitalWrite(24, LOW);
      ignition = false;    // this variable is needed in order to run once the code inside this if
      logohold = millis(); // hold the LOGO screen on, for 2 sec
      inst_disp = true;
     
      //display.begin(SSD1306_SWITCHCAPVCC, 0x3C);           
      tft.wake();
     
      tft.fillScreen(ST7735_WHITE);                             
      tft.drawBitmap(0, 0,  logo, 80, 64, ST7735_RED);     
      delay(5000);
      tft.fillScreen(ST7735_BLACK);                                         

      attachInterrupt(digitalPinToInterrupt(vss_pin), distance, RISING); // attaches the interrupt which related to the VSS signal
      attachInterrupt(digitalPinToInterrupt(LPG_pin), LPG_injector_time, CHANGE); // interrupt for LPG injector signal
      attachPCINT(digitalPinToPinChangeInterrupt(unleaded_pin), UnleadedTime, CHANGE); // petrol injector signal input and interrupt
      while (millis() - logohold < 2000) ;
                                           

  }

    // every 5sec calculates average LPG consumption, remaining distance accordingly to the calculated remaining fuel in tank, average speed and average Unleaded cons.
  if(millis()%5000 < 50)
    {
    avg_LPG_consumption = 100 * used_LPG2/traveled_distance2;
    distance_to_LPGstation = 100 * LPG_in_tank/avg_LPG_consumption;   
    avg_speed = (traveled_distance3 / seconds_passed)*3600;           
    average_L_100km_Unlead = 100 * used_Unleaded2/traveled_distance2;
    }

// For the short and long press function I consulted: http://jmsarduino.blogspot.gr/2009/05/click-for-press-and-hold-for-b.html
// There are many differences though
// "button 1" -- only  SHORT PRESS function -- changes occur on press, because there is no LONG PRESS function
    if (digitalRead(6) != buttonState) {
      buttonState = digitalRead(6);     
      if (buttonState == LOW)             
      {                       
      if (menunumber <= menunumbermax){ // changes the display indications forwards
      if (menunumber == menunumbermax) menunumber =0;
      else menunumber += 1;
      tft.fillScreen(ST7735_BLACK);
      }
      if (menunumber == 12) //if we are at the "Time Set" menu it changes the Hour
      {
        if (h < 23) h += 1, counter = millis();
        else h = 0, counter = millis();
      }
      // if we are at the "LPG Coef." menu it changes the LPG_injector_flow digits
        if (menunumber == 11 && digitLPG == 1){
          if (LPG1 < 9) LPG1 += 1, counter = millis();
          else LPG1 = 0, counter = millis();
        }
        if (menunumber == 11 && digitLPG == 2){
          if (LPG2 < 9) LPG2 += 1, counter = millis();
          else LPG2 = 0, counter = millis();
        }
        if (menunumber == 11 && digitLPG == 3){
          if (LPG3 < 9) LPG3 += 1, counter = millis();
          else LPG3 = 0, counter = millis();
        }
        if (menunumber == 11 && digitLPG == 4){
          if (LPG4 < 9) LPG4 += 1,  counter = millis();
          else LPG4 = 0, counter = millis();
        }
      }
    }

////////// "button 2" functions /////////////////
buttonState2 = digitalRead(7);
if (buttonState2 == LOW && lastButtonState2 == HIGH) lastDebounceTime = millis(); //keeps the time that button2 pressed

if (buttonState2 == HIGH && lastButtonState2 == LOW)
{
if (ignoreRelease == false) // "button 2" SHORT PRESS functions -- on release
  {
  if (menunumber <= menunumbermax)
      {   if (menunumber == 0) menunumber = menunumbermax;
          else menunumber = menunumber - 1;
      tft.fillScreen(ST7735_BLACK);
      }
  if (menunumber == 12) 
      {  if (m < 59) m=m+1, counter = millis();
         else m = 0, counter = millis();
     
      }
  if (menunumber == 11) // LPG coef. setting menu -- "button 2" short press changes the position of the cursor
      { pos += 18;
        digitLPG += 1;
        counter = millis();
        if (digitLPG == 5)
          { pos = 0;
            digitLPG = 1;
          }
      }
  }
else ignoreRelease = false;
}
//////////////////// "button 2" LONG PRESS functions /////////////////////////////////////////////////////
if (digitalRead(7) == HIGH) displaychange = true;   
if (buttonState2 == LOW && (millis() - lastDebounceTime) > 3000 && displaychange == true) // below are the long press functions for button 2
{
      if (menunumber == 0) menunumber = 11, counter = millis(), counter2 = millis(), displaychange = false, digitLPG = 1,  tft.fillScreen(ST7735_BLACK); //goes to the "LPG Coef." menu
      if (menunumber == 1) traveled_distance2 = 0, used_LPG2 = 0, avg_LPG_consumption = 0, used_Unleaded2 = 0,  tft.fillScreen(ST7735_BLACK);// average LPG consumption and average Unleaeded cons. reset
      if (menunumber == 3) traveled_distance3 = 0, seconds_passed = 0, avg_speed = 0,  tft.fillScreen(ST7735_BLACK); // average speed reset
      if (menunumber == 4) traveled_distance = 0,  tft.fillScreen(ST7735_BLACK); //traveled Distance = 0
      if (menunumber == 6) used_LPG = 0,  tft.fillScreen(ST7735_BLACK); // total LPG litres = 0
      if (menunumber == 7) LPG_in_tank = Full_tank,  tft.fillScreen(ST7735_BLACK); // LPG tank reset to full
      if (menunumber == 8) menunumber = 12, counter = millis(), counter2 = millis(), timeRead = true, displaychange = false,  tft.fillScreen(ST7735_BLACK); //goes to the "Time Setting" menu
      if (menunumber == 9) traveled_distance2 = 0, used_LPG2 = 0, avg_LPG_consumption = 0, used_Unleaded2 = 0,  tft.fillScreen(ST7735_BLACK); // same with menunumber = 1
      if (menunumber == 10) used_Unleaded = 0,  tft.fillScreen(ST7735_BLACK); // total unleaded fuel reset
 
ignoreRelease = true;
}
lastButtonState2 = buttonState2;

// below are the misc screens

jremington

#2
Jun 23, 2019, 06:55 pm Last Edit: Jun 23, 2019, 06:56 pm by jremington
Quote
This code worked on uno, i have made many changes
Start over with the working version and introduce the changes again, one by one.

Test the effect of each change and make sure it is working properly, before introducing another.

Not the answer you wanted.

AdamK24

I was doing like you say, but i stop on that problem,
i cant solve it alone, thats why i asking for a help.

Third part of code:
Code: [Select]
// below are the misc screens
switch (menunumber)
{
    case 0:
cons1: 
       
        if(inst_disp == true) displaychange = false, inst_disp = false, digitLPG = 0, pos = 0;
        tft.setTextColor(ST7735_BLUE, ST7735_BLACK);
        tft.drawBitmap(20, 20,  petrolstationpump, 32, 32, ST7735_BLUE);
        tft.setCursor(60, 30);
        tft.setTextSize(1);
        tft.print(F("LPG"));
        tft.setCursor(60,42);
        tft.setTextSize(1);
        if (speed > 2) tft.print(F("l/100km"));
        else tft.print(F("l/h")); //when the car is stopped displays the instant consumption in l/h
        tft.setCursor(20,56);
        tft.setTextSize(4);
        if(instant_LPG_consumption > 99.9) tft.print(F("--.-"));
        else tft.print(instant_LPG_consumption,1);
       
    break;

    case 1:
       
        tft.setTextColor(ST7735_WHITE , ST7735_BLACK);
        tft.drawBitmap(20, 30,  averagecons, 64, 32, ST7735_WHITE);
        tft.setCursor(54, 10);
        tft.setTextSize(1);
        tft.print(F("LPG"));
        tft.setCursor(74,35);
        tft.setTextSize(1);
        tft.print(F("L/100"));
        tft.setCursor(20, 66);
        tft.setTextSize(4);
        if(isnan(avg_LPG_consumption)|| isinf(avg_LPG_consumption)) tft.println(F("---"));
        //else tft.println(avg_LPG_consumption, 1);
       
    break;

    case 2:
       
        tft.setTextColor(ST7735_WHITE, ST7735_BLACK);
        tft.drawBitmap(49, 25,  speedometer, 32, 32, ST7735_WHITE);
        tft.setCursor(40,56);
        tft.setTextSize(4);
        tft.print(speed, 0);
        tft.setCursor(78, 54);
        tft.setTextSize(2);
        tft.print(F("km"));
        tft.setCursor(104, 60);
        tft.setTextSize(3);
        tft.print(F("/"));
        tft.setCursor(115, 72);
        tft.setTextSize(2);
        tft.print(F("h"));
       
    break;
   
    case 3: 
       
        tft.setTextColor(ST7735_WHITE, ST7735_BLACK);
        tft.drawBitmap(31, 25,  avspeed, 64, 32, ST7735_WHITE);
        tft.setCursor(10, 56);
        tft.setTextSize(4);
        tft.print(avg_speed, 0);
        tft.setCursor(94, 54);
        tft.setTextSize(2);
        tft.print(F("km"));
        tft.setCursor(118, 57);
        tft.setTextSize(3);
        tft.print(F("/"));
        tft.setCursor(130, 68);
        tft.setTextSize(2);
        tft.print(F("h"));
       
    break;
     
    case 4:         
       
        tft.setTextColor(ST7735_GREEN, ST7735_BLACK);
        tft.drawBitmap(48, 20,  dist, 32, 32, ST7735_GREEN);
        tft.setCursor(88,38);
        tft.setTextSize(2);
        tft.print(F("km"));
        tft.setCursor(30, 56);
        tft.setTextSize(4);
        tft.print(traveled_distance, 1);
       
    break;
     
    case 5: 
       
        tft.setTextColor(ST7735_WHITE, ST7735_BLACK);
        tft.drawBitmap(20, 25,  dist_to_LPG, 128, 32, ST7735_WHITE);
        tft.setCursor(20, 56);
        tft.setTextSize(4);
        if(distance_to_LPGstation < 10 ||  isnan(distance_to_LPGstation) || isinf(distance_to_LPGstation) ) tft.println(F("---"));
        else tft.print(distance_to_LPGstation,0);
        tft.setTextSize(2);
        tft.setCursor(110,68);
        tft.print(F("km"));
       
    break;
     
    case 6:
       
        tft.setTextColor(ST7735_WHITE, ST7735_BLACK);
        tft.drawBitmap(30, 30,  leaf, 32, 32, ST7735_WHITE);
        tft.setCursor(70, 32);
        tft.setTextSize(1);
        tft.print(F("Total"));
        tft.setCursor(70, 42);
        tft.setTextSize(2);
        tft.print(F("LPG"));
        tft.setCursor(30, 66);
        tft.setTextSize(3);
        tft.print(used_LPG,1);
        tft.print(F("l"));
       
    break;

    case 7:
       
        tft.setTextColor(ST7735_GREEN, ST7735_BLACK);
        tft.drawBitmap(51, 30,  FuelTank, 64, 32, ST7735_WHITE);
        tft.setCursor(30, 66);
        tft.setTextSize(3);
        if (LPG_in_tank <= 0 ) tft.print(F("0.0"));
        else tft.print(LPG_in_tank,1);
        tft.setTextSize(3);
        tft.setCursor(125,63);
        tft.print(F("l"));
     
    break;

    case 8:
 temp1:     if(inst_disp == true) displaychange = false, inst_disp = false;
           
            tft.setTextColor(ST7735_GREEN, ST7735_BLACK);
           
            printTemperature();
            tft.drawFastHLine(0, 48, 168, ST7735_WHITE);
            tft.drawFastHLine(0, 49, 168, ST7735_WHITE);
            tft.setCursor(30, 56);
            tft.setTextSize(3);
            printTime();
          if(sensors.getTempCByIndex(0) < 3.5)
          {
          tft.drawBitmap(0, 3,  snowflake, 16, 16, ST7735_WHITE);
          }
       
    break;
   
    case 9:
       
        tft.setTextColor(ST7735_GREEN, ST7735_BLACK);
        tft.drawBitmap(20, 38,  average, 16, 16, ST7735_GREEN);
        tft.drawBitmap(37, 30,  Unleaded_fill_nozzle, 32, 32, ST7735_GREEN);
        tft.setCursor(84,33);
        tft.setTextSize(2);
        tft.println(F("l/100"));
        tft.setCursor(20, 56);
        tft.setTextSize(4);
        if(isnan(average_L_100km_Unlead)|| isinf(average_L_100km_Unlead)) tft.println(F("---"));
        else tft.println(average_L_100km_Unlead, 1);
       
    break;

    case 10:
       
        tft.setTextColor(ST7735_WHITE, ST7735_BLACK);
        tft.drawBitmap(96, 30,  Unleaded_fill_nozzle, 32, 32, ST7735_WHITE); //(x,y, name, DX, DY, color)
        tft.setTextSize(1);
        tft.setCursor(20, 40);
        tft.println(F("Total"));
        tft.setTextSize(1);
        tft.setCursor(20, 30);
        tft.println(F("Unleaded"));
        tft.setCursor(20, 56);
        tft.setTextSize(4);
        tft.println(used_Unleaded,1);
        tft.setTextSize(2);
        tft.setCursor(105,63);
        tft.println(F("l"));
       
      break;
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////


AdamK24

And last one:
Code: [Select]
// the following are secondary displays and activated only in case we want to set the LPG Coef.(case 11) or the Time (case 12)
     
    case 11: // LPG Coef. Setting menu
       
        tft.setTextColor(ST7735_WHITE, ST7735_BLACK);
        tft.setCursor(20,39);
        tft.setTextSize(2);
        tft.println(F("LPG Coef."));
        tft.drawFastHLine(15, 28, 128, ST7735_WHITE);
        tft.drawFastHLine(15, 29, 128, ST7735_WHITE);
        tft.setCursor(20,66);
        tft.setTextSize(2);

        tft.println(LPG1);
          tft.setCursor(40,66);
        tft.println(LPG2);
          tft.setCursor(60,66);
        tft.println(LPG3);
          tft.setCursor(80,66);
        tft.println(LPG4);
       
        tft.setCursor(pos,70);
        tft.println(F("_"));
        if (digitalRead(7) == HIGH) counter2 = millis(), displaychange = true; //we must release "button 2" at least once in order to be able to go back to instant LPG consuption
        if ((digitalRead(7) == LOW && millis() - counter2 > 3000 && displaychange == true) || millis() - counter > 10000){
            EEPROM.writeByte(40, LPG1); //stores the new LPG coef.
            EEPROM.writeByte(41, LPG2);
            EEPROM.writeByte(42, LPG3);
            EEPROM.writeByte(43, LPG4);
         LPG_injector_flow = (LPG1 * 1000 + LPG2 * 100 + LPG3 * 10 + LPG4) * 1e-11;
         ignoreRelease = true;
         inst_disp = true;
         lastButtonState2 = LOW;
         tft.fillScreen(ST7735_BLACK);
         menunumber = 0; 
         goto cons1;       
        }
       
    break;

    case 12: //RTC set
     
        tft.setTextColor(ST7735_WHITE, ST7735_BLACK);
        tft.setCursor(30,30);
        tft.setTextSize(2);
        tft.print(F("Time Set"));
        tft.drawFastHLine(15, 48, 128, ST7735_WHITE);
        tft.drawFastHLine(15, 49, 128, ST7735_WHITE);

        if (timeRead == true){
        DateTime dt = rtc.now();
        h = dt.hour();
        m = dt.minute();
        m1 = dt.minute();
        timeRead = false;
        }
        tft.setCursor(47, 66);
        tft.setTextSize(2);
        char sdt[15];
        sprintf(sdt, "%02d:%02d", h, m);
        tft.print(sdt);
       
       
        if(digitalRead(7) == HIGH) counter2 = millis(), displaychange = true; //we must release the button 2 at least once in order to be able to go back to Temp and Time screen
        if((digitalRead(7) == LOW && millis() - counter2 > 3000 && displaychange == true) || millis() - counter > 59000){
        DateTime dt = rtc.now();
        s = dt.second();
        if (m != m1) s = (((millis() - counter)/1000))%60;
        else s = dt.second(), m = dt.minute();
        rtc.adjust(DateTime(dt.year(), dt.month(), dt.day(), h, m, s));
        inst_disp = true;
        ignoreRelease = true;
        lastButtonState2 = LOW;
        menunumber = 8;
        }
    break;
      }
  }

ISR(TIMER1_OVF_vect) //TIMER1 overflow interrupt -- occurs every 1sec --
{
    instantSpeed();
   
    LPG_Consumption();
    LPG_injector_open_duration = 0;
   
    unleadedConsumption();
    unleadinj_Open_Duration = 0;
   
    seconds_passed++;
    vss_pulses = 0;
   
TCNT1 = 3036;
}

void distance()
{
  vss_pulses++;
  traveled_distance += vss_pulse_distance; 
  traveled_distance2 += vss_pulse_distance;
  traveled_distance3 += vss_pulse_distance;
                                            // we calculate 3 times the same thing in order to reset the distance, the average cons. and average speed independently
}

void instantSpeed()
{
  speed = (vss_pulse_distance * vss_pulses * 3600); 
}

// The following routine is giving the way to calculate the total time that LPG injector open during the 1sec interval
void LPG_injector_time()
{
  injTime2 = micros();
    if ((injTime2 - injTime1)<5000 && (injTime2 - injTime1)> 4)
    {
    LPG_injector_open_duration = LPG_injector_open_duration + injTime2 - injTime1;
    }   
  injTime1 = injTime2;
}


void LPG_Consumption()
{
if (speed > 2 ) instant_LPG_consumption = (100*((LPG_injector_open_duration * LPG_injector_flow)*3600))/speed;
                                                                                                       
else  instant_LPG_consumption = LPG_injector_open_duration * LPG_injector_flow * 3600; // when the car stops calculates the instant consumption in l/h

used_LPG = used_LPG + (LPG_injector_open_duration * LPG_injector_flow);       
used_LPG2 = used_LPG2 + (LPG_injector_open_duration * LPG_injector_flow);     
LPG_in_tank = LPG_in_tank - (LPG_injector_open_duration * LPG_injector_flow);
}

void UnleadedTime() // it is called every time a change occurs at the gasoline injector signal and calculates gasoline injector opening time, during the 1sec interval

  {
  if (digitalRead(13) == LOW)
      {
        unleadTime1 = micros();
      }
  if (digitalRead(13) == HIGH)
      {
        unleadTime2 = micros();
      }
  if (unleadTime2 > unleadTime1)
      {if ((unleadTime2 - unleadTime1) > 500 && (unleadTime2 - unleadTime1) < 12000) // some conditions to avoid false readings because of noise
                                                                                 
        {
        unleadinj_Open_Duration = unleadinj_Open_Duration + (unleadTime2 - unleadTime1); //total useconds that the gasoline injector opens throughout 1sec                                                                               
        }
      } 
  }

void unleadedConsumption()
{
  if (speed > 2 ) instant_unlead_consumption = (100*((unleadinj_Open_Duration * unleadedFlow)*3600))/speed;
                                                                                                       
  else  instant_unlead_consumption = unleadinj_Open_Duration * unleadedFlow * 3600; // when the car stops calculates the instant consumption in l/h
 
 
  used_Unleaded = used_Unleaded + (unleadinj_Open_Duration * unleadedFlow);   
  used_Unleaded2 = used_Unleaded2 + (unleadinj_Open_Duration * unleadedFlow);
}


void ignitionSignal() // this is called everytime the ingintion signal changes -- if the microcontroller is in sleep mode, it will wake up
{
    ignition = !ignition;
}

void printTime()
{
  DateTime dt = rtc.now();
  char sdt[15];
  sprintf(sdt, "%02d:%02d", dt.hour(), dt.minute());
  tft.println(sdt);         
}

void printTemperature()
{
        // call sensors.requestTemperatures() to issue a global temperature
 // request to all devices on the bus
/********************************************************************/
 
 sensors.requestTemperatures(); // Send the command to get temperature readings 
 //Serial.print(sensors.getTempCByIndex(0)); // Why "byIndex"? 
 //delay(1000);
       
        //if (sensors.getTempCByIndex(0) <0 && sensors.getTempCByIndex(0) > -0.6)
        //if(sensors.getTempCByIndex(0) >= 9.5 || (sensors.getTempCByIndex(0) <= -0.6 && sensors.getTempCByIndex(0) > -9.6)) postemp = 62; //postemp: the x position of the cursor is depended on how many characters the temp has (1, 2 or 3)
        //if(sensors.getTempCByIndex(0) < 9.5 && sensors.getTempCByIndex(0) > -0.6) postemp = 80;
        //if(sensors.getTempCByIndex(0) <= -9.6) postemp = 44;
       
        tft.setCursor(90,30);
        tft.setTextSize(2);
        tft.println(sensors.getTempCByIndex(0), 0);
        tft.setCursor(120, 28);
        tft.setTextSize(1);
        tft.println(F("o"));
        tft.setCursor(128, 30);
        tft.setTextSize(2);
        tft.println(F("C"));

        tft.setCursor(20,30);
        tft.setTextSize(2);
        tft.println(sensors.getTempCByIndex(1), 0);
        tft.setCursor(50, 28);
        tft.setTextSize(1);
        tft.println(F("o"));
        tft.setCursor(58, 30);
        tft.setTextSize(2);
        tft.println(F("C"));
   

}

jremington

#5
Jun 23, 2019, 07:19 pm Last Edit: Jun 23, 2019, 07:19 pm by jremington
Quote
I was doing like you say, but i stop on that problem,
Then undo that last change and figure out what went wrong.

sevenoutpinball

So the version that works on uno fails on mega?  That sounds hard to believe.  Load up the uno version with lots of Serial.print stuff see if it works and then try it on mega.

AdamK24

Quote
Then undo that last change and figure out what went wrong.
You still do not get it, there wasn't any last change. I don't know how to change this part of code like that it could work on mega.

jremington

#8
Jun 23, 2019, 08:28 pm Last Edit: Jun 23, 2019, 08:30 pm by jremington
Quote
I don't know how to change this part of code like that it could work on mega.
Which specific part of the codeDO NOT expect anyone on this forum to comb through four posts of useless, unexplained code fragments.

Please read and follow the instructions in the "How to use this forum" post.

AdamK24

Quote
Which specific part of the code?
This one:

Code: [Select]
noInterrupts();
  // set and initialize the TIMER1
    TCCR1A = 0; // set entire TCCR1A register to 0
    TCCR1B = 0; // set entire TCCR1B register to 0
    TCCR1B |= (1 << CS12);
    TIMSK1 |= (1 << TOIE1);
    TCNT1 = 3036;

  attachPCINT(digitalPinToPinChangeInterrupt(ignition_pin), ignitionSignal, CHANGE);

  interrupts();

//////////////////////////////////////////////////


ISR(TIMER1_OVF_vect) //TIMER1 overflow interrupt -- occurs every 1sec --
{
    instantSpeed();
   
    LPG_Consumption();
    LPG_injector_open_duration = 0;
   
    unleadedConsumption();
    unleadinj_Open_Duration = 0;
   
    seconds_passed++;
    vss_pulses = 0;
   
TCNT1 = 3036;
}






Is it correct for mega?

sevenoutpinball

again, if it works on uno...

try a different mega. 

jremington

#11
Jun 24, 2019, 01:03 am Last Edit: Jun 24, 2019, 01:07 am by jremington
Quote
Is it correct for mega?
If the code compiles without error and the program does what you want, yes.

If not, after carefully reading the instructions in the "How to use this forum" post, supply the required details.

AdamK24

Code compiles without any error but don't work as it should.
Arduino see changes in pin state but doesn't count times between on and off.
Maybe there is a problem with interrupts, i changed the pins for vss pulses, lpg signal and petrol, according to instruction of library PinChangeInterrupt.h for arduino mega but it doesn't change anything.
I was trying many oder ideas and right now i don't know what can i do more.


MorganS

Quote
Code: [Select]
noInterrupts();
  // set and initialize the TIMER1
    TCCR1A = 0; // set entire TCCR1A register to 0
    TCCR1B = 0; // set entire TCCR1B register to 0
    TCCR1B |= (1 << CS12);
    TIMSK1 |= (1 << TOIE1);
    TCNT1 = 3036;

  attachPCINT(digitalPinToPinChangeInterrupt(ignition_pin), ignitionSignal, CHANGE);

  interrupts();

//////////////////////////////////////////////////


ISR(TIMER1_OVF_vect) //TIMER1 overflow interrupt -- occurs every 1sec --
{
    instantSpeed();
   
    LPG_Consumption();
    LPG_injector_open_duration = 0;
   
    unleadedConsumption();
    unleadinj_Open_Duration = 0;
   
    seconds_passed++;
    vss_pulses = 0;
   
TCNT1 = 3036;
}



It's not wrong but it's not necessary either. You can use millis() to time one-second intervals.

Somewhere in the main loop() (which I can't even find in the snippets) you should put a millis timing interval like this...
Code: [Select]

  const unsigned long calculationInterval = 1000; //milliseconds, how often it runs the consumption calculations
  static unsigned long lastConsCalculation = 0;
  if(millis() - lastConsCalculation >= calculationInterval) {
    lastConsCalculation += calculationInterval;
    doConsumptionCalculations()
  }


And then rename ISR(TIMER1_OVF_vect)  to doConsumptionCalculations().

Keep the attachPCINT(...) line. That's still necessary.
 
"The problem is in the code you didn't post."

AdamK24

Hey
Thanks for help, i tryed your idea but without succes.
Orginal code works on uno, it shows some random numbers in cosumption even without concetion to car injector . On mega, all the time everywhere exept temperature and clock only zeros.
 I don't know where is a diference, i had check most pins, and if this is not timer code so it can only be Pin changeinterupt or somethign with Epromex library.

Go Up