1
votes

I wrote a sketch on my Arduino Mega when I was prototyping. Afterwards, I flashed it as is to a atmega328 chip. I got odd results all over the sketch. To fix it, I copied module by module over to a new IDE windows and that is when I noticed something fishy with the analogWrite functions. In order to take away all other variables, I uploaded this sketch which is a slightly modified FADE example sketch

int led = 6;       
int brightness = 0;
int fadeAmount = 5;
void setup() {
  Serial.begin(9600);
  pinMode(led, OUTPUT);
}
void loop() {
  Serial.println(brightness);
  analogWrite(led, brightness);
  brightness = brightness + fadeAmount;
  if (brightness == 0 || brightness == 255) {
    fadeAmount = -fadeAmount ;
  }
  delay(1000);
}

It uploads perfectly fine with no errors and I attached an led and resistor to that pin. when the chip starts running the code, all I get the led flashing and the serial data like this

.5
.0
.5
.0
.5
.0
.5
.0
.5
.0
.5
.0
.5
.10

What can be wrong with it???

2

2 Answers

1
votes

Strange things are happening. I ran the program after copying and pasting your code and got the expected result:

0
5
10
15
20
25
30
35
40
45
50
55
60
65
70
75
80
85
90
95
100
105
110
115
120
125
130
135
140
145
150
155
160
165
170
175
180
185
190
195
200
205
210
215
220
225
230
235
240
245
250
255
250
245
240
235
230
225
220

Are you sure you have pasted the exact code that produces the unexpected results in your side? The dots in front of the numbers are just one of many strange things. Of course the alternating values are another. As is the .10 that suddenly appears after the seros and fives. In short, the fishiness seems to be unrelated to analogwrite.

Unless it is a hardware problem. What value resistor? Are the resistor and LED in series? Does the LED flash with a frequency of 0.5 Hz and a duty cycle of 0.5? or not?

BTW, RBerteig would be correct if your condition checked with 256 instead of 255. His version is indeed better, but if this were the problem you would see a different behaviour

0
votes

An obvious problem is with this line:

if (brightness == 0 || brightness == 255) {

Since you are modifying brightness by adding (or subtracting) 5 on each iteration and 256 is not divisible by 5, neither endpoint is going to test well. Change the == test to an inequality.

if (brightness <= 0 || brightness >= 255) {