/* Title: Capacitor_Meter_1.ino a true Arduino sketch program file Author: Florin Dragan florind@mas.utcluj.ro Date Created: 01-12-2017 Last Modified: 11-12-2017 Purpose: This is an example how to configure the Atmega328P (AVR) to measure a capacitance by using charging time period Capacitor is connected to digital pin 13 for charging (D13 on Arduino Uno and Nano) and A0 as analog to digital input to measure charging voltage. Print the value using the serial port */ #define analogPin A0 // analog pin for measuring capacitor voltage #define chargePin 13 // pin to charge the capacitor - connected to one end of the charging resistor #define dischargePin 11 // pin to discharge the capacitor #define resistorValue 10000.0F // change this to whatever resistor value you are using. F formatter tells compiler it's a floating point value unsigned long startTime; // the momment when starting capacitor charge unsigned long elapsedTime; // the time to charge 63.2% of supply voltage float microFarads; // floating point variable to preserve precision float nanoFarads; void setup(){ pinMode(chargePin, OUTPUT); // set chargePin as output digitalWrite(chargePin, LOW); // and put it on LOW level state Serial.begin(9600); // initialize serial transmission for debugging } void loop(){ digitalWrite(chargePin, HIGH); // set chargePin HIGH and capacitor charging startTime = millis(); // keep the start momment to be used in future // wait until A/D converter reach 63.2% of Vs == Vref // 647 is 63.2% of 1023, which corresponds to full-scale voltage while(analogRead(analogPin) < 648) {} elapsedTime = millis() - startTime; // Read charge time (from start to now) // Convert milliseconds to seconds (10^-3) and Farads to microFarads (10^6), net 10^3 microFarads = ((float)elapsedTime / resistorValue) * 1000; Serial.print(elapsedTime); // print the value to serial port Serial.print(" mS "); // print units and carriage return if (microFarads > 1){ Serial.print((long)microFarads); // print the value to serial port Serial.println(" microFarads"); // print units and carriage return } else { // if value is smaller than one microFarad, convert to nanoFarads (10^-9 Farad). // This is a workaround because Serial.print will not print floats // multiply by 1000 to convert to nanoFarads (10^-9 Farads) nanoFarads = microFarads * 1000.0; Serial.print((long)nanoFarads); // print the value to serial port Serial.println(" nanoFarads"); // print units and carriage return } // dicharge the capacitor by putting charge/discharge pins to LOW digitalWrite(chargePin, LOW); // set charge pin to LOW pinMode(dischargePin, OUTPUT); // set discharge pin to output digitalWrite(dischargePin, LOW); // set discharge pin LOW // wait until capacitor is completely discharged, Voltage must be 0V. while(analogRead(analogPin) > 0) { } // set discharge pin back to input, corresponding to High Impedance pinMode(dischargePin, INPUT); } // end loop