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:
my circuit
and here's my code:
// to run on attiny85
const byte pwmPin = 0;
const byte analogInPin = A2;
void setup() {
pinMode(pwmPin, OUTPUT);
}
void loop() {
int analogIn = analogRead(analogInPin);
analogWrite(pwmPin, analogIn);
}
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.
2 Answers 2
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.Cybergibbons– Cybergibbons2014年03月10日 09:15:53 +00:00Commented Mar 10, 2014 at 9:15
-
1+1 Not a problem. It's good to have it all spelled out in a proper answer anyway.Ricardo– Ricardo2014年03月11日 11:46:55 +00:00Commented Mar 11, 2014 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;
const byte analogInPin = A2;
void setup() {
}
void loop() {
pinMode(pwmPin, OUTPUT);
int analogIn = analogRead(analogInPin);
analogIn = map(analogIn, 0, 1023, 0, 255);
analogWrite(pwmPin, analogIn);
}
-
1the
map
function takes a lot of clock cycles compared to the bitshift describes in Cybergibbons' answer.TheDoctor– TheDoctor2014年03月12日 12:55:13 +00:00Commented Mar 12, 2014 at 12:55
analogIn = map(analogIn, 0, 1023, 0, 255);