Program works only after pressing the reset button arduino

Hi everyone ,

I have a problem with my project .Strange my program works flawlessly when connected using USB but when powered using external power supply, I have to manually reset it for it to start working correctly. Once I do this, it works fine.

I have a Led to see when my programs works or no so i think i'm stuck in the setup() part but maybe not if someone can help me :slight_smile:

You can see my code here :


#include <SD.h>
#include <TimeLib.h>
#include <mcp_can.h>
#include <SPI.h>

//*********************CAN Sheild declarations********************

long unsigned int rxId;
unsigned char len = 0;
unsigned char rxBuf[8];
char msgString[128]; // Array to store serial string

#define CAN0_INT 2   // Set INT 
MCP_CAN CAN0(53);    // Set CS 

//*********************SD Sheild declarations**********************

File myFile;
const int SD_CS_PIN = 9;

//*********************Record Excel declarations*******************

char filename[16];
unsigned long reads_recorded = 0;
uint16_t i = 0;

//*********************Switch and Led declarations*****************

const int buttonPin = 40;     // the number of the pushbutton pin
const int ledPin =  41;      // the number of the LED pin

//********************* Program SETUP *****************************

void setup()
{
  Serial.begin(115200);
  
  while(CAN0.begin(MCP_ANY, CAN_500KBPS, MCP_16MHZ) == CAN_OK){
    SERIAL_PORT_MONITOR.println("CAN init fail, retry...");
    while (1); //wait here forever
  }
  SERIAL_PORT_MONITOR.println("CAN init ok!");

  CAN0.setMode(MCP_NORMAL);  // Set operation mode to normal so the MCP2515 sends acks to received data.

  pinMode(CAN0_INT, INPUT);  // Configuring pin for /INT input
  pinMode(buttonPin, INPUT);
  pinMode(ledPin, OUTPUT);
  
  Serial.println("MCP2515 Library Receive Example...");

  if (SD.begin(SD_CS_PIN))
  {
    SERIAL_PORT_MONITOR.println("SD card is present & ready");
    sprintf(filename, "can_%.03d.csv",i);  //initialise filename
    
    myFile = SD.open(filename, FILE_WRITE);
    if (myFile) // it opened OK
    {
      myFile.println("Time,Pression,Temperature,co2_hydrogen,humidity"); //add header to file
      myFile.close();
      SERIAL_PORT_MONITOR.println("File created!");
    }
    else
      SERIAL_PORT_MONITOR.println("Error opening file");
  }
  else
  {
    SERIAL_PORT_MONITOR.println("SD card missing or failure");
    while (1); //wait here forever
  }
  delay(100);
}


//********************* Fonction ecrire dans Excel ***********************

void writeToFile(float press_pascal, float temp_degC, float co2_true, float humi_pourcent)
{
  myFile = SD.open(filename, FILE_WRITE);
  if (myFile) // it opened OK
  {
    myFile.print(String(minute()));
    myFile.print(":");
    myFile.print(String(second()));
    myFile.print(";");
    myFile.print(String(press_pascal, 2));
    myFile.print(";");
    myFile.print(String(temp_degC, 2));
    myFile.print(";");
    myFile.print(String(co2_true, 2));
    myFile.print(";");
    myFile.println(String(humi_pourcent, 2));
    myFile.close();
  }
  else
    SERIAL_PORT_MONITOR.println("Error opening file");
}

//********************* Program LOOP ***************************

