Adafruit Mega DigitalWrite Crash (SOLVED)

Hello ArduinoForums

This is my first post, so please be patient. I am learning how to program on an Adafruit Metro board, and I’m exploring servo control using a potentiometer as my input.

Everything works fine, and my stepper motor pulse width is controlled by analogRead(A0) which is connected to my potentiometer, and scaling that into a delay with digitalWrite(pin, HIGH), delayMicroseconds(time), digitalWrite(pin, LOW), shown below.

void loop() {
  temp = analogRead(A0);
  //1.25ms pulse width = 0
  //1.75ms pulse width = 180

  digitalWrite(10, HIGH);
  delayMicroseconds(temp/180*500+1250);
  digitalWrite(10, LOW);
  delay(15);
}

However, I wanted to smooth out glitchy motion at the endpoints (max and min potentiometer setpoint) so I added a circular buffer to average the A0 readings. For some reason, after adding in the code below, the Metro becomes unresponsive. I added some serial writes to see what was happening, and the serial output hangs after some indeterminate amount of time (less than 30 seconds after reset). Probing the digital output line shows a constant 0V output (and no pulse generated). This leads me to believe that the Adafruit Mega has crashed.

#include <Arduino.h>

float temp = 0;
float pos = 0;
float circBuffer[10] = {0,0,0,0,0,0,0,0,0,0};
int average;
float sum = 0;
String myString = "";
int i = 0;

void setup() {
  Serial.begin(19200);
}

void loop() 

  sum = 0;
  temp = analogRead(A0);
  temp = temp/1023*180;
  circBuffer[i] = temp;

  for (int x = 0; x < 10; x = x+1) {
    sum = sum + circBuffer[x];
  }
  average = sum/10;

  myString = String(circBuffer[i],4);
    // Serial.println("average");
    // Serial.println(String(average));
    Serial.println("temp");
    Serial.println(String(temp));

  //1.25ms pulse width = 0
  //1.75ms pulse width = 180

  digitalWrite(10, HIGH);
  delayMicroseconds(temp/180*500+1250);
  digitalWrite(10, LOW);
  delay(15);
  
  if (i == 10)
    i = 0;
  else
    i++;
}

I disconnected the servo motor at this point, and the issue still remains. A google search didn’t yield any useful advice, so I came here to see if anyone has experienced this issue before. Does anyone know what might be happening?

Thanks!
Tony

Edit:

  if (i == 10)
    i = 0;
  else
    i++;

I was overrunning the buffer here at i=10. Duh. My mistake, issue resolved.