# attiny85 and arduino - analogRead + pwmOut

I am using the Arduino IDE to program the attiny85. I want to take an incoming analog reading, then based on that reading, output a specific PWM value. Here's my circuit:

and here's my code:

``````// to run on attiny85

const byte pwmPin = 0;

void setup() {
pinMode(pwmPin, OUTPUT);
}

void loop() {
}
``````

should be very simple- I have no problems uploading code to the attiny85, and no problems with simple tests like outputting a specific PWM value (not based on the analog read). but when I try to combine the two- read, then write that value, I can't seem to get things to work. In this circuit for example- I get a reading of 1023 (5v) on the arduino micro- instead of a reading of ~ 790 (3.85v) which is what I should expect. I've used a multimeter to verify the voltages in this circuit- so I think I must either be doing something wrong with my expectations of how to wire up or program the attiny85.

• A schematic of your circuit would probably be more helpful than an implementation schema with a breadboard. Do you have such a schematic? If yes, add it to your question. Mar 9 '14 at 18:58
• I don't see any clock (quartz or ceramic resonator) for your ATtiny, is this normal? Mar 9 '14 at 19:05
• @jfpoilpret yeah you have a few choices for using the internal clock. Mar 9 '14 at 19:06
• i needed to re-range the input to 8 bit. `analogIn = map(analogIn, 0, 1023, 0, 255);` Mar 9 '14 at 20:33
• @GradeSchool It would be helpful if you could write your solution as an actual answer, so that future visitors can find it more easily. Thanks! Mar 9 '14 at 20:54

Analog read is 10-bits (2^10 = 0-1023 range), analog write is 8-bits (2^8 = 0-255 range). Ditch the lower two bits of the result either by doing:

``````analogIn = analogIn >> 2;
``````

which can be shortened to:

``````analogIn >>= 2;
``````

Or you can use the rather complex map function:

``````analogIn = map( analogIn(0, 1023, 0, 255) )
``````
• Sorry, didn't see the answer in the comments. Mar 10 '14 at 9:15
• +1 Not a problem. It's good to have it all spelled out in a proper answer anyway. Mar 11 '14 at 11:46

i needed to re-range the 10bit input to 8 bit for the pwm out.

``````// to run on attiny85

const byte pwmPin = 0;
• the `map` function takes a lot of clock cycles compared to the bitshift describes in Cybergibbons' answer. Mar 12 '14 at 12:55