void loop()
{

  if (digitalRead(buttonPin)== HIGH) 
    {
    digitalWrite(ledPin, HIGH);  // turn LED on
    
  if(!digitalRead(CAN0_INT))                // If CAN0_INT pin is low, read receive buffer
  {
    CAN0.readMsgBuf(&rxId, &len, rxBuf);    // Read data: len = data length, buf = data byte(s)
    
  if((rxId & 0x80000000) == 0x80000000)     // Determine if ID is standard (11 bits) or extended (29 bits)
      sprintf(msgString, "Extended ID: 0x%.8lX  DLC: %1d  Data:", (rxId & 0x1FFFFFFF), len);
  else
      sprintf(msgString, "Standard ID: 0x%.3lX       DLC: %1d  Data:", rxId, len);
  
    Serial.print(msgString);
  
   if((rxId & 0x40000000) == 0x40000000){    // Determine if message is a remote request frame.
      sprintf(msgString, " REMOTE REQUEST FRAME");
      Serial.print(msgString);}
   else 
   {
    for(byte i = 0; i<len; i++)
     {
      sprintf(msgString, " 0x%.2X", rxBuf[i]);
      Serial.print(msgString);
            }
          }
    Serial.println();

    Serial.println("____Pression_Kpa____");
    uint16_t press_raw;
    memcpy(&press_raw, &rxBuf[0], 2); //buf[0] is the first byte in buf, 2 because you want 2 bytes
    float press_pascal = ((press_raw * 0.0078125) - 250);
    Serial.println(press_pascal, 2);  // value to copy on excel

    Serial.println("_____Temperature_____");
    uint16_t temp_raw;
    memcpy(&temp_raw, &rxBuf[2], 2); //buf[2] is the third byte in buf, 2 because you want 2 bytes
    float temp_degC = (((temp_raw * 0.03125)-273)-3) ;
    Serial.println(temp_degC, 2);

    Serial.println("_____CO2_Hydrogen_____");
    uint16_t co2_raw;
    memcpy(&co2_raw, &rxBuf[4], 2); //buf[4] is the fifth byte in buf, 2 because you want 2 bytes
    float co2_true = ((co2_raw * 1) - 0);
    Serial.println(co2_true, 2);

    Serial.println("_____Humidity_%_____");
    uint16_t humi_raw;
    memcpy(&humi_raw, &rxBuf[6], 2); //buf[6] is the six byte in buf, 1 because you want 1 bytes
    float humi_pourcent = ((humi_raw * 0.4) - 0);
    Serial.println(humi_pourcent, 2);

    writeToFile(press_pascal, temp_degC, co2_true, humi_pourcent);
    ++reads_recorded;
  }
}
  else 
      {
         digitalWrite(ledPin, LOW); // turn LED off
         Serial.println("off");
      }
      
//********************* Creation new files excel ***********************
  
  //create new filenames for every 5400 lines written to file
  if(reads_recorded == 5400) {  //reset counter
    reads_recorded = 0;

    //increment file counter
    ++i;
    
    //update finename
    sprintf(filename, "can_%.03d.csv", i);

    myFile = SD.open(filename, FILE_WRITE);
    if (myFile) // it opened OK
    {
      //add header to new file
      myFile.println("  Time,  Pression  ,  Temperature  ,  co2_hydrogen  ,humidity");
      myFile.close();
      SERIAL_PORT_MONITOR.println("New File created!");
    }
    else
      SERIAL_PORT_MONITOR.println("Error opening file");
  }
} 

Your have two types of diagnostic messages in the code. One with a normal Serial

and another with SERIAL_PORT_MONITOR

What is SERIAL_PORT_MONITOR and where it declared?

1 Like

Part of the core :wink: C:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\mega\pins_arduino.h

#define SERIAL_PORT_MONITOR         Serial
#define SERIAL_PORT_HARDWARE        Serial
#define SERIAL_PORT_HARDWARE1       Serial1
#define SERIAL_PORT_HARDWARE2       Serial2
#define SERIAL_PORT_HARDWARE3       Serial3
#define SERIAL_PORT_HARDWARE_OPEN   Serial1
#define SERIAL_PORT_HARDWARE_OPEN1  Serial2
#define SERIAL_PORT_HARDWARE_OPEN2  Serial3
2 Likes

The Mega operates at 5V, and you are powering it with 12V. That means that the tiny, linear voltage regulator on the Mega must dissipate 7V as heat. Because you are powering the CAN bus shield from the 5V output on the Mega, you are most likely overloading the regulator.

My suggestion would be to get a switching voltage regulator (LM2596 based or whatever) to regulate the 12V to 5V and power the Mega and the CAN shield with that.

The reason why it works after a reset could be that on power up, the regulator is overloaded due to an inrush current spike. When you press reset, all the capacitors in the circuit are saturated and thus the inrush current spike is much smaller - if present at all.

2 Likes

Please see this
Arduino code does not work when switching from USB to power supply

1 Like

Thank you for your answers I first tried to add a delay but that does not change the problem.

As far as the power supply is concerned, I will carry out the test next week but I have checked that an Arduino card can be powered between 7 - 12v on this port.

I investigated the issue and observed this.

It works when:

I return the SD card with the whole project not powered. I then supply power and set the switch to On. The led lights up and recording with :slight_smile:

It doesn't work when:

I feed my project, the interuptor is always on OFF I return the SD card then I put ON. Nothing happens nothing lights I have to do a RESET to make it work

