ATTINY13 Analog Read of Voltage Divider

I am using ATTINY13 to measure voltage using voltage divider that will turn-on an LED if V>=12, else turn-off.

This is my code:

int value = 0;
float voltage;
float R1 = 50000.0;
float R2 = 10000.0;

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

void loop(){
  value = analogRead(A2);
  voltage = value * (5.0/1024)*((R1 + R2)/R2);
  if (voltage >= 12 ) {
	 digitalWrite(0, HIGH);
  } else {
	 digitalWrite(0, LOW);
  }	 
  delay(500);
}

My problem is that the Attiny13 doesn't response when I adjust the voltage.
I can't do a serial monitor because arduino will say sketch too big.

Edit: I adjust the voltage using a dc-dc converter

How are you adjusting the voltage?

I am using dc-dc converter

the disadvantage of float calculation,
Let me assume that you apply the adjustable voltage to R1, connect the Attiny between R1 & R2, and R2 to GND, which would make sense to be able to extend the range in which you can measure voltage by 6 times.

Then you calculation is correct.

voltage = value *  ( 5.0 / 1024 ) * ( (R1 + R2) / R2);

(actually it should be (5.0 / 1023) but that is a minor detail )

How have you wired things up exactly. Keep in kind that the ADC is wired differently to the normal GPIO pin names.

Just code with pre-calculated A/D values.

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

void loop() {
  if (analogRead(A2) > 410 ) digitalWrite(0, HIGH);
  else digitalWrite(0, LOW);
}

Are you sure VCC stays 5.0volt when you adjust voltage divider input.
Because this sketch uses default Aref, which makes the result dependent on both A2 and VCC.
For voltage measurements you should use the internal reference (1.1volt Aref) of the chip.
Especially when VCC does not stay 5.0volt.
Leo..

How can I do this?

int rawValue;

void setup() {
  analogReference(INTERNAL); // switch to 1.1volt Aref
}

void loop() {
  rawValue = analogRead(A0); // 0 to about 1.1volt returns 0-1023
}

Leo..

If you use the internal reference you may need to calibrate for the actual value. It is stable, but the actual value may vary by ~10% from the 1.1V for a given chip.

1 Like

Will the 10% variation mitigate after calibration?

Yes, the voltage is stable. The variation is from the manufacturing process.

1 Like

Hi buddy, I hope you would have been successful in your project... would you be able to share the final code to read the supply voltage of Attiny13 accurately ?

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.