user17324: I have an Arduino Nano, and I have some issues with it. Basically it needs to control the brightness of a lamp via PWM (plus some circuitry of course). It's hooked up via serial to a little x86 embedded board which runs Linux, and that board is telling the Arduino the desired brightness level (0-255) every 5 seconds over serial. So the only thing the Arduino has to do is retrieve numbers from the other device over serial, and set the PWM output to those values. Here's the code that runs on the Arduino (I inserted some comments so it's easier to read):
Edit: I removed the original code to clean things up as it's not relevant anymore, but you can still view it here.
There's nothing fancy about the code really. It checks for incoming data about 10 times a second, and if there's any, it converts it into an int and sets the PWM output to that value. I know, that part where I manually extract the number characters probably could be replaced by Arduino library calls for cleaner code, but whatever. It works just fine.
The incoming data as I mentioned is the textual representation of an integer ranging from 0-255 followed by a new line character. This data is sent to the Arduino once every 5 seconds.
So whenever I turn this on, it works just fine for a day or so. But this is supposed to be a system that's constantly on 24/7. If I leave it running for a day or so, the output will start acting weird. I already checked, and the values that the other device sends are perfectly normal. It's the Arduino that messes up something. The brightness is NOT what it needs to be. The Arduino is outputting wrong PWM values. If I simply reset the Arduino (without restarting the other device), everything goes back to normal, and it works again for a day, so the problem is definitely in the Arduino somewhere. But I don't think it's in my code. This piece of code looks super simple and innocent, and I bet it is. I have no idea what causes this.
Could this be a hardware problem? I do have another Arduino, so I could try replacing it with that one. I haven't tried that yet since I already put all components in a case, fixed everything in place with screws, and soldered wires directly to the Arduino, so I would rather not replace it if it's not necessary.
So, any ideas on what could cause this?

Update:
I updated the programs on both devices to use a more error-prone protocol for communicating (as suggested here), which is kind of similar to the NMEA 0183 protocol (basically a simplified version of that). The sender sends the data in the following format now:

A single $ character to indicate the beginning of the data
The data itself (which is the textual representation of a single integer)
A single * character to indicate the end of the data
An exactly two digit long hexadecimal checksum value. This is the bitwise XOR of the ASCII codes of all the characters between $ and * (not including those). Letters (if any) are always uppercase.
The packet is finished up with either \n or \r\n

An example would be $178*3E\n, where \n of course means a newline character.
The code running on the Arduino now is the following:
#include <Time.h>

#define _analogWrite(a, b) analogWrite(a, 255-(b))
#define clamp(X, minVal, maxVal) min(max(X, minVal), maxVal)

const PROGMEM int pwmPin = 3;
time_t lastUpdate = 0;
String incoming = "";
int pwmValue = 0;

inline void flushSerialBuffer() {
    while (Serial.available()) Serial.read();
}

void setup() {
    Serial.begin(9600);
    Serial.setTimeout(500);
    pinMode(pwmPin, OUTPUT);
    _analogWrite(pwmPin, 0);
}

void loop() {
    time_t currentTime = now();

    if (Serial.available()) {
        delay(250); // Just to make sure that all data has arrived in the buffer
        incoming = "";
        incoming = Serial.readStringUntil('\n');
        flushSerialBuffer();
        int b = incoming.indexOf('$') + 1;
        if (b == 0) return; // -1 was returned
        int e = incoming.indexOf('*', b);
        if (e == -1) return;
        int checksum = 0x0;
        for (int i=b; i<e; i++) checksum ^= incoming[i];
        String hexString = String(checksum, HEX);
        hexString.toUpperCase();
        if (hexString.length() < 2) hexString = String("0") + hexString;
        if (!hexString.equals(incoming.substring(e+1, e+3))) return;

        pwmValue = incoming.substring(b, e).toInt();

        if (pwmValue < 0 || pwmValue > 255) pwmValue = 0;
        lastUpdate = currentTime;
    }

    if (currentTime - lastUpdate > 30) pwmValue = 0;

    _analogWrite(pwmPin, pwmValue);

    delay(250);
}

It seems like it's working so far, although I'm still testing if this is reliable over a longer period of time. I will edit the question once again to let you know.

Update 2:
Still no success. After a while it just gets stuck on one PWM value and keeps outputting that, regardless of what it receives over serial. It's kind of like it ignores the incoming data after a day or so. I can verify that the other device still sends data correctly, since if I only restart the Arduino, everything goes back to normal.

user18526: After trying the original code using Arduino IDE 1.6.7, I do not see a problem with using up memory.
Depending on the nature of the errors you are seeing, another possible explanation is that you are getting spurious data between real events. If electrical noise or whatever produces one or more characters on the serial line in the long interval between real data points, the current code will treat it as a new data point. If the bogus characters are numeric, they will be sent to the pwm. In the more likely case of non-numeric data, this code converts them to a value of 0 and sends that to the port. This situation is likely if the Arduino is more than a few feet from the PC. A slew rate limited differential driver and receiver like the MAX488 should greatly reduce the chance of this happening. Also make sure there is a good ground between the ends.
You could also reduce the chance of undetected data errors by delimiting your data with something like a '$' to start, then the data, then '*' then a checksum then a newline. The checksum could be simply the sum of all the characters up to the *, truncated to 8 bits and sent as 2 hex characters. This is what the NMEA protocol used by GPS receivers does. At the receiving end you only accept data packets with the proper format and checksum.

17324: <p>I have an Arduino Nano, and I have some issues with it. Basically it needs to control the brightness of a lamp via PWM (plus some circuitry of course). It's hooked up via serial to a little x86 embedded board which runs Linux, and that board is telling the Arduino the desired brightness level (0-255) every 5 seconds over serial. So the only thing the Arduino has to do is retrieve numbers from the other device over serial, and set the PWM output to those values. Here's the code that runs on the Arduino (I inserted some comments so it's easier to read):</p>

<p><strong><em>Edit: I removed the original code to clean things up as it's not relevant anymore, but you can still view it <a href="http://pastebin.com/RpELDBx2" rel="nofollow noreferrer">here</a>.</em></strong></p>

<p>There's nothing fancy about the code really. It checks for incoming data about 10 times a second, and if there's any, it converts it into an <code>int</code> and sets the PWM output to that value. I know, that part where I manually extract the number characters probably could be replaced by Arduino library calls for cleaner code, but whatever. It works just fine.</p>

<p>The incoming data as I mentioned is the textual representation of an integer ranging from 0-255 followed by a new line character. This data is sent to the Arduino once every 5 seconds.</p>

<p>So whenever I turn this on, it works just fine for a day or so. But this is supposed to be a system that's constantly on 24/7. If I leave it running for a day or so, the output will start acting weird. I already checked, and the values that the other device sends are perfectly normal. It's the Arduino that messes up something. The brightness is NOT what it needs to be. The Arduino is outputting wrong PWM values. If I simply reset the Arduino (without restarting the other device), everything goes back to normal, and it works again for a day, so the problem is definitely in the Arduino somewhere. But I don't think it's in my code. This piece of code looks super simple and innocent, and I bet it is. I have no idea what causes this.</p>

<p>Could this be a hardware problem? I do have another Arduino, so I could try replacing it with that one. I haven't tried that yet since I already put all components in a case, fixed everything in place with screws, and soldered wires directly to the Arduino, so I would rather not replace it if it's not necessary.</p>

<p>So, any ideas on what could cause this?</p>

<hr>

<p><strong>Update:</strong></p>

<p>I updated the programs on both devices to use a more error-prone protocol for communicating (as suggested <a href="https://arduino.stackexchange.com/a/20989/17324">here</a>), which is kind of similar to the <a href="https://en.wikipedia.org/wiki/NMEA_0183" rel="nofollow noreferrer">NMEA 0183</a> protocol (basically a simplified version of that). The sender sends the data in the following format now:</p>

<ul>
<li>A single <code>$</code> character to indicate the beginning of the data</li>
<li>The data itself (which is the textual representation of a single integer)</li>
<li>A single <code>*</code> character to indicate the end of the data</li>
<li>An exactly two digit long hexadecimal checksum value. This is the bitwise XOR of the ASCII codes of all the characters between <code>$</code> and <code>*</code> (not including those). Letters (if any) are always uppercase.</li>
<li>The packet is finished up with either <code>\n</code> or <code>\r\n</code></li>
</ul>

<p>An example would be <code>$178*3E\n</code>, where \n of course means a newline character.</p>

<p>The code running on the Arduino now is the following:</p>

<pre class="lang-cpp prettyprint-override"><code>#include &lt;Time.h&gt;

#define _analogWrite(a, b) analogWrite(a, 255-(b))
#define clamp(X, minVal, maxVal) min(max(X, minVal), maxVal)

const PROGMEM int pwmPin = 3;
time_t lastUpdate = 0;
String incoming = "";
int pwmValue = 0;

inline void flushSerialBuffer() {
    while (Serial.available()) Serial.read();
}

void setup() {
    Serial.begin(9600);
    Serial.setTimeout(500);
    pinMode(pwmPin, OUTPUT);
    _analogWrite(pwmPin, 0);
}

void loop() {
    time_t currentTime = now();

    if (Serial.available()) {
        delay(250); // Just to make sure that all data has arrived in the buffer
        incoming = "";
        incoming = Serial.readStringUntil('\n');
        flushSerialBuffer();
        int b = incoming.indexOf('$') + 1;
        if (b == 0) return; // -1 was returned
        int e = incoming.indexOf('*', b);
        if (e == -1) return;
        int checksum = 0x0;
        for (int i=b; i&lt;e; i++) checksum ^= incoming[i];
        String hexString = String(checksum, HEX);
        hexString.toUpperCase();
        if (hexString.length() &lt; 2) hexString = String("0") + hexString;
        if (!hexString.equals(incoming.substring(e+1, e+3))) return;

        pwmValue = incoming.substring(b, e).toInt();

        if (pwmValue &lt; 0 || pwmValue &gt; 255) pwmValue = 0;
        lastUpdate = currentTime;
    }

    if (currentTime - lastUpdate &gt; 30) pwmValue = 0;

    _analogWrite(pwmPin, pwmValue);

    delay(250);
}
</code></pre>

<p>It seems like it's working so far, although I'm still testing if this is reliable over a longer period of time. I will edit the question once again to let you know.</p>

<hr>

<p><strong>Update 2:</strong></p>

<p>Still no success. After a while it just gets stuck on one PWM value and keeps outputting that, regardless of what it receives over serial. It's kind of like it ignores the incoming data after a day or so. I can verify that the other device still sends data correctly, since if I only restart the Arduino, everything goes back to normal.</p>
 18526: <p>After trying the original code using Arduino IDE 1.6.7, I do not see a problem with using up memory.</p>

<p>Depending on the nature of the errors you are seeing, another possible explanation is that you are getting spurious data between real events. If electrical noise or whatever produces one or more characters on the serial line in the long interval between real data points, the current code will treat it as a new data point. If the bogus characters are numeric, they will be sent to the pwm. In the more likely case of non-numeric data, this code converts them to a value of 0 and sends that to the port. This situation is likely if the Arduino is more than a few feet from the PC. A slew rate limited differential driver and receiver like the MAX488 should greatly reduce the chance of this happening. Also make sure there is a good ground between the ends.</p>

<p>You could also reduce the chance of undetected data errors by delimiting your data with something like a '$' to start, then the data, then '*' then a checksum then a newline. The checksum could be simply the sum of all the characters up to the *, truncated to 8 bits and sent as 2 hex characters. This is what the NMEA protocol used by GPS receivers does. At the receiving end you only accept data packets with the proper format and checksum.</p>