So I think it's this part of the code in the Setup that blocks and I should perhaps enter it in my Loop for it to be done permanently?

 if (SD.begin(SD_CS_PIN))
  {
    SERIAL_PORT_MONITOR.println("SD card is present & ready");
    sprintf(filename, "can_%.03d.csv", i);  //initialise filename
    
    myFile = SD.open(filename, FILE_WRITE);
    if (myFile) // it opened OK
    {
      myFile.println("Time,Pression,Temperature,co2_hydrogen,humidity"); //add header to file
      myFile.close();
      SERIAL_PORT_MONITOR.println("File created!");
    }
    else
      SERIAL_PORT_MONITOR.println("Error opening file");
  }
  else
  {
    SERIAL_PORT_MONITOR.println("SD card missing or failure");
    while (1); //wait here forever
  }

You could also use the on-board LED to signal failure:

void blinking_halt()
{
  pinMode(LED_BUILTIN, OUTPUT);
  while(1)
  {
    digitalWrite(LED_BUILTIN, LOW);
    delay(500);
    digitalWrite(LED_BUILTIN, HIGH);
    delay(500);
  }
}

setup()
{
  ...
  if (SD.begin(SD_CS_PIN))
  {
    ...
  }
  else
  {
    SERIAL_PORT_MONITOR.println("SD card missing or failure");
    blinking_halt();
  }
  ...
}

If the SD card fails, the on-board LED will blink..

EDIT: But have in mind, that if it works with USB power but not when powered through the barrel jack, then the power delivery is most likely to blame and not the code..

1 Like

Hello , this morning i do more test to know if the problems is about alimentation with the +12v on the Arduino Mega.

So i disconect the +12v on my arduino.
I power my sensor with 12v and my arduino with the +5v of the USB. I return the SD card then i put ON the switch. Nothing happens nothing lights I have to do a RESET to make it work ( so the alimentation its not the problems ).

So i want to move the Can and SD check of the setup() to the loop() ,but I don't know how not to interfere with the code already present in my loop...
To constantly check before using my switch,

but how to say in the loop

-I check if the Can is OK
-I check if the SD is ok
-ON switch starts recording
-OFF switch (nothing)

#include <SD.h>
#include <TimeLib.h>
#include <mcp_can.h>
#include <SPI.h>

//*********************CAN Sheild declarations********************

long unsigned int rxId;
unsigned char len = 0;
unsigned char rxBuf[8];
char msgString[128]; // Array to store serial string

#define CAN0_INT 2   // Set INT 
MCP_CAN CAN0(53);    // Set CS 

//*********************SD Sheild declarations**********************

File myFile;
const int SD_CS_PIN = 9;

//*********************Record Excel declarations*******************

char filename[16];
unsigned long reads_recorded = 0;
uint16_t i = 0;

//*********************Switch and Led declarations*****************

const int buttonPin = 40;     // the number of the pushbutton pin
const int ledPin =  41;      // the number of the LED pin

//********************* Program SETUP *****************************

void setup()
{
  Serial.begin(115200);
  
  while(CAN0.begin(MCP_ANY, CAN_500KBPS, MCP_16MHZ) != CAN_OK){
    SERIAL_PORT_MONITOR.println("CAN init fail, retry...");
    while (1); //wait here forever
  }
  SERIAL_PORT_MONITOR.println("CAN init ok!");

  CAN0.setMode(MCP_NORMAL);  // Set operation mode to normal so the MCP2515 sends acks to received data.

  pinMode(CAN0_INT, INPUT);  // Configuring pin for /INT input
  pinMode(buttonPin, INPUT);
  pinMode(ledPin, OUTPUT);
  
  Serial.println("MCP2515 Library Receive Example...");

  if (SD.begin(SD_CS_PIN))
  {
    SERIAL_PORT_MONITOR.println("SD card is present & ready");
    sprintf(filename, "can_%.03d.csv",i);  //initialise filename
    
    myFile = SD.open(filename, FILE_WRITE);
    if (myFile) // it opened OK
    {
      myFile.println("Time,Pression,Temperature,co2_hydrogen,humidity"); //add header to file
      myFile.close();
      SERIAL_PORT_MONITOR.println("File created!");
    }
    else
      SERIAL_PORT_MONITOR.println("Error opening file");
  }
  else
  {
    SERIAL_PORT_MONITOR.println("SD card missing or failure");
    while (1); //wait here forever
  }
}


//********************* Fonction ecrire dans Excel ***********************

