CO2 Sensor Sketch resets randomly

I have the following sketch for getting data from a co2 sensor. I attached the schematic.
The issue I’m having:

The sketch seems to reset randomly. I can tell because it runs through void setup multiple times.

#include <SoftwareSerial.h>

SoftwareSerial mySerial(12, 13); // RX, TX pins on Ardunio

int co2 =0;
double multiplier = 1;// 1 for 2% =20000 PPM, 10 for 20% = 200,000 PPM
uint8_t buffer[25];
uint8_t ind =0;
uint8_t index =0;

int fill_buffer(); // function prototypes here
int format_output();

void setup()
Serial.println(" AN128 Ardunio to Cozir CO2 Sensor - Demonstration code 11/29/2017\n\n");
mySerial.begin(9600); // Start serial communications with sensor
//mySerial.println(“K 0”); // Set Command mode
mySerial.println(“M 6”); // send Mode for Z and z outputs
// “Z xxxxx z xxxxx” (CO2 filtered and unfiltered)
mySerial.println(“K 1”); // set streaming mode

void loop()
fill_buffer(); // function call that reacds CO2 sensor and fills buffer
index = 8; // In ASCII buffer, filtered value is offset from raw by 8 bytes

int fill_buffer(void)
// Fill buffer with sensor ascii data
ind = 0;
while(buffer[ind-1] != 0x0A)
{ // Read sensor and fill buffer up to 0XA = CR
buffer[ind] =;
// buffer() now filled with sensor ascii data
// ind contains the number of characters loaded into buffer up to 0xA = CR
ind = ind -2; // decrement buffer to exactly match last numerical character

int format_output(void)
// read buffer, extract 6 ASCII chars, convert to PPM and print
co2 = buffer[15-index]-0x30;
co2 = co2+((buffer[14-index]-0x30)*10);
co2 +=(buffer[13-index]-0x30)*100;
co2 +=(buffer[12-index]-0x30)*1000;
co2 +=(buffer[11-index]-0x30)10000;
Serial.print("\n CO2 = ");
//Serial.print(" PPM,");

I think it is possible that you are writing past the end of the buffer array into memory that you do not "own". Maybe check that the value of the ind variable never gets to be greater than 24 (before incrementing).

Which CO2 sensor? Post a link to the product page or data sheet.

If it has a heater, don't power it with the 5V output. The regulator may overheat and shut down, rebooting the Arduino.

This is the sensor I am using:

The current draw from the 3.3V output is 100 mA max and should be OK.

What have you done to test @groundFungus suggestion that you are overwriting memory?

If nothing, try

     buffer[ind] =;
     if (ind > 24) {
       Serial.println("array bounds violation");
       ind = 24;

Use code tags when posting code, so it looks like the above.