SpenceKonde / megaTinyCore

Arduino core for the tinyAVR 0/1/2-series - Ones's digit 2,4,5,7 (pincount, 8,14,20,24), tens digit 0, 1, or 2 (featureset), preceded by flash in kb. Library maintainers: porting help available!
Other
551 stars 142 forks source link

ATTiny404: After 1556 calls to analogWrite, sketch restarts. #1130

Open magoldsm opened 1 month ago

magoldsm commented 1 month ago

Discussed in https://github.com/SpenceKonde/megaTinyCore/discussions/1129

Originally posted by **magoldsm** July 18, 2024 In the attached code, I make continuous calls to analogWrite. After 1556 calls, the sketch appears to crash and restart. It occurs regardless of which port I use. It also seems unaffected by malloc'ing 1k of memory or adding a useless 1k byte array, which **suggests** the problem is not a memory leak. The attached file is actually an INO file, renamed to TXT to make it acceptable as an attachment. Thanks for any help anyone is able to render! Michael [AnalogWrite_Test.txt](https://github.com/user-attachments/files/16288554/AnalogWrite_Test.txt)
magoldsm commented 1 month ago

Swapped out the 404 for a 1614. Interestingly, it now runs for 1590 calls before restarting!

moose4lord commented 1 month ago

I tried your code on an ATtiny814 and didn't see a problem. I was too lazy to hook up a device to capture the Serial output, but I added some code to blink an LED during setup to detect if the 814 crashed and restarted. It did not crash and restart.

My test code:

#define PINKY   1   // pin 3, PIN_PA5
#define RING    0   // pin 2, PIN_PA4
#define MIDDLE  6   // pin 8, PIN_PB1
#define INDEX   7   // pin 9, PIN_PB0
#define THUMB   10  // pin 13, PIN_PA3

int port = INDEX;
int writes;

void setup() {
  // put your setup code here, to run once:
  pinMode(port, OUTPUT);
  for(int i=0; i<5; i++) { // blink the LED to show the ATtiny crash/restart
    digitalWrite(port, 0); delay(200);
    digitalWrite(port, 1); delay(200);
  }

  Serial.begin(115200);
  delay(1000);

  Serial.println("Starting");

  auto cp = malloc(1024);
  writes = 0;
}

byte data[1024];      // Taking up memory for this array made no difference.

void loop() {
  Serial.print("writes: "); Serial.println(writes);
  for (int i=0; i<256; i += 2) {
    Serial.print('+');
    analogWrite(port, i);
    writes++;
    delay(5);
  }

  Serial.println("");
  Serial.print("writes: "); Serial.println(writes);
  for (int i=254; i>=0; i -= 2) {
    Serial.print('-');
    analogWrite(port, i);
    writes++;
    delay(5);
  }
  Serial.println("");
}
SpenceKonde commented 1 month ago

byte data[1024]; will not use any memory if the data is never accessed - it will be optimized out. To prevent that, declare the array volatile. That will allow you test if it's a memory problem, which dollars to donuts it is. malloc and it's minion, the String class, are the hands of the devil on embedded systems like this. Avoid at almost any cost.