void writeToFile(float press_pascal, float temp_degC, float co2_true, float humi_pourcent)
{
  myFile = SD.open(filename, FILE_WRITE);
  if (myFile) // it opened OK
  {
    myFile.print(String(minute()));
    myFile.print(":");
    myFile.print(String(second()));
    myFile.print(";");
    myFile.print(String(press_pascal, 2));
    myFile.print(";");
    myFile.print(String(temp_degC, 2));
    myFile.print(";");
    myFile.print(String(co2_true, 2));
    myFile.print(";");
    myFile.println(String(humi_pourcent, 2));
    myFile.close();
  }
  else
    SERIAL_PORT_MONITOR.println("Error opening file");
}

//********************* Program LOOP ***************************

void loop()
{

  if (digitalRead(buttonPin)== HIGH) 
    {
    digitalWrite(ledPin, HIGH);  // turn LED on
    
  if(!digitalRead(CAN0_INT))                // If CAN0_INT pin is low, read receive buffer
  {
    CAN0.readMsgBuf(&rxId, &len, rxBuf);    // Read data: len = data length, buf = data byte(s)
    
  if((rxId & 0x80000000) == 0x80000000)     // Determine if ID is standard (11 bits) or extended (29 bits)
      sprintf(msgString, "Extended ID: 0x%.8lX  DLC: %1d  Data:", (rxId & 0x1FFFFFFF), len);
  else
      sprintf(msgString, "Standard ID: 0x%.3lX       DLC: %1d  Data:", rxId, len);
  
    Serial.print(msgString);
  
   if((rxId & 0x40000000) == 0x40000000){    // Determine if message is a remote request frame.
      sprintf(msgString, " REMOTE REQUEST FRAME");
      Serial.print(msgString);}
   else 
   {
    for(byte i = 0; i<len; i++)
     {
      sprintf(msgString, " 0x%.2X", rxBuf[i]);
      Serial.print(msgString);
            }
          }
    Serial.println();

    Serial.println("____Pression_Kpa____");
    uint16_t press_raw;
    memcpy(&press_raw, &rxBuf[0], 2); //buf[0] is the first byte in buf, 2 because you want 2 bytes
    float press_pascal = ((press_raw * 0.0078125) - 250);
    Serial.println(press_pascal, 2);  // value to copy on excel

    Serial.println("_____Temperature_____");
    uint16_t temp_raw;
    memcpy(&temp_raw, &rxBuf[2], 2); //buf[2] is the third byte in buf, 2 because you want 2 bytes
    float temp_degC = (((temp_raw * 0.03125)-273)-3) ;
    Serial.println(temp_degC, 2);

    Serial.println("_____CO2_Hydrogen_____");
    uint16_t co2_raw;
    memcpy(&co2_raw, &rxBuf[4], 2); //buf[4] is the fifth byte in buf, 2 because you want 2 bytes
    float co2_true = ((co2_raw * 1) - 0);
    Serial.println(co2_true, 2);

    Serial.println("_____Humidity_%_____");
    uint16_t humi_raw;
    memcpy(&humi_raw, &rxBuf[6], 2); //buf[6] is the six byte in buf, 1 because you want 1 bytes
    float humi_pourcent = ((humi_raw * 0.4) - 0);
    Serial.println(humi_pourcent, 2);

    writeToFile(press_pascal, temp_degC, co2_true, humi_pourcent);
    ++reads_recorded;
  }
}
  else 
      {
         digitalWrite(ledPin, LOW); // turn LED off
         Serial.println("off");
      }
      
//********************* Creation new files excel ***********************
  
  //create new filenames for every 5400 lines written to file
  if(reads_recorded == 5400) {  //reset counter
    reads_recorded = 0;

    //increment file counter
    ++i;
    
    //update finename
    sprintf(filename, "can_%.03d.csv", i);

    myFile = SD.open(filename, FILE_WRITE);
    if (myFile) // it opened OK
    {
      //add header to new file
      myFile.println("  Time,  Pression  ,  Temperature  ,  co2_hydrogen  ,humidity");
      myFile.close();
      SERIAL_PORT_MONITOR.println("New File created!");
    }
    else
      SERIAL_PORT_MONITOR.println("Error opening file");
  }
}

Before you start to bodge some silly workaround, you must examine what the problem actually is. Try to read the serial output or use an LED to indicate where in the code the problem is occurring - see post #8.

1 Like

I follow your instruction post#8 ( code just here )

