4

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.

  • 1
    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. – jfpoilpret Mar 9 '14 at 18:58
  • I don't see any clock (quartz or ceramic resonator) for your ATtiny, is this normal? – jfpoilpret Mar 9 '14 at 19:05
  • @jfpoilpret yeah you have a few choices for using the internal clock. – sachleen Mar 9 '14 at 19:06
  • 1
    i needed to re-range the input to 8 bit. analogIn = map(analogIn, 0, 1023, 0, 255); – GradeSchool Mar 9 '14 at 20:33
  • 2
    @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! – Peter Bloomfield Mar 9 '14 at 20:54
8

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 Mar 10 '14 at 9:15
  • 1
    +1 Not a problem. It's good to have it all spelled out in a proper answer anyway. – Ricardo Mar 11 '14 at 11:46
4

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);
}
  • 1
    the map function takes a lot of clock cycles compared to the bitshift describes in Cybergibbons' answer. – TheDoctor Mar 12 '14 at 12:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.