I try the two method of my post#7 and the Led stop blinkafter a reset or if my SD card is present systems off , but if a insert the card SD with my project powered the led blink...

It doesn't work when: i try it with +12v and 5v USB
I feed my project, the interuptor is always on OFF I return the SD card then I put ON. Nothing happens nothing lights I have to do a RESET to make it work ( The Led always blink )

And I can't put my SD card in whenever I want, I have to turn off my whole project and insert it, but I want to be able to put it in anytime

void blinking_halt()
{
  pinMode(LED_BUILTIN, OUTPUT);
  while(1)
  {
    digitalWrite(LED_BUILTIN, LOW);
    delay(500);
    digitalWrite(LED_BUILTIN, HIGH);
    delay(500);
  }
}
void setup()
{
  Serial.begin(115200);
  
  while(CAN0.begin(MCP_ANY, CAN_500KBPS, MCP_16MHZ) != CAN_OK){
    SERIAL_PORT_MONITOR.println("CAN init fail, retry...");
    while (1); //wait here forever
  }
  SERIAL_PORT_MONITOR.println("CAN init ok!");

  CAN0.setMode(MCP_NORMAL);  // Set operation mode to normal so the MCP2515 sends acks to received data.

  pinMode(CAN0_INT, INPUT);  // Configuring pin for /INT input
  pinMode(buttonPin, INPUT);
  pinMode(ledPin, OUTPUT);
  
  Serial.println("MCP2515 Library Receive Example...");

  if (SD.begin(SD_CS_PIN))
  {
    SERIAL_PORT_MONITOR.println("SD card is present & ready");
    sprintf(filename, "can_%.03d.csv",i);  //initialise filename
    
    myFile = SD.open(filename, FILE_WRITE);
    if (myFile) // it opened OK
    {
      myFile.println("Time,Pression,Temperature,co2_hydrogen,humidity"); //add header to file
      myFile.close();
      SERIAL_PORT_MONITOR.println("File created!");
    }
    else
      SERIAL_PORT_MONITOR.println("Error opening file");
  }
  else
  {
    SERIAL_PORT_MONITOR.println("SD card missing or failure");
    blinking_halt();
    while (1); //wait here forever
  }
}

This is new info, you never mentioned this clearly before. If you want to be able to "hotplug" the SD-card, you will need to implement a momentary push button. Then you need to make code which checks if the SD card is present in setup and stores the SD card state in a variable (eg. bool SD_mounted). In loop you must check the state of the button, and if pressed and no SD card is mounted, try to mount. If a SD card is preset, then unmount is. It would be smart to have a LED to indicate whether a SD card is mounted or not.

1 Like

I just want to insert my SD card when my project is powered , read 30min data and eject after that to read on my computer after that i clean the card for other test of temperature.

But at the present time to make works i need tu cut off all the project and insert my sd or do a reset ( but the project is on a box )

And yes i'm not able to insert the card when i want idk to do that -_-

As far as I can tell, your code only logs CAN messages if the button is pressed, so you would need to hold the button for 30 minutes to do what you want. This also looks wrong:

while(CAN0.begin(MCP_ANY, CAN_500KBPS, MCP_16MHZ) == CAN_OK){
    SERIAL_PORT_MONITOR.println("CAN init fail, retry...");
    while (1); //wait here forever
  }

yeah you mean with the while(1); i'm stuck and he don't try everytime to detect the can for example ?
But what i need to do because i think since many post to do that on my void loop() ...

I mean that the code fails if the can is successfully initialized, so the code should not get to the SD card init unless can fails..

I think using 12V power at the Mega's Vin is the main issue. The power requirements of the shield is likely too high to have Vin at 12V. The regulator will deliver much lower current than if, for instance, Vin is supplied with 7V.

Note that with this shield, they specify using 7V at Vin. I suggest trying this as a test.

1 Like

I find a way to makes works my questions i do that :

The first line juste here is the solution of my problem but i have one other for you if you can help me

 while(!SD.begin(SD_CS_PIN));
  
    SERIAL_PORT_MONITOR.println("SD card is present & ready");
    sprintf(filename, "can_%.03d.csv", i);  //initialise filename
    
    myFile = SD.open(filename, FILE_WRITE);
    if (myFile) // it opened OK
    {
      myFile.println("Time,Pression,Temperature,co2_hydrogen,humidity"); //add header to file
      myFile.close();
      SERIAL_PORT_MONITOR.println("File created!");
    }
    else
      SERIAL_PORT_MONITOR.println("Error opening file");
 
}

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.